1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 namespace slpvectorizer {
776 
777 /// Bottom Up SLP Vectorizer.
778 class BoUpSLP {
779   struct TreeEntry;
780   struct ScheduleData;
781 
782 public:
783   using ValueList = SmallVector<Value *, 8>;
784   using InstrList = SmallVector<Instruction *, 16>;
785   using ValueSet = SmallPtrSet<Value *, 16>;
786   using StoreList = SmallVector<StoreInst *, 8>;
787   using ExtraValueToDebugLocsMap =
788       MapVector<Value *, SmallVector<Instruction *, 2>>;
789   using OrdersType = SmallVector<unsigned, 4>;
790 
791   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
792           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
793           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
794           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
795       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
796         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
797     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
798     // Use the vector register size specified by the target unless overridden
799     // by a command-line option.
800     // TODO: It would be better to limit the vectorization factor based on
801     //       data type rather than just register size. For example, x86 AVX has
802     //       256-bit registers, but it does not support integer operations
803     //       at that width (that requires AVX2).
804     if (MaxVectorRegSizeOption.getNumOccurrences())
805       MaxVecRegSize = MaxVectorRegSizeOption;
806     else
807       MaxVecRegSize =
808           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
809               .getFixedSize();
810 
811     if (MinVectorRegSizeOption.getNumOccurrences())
812       MinVecRegSize = MinVectorRegSizeOption;
813     else
814       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
815   }
816 
817   /// Vectorize the tree that starts with the elements in \p VL.
818   /// Returns the vectorized root.
819   Value *vectorizeTree();
820 
821   /// Vectorize the tree but with the list of externally used values \p
822   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
823   /// generated extractvalue instructions.
824   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
825 
826   /// \returns the cost incurred by unwanted spills and fills, caused by
827   /// holding live values over call sites.
828   InstructionCost getSpillCost() const;
829 
830   /// \returns the vectorization cost of the subtree that starts at \p VL.
831   /// A negative number means that this is profitable.
832   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
833 
834   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
835   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
836   void buildTree(ArrayRef<Value *> Roots,
837                  ArrayRef<Value *> UserIgnoreLst = None);
838 
839   /// Builds external uses of the vectorized scalars, i.e. the list of
840   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
841   /// ExternallyUsedValues contains additional list of external uses to handle
842   /// vectorization of reductions.
843   void
844   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
845 
846   /// Clear the internal data structures that are created by 'buildTree'.
847   void deleteTree() {
848     VectorizableTree.clear();
849     ScalarToTreeEntry.clear();
850     MustGather.clear();
851     ExternalUses.clear();
852     for (auto &Iter : BlocksSchedules) {
853       BlockScheduling *BS = Iter.second.get();
854       BS->clear();
855     }
856     MinBWs.clear();
857     InstrElementSize.clear();
858   }
859 
860   unsigned getTreeSize() const { return VectorizableTree.size(); }
861 
862   /// Perform LICM and CSE on the newly generated gather sequences.
863   void optimizeGatherSequence();
864 
865   /// Checks if the specified gather tree entry \p TE can be represented as a
866   /// shuffled vector entry + (possibly) permutation with other gathers. It
867   /// implements the checks only for possibly ordered scalars (Loads,
868   /// ExtractElement, ExtractValue), which can be part of the graph.
869   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
870 
871   /// Gets reordering data for the given tree entry. If the entry is vectorized
872   /// - just return ReorderIndices, otherwise check if the scalars can be
873   /// reordered and return the most optimal order.
874   /// \param TopToBottom If true, include the order of vectorized stores and
875   /// insertelement nodes, otherwise skip them.
876   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
877 
878   /// Reorders the current graph to the most profitable order starting from the
879   /// root node to the leaf nodes. The best order is chosen only from the nodes
880   /// of the same size (vectorization factor). Smaller nodes are considered
881   /// parts of subgraph with smaller VF and they are reordered independently. We
882   /// can make it because we still need to extend smaller nodes to the wider VF
883   /// and we can merge reordering shuffles with the widening shuffles.
884   void reorderTopToBottom();
885 
886   /// Reorders the current graph to the most profitable order starting from
887   /// leaves to the root. It allows to rotate small subgraphs and reduce the
888   /// number of reshuffles if the leaf nodes use the same order. In this case we
889   /// can merge the orders and just shuffle user node instead of shuffling its
890   /// operands. Plus, even the leaf nodes have different orders, it allows to
891   /// sink reordering in the graph closer to the root node and merge it later
892   /// during analysis.
893   void reorderBottomToTop(bool IgnoreReorder = false);
894 
895   /// \return The vector element size in bits to use when vectorizing the
896   /// expression tree ending at \p V. If V is a store, the size is the width of
897   /// the stored value. Otherwise, the size is the width of the largest loaded
898   /// value reaching V. This method is used by the vectorizer to calculate
899   /// vectorization factors.
900   unsigned getVectorElementSize(Value *V);
901 
902   /// Compute the minimum type sizes required to represent the entries in a
903   /// vectorizable tree.
904   void computeMinimumValueSizes();
905 
906   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
907   unsigned getMaxVecRegSize() const {
908     return MaxVecRegSize;
909   }
910 
911   // \returns minimum vector register size as set by cl::opt.
912   unsigned getMinVecRegSize() const {
913     return MinVecRegSize;
914   }
915 
916   unsigned getMinVF(unsigned Sz) const {
917     return std::max(2U, getMinVecRegSize() / Sz);
918   }
919 
920   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
921     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
922       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
923     return MaxVF ? MaxVF : UINT_MAX;
924   }
925 
926   /// Check if homogeneous aggregate is isomorphic to some VectorType.
927   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
928   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
929   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
930   ///
931   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
932   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
933 
934   /// \returns True if the VectorizableTree is both tiny and not fully
935   /// vectorizable. We do not vectorize such trees.
936   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
937 
938   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
939   /// can be load combined in the backend. Load combining may not be allowed in
940   /// the IR optimizer, so we do not want to alter the pattern. For example,
941   /// partially transforming a scalar bswap() pattern into vector code is
942   /// effectively impossible for the backend to undo.
943   /// TODO: If load combining is allowed in the IR optimizer, this analysis
944   ///       may not be necessary.
945   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
946 
947   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
948   /// can be load combined in the backend. Load combining may not be allowed in
949   /// the IR optimizer, so we do not want to alter the pattern. For example,
950   /// partially transforming a scalar bswap() pattern into vector code is
951   /// effectively impossible for the backend to undo.
952   /// TODO: If load combining is allowed in the IR optimizer, this analysis
953   ///       may not be necessary.
954   bool isLoadCombineCandidate() const;
955 
956   OptimizationRemarkEmitter *getORE() { return ORE; }
957 
958   /// This structure holds any data we need about the edges being traversed
959   /// during buildTree_rec(). We keep track of:
960   /// (i) the user TreeEntry index, and
961   /// (ii) the index of the edge.
962   struct EdgeInfo {
963     EdgeInfo() = default;
964     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
965         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
966     /// The user TreeEntry.
967     TreeEntry *UserTE = nullptr;
968     /// The operand index of the use.
969     unsigned EdgeIdx = UINT_MAX;
970 #ifndef NDEBUG
971     friend inline raw_ostream &operator<<(raw_ostream &OS,
972                                           const BoUpSLP::EdgeInfo &EI) {
973       EI.dump(OS);
974       return OS;
975     }
976     /// Debug print.
977     void dump(raw_ostream &OS) const {
978       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
979          << " EdgeIdx:" << EdgeIdx << "}";
980     }
981     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
982 #endif
983   };
984 
985   /// A helper data structure to hold the operands of a vector of instructions.
986   /// This supports a fixed vector length for all operand vectors.
987   class VLOperands {
988     /// For each operand we need (i) the value, and (ii) the opcode that it
989     /// would be attached to if the expression was in a left-linearized form.
990     /// This is required to avoid illegal operand reordering.
991     /// For example:
992     /// \verbatim
993     ///                         0 Op1
994     ///                         |/
995     /// Op1 Op2   Linearized    + Op2
996     ///   \ /     ---------->   |/
997     ///    -                    -
998     ///
999     /// Op1 - Op2            (0 + Op1) - Op2
1000     /// \endverbatim
1001     ///
1002     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1003     ///
1004     /// Another way to think of this is to track all the operations across the
1005     /// path from the operand all the way to the root of the tree and to
1006     /// calculate the operation that corresponds to this path. For example, the
1007     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1008     /// corresponding operation is a '-' (which matches the one in the
1009     /// linearized tree, as shown above).
1010     ///
1011     /// For lack of a better term, we refer to this operation as Accumulated
1012     /// Path Operation (APO).
1013     struct OperandData {
1014       OperandData() = default;
1015       OperandData(Value *V, bool APO, bool IsUsed)
1016           : V(V), APO(APO), IsUsed(IsUsed) {}
1017       /// The operand value.
1018       Value *V = nullptr;
1019       /// TreeEntries only allow a single opcode, or an alternate sequence of
1020       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1021       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1022       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1023       /// (e.g., Add/Mul)
1024       bool APO = false;
1025       /// Helper data for the reordering function.
1026       bool IsUsed = false;
1027     };
1028 
1029     /// During operand reordering, we are trying to select the operand at lane
1030     /// that matches best with the operand at the neighboring lane. Our
1031     /// selection is based on the type of value we are looking for. For example,
1032     /// if the neighboring lane has a load, we need to look for a load that is
1033     /// accessing a consecutive address. These strategies are summarized in the
1034     /// 'ReorderingMode' enumerator.
1035     enum class ReorderingMode {
1036       Load,     ///< Matching loads to consecutive memory addresses
1037       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1038       Constant, ///< Matching constants
1039       Splat,    ///< Matching the same instruction multiple times (broadcast)
1040       Failed,   ///< We failed to create a vectorizable group
1041     };
1042 
1043     using OperandDataVec = SmallVector<OperandData, 2>;
1044 
1045     /// A vector of operand vectors.
1046     SmallVector<OperandDataVec, 4> OpsVec;
1047 
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051 
1052     /// \returns the operand data at \p OpIdx and \p Lane.
1053     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1054       return OpsVec[OpIdx][Lane];
1055     }
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1058     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// Clears the used flag for all entries.
1063     void clearUsed() {
1064       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1065            OpIdx != NumOperands; ++OpIdx)
1066         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1067              ++Lane)
1068           OpsVec[OpIdx][Lane].IsUsed = false;
1069     }
1070 
1071     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1072     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1073       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1074     }
1075 
1076     // The hard-coded scores listed here are not very important, though it shall
1077     // be higher for better matches to improve the resulting cost. When
1078     // computing the scores of matching one sub-tree with another, we are
1079     // basically counting the number of values that are matching. So even if all
1080     // scores are set to 1, we would still get a decent matching result.
1081     // However, sometimes we have to break ties. For example we may have to
1082     // choose between matching loads vs matching opcodes. This is what these
1083     // scores are helping us with: they provide the order of preference. Also,
1084     // this is important if the scalar is externally used or used in another
1085     // tree entry node in the different lane.
1086 
1087     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1088     static const int ScoreConsecutiveLoads = 4;
1089     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1090     static const int ScoreReversedLoads = 3;
1091     /// ExtractElementInst from same vector and consecutive indexes.
1092     static const int ScoreConsecutiveExtracts = 4;
1093     /// ExtractElementInst from same vector and reversed indices.
1094     static const int ScoreReversedExtracts = 3;
1095     /// Constants.
1096     static const int ScoreConstants = 2;
1097     /// Instructions with the same opcode.
1098     static const int ScoreSameOpcode = 2;
1099     /// Instructions with alt opcodes (e.g, add + sub).
1100     static const int ScoreAltOpcodes = 1;
1101     /// Identical instructions (a.k.a. splat or broadcast).
1102     static const int ScoreSplat = 1;
1103     /// Matching with an undef is preferable to failing.
1104     static const int ScoreUndef = 1;
1105     /// Score for failing to find a decent match.
1106     static const int ScoreFail = 0;
1107     /// Score if all users are vectorized.
1108     static const int ScoreAllUserVectorized = 1;
1109 
1110     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1111     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1112     /// MainAltOps.
1113     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1114                                ScalarEvolution &SE, int NumLanes,
1115                                ArrayRef<Value *> MainAltOps) {
1116       if (V1 == V2)
1117         return VLOperands::ScoreSplat;
1118 
1119       auto *LI1 = dyn_cast<LoadInst>(V1);
1120       auto *LI2 = dyn_cast<LoadInst>(V2);
1121       if (LI1 && LI2) {
1122         if (LI1->getParent() != LI2->getParent())
1123           return VLOperands::ScoreFail;
1124 
1125         Optional<int> Dist = getPointersDiff(
1126             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1127             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1128         if (!Dist || *Dist == 0)
1129           return VLOperands::ScoreFail;
1130         // The distance is too large - still may be profitable to use masked
1131         // loads/gathers.
1132         if (std::abs(*Dist) > NumLanes / 2)
1133           return VLOperands::ScoreAltOpcodes;
1134         // This still will detect consecutive loads, but we might have "holes"
1135         // in some cases. It is ok for non-power-2 vectorization and may produce
1136         // better results. It should not affect current vectorization.
1137         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1138                            : VLOperands::ScoreReversedLoads;
1139       }
1140 
1141       auto *C1 = dyn_cast<Constant>(V1);
1142       auto *C2 = dyn_cast<Constant>(V2);
1143       if (C1 && C2)
1144         return VLOperands::ScoreConstants;
1145 
1146       // Extracts from consecutive indexes of the same vector better score as
1147       // the extracts could be optimized away.
1148       Value *EV1;
1149       ConstantInt *Ex1Idx;
1150       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1151         // Undefs are always profitable for extractelements.
1152         if (isa<UndefValue>(V2))
1153           return VLOperands::ScoreConsecutiveExtracts;
1154         Value *EV2 = nullptr;
1155         ConstantInt *Ex2Idx = nullptr;
1156         if (match(V2,
1157                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1158                                                          m_Undef())))) {
1159           // Undefs are always profitable for extractelements.
1160           if (!Ex2Idx)
1161             return VLOperands::ScoreConsecutiveExtracts;
1162           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1163             return VLOperands::ScoreConsecutiveExtracts;
1164           if (EV2 == EV1) {
1165             int Idx1 = Ex1Idx->getZExtValue();
1166             int Idx2 = Ex2Idx->getZExtValue();
1167             int Dist = Idx2 - Idx1;
1168             // The distance is too large - still may be profitable to use
1169             // shuffles.
1170             if (std::abs(Dist) == 0)
1171               return VLOperands::ScoreSplat;
1172             if (std::abs(Dist) > NumLanes / 2)
1173               return VLOperands::ScoreSameOpcode;
1174             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1175                               : VLOperands::ScoreReversedExtracts;
1176           }
1177           return VLOperands::ScoreAltOpcodes;
1178         }
1179         return VLOperands::ScoreFail;
1180       }
1181 
1182       auto *I1 = dyn_cast<Instruction>(V1);
1183       auto *I2 = dyn_cast<Instruction>(V2);
1184       if (I1 && I2) {
1185         if (I1->getParent() != I2->getParent())
1186           return VLOperands::ScoreFail;
1187         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1188         Ops.push_back(I1);
1189         Ops.push_back(I2);
1190         InstructionsState S = getSameOpcode(Ops);
1191         // Note: Only consider instructions with <= 2 operands to avoid
1192         // complexity explosion.
1193         if (S.getOpcode() &&
1194             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1195              !S.isAltShuffle()) &&
1196             all_of(Ops, [&S](Value *V) {
1197               return cast<Instruction>(V)->getNumOperands() ==
1198                      S.MainOp->getNumOperands();
1199             }))
1200           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1201                                   : VLOperands::ScoreSameOpcode;
1202       }
1203 
1204       if (isa<UndefValue>(V2))
1205         return VLOperands::ScoreUndef;
1206 
1207       return VLOperands::ScoreFail;
1208     }
1209 
1210     /// \param Lane lane of the operands under analysis.
1211     /// \param OpIdx operand index in \p Lane lane we're looking the best
1212     /// candidate for.
1213     /// \param Idx operand index of the current candidate value.
1214     /// \returns The additional score due to possible broadcasting of the
1215     /// elements in the lane. It is more profitable to have power-of-2 unique
1216     /// elements in the lane, it will be vectorized with higher probability
1217     /// after removing duplicates. Currently the SLP vectorizer supports only
1218     /// vectorization of the power-of-2 number of unique scalars.
1219     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1220       Value *IdxLaneV = getData(Idx, Lane).V;
1221       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1222         return 0;
1223       SmallPtrSet<Value *, 4> Uniques;
1224       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1225         if (Ln == Lane)
1226           continue;
1227         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1228         if (!isa<Instruction>(OpIdxLnV))
1229           return 0;
1230         Uniques.insert(OpIdxLnV);
1231       }
1232       int UniquesCount = Uniques.size();
1233       int UniquesCntWithIdxLaneV =
1234           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1235       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1236       int UniquesCntWithOpIdxLaneV =
1237           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1238       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1239         return 0;
1240       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1241               UniquesCntWithOpIdxLaneV) -
1242              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1243     }
1244 
1245     /// \param Lane lane of the operands under analysis.
1246     /// \param OpIdx operand index in \p Lane lane we're looking the best
1247     /// candidate for.
1248     /// \param Idx operand index of the current candidate value.
1249     /// \returns The additional score for the scalar which users are all
1250     /// vectorized.
1251     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1252       Value *IdxLaneV = getData(Idx, Lane).V;
1253       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1254       // Do not care about number of uses for vector-like instructions
1255       // (extractelement/extractvalue with constant indices), they are extracts
1256       // themselves and already externally used. Vectorization of such
1257       // instructions does not add extra extractelement instruction, just may
1258       // remove it.
1259       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1260           isVectorLikeInstWithConstOps(OpIdxLaneV))
1261         return VLOperands::ScoreAllUserVectorized;
1262       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1263       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1264         return 0;
1265       return R.areAllUsersVectorized(IdxLaneI, None)
1266                  ? VLOperands::ScoreAllUserVectorized
1267                  : 0;
1268     }
1269 
1270     /// Go through the operands of \p LHS and \p RHS recursively until \p
1271     /// MaxLevel, and return the cummulative score. For example:
1272     /// \verbatim
1273     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1274     ///     \ /         \ /         \ /        \ /
1275     ///      +           +           +          +
1276     ///     G1          G2          G3         G4
1277     /// \endverbatim
1278     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1279     /// each level recursively, accumulating the score. It starts from matching
1280     /// the additions at level 0, then moves on to the loads (level 1). The
1281     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1282     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1283     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1284     /// Please note that the order of the operands does not matter, as we
1285     /// evaluate the score of all profitable combinations of operands. In
1286     /// other words the score of G1 and G4 is the same as G1 and G2. This
1287     /// heuristic is based on ideas described in:
1288     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1289     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1290     ///   Luís F. W. Góes
1291     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1292                            ArrayRef<Value *> MainAltOps) {
1293 
1294       // Get the shallow score of V1 and V2.
1295       int ShallowScoreAtThisLevel =
1296           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1297 
1298       // If reached MaxLevel,
1299       //  or if V1 and V2 are not instructions,
1300       //  or if they are SPLAT,
1301       //  or if they are not consecutive,
1302       //  or if profitable to vectorize loads or extractelements, early return
1303       //  the current cost.
1304       auto *I1 = dyn_cast<Instruction>(LHS);
1305       auto *I2 = dyn_cast<Instruction>(RHS);
1306       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1307           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1308           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1309             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1310             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1311            ShallowScoreAtThisLevel))
1312         return ShallowScoreAtThisLevel;
1313       assert(I1 && I2 && "Should have early exited.");
1314 
1315       // Contains the I2 operand indexes that got matched with I1 operands.
1316       SmallSet<unsigned, 4> Op2Used;
1317 
1318       // Recursion towards the operands of I1 and I2. We are trying all possible
1319       // operand pairs, and keeping track of the best score.
1320       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1321            OpIdx1 != NumOperands1; ++OpIdx1) {
1322         // Try to pair op1I with the best operand of I2.
1323         int MaxTmpScore = 0;
1324         unsigned MaxOpIdx2 = 0;
1325         bool FoundBest = false;
1326         // If I2 is commutative try all combinations.
1327         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1328         unsigned ToIdx = isCommutative(I2)
1329                              ? I2->getNumOperands()
1330                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1331         assert(FromIdx <= ToIdx && "Bad index");
1332         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1333           // Skip operands already paired with OpIdx1.
1334           if (Op2Used.count(OpIdx2))
1335             continue;
1336           // Recursively calculate the cost at each level
1337           int TmpScore =
1338               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1339                                  CurrLevel + 1, MaxLevel, None);
1340           // Look for the best score.
1341           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1342             MaxTmpScore = TmpScore;
1343             MaxOpIdx2 = OpIdx2;
1344             FoundBest = true;
1345           }
1346         }
1347         if (FoundBest) {
1348           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1349           Op2Used.insert(MaxOpIdx2);
1350           ShallowScoreAtThisLevel += MaxTmpScore;
1351         }
1352       }
1353       return ShallowScoreAtThisLevel;
1354     }
1355 
1356     /// Score scaling factor for fully compatible instructions but with
1357     /// different number of external uses. Allows better selection of the
1358     /// instructions with less external uses.
1359     static const int ScoreScaleFactor = 10;
1360 
1361     /// \Returns the look-ahead score, which tells us how much the sub-trees
1362     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1363     /// score. This helps break ties in an informed way when we cannot decide on
1364     /// the order of the operands by just considering the immediate
1365     /// predecessors.
1366     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1367                           int Lane, unsigned OpIdx, unsigned Idx,
1368                           bool &IsUsed) {
1369       int Score =
1370           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1371       if (Score) {
1372         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1373         if (Score <= -SplatScore) {
1374           // Set the minimum score for splat-like sequence to avoid setting
1375           // failed state.
1376           Score = 1;
1377         } else {
1378           Score += SplatScore;
1379           // Scale score to see the difference between different operands
1380           // and similar operands but all vectorized/not all vectorized
1381           // uses. It does not affect actual selection of the best
1382           // compatible operand in general, just allows to select the
1383           // operand with all vectorized uses.
1384           Score *= ScoreScaleFactor;
1385           Score += getExternalUseScore(Lane, OpIdx, Idx);
1386           IsUsed = true;
1387         }
1388       }
1389       return Score;
1390     }
1391 
1392     /// Best defined scores per lanes between the passes. Used to choose the
1393     /// best operand (with the highest score) between the passes.
1394     /// The key - {Operand Index, Lane}.
1395     /// The value - the best score between the passes for the lane and the
1396     /// operand.
1397     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1398         BestScoresPerLanes;
1399 
1400     // Search all operands in Ops[*][Lane] for the one that matches best
1401     // Ops[OpIdx][LastLane] and return its opreand index.
1402     // If no good match can be found, return None.
1403     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1404                                       ArrayRef<ReorderingMode> ReorderingModes,
1405                                       ArrayRef<Value *> MainAltOps) {
1406       unsigned NumOperands = getNumOperands();
1407 
1408       // The operand of the previous lane at OpIdx.
1409       Value *OpLastLane = getData(OpIdx, LastLane).V;
1410 
1411       // Our strategy mode for OpIdx.
1412       ReorderingMode RMode = ReorderingModes[OpIdx];
1413       if (RMode == ReorderingMode::Failed)
1414         return None;
1415 
1416       // The linearized opcode of the operand at OpIdx, Lane.
1417       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1418 
1419       // The best operand index and its score.
1420       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1421       // are using the score to differentiate between the two.
1422       struct BestOpData {
1423         Optional<unsigned> Idx = None;
1424         unsigned Score = 0;
1425       } BestOp;
1426       BestOp.Score =
1427           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1428               .first->second;
1429 
1430       // Track if the operand must be marked as used. If the operand is set to
1431       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1432       // want to reestimate the operands again on the following iterations).
1433       bool IsUsed =
1434           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1435       // Iterate through all unused operands and look for the best.
1436       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1437         // Get the operand at Idx and Lane.
1438         OperandData &OpData = getData(Idx, Lane);
1439         Value *Op = OpData.V;
1440         bool OpAPO = OpData.APO;
1441 
1442         // Skip already selected operands.
1443         if (OpData.IsUsed)
1444           continue;
1445 
1446         // Skip if we are trying to move the operand to a position with a
1447         // different opcode in the linearized tree form. This would break the
1448         // semantics.
1449         if (OpAPO != OpIdxAPO)
1450           continue;
1451 
1452         // Look for an operand that matches the current mode.
1453         switch (RMode) {
1454         case ReorderingMode::Load:
1455         case ReorderingMode::Constant:
1456         case ReorderingMode::Opcode: {
1457           bool LeftToRight = Lane > LastLane;
1458           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1459           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1460           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1461                                         OpIdx, Idx, IsUsed);
1462           if (Score > static_cast<int>(BestOp.Score)) {
1463             BestOp.Idx = Idx;
1464             BestOp.Score = Score;
1465             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1466           }
1467           break;
1468         }
1469         case ReorderingMode::Splat:
1470           if (Op == OpLastLane)
1471             BestOp.Idx = Idx;
1472           break;
1473         case ReorderingMode::Failed:
1474           llvm_unreachable("Not expected Failed reordering mode.");
1475         }
1476       }
1477 
1478       if (BestOp.Idx) {
1479         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1480         return BestOp.Idx;
1481       }
1482       // If we could not find a good match return None.
1483       return None;
1484     }
1485 
1486     /// Helper for reorderOperandVecs.
1487     /// \returns the lane that we should start reordering from. This is the one
1488     /// which has the least number of operands that can freely move about or
1489     /// less profitable because it already has the most optimal set of operands.
1490     unsigned getBestLaneToStartReordering() const {
1491       unsigned Min = UINT_MAX;
1492       unsigned SameOpNumber = 0;
1493       // std::pair<unsigned, unsigned> is used to implement a simple voting
1494       // algorithm and choose the lane with the least number of operands that
1495       // can freely move about or less profitable because it already has the
1496       // most optimal set of operands. The first unsigned is a counter for
1497       // voting, the second unsigned is the counter of lanes with instructions
1498       // with same/alternate opcodes and same parent basic block.
1499       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1500       // Try to be closer to the original results, if we have multiple lanes
1501       // with same cost. If 2 lanes have the same cost, use the one with the
1502       // lowest index.
1503       for (int I = getNumLanes(); I > 0; --I) {
1504         unsigned Lane = I - 1;
1505         OperandsOrderData NumFreeOpsHash =
1506             getMaxNumOperandsThatCanBeReordered(Lane);
1507         // Compare the number of operands that can move and choose the one with
1508         // the least number.
1509         if (NumFreeOpsHash.NumOfAPOs < Min) {
1510           Min = NumFreeOpsHash.NumOfAPOs;
1511           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1512           HashMap.clear();
1513           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1514         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1515                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1516           // Select the most optimal lane in terms of number of operands that
1517           // should be moved around.
1518           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1519           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1520         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1521                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1522           auto It = HashMap.find(NumFreeOpsHash.Hash);
1523           if (It == HashMap.end())
1524             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525           else
1526             ++It->second.first;
1527         }
1528       }
1529       // Select the lane with the minimum counter.
1530       unsigned BestLane = 0;
1531       unsigned CntMin = UINT_MAX;
1532       for (const auto &Data : reverse(HashMap)) {
1533         if (Data.second.first < CntMin) {
1534           CntMin = Data.second.first;
1535           BestLane = Data.second.second;
1536         }
1537       }
1538       return BestLane;
1539     }
1540 
1541     /// Data structure that helps to reorder operands.
1542     struct OperandsOrderData {
1543       /// The best number of operands with the same APOs, which can be
1544       /// reordered.
1545       unsigned NumOfAPOs = UINT_MAX;
1546       /// Number of operands with the same/alternate instruction opcode and
1547       /// parent.
1548       unsigned NumOpsWithSameOpcodeParent = 0;
1549       /// Hash for the actual operands ordering.
1550       /// Used to count operands, actually their position id and opcode
1551       /// value. It is used in the voting mechanism to find the lane with the
1552       /// least number of operands that can freely move about or less profitable
1553       /// because it already has the most optimal set of operands. Can be
1554       /// replaced with SmallVector<unsigned> instead but hash code is faster
1555       /// and requires less memory.
1556       unsigned Hash = 0;
1557     };
1558     /// \returns the maximum number of operands that are allowed to be reordered
1559     /// for \p Lane and the number of compatible instructions(with the same
1560     /// parent/opcode). This is used as a heuristic for selecting the first lane
1561     /// to start operand reordering.
1562     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1563       unsigned CntTrue = 0;
1564       unsigned NumOperands = getNumOperands();
1565       // Operands with the same APO can be reordered. We therefore need to count
1566       // how many of them we have for each APO, like this: Cnt[APO] = x.
1567       // Since we only have two APOs, namely true and false, we can avoid using
1568       // a map. Instead we can simply count the number of operands that
1569       // correspond to one of them (in this case the 'true' APO), and calculate
1570       // the other by subtracting it from the total number of operands.
1571       // Operands with the same instruction opcode and parent are more
1572       // profitable since we don't need to move them in many cases, with a high
1573       // probability such lane already can be vectorized effectively.
1574       bool AllUndefs = true;
1575       unsigned NumOpsWithSameOpcodeParent = 0;
1576       Instruction *OpcodeI = nullptr;
1577       BasicBlock *Parent = nullptr;
1578       unsigned Hash = 0;
1579       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1580         const OperandData &OpData = getData(OpIdx, Lane);
1581         if (OpData.APO)
1582           ++CntTrue;
1583         // Use Boyer-Moore majority voting for finding the majority opcode and
1584         // the number of times it occurs.
1585         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1586           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1587               I->getParent() != Parent) {
1588             if (NumOpsWithSameOpcodeParent == 0) {
1589               NumOpsWithSameOpcodeParent = 1;
1590               OpcodeI = I;
1591               Parent = I->getParent();
1592             } else {
1593               --NumOpsWithSameOpcodeParent;
1594             }
1595           } else {
1596             ++NumOpsWithSameOpcodeParent;
1597           }
1598         }
1599         Hash = hash_combine(
1600             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1601         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1602       }
1603       if (AllUndefs)
1604         return {};
1605       OperandsOrderData Data;
1606       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1607       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1608       Data.Hash = Hash;
1609       return Data;
1610     }
1611 
1612     /// Go through the instructions in VL and append their operands.
1613     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1614       assert(!VL.empty() && "Bad VL");
1615       assert((empty() || VL.size() == getNumLanes()) &&
1616              "Expected same number of lanes");
1617       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1618       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1619       OpsVec.resize(NumOperands);
1620       unsigned NumLanes = VL.size();
1621       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1622         OpsVec[OpIdx].resize(NumLanes);
1623         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1624           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1625           // Our tree has just 3 nodes: the root and two operands.
1626           // It is therefore trivial to get the APO. We only need to check the
1627           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1628           // RHS operand. The LHS operand of both add and sub is never attached
1629           // to an inversese operation in the linearized form, therefore its APO
1630           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1631 
1632           // Since operand reordering is performed on groups of commutative
1633           // operations or alternating sequences (e.g., +, -), we can safely
1634           // tell the inverse operations by checking commutativity.
1635           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1636           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1637           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1638                                  APO, false};
1639         }
1640       }
1641     }
1642 
1643     /// \returns the number of operands.
1644     unsigned getNumOperands() const { return OpsVec.size(); }
1645 
1646     /// \returns the number of lanes.
1647     unsigned getNumLanes() const { return OpsVec[0].size(); }
1648 
1649     /// \returns the operand value at \p OpIdx and \p Lane.
1650     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1651       return getData(OpIdx, Lane).V;
1652     }
1653 
1654     /// \returns true if the data structure is empty.
1655     bool empty() const { return OpsVec.empty(); }
1656 
1657     /// Clears the data.
1658     void clear() { OpsVec.clear(); }
1659 
1660     /// \Returns true if there are enough operands identical to \p Op to fill
1661     /// the whole vector.
1662     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1663     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1664       bool OpAPO = getData(OpIdx, Lane).APO;
1665       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1666         if (Ln == Lane)
1667           continue;
1668         // This is set to true if we found a candidate for broadcast at Lane.
1669         bool FoundCandidate = false;
1670         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1671           OperandData &Data = getData(OpI, Ln);
1672           if (Data.APO != OpAPO || Data.IsUsed)
1673             continue;
1674           if (Data.V == Op) {
1675             FoundCandidate = true;
1676             Data.IsUsed = true;
1677             break;
1678           }
1679         }
1680         if (!FoundCandidate)
1681           return false;
1682       }
1683       return true;
1684     }
1685 
1686   public:
1687     /// Initialize with all the operands of the instruction vector \p RootVL.
1688     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1689                ScalarEvolution &SE, const BoUpSLP &R)
1690         : DL(DL), SE(SE), R(R) {
1691       // Append all the operands of RootVL.
1692       appendOperandsOfVL(RootVL);
1693     }
1694 
1695     /// \Returns a value vector with the operands across all lanes for the
1696     /// opearnd at \p OpIdx.
1697     ValueList getVL(unsigned OpIdx) const {
1698       ValueList OpVL(OpsVec[OpIdx].size());
1699       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1700              "Expected same num of lanes across all operands");
1701       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1702         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1703       return OpVL;
1704     }
1705 
1706     // Performs operand reordering for 2 or more operands.
1707     // The original operands are in OrigOps[OpIdx][Lane].
1708     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1709     void reorder() {
1710       unsigned NumOperands = getNumOperands();
1711       unsigned NumLanes = getNumLanes();
1712       // Each operand has its own mode. We are using this mode to help us select
1713       // the instructions for each lane, so that they match best with the ones
1714       // we have selected so far.
1715       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1716 
1717       // This is a greedy single-pass algorithm. We are going over each lane
1718       // once and deciding on the best order right away with no back-tracking.
1719       // However, in order to increase its effectiveness, we start with the lane
1720       // that has operands that can move the least. For example, given the
1721       // following lanes:
1722       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1723       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1724       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1725       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1726       // we will start at Lane 1, since the operands of the subtraction cannot
1727       // be reordered. Then we will visit the rest of the lanes in a circular
1728       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1729 
1730       // Find the first lane that we will start our search from.
1731       unsigned FirstLane = getBestLaneToStartReordering();
1732 
1733       // Initialize the modes.
1734       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1735         Value *OpLane0 = getValue(OpIdx, FirstLane);
1736         // Keep track if we have instructions with all the same opcode on one
1737         // side.
1738         if (isa<LoadInst>(OpLane0))
1739           ReorderingModes[OpIdx] = ReorderingMode::Load;
1740         else if (isa<Instruction>(OpLane0)) {
1741           // Check if OpLane0 should be broadcast.
1742           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1743             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1744           else
1745             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1746         }
1747         else if (isa<Constant>(OpLane0))
1748           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1749         else if (isa<Argument>(OpLane0))
1750           // Our best hope is a Splat. It may save some cost in some cases.
1751           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1752         else
1753           // NOTE: This should be unreachable.
1754           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1755       }
1756 
1757       // Check that we don't have same operands. No need to reorder if operands
1758       // are just perfect diamond or shuffled diamond match. Do not do it only
1759       // for possible broadcasts or non-power of 2 number of scalars (just for
1760       // now).
1761       auto &&SkipReordering = [this]() {
1762         SmallPtrSet<Value *, 4> UniqueValues;
1763         ArrayRef<OperandData> Op0 = OpsVec.front();
1764         for (const OperandData &Data : Op0)
1765           UniqueValues.insert(Data.V);
1766         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1767           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1768                 return !UniqueValues.contains(Data.V);
1769               }))
1770             return false;
1771         }
1772         // TODO: Check if we can remove a check for non-power-2 number of
1773         // scalars after full support of non-power-2 vectorization.
1774         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1775       };
1776 
1777       // If the initial strategy fails for any of the operand indexes, then we
1778       // perform reordering again in a second pass. This helps avoid assigning
1779       // high priority to the failed strategy, and should improve reordering for
1780       // the non-failed operand indexes.
1781       for (int Pass = 0; Pass != 2; ++Pass) {
1782         // Check if no need to reorder operands since they're are perfect or
1783         // shuffled diamond match.
1784         // Need to to do it to avoid extra external use cost counting for
1785         // shuffled matches, which may cause regressions.
1786         if (SkipReordering())
1787           break;
1788         // Skip the second pass if the first pass did not fail.
1789         bool StrategyFailed = false;
1790         // Mark all operand data as free to use.
1791         clearUsed();
1792         // We keep the original operand order for the FirstLane, so reorder the
1793         // rest of the lanes. We are visiting the nodes in a circular fashion,
1794         // using FirstLane as the center point and increasing the radius
1795         // distance.
1796         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1797         for (unsigned I = 0; I < NumOperands; ++I)
1798           MainAltOps[I].push_back(getData(I, FirstLane).V);
1799 
1800         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1801           // Visit the lane on the right and then the lane on the left.
1802           for (int Direction : {+1, -1}) {
1803             int Lane = FirstLane + Direction * Distance;
1804             if (Lane < 0 || Lane >= (int)NumLanes)
1805               continue;
1806             int LastLane = Lane - Direction;
1807             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1808                    "Out of bounds");
1809             // Look for a good match for each operand.
1810             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1811               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1812               Optional<unsigned> BestIdx = getBestOperand(
1813                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1814               // By not selecting a value, we allow the operands that follow to
1815               // select a better matching value. We will get a non-null value in
1816               // the next run of getBestOperand().
1817               if (BestIdx) {
1818                 // Swap the current operand with the one returned by
1819                 // getBestOperand().
1820                 swap(OpIdx, BestIdx.getValue(), Lane);
1821               } else {
1822                 // We failed to find a best operand, set mode to 'Failed'.
1823                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1824                 // Enable the second pass.
1825                 StrategyFailed = true;
1826               }
1827               // Try to get the alternate opcode and follow it during analysis.
1828               if (MainAltOps[OpIdx].size() != 2) {
1829                 OperandData &AltOp = getData(OpIdx, Lane);
1830                 InstructionsState OpS =
1831                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1832                 if (OpS.getOpcode() && OpS.isAltShuffle())
1833                   MainAltOps[OpIdx].push_back(AltOp.V);
1834               }
1835             }
1836           }
1837         }
1838         // Skip second pass if the strategy did not fail.
1839         if (!StrategyFailed)
1840           break;
1841       }
1842     }
1843 
1844 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1845     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1846       switch (RMode) {
1847       case ReorderingMode::Load:
1848         return "Load";
1849       case ReorderingMode::Opcode:
1850         return "Opcode";
1851       case ReorderingMode::Constant:
1852         return "Constant";
1853       case ReorderingMode::Splat:
1854         return "Splat";
1855       case ReorderingMode::Failed:
1856         return "Failed";
1857       }
1858       llvm_unreachable("Unimplemented Reordering Type");
1859     }
1860 
1861     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1862                                                    raw_ostream &OS) {
1863       return OS << getModeStr(RMode);
1864     }
1865 
1866     /// Debug print.
1867     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1868       printMode(RMode, dbgs());
1869     }
1870 
1871     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1872       return printMode(RMode, OS);
1873     }
1874 
1875     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1876       const unsigned Indent = 2;
1877       unsigned Cnt = 0;
1878       for (const OperandDataVec &OpDataVec : OpsVec) {
1879         OS << "Operand " << Cnt++ << "\n";
1880         for (const OperandData &OpData : OpDataVec) {
1881           OS.indent(Indent) << "{";
1882           if (Value *V = OpData.V)
1883             OS << *V;
1884           else
1885             OS << "null";
1886           OS << ", APO:" << OpData.APO << "}\n";
1887         }
1888         OS << "\n";
1889       }
1890       return OS;
1891     }
1892 
1893     /// Debug print.
1894     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1895 #endif
1896   };
1897 
1898   /// Checks if the instruction is marked for deletion.
1899   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1900 
1901   /// Marks values operands for later deletion by replacing them with Undefs.
1902   void eraseInstructions(ArrayRef<Value *> AV);
1903 
1904   ~BoUpSLP();
1905 
1906 private:
1907   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1908   /// reordering (i.e. the operands can be reordered because they have only one
1909   /// user and reordarable).
1910   /// \param NonVectorized List of all gather nodes that require reordering
1911   /// (e.g., gather of extractlements or partially vectorizable loads).
1912   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1913   /// reordering, subset of \p NonVectorized.
1914   bool
1915   canReorderOperands(TreeEntry *UserTE,
1916                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1917                      ArrayRef<TreeEntry *> ReorderableGathers,
1918                      SmallVectorImpl<TreeEntry *> &GatherOps);
1919 
1920   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1921   /// if any. If it is not vectorized (gather node), returns nullptr.
1922   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1923     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1924     TreeEntry *TE = nullptr;
1925     const auto *It = find_if(VL, [this, &TE](Value *V) {
1926       TE = getTreeEntry(V);
1927       return TE;
1928     });
1929     if (It != VL.end() && TE->isSame(VL))
1930       return TE;
1931     return nullptr;
1932   }
1933 
1934   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1935   /// if any. If it is not vectorized (gather node), returns nullptr.
1936   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1937                                         unsigned OpIdx) const {
1938     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1939         const_cast<TreeEntry *>(UserTE), OpIdx);
1940   }
1941 
1942   /// Checks if all users of \p I are the part of the vectorization tree.
1943   bool areAllUsersVectorized(Instruction *I,
1944                              ArrayRef<Value *> VectorizedVals) const;
1945 
1946   /// \returns the cost of the vectorizable entry.
1947   InstructionCost getEntryCost(const TreeEntry *E,
1948                                ArrayRef<Value *> VectorizedVals);
1949 
1950   /// This is the recursive part of buildTree.
1951   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1952                      const EdgeInfo &EI);
1953 
1954   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1955   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1956   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1957   /// returns false, setting \p CurrentOrder to either an empty vector or a
1958   /// non-identity permutation that allows to reuse extract instructions.
1959   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1960                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1961 
1962   /// Vectorize a single entry in the tree.
1963   Value *vectorizeTree(TreeEntry *E);
1964 
1965   /// Vectorize a single entry in the tree, starting in \p VL.
1966   Value *vectorizeTree(ArrayRef<Value *> VL);
1967 
1968   /// \returns the scalarization cost for this type. Scalarization in this
1969   /// context means the creation of vectors from a group of scalars. If \p
1970   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1971   /// vector elements.
1972   InstructionCost getGatherCost(FixedVectorType *Ty,
1973                                 const APInt &ShuffledIndices,
1974                                 bool NeedToShuffle) const;
1975 
1976   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1977   /// tree entries.
1978   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1979   /// previous tree entries. \p Mask is filled with the shuffle mask.
1980   Optional<TargetTransformInfo::ShuffleKind>
1981   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1982                         SmallVectorImpl<const TreeEntry *> &Entries);
1983 
1984   /// \returns the scalarization cost for this list of values. Assuming that
1985   /// this subtree gets vectorized, we may need to extract the values from the
1986   /// roots. This method calculates the cost of extracting the values.
1987   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1988 
1989   /// Set the Builder insert point to one after the last instruction in
1990   /// the bundle
1991   void setInsertPointAfterBundle(const TreeEntry *E);
1992 
1993   /// \returns a vector from a collection of scalars in \p VL.
1994   Value *gather(ArrayRef<Value *> VL);
1995 
1996   /// \returns whether the VectorizableTree is fully vectorizable and will
1997   /// be beneficial even the tree height is tiny.
1998   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1999 
2000   /// Reorder commutative or alt operands to get better probability of
2001   /// generating vectorized code.
2002   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2003                                              SmallVectorImpl<Value *> &Left,
2004                                              SmallVectorImpl<Value *> &Right,
2005                                              const DataLayout &DL,
2006                                              ScalarEvolution &SE,
2007                                              const BoUpSLP &R);
2008   struct TreeEntry {
2009     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2010     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2011 
2012     /// \returns true if the scalars in VL are equal to this entry.
2013     bool isSame(ArrayRef<Value *> VL) const {
2014       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2015         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2016           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2017         return VL.size() == Mask.size() &&
2018                std::equal(VL.begin(), VL.end(), Mask.begin(),
2019                           [Scalars](Value *V, int Idx) {
2020                             return (isa<UndefValue>(V) &&
2021                                     Idx == UndefMaskElem) ||
2022                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2023                           });
2024       };
2025       if (!ReorderIndices.empty()) {
2026         // TODO: implement matching if the nodes are just reordered, still can
2027         // treat the vector as the same if the list of scalars matches VL
2028         // directly, without reordering.
2029         SmallVector<int> Mask;
2030         inversePermutation(ReorderIndices, Mask);
2031         if (VL.size() == Scalars.size())
2032           return IsSame(Scalars, Mask);
2033         if (VL.size() == ReuseShuffleIndices.size()) {
2034           ::addMask(Mask, ReuseShuffleIndices);
2035           return IsSame(Scalars, Mask);
2036         }
2037         return false;
2038       }
2039       return IsSame(Scalars, ReuseShuffleIndices);
2040     }
2041 
2042     /// \returns true if current entry has same operands as \p TE.
2043     bool hasEqualOperands(const TreeEntry &TE) const {
2044       if (TE.getNumOperands() != getNumOperands())
2045         return false;
2046       SmallBitVector Used(getNumOperands());
2047       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2048         unsigned PrevCount = Used.count();
2049         for (unsigned K = 0; K < E; ++K) {
2050           if (Used.test(K))
2051             continue;
2052           if (getOperand(K) == TE.getOperand(I)) {
2053             Used.set(K);
2054             break;
2055           }
2056         }
2057         // Check if we actually found the matching operand.
2058         if (PrevCount == Used.count())
2059           return false;
2060       }
2061       return true;
2062     }
2063 
2064     /// \return Final vectorization factor for the node. Defined by the total
2065     /// number of vectorized scalars, including those, used several times in the
2066     /// entry and counted in the \a ReuseShuffleIndices, if any.
2067     unsigned getVectorFactor() const {
2068       if (!ReuseShuffleIndices.empty())
2069         return ReuseShuffleIndices.size();
2070       return Scalars.size();
2071     };
2072 
2073     /// A vector of scalars.
2074     ValueList Scalars;
2075 
2076     /// The Scalars are vectorized into this value. It is initialized to Null.
2077     Value *VectorizedValue = nullptr;
2078 
2079     /// Do we need to gather this sequence or vectorize it
2080     /// (either with vector instruction or with scatter/gather
2081     /// intrinsics for store/load)?
2082     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2083     EntryState State;
2084 
2085     /// Does this sequence require some shuffling?
2086     SmallVector<int, 4> ReuseShuffleIndices;
2087 
2088     /// Does this entry require reordering?
2089     SmallVector<unsigned, 4> ReorderIndices;
2090 
2091     /// Points back to the VectorizableTree.
2092     ///
2093     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2094     /// to be a pointer and needs to be able to initialize the child iterator.
2095     /// Thus we need a reference back to the container to translate the indices
2096     /// to entries.
2097     VecTreeTy &Container;
2098 
2099     /// The TreeEntry index containing the user of this entry.  We can actually
2100     /// have multiple users so the data structure is not truly a tree.
2101     SmallVector<EdgeInfo, 1> UserTreeIndices;
2102 
2103     /// The index of this treeEntry in VectorizableTree.
2104     int Idx = -1;
2105 
2106   private:
2107     /// The operands of each instruction in each lane Operands[op_index][lane].
2108     /// Note: This helps avoid the replication of the code that performs the
2109     /// reordering of operands during buildTree_rec() and vectorizeTree().
2110     SmallVector<ValueList, 2> Operands;
2111 
2112     /// The main/alternate instruction.
2113     Instruction *MainOp = nullptr;
2114     Instruction *AltOp = nullptr;
2115 
2116   public:
2117     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2118     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2119       if (Operands.size() < OpIdx + 1)
2120         Operands.resize(OpIdx + 1);
2121       assert(Operands[OpIdx].empty() && "Already resized?");
2122       assert(OpVL.size() <= Scalars.size() &&
2123              "Number of operands is greater than the number of scalars.");
2124       Operands[OpIdx].resize(OpVL.size());
2125       copy(OpVL, Operands[OpIdx].begin());
2126     }
2127 
2128     /// Set the operands of this bundle in their original order.
2129     void setOperandsInOrder() {
2130       assert(Operands.empty() && "Already initialized?");
2131       auto *I0 = cast<Instruction>(Scalars[0]);
2132       Operands.resize(I0->getNumOperands());
2133       unsigned NumLanes = Scalars.size();
2134       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2135            OpIdx != NumOperands; ++OpIdx) {
2136         Operands[OpIdx].resize(NumLanes);
2137         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2138           auto *I = cast<Instruction>(Scalars[Lane]);
2139           assert(I->getNumOperands() == NumOperands &&
2140                  "Expected same number of operands");
2141           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2142         }
2143       }
2144     }
2145 
2146     /// Reorders operands of the node to the given mask \p Mask.
2147     void reorderOperands(ArrayRef<int> Mask) {
2148       for (ValueList &Operand : Operands)
2149         reorderScalars(Operand, Mask);
2150     }
2151 
2152     /// \returns the \p OpIdx operand of this TreeEntry.
2153     ValueList &getOperand(unsigned OpIdx) {
2154       assert(OpIdx < Operands.size() && "Off bounds");
2155       return Operands[OpIdx];
2156     }
2157 
2158     /// \returns the \p OpIdx operand of this TreeEntry.
2159     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2160       assert(OpIdx < Operands.size() && "Off bounds");
2161       return Operands[OpIdx];
2162     }
2163 
2164     /// \returns the number of operands.
2165     unsigned getNumOperands() const { return Operands.size(); }
2166 
2167     /// \return the single \p OpIdx operand.
2168     Value *getSingleOperand(unsigned OpIdx) const {
2169       assert(OpIdx < Operands.size() && "Off bounds");
2170       assert(!Operands[OpIdx].empty() && "No operand available");
2171       return Operands[OpIdx][0];
2172     }
2173 
2174     /// Some of the instructions in the list have alternate opcodes.
2175     bool isAltShuffle() const { return MainOp != AltOp; }
2176 
2177     bool isOpcodeOrAlt(Instruction *I) const {
2178       unsigned CheckedOpcode = I->getOpcode();
2179       return (getOpcode() == CheckedOpcode ||
2180               getAltOpcode() == CheckedOpcode);
2181     }
2182 
2183     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2184     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2185     /// \p OpValue.
2186     Value *isOneOf(Value *Op) const {
2187       auto *I = dyn_cast<Instruction>(Op);
2188       if (I && isOpcodeOrAlt(I))
2189         return Op;
2190       return MainOp;
2191     }
2192 
2193     void setOperations(const InstructionsState &S) {
2194       MainOp = S.MainOp;
2195       AltOp = S.AltOp;
2196     }
2197 
2198     Instruction *getMainOp() const {
2199       return MainOp;
2200     }
2201 
2202     Instruction *getAltOp() const {
2203       return AltOp;
2204     }
2205 
2206     /// The main/alternate opcodes for the list of instructions.
2207     unsigned getOpcode() const {
2208       return MainOp ? MainOp->getOpcode() : 0;
2209     }
2210 
2211     unsigned getAltOpcode() const {
2212       return AltOp ? AltOp->getOpcode() : 0;
2213     }
2214 
2215     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2216     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2217     int findLaneForValue(Value *V) const {
2218       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2219       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2220       if (!ReorderIndices.empty())
2221         FoundLane = ReorderIndices[FoundLane];
2222       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2223       if (!ReuseShuffleIndices.empty()) {
2224         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2225                                   find(ReuseShuffleIndices, FoundLane));
2226       }
2227       return FoundLane;
2228     }
2229 
2230 #ifndef NDEBUG
2231     /// Debug printer.
2232     LLVM_DUMP_METHOD void dump() const {
2233       dbgs() << Idx << ".\n";
2234       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2235         dbgs() << "Operand " << OpI << ":\n";
2236         for (const Value *V : Operands[OpI])
2237           dbgs().indent(2) << *V << "\n";
2238       }
2239       dbgs() << "Scalars: \n";
2240       for (Value *V : Scalars)
2241         dbgs().indent(2) << *V << "\n";
2242       dbgs() << "State: ";
2243       switch (State) {
2244       case Vectorize:
2245         dbgs() << "Vectorize\n";
2246         break;
2247       case ScatterVectorize:
2248         dbgs() << "ScatterVectorize\n";
2249         break;
2250       case NeedToGather:
2251         dbgs() << "NeedToGather\n";
2252         break;
2253       }
2254       dbgs() << "MainOp: ";
2255       if (MainOp)
2256         dbgs() << *MainOp << "\n";
2257       else
2258         dbgs() << "NULL\n";
2259       dbgs() << "AltOp: ";
2260       if (AltOp)
2261         dbgs() << *AltOp << "\n";
2262       else
2263         dbgs() << "NULL\n";
2264       dbgs() << "VectorizedValue: ";
2265       if (VectorizedValue)
2266         dbgs() << *VectorizedValue << "\n";
2267       else
2268         dbgs() << "NULL\n";
2269       dbgs() << "ReuseShuffleIndices: ";
2270       if (ReuseShuffleIndices.empty())
2271         dbgs() << "Empty";
2272       else
2273         for (int ReuseIdx : ReuseShuffleIndices)
2274           dbgs() << ReuseIdx << ", ";
2275       dbgs() << "\n";
2276       dbgs() << "ReorderIndices: ";
2277       for (unsigned ReorderIdx : ReorderIndices)
2278         dbgs() << ReorderIdx << ", ";
2279       dbgs() << "\n";
2280       dbgs() << "UserTreeIndices: ";
2281       for (const auto &EInfo : UserTreeIndices)
2282         dbgs() << EInfo << ", ";
2283       dbgs() << "\n";
2284     }
2285 #endif
2286   };
2287 
2288 #ifndef NDEBUG
2289   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2290                      InstructionCost VecCost,
2291                      InstructionCost ScalarCost) const {
2292     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2293     dbgs() << "SLP: Costs:\n";
2294     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2295     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2296     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2297     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2298                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2299   }
2300 #endif
2301 
2302   /// Create a new VectorizableTree entry.
2303   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2304                           const InstructionsState &S,
2305                           const EdgeInfo &UserTreeIdx,
2306                           ArrayRef<int> ReuseShuffleIndices = None,
2307                           ArrayRef<unsigned> ReorderIndices = None) {
2308     TreeEntry::EntryState EntryState =
2309         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2310     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2311                         ReuseShuffleIndices, ReorderIndices);
2312   }
2313 
2314   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2315                           TreeEntry::EntryState EntryState,
2316                           Optional<ScheduleData *> Bundle,
2317                           const InstructionsState &S,
2318                           const EdgeInfo &UserTreeIdx,
2319                           ArrayRef<int> ReuseShuffleIndices = None,
2320                           ArrayRef<unsigned> ReorderIndices = None) {
2321     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2322             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2323            "Need to vectorize gather entry?");
2324     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2325     TreeEntry *Last = VectorizableTree.back().get();
2326     Last->Idx = VectorizableTree.size() - 1;
2327     Last->State = EntryState;
2328     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2329                                      ReuseShuffleIndices.end());
2330     if (ReorderIndices.empty()) {
2331       Last->Scalars.assign(VL.begin(), VL.end());
2332       Last->setOperations(S);
2333     } else {
2334       // Reorder scalars and build final mask.
2335       Last->Scalars.assign(VL.size(), nullptr);
2336       transform(ReorderIndices, Last->Scalars.begin(),
2337                 [VL](unsigned Idx) -> Value * {
2338                   if (Idx >= VL.size())
2339                     return UndefValue::get(VL.front()->getType());
2340                   return VL[Idx];
2341                 });
2342       InstructionsState S = getSameOpcode(Last->Scalars);
2343       Last->setOperations(S);
2344       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2345     }
2346     if (Last->State != TreeEntry::NeedToGather) {
2347       for (Value *V : VL) {
2348         assert(!getTreeEntry(V) && "Scalar already in tree!");
2349         ScalarToTreeEntry[V] = Last;
2350       }
2351       // Update the scheduler bundle to point to this TreeEntry.
2352       unsigned Lane = 0;
2353       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2354            BundleMember = BundleMember->NextInBundle) {
2355         BundleMember->TE = Last;
2356         BundleMember->Lane = Lane;
2357         ++Lane;
2358       }
2359       assert((!Bundle.getValue() || Lane == VL.size()) &&
2360              "Bundle and VL out of sync");
2361     } else {
2362       MustGather.insert(VL.begin(), VL.end());
2363     }
2364 
2365     if (UserTreeIdx.UserTE)
2366       Last->UserTreeIndices.push_back(UserTreeIdx);
2367 
2368     return Last;
2369   }
2370 
2371   /// -- Vectorization State --
2372   /// Holds all of the tree entries.
2373   TreeEntry::VecTreeTy VectorizableTree;
2374 
2375 #ifndef NDEBUG
2376   /// Debug printer.
2377   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2378     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2379       VectorizableTree[Id]->dump();
2380       dbgs() << "\n";
2381     }
2382   }
2383 #endif
2384 
2385   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2386 
2387   const TreeEntry *getTreeEntry(Value *V) const {
2388     return ScalarToTreeEntry.lookup(V);
2389   }
2390 
2391   /// Maps a specific scalar to its tree entry.
2392   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2393 
2394   /// Maps a value to the proposed vectorizable size.
2395   SmallDenseMap<Value *, unsigned> InstrElementSize;
2396 
2397   /// A list of scalars that we found that we need to keep as scalars.
2398   ValueSet MustGather;
2399 
2400   /// This POD struct describes one external user in the vectorized tree.
2401   struct ExternalUser {
2402     ExternalUser(Value *S, llvm::User *U, int L)
2403         : Scalar(S), User(U), Lane(L) {}
2404 
2405     // Which scalar in our function.
2406     Value *Scalar;
2407 
2408     // Which user that uses the scalar.
2409     llvm::User *User;
2410 
2411     // Which lane does the scalar belong to.
2412     int Lane;
2413   };
2414   using UserList = SmallVector<ExternalUser, 16>;
2415 
2416   /// Checks if two instructions may access the same memory.
2417   ///
2418   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2419   /// is invariant in the calling loop.
2420   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2421                  Instruction *Inst2) {
2422     // First check if the result is already in the cache.
2423     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2424     Optional<bool> &result = AliasCache[key];
2425     if (result.hasValue()) {
2426       return result.getValue();
2427     }
2428     bool aliased = true;
2429     if (Loc1.Ptr && isSimple(Inst1))
2430       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2431     // Store the result in the cache.
2432     result = aliased;
2433     return aliased;
2434   }
2435 
2436   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2437 
2438   /// Cache for alias results.
2439   /// TODO: consider moving this to the AliasAnalysis itself.
2440   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2441 
2442   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2443   // globally through SLP because we don't perform any action which
2444   // invalidates capture results.
2445   BatchAAResults BatchAA;
2446 
2447   /// Removes an instruction from its block and eventually deletes it.
2448   /// It's like Instruction::eraseFromParent() except that the actual deletion
2449   /// is delayed until BoUpSLP is destructed.
2450   /// This is required to ensure that there are no incorrect collisions in the
2451   /// AliasCache, which can happen if a new instruction is allocated at the
2452   /// same address as a previously deleted instruction.
2453   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2454     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2455     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2456   }
2457 
2458   /// Temporary store for deleted instructions. Instructions will be deleted
2459   /// eventually when the BoUpSLP is destructed.
2460   DenseMap<Instruction *, bool> DeletedInstructions;
2461 
2462   /// A list of values that need to extracted out of the tree.
2463   /// This list holds pairs of (Internal Scalar : External User). External User
2464   /// can be nullptr, it means that this Internal Scalar will be used later,
2465   /// after vectorization.
2466   UserList ExternalUses;
2467 
2468   /// Values used only by @llvm.assume calls.
2469   SmallPtrSet<const Value *, 32> EphValues;
2470 
2471   /// Holds all of the instructions that we gathered.
2472   SetVector<Instruction *> GatherShuffleSeq;
2473 
2474   /// A list of blocks that we are going to CSE.
2475   SetVector<BasicBlock *> CSEBlocks;
2476 
2477   /// Contains all scheduling relevant data for an instruction.
2478   /// A ScheduleData either represents a single instruction or a member of an
2479   /// instruction bundle (= a group of instructions which is combined into a
2480   /// vector instruction).
2481   struct ScheduleData {
2482     // The initial value for the dependency counters. It means that the
2483     // dependencies are not calculated yet.
2484     enum { InvalidDeps = -1 };
2485 
2486     ScheduleData() = default;
2487 
2488     void init(int BlockSchedulingRegionID, Value *OpVal) {
2489       FirstInBundle = this;
2490       NextInBundle = nullptr;
2491       NextLoadStore = nullptr;
2492       IsScheduled = false;
2493       SchedulingRegionID = BlockSchedulingRegionID;
2494       clearDependencies();
2495       OpValue = OpVal;
2496       TE = nullptr;
2497       Lane = -1;
2498     }
2499 
2500     /// Verify basic self consistency properties
2501     void verify() {
2502       if (hasValidDependencies()) {
2503         assert(UnscheduledDeps <= Dependencies && "invariant");
2504       } else {
2505         assert(UnscheduledDeps == Dependencies && "invariant");
2506       }
2507 
2508       if (IsScheduled) {
2509         assert(isSchedulingEntity() &&
2510                 "unexpected scheduled state");
2511         for (const ScheduleData *BundleMember = this; BundleMember;
2512              BundleMember = BundleMember->NextInBundle) {
2513           assert(BundleMember->hasValidDependencies() &&
2514                  BundleMember->UnscheduledDeps == 0 &&
2515                  "unexpected scheduled state");
2516           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2517                  "only bundle is marked scheduled");
2518         }
2519       }
2520 
2521       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2522              "all bundle members must be in same basic block");
2523     }
2524 
2525     /// Returns true if the dependency information has been calculated.
2526     /// Note that depenendency validity can vary between instructions within
2527     /// a single bundle.
2528     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2529 
2530     /// Returns true for single instructions and for bundle representatives
2531     /// (= the head of a bundle).
2532     bool isSchedulingEntity() const { return FirstInBundle == this; }
2533 
2534     /// Returns true if it represents an instruction bundle and not only a
2535     /// single instruction.
2536     bool isPartOfBundle() const {
2537       return NextInBundle != nullptr || FirstInBundle != this;
2538     }
2539 
2540     /// Returns true if it is ready for scheduling, i.e. it has no more
2541     /// unscheduled depending instructions/bundles.
2542     bool isReady() const {
2543       assert(isSchedulingEntity() &&
2544              "can't consider non-scheduling entity for ready list");
2545       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2546     }
2547 
2548     /// Modifies the number of unscheduled dependencies for this instruction,
2549     /// and returns the number of remaining dependencies for the containing
2550     /// bundle.
2551     int incrementUnscheduledDeps(int Incr) {
2552       assert(hasValidDependencies() &&
2553              "increment of unscheduled deps would be meaningless");
2554       UnscheduledDeps += Incr;
2555       return FirstInBundle->unscheduledDepsInBundle();
2556     }
2557 
2558     /// Sets the number of unscheduled dependencies to the number of
2559     /// dependencies.
2560     void resetUnscheduledDeps() {
2561       UnscheduledDeps = Dependencies;
2562     }
2563 
2564     /// Clears all dependency information.
2565     void clearDependencies() {
2566       Dependencies = InvalidDeps;
2567       resetUnscheduledDeps();
2568       MemoryDependencies.clear();
2569     }
2570 
2571     int unscheduledDepsInBundle() const {
2572       assert(isSchedulingEntity() && "only meaningful on the bundle");
2573       int Sum = 0;
2574       for (const ScheduleData *BundleMember = this; BundleMember;
2575            BundleMember = BundleMember->NextInBundle) {
2576         if (BundleMember->UnscheduledDeps == InvalidDeps)
2577           return InvalidDeps;
2578         Sum += BundleMember->UnscheduledDeps;
2579       }
2580       return Sum;
2581     }
2582 
2583     void dump(raw_ostream &os) const {
2584       if (!isSchedulingEntity()) {
2585         os << "/ " << *Inst;
2586       } else if (NextInBundle) {
2587         os << '[' << *Inst;
2588         ScheduleData *SD = NextInBundle;
2589         while (SD) {
2590           os << ';' << *SD->Inst;
2591           SD = SD->NextInBundle;
2592         }
2593         os << ']';
2594       } else {
2595         os << *Inst;
2596       }
2597     }
2598 
2599     Instruction *Inst = nullptr;
2600 
2601     /// Opcode of the current instruction in the schedule data.
2602     Value *OpValue = nullptr;
2603 
2604     /// The TreeEntry that this instruction corresponds to.
2605     TreeEntry *TE = nullptr;
2606 
2607     /// Points to the head in an instruction bundle (and always to this for
2608     /// single instructions).
2609     ScheduleData *FirstInBundle = nullptr;
2610 
2611     /// Single linked list of all instructions in a bundle. Null if it is a
2612     /// single instruction.
2613     ScheduleData *NextInBundle = nullptr;
2614 
2615     /// Single linked list of all memory instructions (e.g. load, store, call)
2616     /// in the block - until the end of the scheduling region.
2617     ScheduleData *NextLoadStore = nullptr;
2618 
2619     /// The dependent memory instructions.
2620     /// This list is derived on demand in calculateDependencies().
2621     SmallVector<ScheduleData *, 4> MemoryDependencies;
2622 
2623     /// This ScheduleData is in the current scheduling region if this matches
2624     /// the current SchedulingRegionID of BlockScheduling.
2625     int SchedulingRegionID = 0;
2626 
2627     /// Used for getting a "good" final ordering of instructions.
2628     int SchedulingPriority = 0;
2629 
2630     /// The number of dependencies. Constitutes of the number of users of the
2631     /// instruction plus the number of dependent memory instructions (if any).
2632     /// This value is calculated on demand.
2633     /// If InvalidDeps, the number of dependencies is not calculated yet.
2634     int Dependencies = InvalidDeps;
2635 
2636     /// The number of dependencies minus the number of dependencies of scheduled
2637     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2638     /// for scheduling.
2639     /// Note that this is negative as long as Dependencies is not calculated.
2640     int UnscheduledDeps = InvalidDeps;
2641 
2642     /// The lane of this node in the TreeEntry.
2643     int Lane = -1;
2644 
2645     /// True if this instruction is scheduled (or considered as scheduled in the
2646     /// dry-run).
2647     bool IsScheduled = false;
2648   };
2649 
2650 #ifndef NDEBUG
2651   friend inline raw_ostream &operator<<(raw_ostream &os,
2652                                         const BoUpSLP::ScheduleData &SD) {
2653     SD.dump(os);
2654     return os;
2655   }
2656 #endif
2657 
2658   friend struct GraphTraits<BoUpSLP *>;
2659   friend struct DOTGraphTraits<BoUpSLP *>;
2660 
2661   /// Contains all scheduling data for a basic block.
2662   struct BlockScheduling {
2663     BlockScheduling(BasicBlock *BB)
2664         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2665 
2666     void clear() {
2667       ReadyInsts.clear();
2668       ScheduleStart = nullptr;
2669       ScheduleEnd = nullptr;
2670       FirstLoadStoreInRegion = nullptr;
2671       LastLoadStoreInRegion = nullptr;
2672 
2673       // Reduce the maximum schedule region size by the size of the
2674       // previous scheduling run.
2675       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2676       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2677         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2678       ScheduleRegionSize = 0;
2679 
2680       // Make a new scheduling region, i.e. all existing ScheduleData is not
2681       // in the new region yet.
2682       ++SchedulingRegionID;
2683     }
2684 
2685     ScheduleData *getScheduleData(Instruction *I) {
2686       if (BB != I->getParent())
2687         // Avoid lookup if can't possibly be in map.
2688         return nullptr;
2689       ScheduleData *SD = ScheduleDataMap[I];
2690       if (SD && isInSchedulingRegion(SD))
2691         return SD;
2692       return nullptr;
2693     }
2694 
2695     ScheduleData *getScheduleData(Value *V) {
2696       if (auto *I = dyn_cast<Instruction>(V))
2697         return getScheduleData(I);
2698       return nullptr;
2699     }
2700 
2701     ScheduleData *getScheduleData(Value *V, Value *Key) {
2702       if (V == Key)
2703         return getScheduleData(V);
2704       auto I = ExtraScheduleDataMap.find(V);
2705       if (I != ExtraScheduleDataMap.end()) {
2706         ScheduleData *SD = I->second[Key];
2707         if (SD && isInSchedulingRegion(SD))
2708           return SD;
2709       }
2710       return nullptr;
2711     }
2712 
2713     bool isInSchedulingRegion(ScheduleData *SD) const {
2714       return SD->SchedulingRegionID == SchedulingRegionID;
2715     }
2716 
2717     /// Marks an instruction as scheduled and puts all dependent ready
2718     /// instructions into the ready-list.
2719     template <typename ReadyListType>
2720     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2721       SD->IsScheduled = true;
2722       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2723 
2724       for (ScheduleData *BundleMember = SD; BundleMember;
2725            BundleMember = BundleMember->NextInBundle) {
2726         if (BundleMember->Inst != BundleMember->OpValue)
2727           continue;
2728 
2729         // Handle the def-use chain dependencies.
2730 
2731         // Decrement the unscheduled counter and insert to ready list if ready.
2732         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2733           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2734             if (OpDef && OpDef->hasValidDependencies() &&
2735                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2736               // There are no more unscheduled dependencies after
2737               // decrementing, so we can put the dependent instruction
2738               // into the ready list.
2739               ScheduleData *DepBundle = OpDef->FirstInBundle;
2740               assert(!DepBundle->IsScheduled &&
2741                      "already scheduled bundle gets ready");
2742               ReadyList.insert(DepBundle);
2743               LLVM_DEBUG(dbgs()
2744                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2745             }
2746           });
2747         };
2748 
2749         // If BundleMember is a vector bundle, its operands may have been
2750         // reordered during buildTree(). We therefore need to get its operands
2751         // through the TreeEntry.
2752         if (TreeEntry *TE = BundleMember->TE) {
2753           int Lane = BundleMember->Lane;
2754           assert(Lane >= 0 && "Lane not set");
2755 
2756           // Since vectorization tree is being built recursively this assertion
2757           // ensures that the tree entry has all operands set before reaching
2758           // this code. Couple of exceptions known at the moment are extracts
2759           // where their second (immediate) operand is not added. Since
2760           // immediates do not affect scheduler behavior this is considered
2761           // okay.
2762           auto *In = TE->getMainOp();
2763           assert(In &&
2764                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2765                   In->getNumOperands() == TE->getNumOperands()) &&
2766                  "Missed TreeEntry operands?");
2767           (void)In; // fake use to avoid build failure when assertions disabled
2768 
2769           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2770                OpIdx != NumOperands; ++OpIdx)
2771             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2772               DecrUnsched(I);
2773         } else {
2774           // If BundleMember is a stand-alone instruction, no operand reordering
2775           // has taken place, so we directly access its operands.
2776           for (Use &U : BundleMember->Inst->operands())
2777             if (auto *I = dyn_cast<Instruction>(U.get()))
2778               DecrUnsched(I);
2779         }
2780         // Handle the memory dependencies.
2781         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2782           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2783             // There are no more unscheduled dependencies after decrementing,
2784             // so we can put the dependent instruction into the ready list.
2785             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2786             assert(!DepBundle->IsScheduled &&
2787                    "already scheduled bundle gets ready");
2788             ReadyList.insert(DepBundle);
2789             LLVM_DEBUG(dbgs()
2790                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2791           }
2792         }
2793       }
2794     }
2795 
2796     /// Verify basic self consistency properties of the data structure.
2797     void verify() {
2798       if (!ScheduleStart)
2799         return;
2800 
2801       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2802              ScheduleStart->comesBefore(ScheduleEnd) &&
2803              "Not a valid scheduling region?");
2804 
2805       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2806         auto *SD = getScheduleData(I);
2807         assert(SD && "primary scheduledata must exist in window");
2808         assert(isInSchedulingRegion(SD) &&
2809                "primary schedule data not in window?");
2810         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2811                "entire bundle in window!");
2812         (void)SD;
2813         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2814       }
2815 
2816       for (auto *SD : ReadyInsts) {
2817         assert(SD->isSchedulingEntity() && SD->isReady() &&
2818                "item in ready list not ready?");
2819         (void)SD;
2820       }
2821     }
2822 
2823     void doForAllOpcodes(Value *V,
2824                          function_ref<void(ScheduleData *SD)> Action) {
2825       if (ScheduleData *SD = getScheduleData(V))
2826         Action(SD);
2827       auto I = ExtraScheduleDataMap.find(V);
2828       if (I != ExtraScheduleDataMap.end())
2829         for (auto &P : I->second)
2830           if (isInSchedulingRegion(P.second))
2831             Action(P.second);
2832     }
2833 
2834     /// Put all instructions into the ReadyList which are ready for scheduling.
2835     template <typename ReadyListType>
2836     void initialFillReadyList(ReadyListType &ReadyList) {
2837       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2838         doForAllOpcodes(I, [&](ScheduleData *SD) {
2839           if (SD->isSchedulingEntity() && SD->isReady()) {
2840             ReadyList.insert(SD);
2841             LLVM_DEBUG(dbgs()
2842                        << "SLP:    initially in ready list: " << *SD << "\n");
2843           }
2844         });
2845       }
2846     }
2847 
2848     /// Build a bundle from the ScheduleData nodes corresponding to the
2849     /// scalar instruction for each lane.
2850     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2851 
2852     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2853     /// cyclic dependencies. This is only a dry-run, no instructions are
2854     /// actually moved at this stage.
2855     /// \returns the scheduling bundle. The returned Optional value is non-None
2856     /// if \p VL is allowed to be scheduled.
2857     Optional<ScheduleData *>
2858     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2859                       const InstructionsState &S);
2860 
2861     /// Un-bundles a group of instructions.
2862     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2863 
2864     /// Allocates schedule data chunk.
2865     ScheduleData *allocateScheduleDataChunks();
2866 
2867     /// Extends the scheduling region so that V is inside the region.
2868     /// \returns true if the region size is within the limit.
2869     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2870 
2871     /// Initialize the ScheduleData structures for new instructions in the
2872     /// scheduling region.
2873     void initScheduleData(Instruction *FromI, Instruction *ToI,
2874                           ScheduleData *PrevLoadStore,
2875                           ScheduleData *NextLoadStore);
2876 
2877     /// Updates the dependency information of a bundle and of all instructions/
2878     /// bundles which depend on the original bundle.
2879     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2880                                BoUpSLP *SLP);
2881 
2882     /// Sets all instruction in the scheduling region to un-scheduled.
2883     void resetSchedule();
2884 
2885     BasicBlock *BB;
2886 
2887     /// Simple memory allocation for ScheduleData.
2888     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2889 
2890     /// The size of a ScheduleData array in ScheduleDataChunks.
2891     int ChunkSize;
2892 
2893     /// The allocator position in the current chunk, which is the last entry
2894     /// of ScheduleDataChunks.
2895     int ChunkPos;
2896 
2897     /// Attaches ScheduleData to Instruction.
2898     /// Note that the mapping survives during all vectorization iterations, i.e.
2899     /// ScheduleData structures are recycled.
2900     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2901 
2902     /// Attaches ScheduleData to Instruction with the leading key.
2903     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2904         ExtraScheduleDataMap;
2905 
2906     /// The ready-list for scheduling (only used for the dry-run).
2907     SetVector<ScheduleData *> ReadyInsts;
2908 
2909     /// The first instruction of the scheduling region.
2910     Instruction *ScheduleStart = nullptr;
2911 
2912     /// The first instruction _after_ the scheduling region.
2913     Instruction *ScheduleEnd = nullptr;
2914 
2915     /// The first memory accessing instruction in the scheduling region
2916     /// (can be null).
2917     ScheduleData *FirstLoadStoreInRegion = nullptr;
2918 
2919     /// The last memory accessing instruction in the scheduling region
2920     /// (can be null).
2921     ScheduleData *LastLoadStoreInRegion = nullptr;
2922 
2923     /// The current size of the scheduling region.
2924     int ScheduleRegionSize = 0;
2925 
2926     /// The maximum size allowed for the scheduling region.
2927     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2928 
2929     /// The ID of the scheduling region. For a new vectorization iteration this
2930     /// is incremented which "removes" all ScheduleData from the region.
2931     /// Make sure that the initial SchedulingRegionID is greater than the
2932     /// initial SchedulingRegionID in ScheduleData (which is 0).
2933     int SchedulingRegionID = 1;
2934   };
2935 
2936   /// Attaches the BlockScheduling structures to basic blocks.
2937   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2938 
2939   /// Performs the "real" scheduling. Done before vectorization is actually
2940   /// performed in a basic block.
2941   void scheduleBlock(BlockScheduling *BS);
2942 
2943   /// List of users to ignore during scheduling and that don't need extracting.
2944   ArrayRef<Value *> UserIgnoreList;
2945 
2946   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2947   /// sorted SmallVectors of unsigned.
2948   struct OrdersTypeDenseMapInfo {
2949     static OrdersType getEmptyKey() {
2950       OrdersType V;
2951       V.push_back(~1U);
2952       return V;
2953     }
2954 
2955     static OrdersType getTombstoneKey() {
2956       OrdersType V;
2957       V.push_back(~2U);
2958       return V;
2959     }
2960 
2961     static unsigned getHashValue(const OrdersType &V) {
2962       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2963     }
2964 
2965     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2966       return LHS == RHS;
2967     }
2968   };
2969 
2970   // Analysis and block reference.
2971   Function *F;
2972   ScalarEvolution *SE;
2973   TargetTransformInfo *TTI;
2974   TargetLibraryInfo *TLI;
2975   LoopInfo *LI;
2976   DominatorTree *DT;
2977   AssumptionCache *AC;
2978   DemandedBits *DB;
2979   const DataLayout *DL;
2980   OptimizationRemarkEmitter *ORE;
2981 
2982   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2983   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2984 
2985   /// Instruction builder to construct the vectorized tree.
2986   IRBuilder<> Builder;
2987 
2988   /// A map of scalar integer values to the smallest bit width with which they
2989   /// can legally be represented. The values map to (width, signed) pairs,
2990   /// where "width" indicates the minimum bit width and "signed" is True if the
2991   /// value must be signed-extended, rather than zero-extended, back to its
2992   /// original width.
2993   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2994 };
2995 
2996 } // end namespace slpvectorizer
2997 
2998 template <> struct GraphTraits<BoUpSLP *> {
2999   using TreeEntry = BoUpSLP::TreeEntry;
3000 
3001   /// NodeRef has to be a pointer per the GraphWriter.
3002   using NodeRef = TreeEntry *;
3003 
3004   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3005 
3006   /// Add the VectorizableTree to the index iterator to be able to return
3007   /// TreeEntry pointers.
3008   struct ChildIteratorType
3009       : public iterator_adaptor_base<
3010             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3011     ContainerTy &VectorizableTree;
3012 
3013     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3014                       ContainerTy &VT)
3015         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3016 
3017     NodeRef operator*() { return I->UserTE; }
3018   };
3019 
3020   static NodeRef getEntryNode(BoUpSLP &R) {
3021     return R.VectorizableTree[0].get();
3022   }
3023 
3024   static ChildIteratorType child_begin(NodeRef N) {
3025     return {N->UserTreeIndices.begin(), N->Container};
3026   }
3027 
3028   static ChildIteratorType child_end(NodeRef N) {
3029     return {N->UserTreeIndices.end(), N->Container};
3030   }
3031 
3032   /// For the node iterator we just need to turn the TreeEntry iterator into a
3033   /// TreeEntry* iterator so that it dereferences to NodeRef.
3034   class nodes_iterator {
3035     using ItTy = ContainerTy::iterator;
3036     ItTy It;
3037 
3038   public:
3039     nodes_iterator(const ItTy &It2) : It(It2) {}
3040     NodeRef operator*() { return It->get(); }
3041     nodes_iterator operator++() {
3042       ++It;
3043       return *this;
3044     }
3045     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3046   };
3047 
3048   static nodes_iterator nodes_begin(BoUpSLP *R) {
3049     return nodes_iterator(R->VectorizableTree.begin());
3050   }
3051 
3052   static nodes_iterator nodes_end(BoUpSLP *R) {
3053     return nodes_iterator(R->VectorizableTree.end());
3054   }
3055 
3056   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3057 };
3058 
3059 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3060   using TreeEntry = BoUpSLP::TreeEntry;
3061 
3062   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3063 
3064   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3065     std::string Str;
3066     raw_string_ostream OS(Str);
3067     if (isSplat(Entry->Scalars))
3068       OS << "<splat> ";
3069     for (auto V : Entry->Scalars) {
3070       OS << *V;
3071       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3072             return EU.Scalar == V;
3073           }))
3074         OS << " <extract>";
3075       OS << "\n";
3076     }
3077     return Str;
3078   }
3079 
3080   static std::string getNodeAttributes(const TreeEntry *Entry,
3081                                        const BoUpSLP *) {
3082     if (Entry->State == TreeEntry::NeedToGather)
3083       return "color=red";
3084     return "";
3085   }
3086 };
3087 
3088 } // end namespace llvm
3089 
3090 BoUpSLP::~BoUpSLP() {
3091   for (const auto &Pair : DeletedInstructions) {
3092     // Replace operands of ignored instructions with Undefs in case if they were
3093     // marked for deletion.
3094     if (Pair.getSecond()) {
3095       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3096       Pair.getFirst()->replaceAllUsesWith(Undef);
3097     }
3098     Pair.getFirst()->dropAllReferences();
3099   }
3100   for (const auto &Pair : DeletedInstructions) {
3101     assert(Pair.getFirst()->use_empty() &&
3102            "trying to erase instruction with users.");
3103     Pair.getFirst()->eraseFromParent();
3104   }
3105 #ifdef EXPENSIVE_CHECKS
3106   // If we could guarantee that this call is not extremely slow, we could
3107   // remove the ifdef limitation (see PR47712).
3108   assert(!verifyFunction(*F, &dbgs()));
3109 #endif
3110 }
3111 
3112 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3113   for (auto *V : AV) {
3114     if (auto *I = dyn_cast<Instruction>(V))
3115       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3116   };
3117 }
3118 
3119 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3120 /// contains original mask for the scalars reused in the node. Procedure
3121 /// transform this mask in accordance with the given \p Mask.
3122 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3123   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3124          "Expected non-empty mask.");
3125   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3126   Prev.swap(Reuses);
3127   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3128     if (Mask[I] != UndefMaskElem)
3129       Reuses[Mask[I]] = Prev[I];
3130 }
3131 
3132 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3133 /// the original order of the scalars. Procedure transforms the provided order
3134 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3135 /// identity order, \p Order is cleared.
3136 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3137   assert(!Mask.empty() && "Expected non-empty mask.");
3138   SmallVector<int> MaskOrder;
3139   if (Order.empty()) {
3140     MaskOrder.resize(Mask.size());
3141     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3142   } else {
3143     inversePermutation(Order, MaskOrder);
3144   }
3145   reorderReuses(MaskOrder, Mask);
3146   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3147     Order.clear();
3148     return;
3149   }
3150   Order.assign(Mask.size(), Mask.size());
3151   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3152     if (MaskOrder[I] != UndefMaskElem)
3153       Order[MaskOrder[I]] = I;
3154   fixupOrderingIndices(Order);
3155 }
3156 
3157 Optional<BoUpSLP::OrdersType>
3158 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3159   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3160   unsigned NumScalars = TE.Scalars.size();
3161   OrdersType CurrentOrder(NumScalars, NumScalars);
3162   SmallVector<int> Positions;
3163   SmallBitVector UsedPositions(NumScalars);
3164   const TreeEntry *STE = nullptr;
3165   // Try to find all gathered scalars that are gets vectorized in other
3166   // vectorize node. Here we can have only one single tree vector node to
3167   // correctly identify order of the gathered scalars.
3168   for (unsigned I = 0; I < NumScalars; ++I) {
3169     Value *V = TE.Scalars[I];
3170     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3171       continue;
3172     if (const auto *LocalSTE = getTreeEntry(V)) {
3173       if (!STE)
3174         STE = LocalSTE;
3175       else if (STE != LocalSTE)
3176         // Take the order only from the single vector node.
3177         return None;
3178       unsigned Lane =
3179           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3180       if (Lane >= NumScalars)
3181         return None;
3182       if (CurrentOrder[Lane] != NumScalars) {
3183         if (Lane != I)
3184           continue;
3185         UsedPositions.reset(CurrentOrder[Lane]);
3186       }
3187       // The partial identity (where only some elements of the gather node are
3188       // in the identity order) is good.
3189       CurrentOrder[Lane] = I;
3190       UsedPositions.set(I);
3191     }
3192   }
3193   // Need to keep the order if we have a vector entry and at least 2 scalars or
3194   // the vectorized entry has just 2 scalars.
3195   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3196     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3197       for (unsigned I = 0; I < NumScalars; ++I)
3198         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3199           return false;
3200       return true;
3201     };
3202     if (IsIdentityOrder(CurrentOrder)) {
3203       CurrentOrder.clear();
3204       return CurrentOrder;
3205     }
3206     auto *It = CurrentOrder.begin();
3207     for (unsigned I = 0; I < NumScalars;) {
3208       if (UsedPositions.test(I)) {
3209         ++I;
3210         continue;
3211       }
3212       if (*It == NumScalars) {
3213         *It = I;
3214         ++I;
3215       }
3216       ++It;
3217     }
3218     return CurrentOrder;
3219   }
3220   return None;
3221 }
3222 
3223 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3224                                                          bool TopToBottom) {
3225   // No need to reorder if need to shuffle reuses, still need to shuffle the
3226   // node.
3227   if (!TE.ReuseShuffleIndices.empty())
3228     return None;
3229   if (TE.State == TreeEntry::Vectorize &&
3230       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3231        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3232       !TE.isAltShuffle())
3233     return TE.ReorderIndices;
3234   if (TE.State == TreeEntry::NeedToGather) {
3235     // TODO: add analysis of other gather nodes with extractelement
3236     // instructions and other values/instructions, not only undefs.
3237     if (((TE.getOpcode() == Instruction::ExtractElement &&
3238           !TE.isAltShuffle()) ||
3239          (all_of(TE.Scalars,
3240                  [](Value *V) {
3241                    return isa<UndefValue, ExtractElementInst>(V);
3242                  }) &&
3243           any_of(TE.Scalars,
3244                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3245         all_of(TE.Scalars,
3246                [](Value *V) {
3247                  auto *EE = dyn_cast<ExtractElementInst>(V);
3248                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3249                }) &&
3250         allSameType(TE.Scalars)) {
3251       // Check that gather of extractelements can be represented as
3252       // just a shuffle of a single vector.
3253       OrdersType CurrentOrder;
3254       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3255       if (Reuse || !CurrentOrder.empty()) {
3256         if (!CurrentOrder.empty())
3257           fixupOrderingIndices(CurrentOrder);
3258         return CurrentOrder;
3259       }
3260     }
3261     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3262       return CurrentOrder;
3263   }
3264   return None;
3265 }
3266 
3267 void BoUpSLP::reorderTopToBottom() {
3268   // Maps VF to the graph nodes.
3269   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3270   // ExtractElement gather nodes which can be vectorized and need to handle
3271   // their ordering.
3272   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3273   // Find all reorderable nodes with the given VF.
3274   // Currently the are vectorized stores,loads,extracts + some gathering of
3275   // extracts.
3276   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3277                                  const std::unique_ptr<TreeEntry> &TE) {
3278     if (Optional<OrdersType> CurrentOrder =
3279             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3280       // Do not include ordering for nodes used in the alt opcode vectorization,
3281       // better to reorder them during bottom-to-top stage. If follow the order
3282       // here, it causes reordering of the whole graph though actually it is
3283       // profitable just to reorder the subgraph that starts from the alternate
3284       // opcode vectorization node. Such nodes already end-up with the shuffle
3285       // instruction and it is just enough to change this shuffle rather than
3286       // rotate the scalars for the whole graph.
3287       unsigned Cnt = 0;
3288       const TreeEntry *UserTE = TE.get();
3289       while (UserTE && Cnt < RecursionMaxDepth) {
3290         if (UserTE->UserTreeIndices.size() != 1)
3291           break;
3292         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3293               return EI.UserTE->State == TreeEntry::Vectorize &&
3294                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3295             }))
3296           return;
3297         if (UserTE->UserTreeIndices.empty())
3298           UserTE = nullptr;
3299         else
3300           UserTE = UserTE->UserTreeIndices.back().UserTE;
3301         ++Cnt;
3302       }
3303       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3304       if (TE->State != TreeEntry::Vectorize)
3305         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3306     }
3307   });
3308 
3309   // Reorder the graph nodes according to their vectorization factor.
3310   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3311        VF /= 2) {
3312     auto It = VFToOrderedEntries.find(VF);
3313     if (It == VFToOrderedEntries.end())
3314       continue;
3315     // Try to find the most profitable order. We just are looking for the most
3316     // used order and reorder scalar elements in the nodes according to this
3317     // mostly used order.
3318     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3319     // All operands are reordered and used only in this node - propagate the
3320     // most used order to the user node.
3321     MapVector<OrdersType, unsigned,
3322               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3323         OrdersUses;
3324     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3325     for (const TreeEntry *OpTE : OrderedEntries) {
3326       // No need to reorder this nodes, still need to extend and to use shuffle,
3327       // just need to merge reordering shuffle and the reuse shuffle.
3328       if (!OpTE->ReuseShuffleIndices.empty())
3329         continue;
3330       // Count number of orders uses.
3331       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3332         if (OpTE->State == TreeEntry::NeedToGather)
3333           return GathersToOrders.find(OpTE)->second;
3334         return OpTE->ReorderIndices;
3335       }();
3336       // Stores actually store the mask, not the order, need to invert.
3337       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3338           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3339         SmallVector<int> Mask;
3340         inversePermutation(Order, Mask);
3341         unsigned E = Order.size();
3342         OrdersType CurrentOrder(E, E);
3343         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3344           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3345         });
3346         fixupOrderingIndices(CurrentOrder);
3347         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3348       } else {
3349         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3350       }
3351     }
3352     // Set order of the user node.
3353     if (OrdersUses.empty())
3354       continue;
3355     // Choose the most used order.
3356     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3357     unsigned Cnt = OrdersUses.front().second;
3358     for (const auto &Pair : drop_begin(OrdersUses)) {
3359       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3360         BestOrder = Pair.first;
3361         Cnt = Pair.second;
3362       }
3363     }
3364     // Set order of the user node.
3365     if (BestOrder.empty())
3366       continue;
3367     SmallVector<int> Mask;
3368     inversePermutation(BestOrder, Mask);
3369     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3370     unsigned E = BestOrder.size();
3371     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3372       return I < E ? static_cast<int>(I) : UndefMaskElem;
3373     });
3374     // Do an actual reordering, if profitable.
3375     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3376       // Just do the reordering for the nodes with the given VF.
3377       if (TE->Scalars.size() != VF) {
3378         if (TE->ReuseShuffleIndices.size() == VF) {
3379           // Need to reorder the reuses masks of the operands with smaller VF to
3380           // be able to find the match between the graph nodes and scalar
3381           // operands of the given node during vectorization/cost estimation.
3382           assert(all_of(TE->UserTreeIndices,
3383                         [VF, &TE](const EdgeInfo &EI) {
3384                           return EI.UserTE->Scalars.size() == VF ||
3385                                  EI.UserTE->Scalars.size() ==
3386                                      TE->Scalars.size();
3387                         }) &&
3388                  "All users must be of VF size.");
3389           // Update ordering of the operands with the smaller VF than the given
3390           // one.
3391           reorderReuses(TE->ReuseShuffleIndices, Mask);
3392         }
3393         continue;
3394       }
3395       if (TE->State == TreeEntry::Vectorize &&
3396           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3397               InsertElementInst>(TE->getMainOp()) &&
3398           !TE->isAltShuffle()) {
3399         // Build correct orders for extract{element,value}, loads and
3400         // stores.
3401         reorderOrder(TE->ReorderIndices, Mask);
3402         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3403           TE->reorderOperands(Mask);
3404       } else {
3405         // Reorder the node and its operands.
3406         TE->reorderOperands(Mask);
3407         assert(TE->ReorderIndices.empty() &&
3408                "Expected empty reorder sequence.");
3409         reorderScalars(TE->Scalars, Mask);
3410       }
3411       if (!TE->ReuseShuffleIndices.empty()) {
3412         // Apply reversed order to keep the original ordering of the reused
3413         // elements to avoid extra reorder indices shuffling.
3414         OrdersType CurrentOrder;
3415         reorderOrder(CurrentOrder, MaskOrder);
3416         SmallVector<int> NewReuses;
3417         inversePermutation(CurrentOrder, NewReuses);
3418         addMask(NewReuses, TE->ReuseShuffleIndices);
3419         TE->ReuseShuffleIndices.swap(NewReuses);
3420       }
3421     }
3422   }
3423 }
3424 
3425 bool BoUpSLP::canReorderOperands(
3426     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3427     ArrayRef<TreeEntry *> ReorderableGathers,
3428     SmallVectorImpl<TreeEntry *> &GatherOps) {
3429   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3430     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3431           return OpData.first == I &&
3432                  OpData.second->State == TreeEntry::Vectorize;
3433         }))
3434       continue;
3435     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3436       // Do not reorder if operand node is used by many user nodes.
3437       if (any_of(TE->UserTreeIndices,
3438                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3439         return false;
3440       // Add the node to the list of the ordered nodes with the identity
3441       // order.
3442       Edges.emplace_back(I, TE);
3443       continue;
3444     }
3445     ArrayRef<Value *> VL = UserTE->getOperand(I);
3446     TreeEntry *Gather = nullptr;
3447     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3448           assert(TE->State != TreeEntry::Vectorize &&
3449                  "Only non-vectorized nodes are expected.");
3450           if (TE->isSame(VL)) {
3451             Gather = TE;
3452             return true;
3453           }
3454           return false;
3455         }) > 1)
3456       return false;
3457     if (Gather)
3458       GatherOps.push_back(Gather);
3459   }
3460   return true;
3461 }
3462 
3463 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3464   SetVector<TreeEntry *> OrderedEntries;
3465   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3466   // Find all reorderable leaf nodes with the given VF.
3467   // Currently the are vectorized loads,extracts without alternate operands +
3468   // some gathering of extracts.
3469   SmallVector<TreeEntry *> NonVectorized;
3470   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3471                               &NonVectorized](
3472                                  const std::unique_ptr<TreeEntry> &TE) {
3473     if (TE->State != TreeEntry::Vectorize)
3474       NonVectorized.push_back(TE.get());
3475     if (Optional<OrdersType> CurrentOrder =
3476             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3477       OrderedEntries.insert(TE.get());
3478       if (TE->State != TreeEntry::Vectorize)
3479         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3480     }
3481   });
3482 
3483   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3484   // I.e., if the node has operands, that are reordered, try to make at least
3485   // one operand order in the natural order and reorder others + reorder the
3486   // user node itself.
3487   SmallPtrSet<const TreeEntry *, 4> Visited;
3488   while (!OrderedEntries.empty()) {
3489     // 1. Filter out only reordered nodes.
3490     // 2. If the entry has multiple uses - skip it and jump to the next node.
3491     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3492     SmallVector<TreeEntry *> Filtered;
3493     for (TreeEntry *TE : OrderedEntries) {
3494       if (!(TE->State == TreeEntry::Vectorize ||
3495             (TE->State == TreeEntry::NeedToGather &&
3496              GathersToOrders.count(TE))) ||
3497           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3498           !all_of(drop_begin(TE->UserTreeIndices),
3499                   [TE](const EdgeInfo &EI) {
3500                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3501                   }) ||
3502           !Visited.insert(TE).second) {
3503         Filtered.push_back(TE);
3504         continue;
3505       }
3506       // Build a map between user nodes and their operands order to speedup
3507       // search. The graph currently does not provide this dependency directly.
3508       for (EdgeInfo &EI : TE->UserTreeIndices) {
3509         TreeEntry *UserTE = EI.UserTE;
3510         auto It = Users.find(UserTE);
3511         if (It == Users.end())
3512           It = Users.insert({UserTE, {}}).first;
3513         It->second.emplace_back(EI.EdgeIdx, TE);
3514       }
3515     }
3516     // Erase filtered entries.
3517     for_each(Filtered,
3518              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3519     for (auto &Data : Users) {
3520       // Check that operands are used only in the User node.
3521       SmallVector<TreeEntry *> GatherOps;
3522       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3523                               GatherOps)) {
3524         for_each(Data.second,
3525                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3526                    OrderedEntries.remove(Op.second);
3527                  });
3528         continue;
3529       }
3530       // All operands are reordered and used only in this node - propagate the
3531       // most used order to the user node.
3532       MapVector<OrdersType, unsigned,
3533                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3534           OrdersUses;
3535       // Do the analysis for each tree entry only once, otherwise the order of
3536       // the same node my be considered several times, though might be not
3537       // profitable.
3538       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3539       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3540       for (const auto &Op : Data.second) {
3541         TreeEntry *OpTE = Op.second;
3542         if (!VisitedOps.insert(OpTE).second)
3543           continue;
3544         if (!OpTE->ReuseShuffleIndices.empty() ||
3545             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3546           continue;
3547         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3548           if (OpTE->State == TreeEntry::NeedToGather)
3549             return GathersToOrders.find(OpTE)->second;
3550           return OpTE->ReorderIndices;
3551         }();
3552         unsigned NumOps = count_if(
3553             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3554               return P.second == OpTE;
3555             });
3556         // Stores actually store the mask, not the order, need to invert.
3557         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3558             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3559           SmallVector<int> Mask;
3560           inversePermutation(Order, Mask);
3561           unsigned E = Order.size();
3562           OrdersType CurrentOrder(E, E);
3563           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3564             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3565           });
3566           fixupOrderingIndices(CurrentOrder);
3567           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3568               NumOps;
3569         } else {
3570           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3571         }
3572         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3573         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3574                                             const TreeEntry *TE) {
3575           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3576               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3577               (IgnoreReorder && TE->Idx == 0))
3578             return true;
3579           if (TE->State == TreeEntry::NeedToGather) {
3580             auto It = GathersToOrders.find(TE);
3581             if (It != GathersToOrders.end())
3582               return !It->second.empty();
3583             return true;
3584           }
3585           return false;
3586         };
3587         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3588           TreeEntry *UserTE = EI.UserTE;
3589           if (!VisitedUsers.insert(UserTE).second)
3590             continue;
3591           // May reorder user node if it requires reordering, has reused
3592           // scalars, is an alternate op vectorize node or its op nodes require
3593           // reordering.
3594           if (AllowsReordering(UserTE))
3595             continue;
3596           // Check if users allow reordering.
3597           // Currently look up just 1 level of operands to avoid increase of
3598           // the compile time.
3599           // Profitable to reorder if definitely more operands allow
3600           // reordering rather than those with natural order.
3601           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3602           if (static_cast<unsigned>(count_if(
3603                   Ops, [UserTE, &AllowsReordering](
3604                            const std::pair<unsigned, TreeEntry *> &Op) {
3605                     return AllowsReordering(Op.second) &&
3606                            all_of(Op.second->UserTreeIndices,
3607                                   [UserTE](const EdgeInfo &EI) {
3608                                     return EI.UserTE == UserTE;
3609                                   });
3610                   })) <= Ops.size() / 2)
3611             ++Res.first->second;
3612         }
3613       }
3614       // If no orders - skip current nodes and jump to the next one, if any.
3615       if (OrdersUses.empty()) {
3616         for_each(Data.second,
3617                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3618                    OrderedEntries.remove(Op.second);
3619                  });
3620         continue;
3621       }
3622       // Choose the best order.
3623       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3624       unsigned Cnt = OrdersUses.front().second;
3625       for (const auto &Pair : drop_begin(OrdersUses)) {
3626         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3627           BestOrder = Pair.first;
3628           Cnt = Pair.second;
3629         }
3630       }
3631       // Set order of the user node (reordering of operands and user nodes).
3632       if (BestOrder.empty()) {
3633         for_each(Data.second,
3634                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3635                    OrderedEntries.remove(Op.second);
3636                  });
3637         continue;
3638       }
3639       // Erase operands from OrderedEntries list and adjust their orders.
3640       VisitedOps.clear();
3641       SmallVector<int> Mask;
3642       inversePermutation(BestOrder, Mask);
3643       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3644       unsigned E = BestOrder.size();
3645       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3646         return I < E ? static_cast<int>(I) : UndefMaskElem;
3647       });
3648       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3649         TreeEntry *TE = Op.second;
3650         OrderedEntries.remove(TE);
3651         if (!VisitedOps.insert(TE).second)
3652           continue;
3653         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3654           // Just reorder reuses indices.
3655           reorderReuses(TE->ReuseShuffleIndices, Mask);
3656           continue;
3657         }
3658         // Gathers are processed separately.
3659         if (TE->State != TreeEntry::Vectorize)
3660           continue;
3661         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3662                 TE->ReorderIndices.empty()) &&
3663                "Non-matching sizes of user/operand entries.");
3664         reorderOrder(TE->ReorderIndices, Mask);
3665       }
3666       // For gathers just need to reorder its scalars.
3667       for (TreeEntry *Gather : GatherOps) {
3668         assert(Gather->ReorderIndices.empty() &&
3669                "Unexpected reordering of gathers.");
3670         if (!Gather->ReuseShuffleIndices.empty()) {
3671           // Just reorder reuses indices.
3672           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3673           continue;
3674         }
3675         reorderScalars(Gather->Scalars, Mask);
3676         OrderedEntries.remove(Gather);
3677       }
3678       // Reorder operands of the user node and set the ordering for the user
3679       // node itself.
3680       if (Data.first->State != TreeEntry::Vectorize ||
3681           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3682               Data.first->getMainOp()) ||
3683           Data.first->isAltShuffle())
3684         Data.first->reorderOperands(Mask);
3685       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3686           Data.first->isAltShuffle()) {
3687         reorderScalars(Data.first->Scalars, Mask);
3688         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3689         if (Data.first->ReuseShuffleIndices.empty() &&
3690             !Data.first->ReorderIndices.empty() &&
3691             !Data.first->isAltShuffle()) {
3692           // Insert user node to the list to try to sink reordering deeper in
3693           // the graph.
3694           OrderedEntries.insert(Data.first);
3695         }
3696       } else {
3697         reorderOrder(Data.first->ReorderIndices, Mask);
3698       }
3699     }
3700   }
3701   // If the reordering is unnecessary, just remove the reorder.
3702   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3703       VectorizableTree.front()->ReuseShuffleIndices.empty())
3704     VectorizableTree.front()->ReorderIndices.clear();
3705 }
3706 
3707 void BoUpSLP::buildExternalUses(
3708     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3709   // Collect the values that we need to extract from the tree.
3710   for (auto &TEPtr : VectorizableTree) {
3711     TreeEntry *Entry = TEPtr.get();
3712 
3713     // No need to handle users of gathered values.
3714     if (Entry->State == TreeEntry::NeedToGather)
3715       continue;
3716 
3717     // For each lane:
3718     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3719       Value *Scalar = Entry->Scalars[Lane];
3720       int FoundLane = Entry->findLaneForValue(Scalar);
3721 
3722       // Check if the scalar is externally used as an extra arg.
3723       auto ExtI = ExternallyUsedValues.find(Scalar);
3724       if (ExtI != ExternallyUsedValues.end()) {
3725         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3726                           << Lane << " from " << *Scalar << ".\n");
3727         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3728       }
3729       for (User *U : Scalar->users()) {
3730         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3731 
3732         Instruction *UserInst = dyn_cast<Instruction>(U);
3733         if (!UserInst)
3734           continue;
3735 
3736         if (isDeleted(UserInst))
3737           continue;
3738 
3739         // Skip in-tree scalars that become vectors
3740         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3741           Value *UseScalar = UseEntry->Scalars[0];
3742           // Some in-tree scalars will remain as scalar in vectorized
3743           // instructions. If that is the case, the one in Lane 0 will
3744           // be used.
3745           if (UseScalar != U ||
3746               UseEntry->State == TreeEntry::ScatterVectorize ||
3747               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3748             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3749                               << ".\n");
3750             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3751             continue;
3752           }
3753         }
3754 
3755         // Ignore users in the user ignore list.
3756         if (is_contained(UserIgnoreList, UserInst))
3757           continue;
3758 
3759         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3760                           << Lane << " from " << *Scalar << ".\n");
3761         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3762       }
3763     }
3764   }
3765 }
3766 
3767 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3768                         ArrayRef<Value *> UserIgnoreLst) {
3769   deleteTree();
3770   UserIgnoreList = UserIgnoreLst;
3771   if (!allSameType(Roots))
3772     return;
3773   buildTree_rec(Roots, 0, EdgeInfo());
3774 }
3775 
3776 namespace {
3777 /// Tracks the state we can represent the loads in the given sequence.
3778 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3779 } // anonymous namespace
3780 
3781 /// Checks if the given array of loads can be represented as a vectorized,
3782 /// scatter or just simple gather.
3783 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3784                                     const TargetTransformInfo &TTI,
3785                                     const DataLayout &DL, ScalarEvolution &SE,
3786                                     SmallVectorImpl<unsigned> &Order,
3787                                     SmallVectorImpl<Value *> &PointerOps) {
3788   // Check that a vectorized load would load the same memory as a scalar
3789   // load. For example, we don't want to vectorize loads that are smaller
3790   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3791   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3792   // from such a struct, we read/write packed bits disagreeing with the
3793   // unvectorized version.
3794   Type *ScalarTy = VL0->getType();
3795 
3796   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3797     return LoadsState::Gather;
3798 
3799   // Make sure all loads in the bundle are simple - we can't vectorize
3800   // atomic or volatile loads.
3801   PointerOps.clear();
3802   PointerOps.resize(VL.size());
3803   auto *POIter = PointerOps.begin();
3804   for (Value *V : VL) {
3805     auto *L = cast<LoadInst>(V);
3806     if (!L->isSimple())
3807       return LoadsState::Gather;
3808     *POIter = L->getPointerOperand();
3809     ++POIter;
3810   }
3811 
3812   Order.clear();
3813   // Check the order of pointer operands.
3814   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3815     Value *Ptr0;
3816     Value *PtrN;
3817     if (Order.empty()) {
3818       Ptr0 = PointerOps.front();
3819       PtrN = PointerOps.back();
3820     } else {
3821       Ptr0 = PointerOps[Order.front()];
3822       PtrN = PointerOps[Order.back()];
3823     }
3824     Optional<int> Diff =
3825         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3826     // Check that the sorted loads are consecutive.
3827     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3828       return LoadsState::Vectorize;
3829     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3830     for (Value *V : VL)
3831       CommonAlignment =
3832           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3833     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3834                                 CommonAlignment))
3835       return LoadsState::ScatterVectorize;
3836   }
3837 
3838   return LoadsState::Gather;
3839 }
3840 
3841 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3842                             const EdgeInfo &UserTreeIdx) {
3843   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3844 
3845   SmallVector<int> ReuseShuffleIndicies;
3846   SmallVector<Value *> UniqueValues;
3847   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3848                                 &UserTreeIdx,
3849                                 this](const InstructionsState &S) {
3850     // Check that every instruction appears once in this bundle.
3851     DenseMap<Value *, unsigned> UniquePositions;
3852     for (Value *V : VL) {
3853       if (isConstant(V)) {
3854         ReuseShuffleIndicies.emplace_back(
3855             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3856         UniqueValues.emplace_back(V);
3857         continue;
3858       }
3859       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3860       ReuseShuffleIndicies.emplace_back(Res.first->second);
3861       if (Res.second)
3862         UniqueValues.emplace_back(V);
3863     }
3864     size_t NumUniqueScalarValues = UniqueValues.size();
3865     if (NumUniqueScalarValues == VL.size()) {
3866       ReuseShuffleIndicies.clear();
3867     } else {
3868       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3869       if (NumUniqueScalarValues <= 1 ||
3870           (UniquePositions.size() == 1 && all_of(UniqueValues,
3871                                                  [](Value *V) {
3872                                                    return isa<UndefValue>(V) ||
3873                                                           !isConstant(V);
3874                                                  })) ||
3875           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3876         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3877         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3878         return false;
3879       }
3880       VL = UniqueValues;
3881     }
3882     return true;
3883   };
3884 
3885   InstructionsState S = getSameOpcode(VL);
3886   if (Depth == RecursionMaxDepth) {
3887     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3888     if (TryToFindDuplicates(S))
3889       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3890                    ReuseShuffleIndicies);
3891     return;
3892   }
3893 
3894   // Don't handle scalable vectors
3895   if (S.getOpcode() == Instruction::ExtractElement &&
3896       isa<ScalableVectorType>(
3897           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3898     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3899     if (TryToFindDuplicates(S))
3900       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3901                    ReuseShuffleIndicies);
3902     return;
3903   }
3904 
3905   // Don't handle vectors.
3906   if (S.OpValue->getType()->isVectorTy() &&
3907       !isa<InsertElementInst>(S.OpValue)) {
3908     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3909     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3910     return;
3911   }
3912 
3913   // Avoid attempting to schedule allocas; there are unmodeled dependencies
3914   // for "static" alloca status and for reordering with stacksave calls.
3915   for (Value *V : VL) {
3916     if (isa<AllocaInst>(V)) {
3917       LLVM_DEBUG(dbgs() << "SLP: Gathering due to alloca.\n");
3918       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3919       return;
3920     }
3921   }
3922 
3923   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3924     if (SI->getValueOperand()->getType()->isVectorTy()) {
3925       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3926       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3927       return;
3928     }
3929 
3930   // If all of the operands are identical or constant we have a simple solution.
3931   // If we deal with insert/extract instructions, they all must have constant
3932   // indices, otherwise we should gather them, not try to vectorize.
3933   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3934       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3935        !all_of(VL, isVectorLikeInstWithConstOps))) {
3936     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3937     if (TryToFindDuplicates(S))
3938       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3939                    ReuseShuffleIndicies);
3940     return;
3941   }
3942 
3943   // We now know that this is a vector of instructions of the same type from
3944   // the same block.
3945 
3946   // Don't vectorize ephemeral values.
3947   for (Value *V : VL) {
3948     if (EphValues.count(V)) {
3949       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3950                         << ") is ephemeral.\n");
3951       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3952       return;
3953     }
3954   }
3955 
3956   // Check if this is a duplicate of another entry.
3957   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3958     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3959     if (!E->isSame(VL)) {
3960       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3961       if (TryToFindDuplicates(S))
3962         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3963                      ReuseShuffleIndicies);
3964       return;
3965     }
3966     // Record the reuse of the tree node.  FIXME, currently this is only used to
3967     // properly draw the graph rather than for the actual vectorization.
3968     E->UserTreeIndices.push_back(UserTreeIdx);
3969     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3970                       << ".\n");
3971     return;
3972   }
3973 
3974   // Check that none of the instructions in the bundle are already in the tree.
3975   for (Value *V : VL) {
3976     auto *I = dyn_cast<Instruction>(V);
3977     if (!I)
3978       continue;
3979     if (getTreeEntry(I)) {
3980       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3981                         << ") is already in tree.\n");
3982       if (TryToFindDuplicates(S))
3983         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3984                      ReuseShuffleIndicies);
3985       return;
3986     }
3987   }
3988 
3989   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3990   for (Value *V : VL) {
3991     if (is_contained(UserIgnoreList, V)) {
3992       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3993       if (TryToFindDuplicates(S))
3994         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3995                      ReuseShuffleIndicies);
3996       return;
3997     }
3998   }
3999 
4000   // Check that all of the users of the scalars that we want to vectorize are
4001   // schedulable.
4002   auto *VL0 = cast<Instruction>(S.OpValue);
4003   BasicBlock *BB = VL0->getParent();
4004 
4005   if (!DT->isReachableFromEntry(BB)) {
4006     // Don't go into unreachable blocks. They may contain instructions with
4007     // dependency cycles which confuse the final scheduling.
4008     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4009     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4010     return;
4011   }
4012 
4013   // Check that every instruction appears once in this bundle.
4014   if (!TryToFindDuplicates(S))
4015     return;
4016 
4017   auto &BSRef = BlocksSchedules[BB];
4018   if (!BSRef)
4019     BSRef = std::make_unique<BlockScheduling>(BB);
4020 
4021   BlockScheduling &BS = *BSRef.get();
4022 
4023   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4024 #ifdef EXPENSIVE_CHECKS
4025   // Make sure we didn't break any internal invariants
4026   BS.verify();
4027 #endif
4028   if (!Bundle) {
4029     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4030     assert((!BS.getScheduleData(VL0) ||
4031             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4032            "tryScheduleBundle should cancelScheduling on failure");
4033     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4034                  ReuseShuffleIndicies);
4035     return;
4036   }
4037   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4038 
4039   unsigned ShuffleOrOp = S.isAltShuffle() ?
4040                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4041   switch (ShuffleOrOp) {
4042     case Instruction::PHI: {
4043       auto *PH = cast<PHINode>(VL0);
4044 
4045       // Check for terminator values (e.g. invoke).
4046       for (Value *V : VL)
4047         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4048           Instruction *Term = dyn_cast<Instruction>(
4049               cast<PHINode>(V)->getIncomingValueForBlock(
4050                   PH->getIncomingBlock(I)));
4051           if (Term && Term->isTerminator()) {
4052             LLVM_DEBUG(dbgs()
4053                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4054             BS.cancelScheduling(VL, VL0);
4055             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4056                          ReuseShuffleIndicies);
4057             return;
4058           }
4059         }
4060 
4061       TreeEntry *TE =
4062           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4063       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4064 
4065       // Keeps the reordered operands to avoid code duplication.
4066       SmallVector<ValueList, 2> OperandsVec;
4067       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4068         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4069           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4070           TE->setOperand(I, Operands);
4071           OperandsVec.push_back(Operands);
4072           continue;
4073         }
4074         ValueList Operands;
4075         // Prepare the operand vector.
4076         for (Value *V : VL)
4077           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4078               PH->getIncomingBlock(I)));
4079         TE->setOperand(I, Operands);
4080         OperandsVec.push_back(Operands);
4081       }
4082       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4083         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4084       return;
4085     }
4086     case Instruction::ExtractValue:
4087     case Instruction::ExtractElement: {
4088       OrdersType CurrentOrder;
4089       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4090       if (Reuse) {
4091         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4092         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4093                      ReuseShuffleIndicies);
4094         // This is a special case, as it does not gather, but at the same time
4095         // we are not extending buildTree_rec() towards the operands.
4096         ValueList Op0;
4097         Op0.assign(VL.size(), VL0->getOperand(0));
4098         VectorizableTree.back()->setOperand(0, Op0);
4099         return;
4100       }
4101       if (!CurrentOrder.empty()) {
4102         LLVM_DEBUG({
4103           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4104                     "with order";
4105           for (unsigned Idx : CurrentOrder)
4106             dbgs() << " " << Idx;
4107           dbgs() << "\n";
4108         });
4109         fixupOrderingIndices(CurrentOrder);
4110         // Insert new order with initial value 0, if it does not exist,
4111         // otherwise return the iterator to the existing one.
4112         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4113                      ReuseShuffleIndicies, CurrentOrder);
4114         // This is a special case, as it does not gather, but at the same time
4115         // we are not extending buildTree_rec() towards the operands.
4116         ValueList Op0;
4117         Op0.assign(VL.size(), VL0->getOperand(0));
4118         VectorizableTree.back()->setOperand(0, Op0);
4119         return;
4120       }
4121       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4122       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4123                    ReuseShuffleIndicies);
4124       BS.cancelScheduling(VL, VL0);
4125       return;
4126     }
4127     case Instruction::InsertElement: {
4128       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4129 
4130       // Check that we have a buildvector and not a shuffle of 2 or more
4131       // different vectors.
4132       ValueSet SourceVectors;
4133       for (Value *V : VL) {
4134         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4135         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4136       }
4137 
4138       if (count_if(VL, [&SourceVectors](Value *V) {
4139             return !SourceVectors.contains(V);
4140           }) >= 2) {
4141         // Found 2nd source vector - cancel.
4142         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4143                              "different source vectors.\n");
4144         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4145         BS.cancelScheduling(VL, VL0);
4146         return;
4147       }
4148 
4149       auto OrdCompare = [](const std::pair<int, int> &P1,
4150                            const std::pair<int, int> &P2) {
4151         return P1.first > P2.first;
4152       };
4153       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4154                     decltype(OrdCompare)>
4155           Indices(OrdCompare);
4156       for (int I = 0, E = VL.size(); I < E; ++I) {
4157         unsigned Idx = *getInsertIndex(VL[I]);
4158         Indices.emplace(Idx, I);
4159       }
4160       OrdersType CurrentOrder(VL.size(), VL.size());
4161       bool IsIdentity = true;
4162       for (int I = 0, E = VL.size(); I < E; ++I) {
4163         CurrentOrder[Indices.top().second] = I;
4164         IsIdentity &= Indices.top().second == I;
4165         Indices.pop();
4166       }
4167       if (IsIdentity)
4168         CurrentOrder.clear();
4169       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4170                                    None, CurrentOrder);
4171       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4172 
4173       constexpr int NumOps = 2;
4174       ValueList VectorOperands[NumOps];
4175       for (int I = 0; I < NumOps; ++I) {
4176         for (Value *V : VL)
4177           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4178 
4179         TE->setOperand(I, VectorOperands[I]);
4180       }
4181       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4182       return;
4183     }
4184     case Instruction::Load: {
4185       // Check that a vectorized load would load the same memory as a scalar
4186       // load. For example, we don't want to vectorize loads that are smaller
4187       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4188       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4189       // from such a struct, we read/write packed bits disagreeing with the
4190       // unvectorized version.
4191       SmallVector<Value *> PointerOps;
4192       OrdersType CurrentOrder;
4193       TreeEntry *TE = nullptr;
4194       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4195                                 PointerOps)) {
4196       case LoadsState::Vectorize:
4197         if (CurrentOrder.empty()) {
4198           // Original loads are consecutive and does not require reordering.
4199           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4200                             ReuseShuffleIndicies);
4201           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4202         } else {
4203           fixupOrderingIndices(CurrentOrder);
4204           // Need to reorder.
4205           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4206                             ReuseShuffleIndicies, CurrentOrder);
4207           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4208         }
4209         TE->setOperandsInOrder();
4210         break;
4211       case LoadsState::ScatterVectorize:
4212         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4213         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4214                           UserTreeIdx, ReuseShuffleIndicies);
4215         TE->setOperandsInOrder();
4216         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4217         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4218         break;
4219       case LoadsState::Gather:
4220         BS.cancelScheduling(VL, VL0);
4221         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4222                      ReuseShuffleIndicies);
4223 #ifndef NDEBUG
4224         Type *ScalarTy = VL0->getType();
4225         if (DL->getTypeSizeInBits(ScalarTy) !=
4226             DL->getTypeAllocSizeInBits(ScalarTy))
4227           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4228         else if (any_of(VL, [](Value *V) {
4229                    return !cast<LoadInst>(V)->isSimple();
4230                  }))
4231           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4232         else
4233           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4234 #endif // NDEBUG
4235         break;
4236       }
4237       return;
4238     }
4239     case Instruction::ZExt:
4240     case Instruction::SExt:
4241     case Instruction::FPToUI:
4242     case Instruction::FPToSI:
4243     case Instruction::FPExt:
4244     case Instruction::PtrToInt:
4245     case Instruction::IntToPtr:
4246     case Instruction::SIToFP:
4247     case Instruction::UIToFP:
4248     case Instruction::Trunc:
4249     case Instruction::FPTrunc:
4250     case Instruction::BitCast: {
4251       Type *SrcTy = VL0->getOperand(0)->getType();
4252       for (Value *V : VL) {
4253         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4254         if (Ty != SrcTy || !isValidElementType(Ty)) {
4255           BS.cancelScheduling(VL, VL0);
4256           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4257                        ReuseShuffleIndicies);
4258           LLVM_DEBUG(dbgs()
4259                      << "SLP: Gathering casts with different src types.\n");
4260           return;
4261         }
4262       }
4263       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4264                                    ReuseShuffleIndicies);
4265       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4266 
4267       TE->setOperandsInOrder();
4268       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4269         ValueList Operands;
4270         // Prepare the operand vector.
4271         for (Value *V : VL)
4272           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4273 
4274         buildTree_rec(Operands, Depth + 1, {TE, i});
4275       }
4276       return;
4277     }
4278     case Instruction::ICmp:
4279     case Instruction::FCmp: {
4280       // Check that all of the compares have the same predicate.
4281       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4282       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4283       Type *ComparedTy = VL0->getOperand(0)->getType();
4284       for (Value *V : VL) {
4285         CmpInst *Cmp = cast<CmpInst>(V);
4286         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4287             Cmp->getOperand(0)->getType() != ComparedTy) {
4288           BS.cancelScheduling(VL, VL0);
4289           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4290                        ReuseShuffleIndicies);
4291           LLVM_DEBUG(dbgs()
4292                      << "SLP: Gathering cmp with different predicate.\n");
4293           return;
4294         }
4295       }
4296 
4297       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4298                                    ReuseShuffleIndicies);
4299       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4300 
4301       ValueList Left, Right;
4302       if (cast<CmpInst>(VL0)->isCommutative()) {
4303         // Commutative predicate - collect + sort operands of the instructions
4304         // so that each side is more likely to have the same opcode.
4305         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4306         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4307       } else {
4308         // Collect operands - commute if it uses the swapped predicate.
4309         for (Value *V : VL) {
4310           auto *Cmp = cast<CmpInst>(V);
4311           Value *LHS = Cmp->getOperand(0);
4312           Value *RHS = Cmp->getOperand(1);
4313           if (Cmp->getPredicate() != P0)
4314             std::swap(LHS, RHS);
4315           Left.push_back(LHS);
4316           Right.push_back(RHS);
4317         }
4318       }
4319       TE->setOperand(0, Left);
4320       TE->setOperand(1, Right);
4321       buildTree_rec(Left, Depth + 1, {TE, 0});
4322       buildTree_rec(Right, Depth + 1, {TE, 1});
4323       return;
4324     }
4325     case Instruction::Select:
4326     case Instruction::FNeg:
4327     case Instruction::Add:
4328     case Instruction::FAdd:
4329     case Instruction::Sub:
4330     case Instruction::FSub:
4331     case Instruction::Mul:
4332     case Instruction::FMul:
4333     case Instruction::UDiv:
4334     case Instruction::SDiv:
4335     case Instruction::FDiv:
4336     case Instruction::URem:
4337     case Instruction::SRem:
4338     case Instruction::FRem:
4339     case Instruction::Shl:
4340     case Instruction::LShr:
4341     case Instruction::AShr:
4342     case Instruction::And:
4343     case Instruction::Or:
4344     case Instruction::Xor: {
4345       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4346                                    ReuseShuffleIndicies);
4347       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4348 
4349       // Sort operands of the instructions so that each side is more likely to
4350       // have the same opcode.
4351       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4352         ValueList Left, Right;
4353         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4354         TE->setOperand(0, Left);
4355         TE->setOperand(1, Right);
4356         buildTree_rec(Left, Depth + 1, {TE, 0});
4357         buildTree_rec(Right, Depth + 1, {TE, 1});
4358         return;
4359       }
4360 
4361       TE->setOperandsInOrder();
4362       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4363         ValueList Operands;
4364         // Prepare the operand vector.
4365         for (Value *V : VL)
4366           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4367 
4368         buildTree_rec(Operands, Depth + 1, {TE, i});
4369       }
4370       return;
4371     }
4372     case Instruction::GetElementPtr: {
4373       // We don't combine GEPs with complicated (nested) indexing.
4374       for (Value *V : VL) {
4375         if (cast<Instruction>(V)->getNumOperands() != 2) {
4376           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4377           BS.cancelScheduling(VL, VL0);
4378           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4379                        ReuseShuffleIndicies);
4380           return;
4381         }
4382       }
4383 
4384       // We can't combine several GEPs into one vector if they operate on
4385       // different types.
4386       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4387       for (Value *V : VL) {
4388         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4389         if (Ty0 != CurTy) {
4390           LLVM_DEBUG(dbgs()
4391                      << "SLP: not-vectorizable GEP (different types).\n");
4392           BS.cancelScheduling(VL, VL0);
4393           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4394                        ReuseShuffleIndicies);
4395           return;
4396         }
4397       }
4398 
4399       // We don't combine GEPs with non-constant indexes.
4400       Type *Ty1 = VL0->getOperand(1)->getType();
4401       for (Value *V : VL) {
4402         auto Op = cast<Instruction>(V)->getOperand(1);
4403         if (!isa<ConstantInt>(Op) ||
4404             (Op->getType() != Ty1 &&
4405              Op->getType()->getScalarSizeInBits() >
4406                  DL->getIndexSizeInBits(
4407                      V->getType()->getPointerAddressSpace()))) {
4408           LLVM_DEBUG(dbgs()
4409                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4410           BS.cancelScheduling(VL, VL0);
4411           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4412                        ReuseShuffleIndicies);
4413           return;
4414         }
4415       }
4416 
4417       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4418                                    ReuseShuffleIndicies);
4419       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4420       SmallVector<ValueList, 2> Operands(2);
4421       // Prepare the operand vector for pointer operands.
4422       for (Value *V : VL)
4423         Operands.front().push_back(
4424             cast<GetElementPtrInst>(V)->getPointerOperand());
4425       TE->setOperand(0, Operands.front());
4426       // Need to cast all indices to the same type before vectorization to
4427       // avoid crash.
4428       // Required to be able to find correct matches between different gather
4429       // nodes and reuse the vectorized values rather than trying to gather them
4430       // again.
4431       int IndexIdx = 1;
4432       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4433       Type *Ty = all_of(VL,
4434                         [VL0Ty, IndexIdx](Value *V) {
4435                           return VL0Ty == cast<GetElementPtrInst>(V)
4436                                               ->getOperand(IndexIdx)
4437                                               ->getType();
4438                         })
4439                      ? VL0Ty
4440                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4441                                             ->getPointerOperandType()
4442                                             ->getScalarType());
4443       // Prepare the operand vector.
4444       for (Value *V : VL) {
4445         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4446         auto *CI = cast<ConstantInt>(Op);
4447         Operands.back().push_back(ConstantExpr::getIntegerCast(
4448             CI, Ty, CI->getValue().isSignBitSet()));
4449       }
4450       TE->setOperand(IndexIdx, Operands.back());
4451 
4452       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4453         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4454       return;
4455     }
4456     case Instruction::Store: {
4457       // Check if the stores are consecutive or if we need to swizzle them.
4458       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4459       // Avoid types that are padded when being allocated as scalars, while
4460       // being packed together in a vector (such as i1).
4461       if (DL->getTypeSizeInBits(ScalarTy) !=
4462           DL->getTypeAllocSizeInBits(ScalarTy)) {
4463         BS.cancelScheduling(VL, VL0);
4464         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4465                      ReuseShuffleIndicies);
4466         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4467         return;
4468       }
4469       // Make sure all stores in the bundle are simple - we can't vectorize
4470       // atomic or volatile stores.
4471       SmallVector<Value *, 4> PointerOps(VL.size());
4472       ValueList Operands(VL.size());
4473       auto POIter = PointerOps.begin();
4474       auto OIter = Operands.begin();
4475       for (Value *V : VL) {
4476         auto *SI = cast<StoreInst>(V);
4477         if (!SI->isSimple()) {
4478           BS.cancelScheduling(VL, VL0);
4479           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4480                        ReuseShuffleIndicies);
4481           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4482           return;
4483         }
4484         *POIter = SI->getPointerOperand();
4485         *OIter = SI->getValueOperand();
4486         ++POIter;
4487         ++OIter;
4488       }
4489 
4490       OrdersType CurrentOrder;
4491       // Check the order of pointer operands.
4492       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4493         Value *Ptr0;
4494         Value *PtrN;
4495         if (CurrentOrder.empty()) {
4496           Ptr0 = PointerOps.front();
4497           PtrN = PointerOps.back();
4498         } else {
4499           Ptr0 = PointerOps[CurrentOrder.front()];
4500           PtrN = PointerOps[CurrentOrder.back()];
4501         }
4502         Optional<int> Dist =
4503             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4504         // Check that the sorted pointer operands are consecutive.
4505         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4506           if (CurrentOrder.empty()) {
4507             // Original stores are consecutive and does not require reordering.
4508             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4509                                          UserTreeIdx, ReuseShuffleIndicies);
4510             TE->setOperandsInOrder();
4511             buildTree_rec(Operands, Depth + 1, {TE, 0});
4512             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4513           } else {
4514             fixupOrderingIndices(CurrentOrder);
4515             TreeEntry *TE =
4516                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4517                              ReuseShuffleIndicies, CurrentOrder);
4518             TE->setOperandsInOrder();
4519             buildTree_rec(Operands, Depth + 1, {TE, 0});
4520             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4521           }
4522           return;
4523         }
4524       }
4525 
4526       BS.cancelScheduling(VL, VL0);
4527       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4528                    ReuseShuffleIndicies);
4529       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4530       return;
4531     }
4532     case Instruction::Call: {
4533       // Check if the calls are all to the same vectorizable intrinsic or
4534       // library function.
4535       CallInst *CI = cast<CallInst>(VL0);
4536       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4537 
4538       VFShape Shape = VFShape::get(
4539           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4540           false /*HasGlobalPred*/);
4541       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4542 
4543       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4544         BS.cancelScheduling(VL, VL0);
4545         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4546                      ReuseShuffleIndicies);
4547         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4548         return;
4549       }
4550       Function *F = CI->getCalledFunction();
4551       unsigned NumArgs = CI->arg_size();
4552       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4553       for (unsigned j = 0; j != NumArgs; ++j)
4554         if (hasVectorInstrinsicScalarOpd(ID, j))
4555           ScalarArgs[j] = CI->getArgOperand(j);
4556       for (Value *V : VL) {
4557         CallInst *CI2 = dyn_cast<CallInst>(V);
4558         if (!CI2 || CI2->getCalledFunction() != F ||
4559             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4560             (VecFunc &&
4561              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4562             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4563           BS.cancelScheduling(VL, VL0);
4564           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4565                        ReuseShuffleIndicies);
4566           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4567                             << "\n");
4568           return;
4569         }
4570         // Some intrinsics have scalar arguments and should be same in order for
4571         // them to be vectorized.
4572         for (unsigned j = 0; j != NumArgs; ++j) {
4573           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4574             Value *A1J = CI2->getArgOperand(j);
4575             if (ScalarArgs[j] != A1J) {
4576               BS.cancelScheduling(VL, VL0);
4577               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4578                            ReuseShuffleIndicies);
4579               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4580                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4581                                 << "\n");
4582               return;
4583             }
4584           }
4585         }
4586         // Verify that the bundle operands are identical between the two calls.
4587         if (CI->hasOperandBundles() &&
4588             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4589                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4590                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4591           BS.cancelScheduling(VL, VL0);
4592           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4593                        ReuseShuffleIndicies);
4594           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4595                             << *CI << "!=" << *V << '\n');
4596           return;
4597         }
4598       }
4599 
4600       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4601                                    ReuseShuffleIndicies);
4602       TE->setOperandsInOrder();
4603       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4604         // For scalar operands no need to to create an entry since no need to
4605         // vectorize it.
4606         if (hasVectorInstrinsicScalarOpd(ID, i))
4607           continue;
4608         ValueList Operands;
4609         // Prepare the operand vector.
4610         for (Value *V : VL) {
4611           auto *CI2 = cast<CallInst>(V);
4612           Operands.push_back(CI2->getArgOperand(i));
4613         }
4614         buildTree_rec(Operands, Depth + 1, {TE, i});
4615       }
4616       return;
4617     }
4618     case Instruction::ShuffleVector: {
4619       // If this is not an alternate sequence of opcode like add-sub
4620       // then do not vectorize this instruction.
4621       if (!S.isAltShuffle()) {
4622         BS.cancelScheduling(VL, VL0);
4623         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4624                      ReuseShuffleIndicies);
4625         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4626         return;
4627       }
4628       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4629                                    ReuseShuffleIndicies);
4630       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4631 
4632       // Reorder operands if reordering would enable vectorization.
4633       auto *CI = dyn_cast<CmpInst>(VL0);
4634       if (isa<BinaryOperator>(VL0) || CI) {
4635         ValueList Left, Right;
4636         if (!CI || all_of(VL, [](Value *V) {
4637               return cast<CmpInst>(V)->isCommutative();
4638             })) {
4639           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4640         } else {
4641           CmpInst::Predicate P0 = CI->getPredicate();
4642           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4643           assert(P0 != AltP0 &&
4644                  "Expected different main/alternate predicates.");
4645           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4646           Value *BaseOp0 = VL0->getOperand(0);
4647           Value *BaseOp1 = VL0->getOperand(1);
4648           // Collect operands - commute if it uses the swapped predicate or
4649           // alternate operation.
4650           for (Value *V : VL) {
4651             auto *Cmp = cast<CmpInst>(V);
4652             Value *LHS = Cmp->getOperand(0);
4653             Value *RHS = Cmp->getOperand(1);
4654             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4655             if (P0 == AltP0Swapped) {
4656               if (CI != Cmp && S.AltOp != Cmp &&
4657                   ((P0 == CurrentPred &&
4658                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4659                    (AltP0 == CurrentPred &&
4660                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4661                 std::swap(LHS, RHS);
4662             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4663               std::swap(LHS, RHS);
4664             }
4665             Left.push_back(LHS);
4666             Right.push_back(RHS);
4667           }
4668         }
4669         TE->setOperand(0, Left);
4670         TE->setOperand(1, Right);
4671         buildTree_rec(Left, Depth + 1, {TE, 0});
4672         buildTree_rec(Right, Depth + 1, {TE, 1});
4673         return;
4674       }
4675 
4676       TE->setOperandsInOrder();
4677       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4678         ValueList Operands;
4679         // Prepare the operand vector.
4680         for (Value *V : VL)
4681           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4682 
4683         buildTree_rec(Operands, Depth + 1, {TE, i});
4684       }
4685       return;
4686     }
4687     default:
4688       BS.cancelScheduling(VL, VL0);
4689       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4690                    ReuseShuffleIndicies);
4691       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4692       return;
4693   }
4694 }
4695 
4696 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4697   unsigned N = 1;
4698   Type *EltTy = T;
4699 
4700   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4701          isa<VectorType>(EltTy)) {
4702     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4703       // Check that struct is homogeneous.
4704       for (const auto *Ty : ST->elements())
4705         if (Ty != *ST->element_begin())
4706           return 0;
4707       N *= ST->getNumElements();
4708       EltTy = *ST->element_begin();
4709     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4710       N *= AT->getNumElements();
4711       EltTy = AT->getElementType();
4712     } else {
4713       auto *VT = cast<FixedVectorType>(EltTy);
4714       N *= VT->getNumElements();
4715       EltTy = VT->getElementType();
4716     }
4717   }
4718 
4719   if (!isValidElementType(EltTy))
4720     return 0;
4721   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4722   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4723     return 0;
4724   return N;
4725 }
4726 
4727 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4728                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4729   const auto *It = find_if(VL, [](Value *V) {
4730     return isa<ExtractElementInst, ExtractValueInst>(V);
4731   });
4732   assert(It != VL.end() && "Expected at least one extract instruction.");
4733   auto *E0 = cast<Instruction>(*It);
4734   assert(all_of(VL,
4735                 [](Value *V) {
4736                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4737                       V);
4738                 }) &&
4739          "Invalid opcode");
4740   // Check if all of the extracts come from the same vector and from the
4741   // correct offset.
4742   Value *Vec = E0->getOperand(0);
4743 
4744   CurrentOrder.clear();
4745 
4746   // We have to extract from a vector/aggregate with the same number of elements.
4747   unsigned NElts;
4748   if (E0->getOpcode() == Instruction::ExtractValue) {
4749     const DataLayout &DL = E0->getModule()->getDataLayout();
4750     NElts = canMapToVector(Vec->getType(), DL);
4751     if (!NElts)
4752       return false;
4753     // Check if load can be rewritten as load of vector.
4754     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4755     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4756       return false;
4757   } else {
4758     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4759   }
4760 
4761   if (NElts != VL.size())
4762     return false;
4763 
4764   // Check that all of the indices extract from the correct offset.
4765   bool ShouldKeepOrder = true;
4766   unsigned E = VL.size();
4767   // Assign to all items the initial value E + 1 so we can check if the extract
4768   // instruction index was used already.
4769   // Also, later we can check that all the indices are used and we have a
4770   // consecutive access in the extract instructions, by checking that no
4771   // element of CurrentOrder still has value E + 1.
4772   CurrentOrder.assign(E, E);
4773   unsigned I = 0;
4774   for (; I < E; ++I) {
4775     auto *Inst = dyn_cast<Instruction>(VL[I]);
4776     if (!Inst)
4777       continue;
4778     if (Inst->getOperand(0) != Vec)
4779       break;
4780     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4781       if (isa<UndefValue>(EE->getIndexOperand()))
4782         continue;
4783     Optional<unsigned> Idx = getExtractIndex(Inst);
4784     if (!Idx)
4785       break;
4786     const unsigned ExtIdx = *Idx;
4787     if (ExtIdx != I) {
4788       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4789         break;
4790       ShouldKeepOrder = false;
4791       CurrentOrder[ExtIdx] = I;
4792     } else {
4793       if (CurrentOrder[I] != E)
4794         break;
4795       CurrentOrder[I] = I;
4796     }
4797   }
4798   if (I < E) {
4799     CurrentOrder.clear();
4800     return false;
4801   }
4802   if (ShouldKeepOrder)
4803     CurrentOrder.clear();
4804 
4805   return ShouldKeepOrder;
4806 }
4807 
4808 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4809                                     ArrayRef<Value *> VectorizedVals) const {
4810   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4811          all_of(I->users(), [this](User *U) {
4812            return ScalarToTreeEntry.count(U) > 0 ||
4813                   isVectorLikeInstWithConstOps(U) ||
4814                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4815          });
4816 }
4817 
4818 static std::pair<InstructionCost, InstructionCost>
4819 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4820                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4821   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4822 
4823   // Calculate the cost of the scalar and vector calls.
4824   SmallVector<Type *, 4> VecTys;
4825   for (Use &Arg : CI->args())
4826     VecTys.push_back(
4827         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4828   FastMathFlags FMF;
4829   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4830     FMF = FPCI->getFastMathFlags();
4831   SmallVector<const Value *> Arguments(CI->args());
4832   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4833                                     dyn_cast<IntrinsicInst>(CI));
4834   auto IntrinsicCost =
4835     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4836 
4837   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4838                                      VecTy->getNumElements())),
4839                             false /*HasGlobalPred*/);
4840   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4841   auto LibCost = IntrinsicCost;
4842   if (!CI->isNoBuiltin() && VecFunc) {
4843     // Calculate the cost of the vector library call.
4844     // If the corresponding vector call is cheaper, return its cost.
4845     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4846                                     TTI::TCK_RecipThroughput);
4847   }
4848   return {IntrinsicCost, LibCost};
4849 }
4850 
4851 /// Compute the cost of creating a vector of type \p VecTy containing the
4852 /// extracted values from \p VL.
4853 static InstructionCost
4854 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4855                    TargetTransformInfo::ShuffleKind ShuffleKind,
4856                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4857   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4858 
4859   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4860       VecTy->getNumElements() < NumOfParts)
4861     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4862 
4863   bool AllConsecutive = true;
4864   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4865   unsigned Idx = -1;
4866   InstructionCost Cost = 0;
4867 
4868   // Process extracts in blocks of EltsPerVector to check if the source vector
4869   // operand can be re-used directly. If not, add the cost of creating a shuffle
4870   // to extract the values into a vector register.
4871   for (auto *V : VL) {
4872     ++Idx;
4873 
4874     // Need to exclude undefs from analysis.
4875     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4876       continue;
4877 
4878     // Reached the start of a new vector registers.
4879     if (Idx % EltsPerVector == 0) {
4880       AllConsecutive = true;
4881       continue;
4882     }
4883 
4884     // Check all extracts for a vector register on the target directly
4885     // extract values in order.
4886     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4887     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4888       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4889       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4890                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4891     }
4892 
4893     if (AllConsecutive)
4894       continue;
4895 
4896     // Skip all indices, except for the last index per vector block.
4897     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4898       continue;
4899 
4900     // If we have a series of extracts which are not consecutive and hence
4901     // cannot re-use the source vector register directly, compute the shuffle
4902     // cost to extract the a vector with EltsPerVector elements.
4903     Cost += TTI.getShuffleCost(
4904         TargetTransformInfo::SK_PermuteSingleSrc,
4905         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4906   }
4907   return Cost;
4908 }
4909 
4910 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4911 /// operations operands.
4912 static void
4913 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4914                       ArrayRef<int> ReusesIndices,
4915                       const function_ref<bool(Instruction *)> IsAltOp,
4916                       SmallVectorImpl<int> &Mask,
4917                       SmallVectorImpl<Value *> *OpScalars = nullptr,
4918                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
4919   unsigned Sz = VL.size();
4920   Mask.assign(Sz, UndefMaskElem);
4921   SmallVector<int> OrderMask;
4922   if (!ReorderIndices.empty())
4923     inversePermutation(ReorderIndices, OrderMask);
4924   for (unsigned I = 0; I < Sz; ++I) {
4925     unsigned Idx = I;
4926     if (!ReorderIndices.empty())
4927       Idx = OrderMask[I];
4928     auto *OpInst = cast<Instruction>(VL[Idx]);
4929     if (IsAltOp(OpInst)) {
4930       Mask[I] = Sz + Idx;
4931       if (AltScalars)
4932         AltScalars->push_back(OpInst);
4933     } else {
4934       Mask[I] = Idx;
4935       if (OpScalars)
4936         OpScalars->push_back(OpInst);
4937     }
4938   }
4939   if (!ReusesIndices.empty()) {
4940     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4941     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4942       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4943     });
4944     Mask.swap(NewMask);
4945   }
4946 }
4947 
4948 /// Checks if the specified instruction \p I is an alternate operation for the
4949 /// given \p MainOp and \p AltOp instructions.
4950 static bool isAlternateInstruction(const Instruction *I,
4951                                    const Instruction *MainOp,
4952                                    const Instruction *AltOp) {
4953   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
4954     auto *AltCI0 = cast<CmpInst>(AltOp);
4955     auto *CI = cast<CmpInst>(I);
4956     CmpInst::Predicate P0 = CI0->getPredicate();
4957     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
4958     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
4959     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4960     CmpInst::Predicate CurrentPred = CI->getPredicate();
4961     if (P0 == AltP0Swapped)
4962       return I == AltCI0 ||
4963              (I != MainOp &&
4964               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
4965                                    CI->getOperand(0), CI->getOperand(1)));
4966     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
4967   }
4968   return I->getOpcode() == AltOp->getOpcode();
4969 }
4970 
4971 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4972                                       ArrayRef<Value *> VectorizedVals) {
4973   ArrayRef<Value*> VL = E->Scalars;
4974 
4975   Type *ScalarTy = VL[0]->getType();
4976   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4977     ScalarTy = SI->getValueOperand()->getType();
4978   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4979     ScalarTy = CI->getOperand(0)->getType();
4980   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4981     ScalarTy = IE->getOperand(1)->getType();
4982   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4983   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4984 
4985   // If we have computed a smaller type for the expression, update VecTy so
4986   // that the costs will be accurate.
4987   if (MinBWs.count(VL[0]))
4988     VecTy = FixedVectorType::get(
4989         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4990   unsigned EntryVF = E->getVectorFactor();
4991   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4992 
4993   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4994   // FIXME: it tries to fix a problem with MSVC buildbots.
4995   TargetTransformInfo &TTIRef = *TTI;
4996   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4997                                VectorizedVals, E](InstructionCost &Cost) {
4998     DenseMap<Value *, int> ExtractVectorsTys;
4999     SmallPtrSet<Value *, 4> CheckedExtracts;
5000     for (auto *V : VL) {
5001       if (isa<UndefValue>(V))
5002         continue;
5003       // If all users of instruction are going to be vectorized and this
5004       // instruction itself is not going to be vectorized, consider this
5005       // instruction as dead and remove its cost from the final cost of the
5006       // vectorized tree.
5007       // Also, avoid adjusting the cost for extractelements with multiple uses
5008       // in different graph entries.
5009       const TreeEntry *VE = getTreeEntry(V);
5010       if (!CheckedExtracts.insert(V).second ||
5011           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5012           (VE && VE != E))
5013         continue;
5014       auto *EE = cast<ExtractElementInst>(V);
5015       Optional<unsigned> EEIdx = getExtractIndex(EE);
5016       if (!EEIdx)
5017         continue;
5018       unsigned Idx = *EEIdx;
5019       if (TTIRef.getNumberOfParts(VecTy) !=
5020           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5021         auto It =
5022             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5023         It->getSecond() = std::min<int>(It->second, Idx);
5024       }
5025       // Take credit for instruction that will become dead.
5026       if (EE->hasOneUse()) {
5027         Instruction *Ext = EE->user_back();
5028         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5029             all_of(Ext->users(),
5030                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5031           // Use getExtractWithExtendCost() to calculate the cost of
5032           // extractelement/ext pair.
5033           Cost -=
5034               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5035                                               EE->getVectorOperandType(), Idx);
5036           // Add back the cost of s|zext which is subtracted separately.
5037           Cost += TTIRef.getCastInstrCost(
5038               Ext->getOpcode(), Ext->getType(), EE->getType(),
5039               TTI::getCastContextHint(Ext), CostKind, Ext);
5040           continue;
5041         }
5042       }
5043       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5044                                         EE->getVectorOperandType(), Idx);
5045     }
5046     // Add a cost for subvector extracts/inserts if required.
5047     for (const auto &Data : ExtractVectorsTys) {
5048       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5049       unsigned NumElts = VecTy->getNumElements();
5050       if (Data.second % NumElts == 0)
5051         continue;
5052       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5053         unsigned Idx = (Data.second / NumElts) * NumElts;
5054         unsigned EENumElts = EEVTy->getNumElements();
5055         if (Idx + NumElts <= EENumElts) {
5056           Cost +=
5057               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5058                                     EEVTy, None, Idx, VecTy);
5059         } else {
5060           // Need to round up the subvector type vectorization factor to avoid a
5061           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5062           // <= EENumElts.
5063           auto *SubVT =
5064               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5065           Cost +=
5066               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5067                                     EEVTy, None, Idx, SubVT);
5068         }
5069       } else {
5070         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5071                                       VecTy, None, 0, EEVTy);
5072       }
5073     }
5074   };
5075   if (E->State == TreeEntry::NeedToGather) {
5076     if (allConstant(VL))
5077       return 0;
5078     if (isa<InsertElementInst>(VL[0]))
5079       return InstructionCost::getInvalid();
5080     SmallVector<int> Mask;
5081     SmallVector<const TreeEntry *> Entries;
5082     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5083         isGatherShuffledEntry(E, Mask, Entries);
5084     if (Shuffle.hasValue()) {
5085       InstructionCost GatherCost = 0;
5086       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5087         // Perfect match in the graph, will reuse the previously vectorized
5088         // node. Cost is 0.
5089         LLVM_DEBUG(
5090             dbgs()
5091             << "SLP: perfect diamond match for gather bundle that starts with "
5092             << *VL.front() << ".\n");
5093         if (NeedToShuffleReuses)
5094           GatherCost =
5095               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5096                                   FinalVecTy, E->ReuseShuffleIndices);
5097       } else {
5098         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5099                           << " entries for bundle that starts with "
5100                           << *VL.front() << ".\n");
5101         // Detected that instead of gather we can emit a shuffle of single/two
5102         // previously vectorized nodes. Add the cost of the permutation rather
5103         // than gather.
5104         ::addMask(Mask, E->ReuseShuffleIndices);
5105         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5106       }
5107       return GatherCost;
5108     }
5109     if ((E->getOpcode() == Instruction::ExtractElement ||
5110          all_of(E->Scalars,
5111                 [](Value *V) {
5112                   return isa<ExtractElementInst, UndefValue>(V);
5113                 })) &&
5114         allSameType(VL)) {
5115       // Check that gather of extractelements can be represented as just a
5116       // shuffle of a single/two vectors the scalars are extracted from.
5117       SmallVector<int> Mask;
5118       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5119           isFixedVectorShuffle(VL, Mask);
5120       if (ShuffleKind.hasValue()) {
5121         // Found the bunch of extractelement instructions that must be gathered
5122         // into a vector and can be represented as a permutation elements in a
5123         // single input vector or of 2 input vectors.
5124         InstructionCost Cost =
5125             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5126         AdjustExtractsCost(Cost);
5127         if (NeedToShuffleReuses)
5128           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5129                                       FinalVecTy, E->ReuseShuffleIndices);
5130         return Cost;
5131       }
5132     }
5133     if (isSplat(VL)) {
5134       // Found the broadcasting of the single scalar, calculate the cost as the
5135       // broadcast.
5136       assert(VecTy == FinalVecTy &&
5137              "No reused scalars expected for broadcast.");
5138       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5139     }
5140     InstructionCost ReuseShuffleCost = 0;
5141     if (NeedToShuffleReuses)
5142       ReuseShuffleCost = TTI->getShuffleCost(
5143           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5144     // Improve gather cost for gather of loads, if we can group some of the
5145     // loads into vector loads.
5146     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5147         !E->isAltShuffle()) {
5148       BoUpSLP::ValueSet VectorizedLoads;
5149       unsigned StartIdx = 0;
5150       unsigned VF = VL.size() / 2;
5151       unsigned VectorizedCnt = 0;
5152       unsigned ScatterVectorizeCnt = 0;
5153       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5154       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5155         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5156              Cnt += VF) {
5157           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5158           if (!VectorizedLoads.count(Slice.front()) &&
5159               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5160             SmallVector<Value *> PointerOps;
5161             OrdersType CurrentOrder;
5162             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5163                                               *SE, CurrentOrder, PointerOps);
5164             switch (LS) {
5165             case LoadsState::Vectorize:
5166             case LoadsState::ScatterVectorize:
5167               // Mark the vectorized loads so that we don't vectorize them
5168               // again.
5169               if (LS == LoadsState::Vectorize)
5170                 ++VectorizedCnt;
5171               else
5172                 ++ScatterVectorizeCnt;
5173               VectorizedLoads.insert(Slice.begin(), Slice.end());
5174               // If we vectorized initial block, no need to try to vectorize it
5175               // again.
5176               if (Cnt == StartIdx)
5177                 StartIdx += VF;
5178               break;
5179             case LoadsState::Gather:
5180               break;
5181             }
5182           }
5183         }
5184         // Check if the whole array was vectorized already - exit.
5185         if (StartIdx >= VL.size())
5186           break;
5187         // Found vectorizable parts - exit.
5188         if (!VectorizedLoads.empty())
5189           break;
5190       }
5191       if (!VectorizedLoads.empty()) {
5192         InstructionCost GatherCost = 0;
5193         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5194         bool NeedInsertSubvectorAnalysis =
5195             !NumParts || (VL.size() / VF) > NumParts;
5196         // Get the cost for gathered loads.
5197         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5198           if (VectorizedLoads.contains(VL[I]))
5199             continue;
5200           GatherCost += getGatherCost(VL.slice(I, VF));
5201         }
5202         // The cost for vectorized loads.
5203         InstructionCost ScalarsCost = 0;
5204         for (Value *V : VectorizedLoads) {
5205           auto *LI = cast<LoadInst>(V);
5206           ScalarsCost += TTI->getMemoryOpCost(
5207               Instruction::Load, LI->getType(), LI->getAlign(),
5208               LI->getPointerAddressSpace(), CostKind, LI);
5209         }
5210         auto *LI = cast<LoadInst>(E->getMainOp());
5211         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5212         Align Alignment = LI->getAlign();
5213         GatherCost +=
5214             VectorizedCnt *
5215             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5216                                  LI->getPointerAddressSpace(), CostKind, LI);
5217         GatherCost += ScatterVectorizeCnt *
5218                       TTI->getGatherScatterOpCost(
5219                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5220                           /*VariableMask=*/false, Alignment, CostKind, LI);
5221         if (NeedInsertSubvectorAnalysis) {
5222           // Add the cost for the subvectors insert.
5223           for (int I = VF, E = VL.size(); I < E; I += VF)
5224             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5225                                               None, I, LoadTy);
5226         }
5227         return ReuseShuffleCost + GatherCost - ScalarsCost;
5228       }
5229     }
5230     return ReuseShuffleCost + getGatherCost(VL);
5231   }
5232   InstructionCost CommonCost = 0;
5233   SmallVector<int> Mask;
5234   if (!E->ReorderIndices.empty()) {
5235     SmallVector<int> NewMask;
5236     if (E->getOpcode() == Instruction::Store) {
5237       // For stores the order is actually a mask.
5238       NewMask.resize(E->ReorderIndices.size());
5239       copy(E->ReorderIndices, NewMask.begin());
5240     } else {
5241       inversePermutation(E->ReorderIndices, NewMask);
5242     }
5243     ::addMask(Mask, NewMask);
5244   }
5245   if (NeedToShuffleReuses)
5246     ::addMask(Mask, E->ReuseShuffleIndices);
5247   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5248     CommonCost =
5249         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5250   assert((E->State == TreeEntry::Vectorize ||
5251           E->State == TreeEntry::ScatterVectorize) &&
5252          "Unhandled state");
5253   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5254   Instruction *VL0 = E->getMainOp();
5255   unsigned ShuffleOrOp =
5256       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5257   switch (ShuffleOrOp) {
5258     case Instruction::PHI:
5259       return 0;
5260 
5261     case Instruction::ExtractValue:
5262     case Instruction::ExtractElement: {
5263       // The common cost of removal ExtractElement/ExtractValue instructions +
5264       // the cost of shuffles, if required to resuffle the original vector.
5265       if (NeedToShuffleReuses) {
5266         unsigned Idx = 0;
5267         for (unsigned I : E->ReuseShuffleIndices) {
5268           if (ShuffleOrOp == Instruction::ExtractElement) {
5269             auto *EE = cast<ExtractElementInst>(VL[I]);
5270             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5271                                                   EE->getVectorOperandType(),
5272                                                   *getExtractIndex(EE));
5273           } else {
5274             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5275                                                   VecTy, Idx);
5276             ++Idx;
5277           }
5278         }
5279         Idx = EntryVF;
5280         for (Value *V : VL) {
5281           if (ShuffleOrOp == Instruction::ExtractElement) {
5282             auto *EE = cast<ExtractElementInst>(V);
5283             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5284                                                   EE->getVectorOperandType(),
5285                                                   *getExtractIndex(EE));
5286           } else {
5287             --Idx;
5288             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5289                                                   VecTy, Idx);
5290           }
5291         }
5292       }
5293       if (ShuffleOrOp == Instruction::ExtractValue) {
5294         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5295           auto *EI = cast<Instruction>(VL[I]);
5296           // Take credit for instruction that will become dead.
5297           if (EI->hasOneUse()) {
5298             Instruction *Ext = EI->user_back();
5299             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5300                 all_of(Ext->users(),
5301                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5302               // Use getExtractWithExtendCost() to calculate the cost of
5303               // extractelement/ext pair.
5304               CommonCost -= TTI->getExtractWithExtendCost(
5305                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5306               // Add back the cost of s|zext which is subtracted separately.
5307               CommonCost += TTI->getCastInstrCost(
5308                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5309                   TTI::getCastContextHint(Ext), CostKind, Ext);
5310               continue;
5311             }
5312           }
5313           CommonCost -=
5314               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5315         }
5316       } else {
5317         AdjustExtractsCost(CommonCost);
5318       }
5319       return CommonCost;
5320     }
5321     case Instruction::InsertElement: {
5322       assert(E->ReuseShuffleIndices.empty() &&
5323              "Unique insertelements only are expected.");
5324       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5325 
5326       unsigned const NumElts = SrcVecTy->getNumElements();
5327       unsigned const NumScalars = VL.size();
5328       APInt DemandedElts = APInt::getZero(NumElts);
5329       // TODO: Add support for Instruction::InsertValue.
5330       SmallVector<int> Mask;
5331       if (!E->ReorderIndices.empty()) {
5332         inversePermutation(E->ReorderIndices, Mask);
5333         Mask.append(NumElts - NumScalars, UndefMaskElem);
5334       } else {
5335         Mask.assign(NumElts, UndefMaskElem);
5336         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5337       }
5338       unsigned Offset = *getInsertIndex(VL0);
5339       bool IsIdentity = true;
5340       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5341       Mask.swap(PrevMask);
5342       for (unsigned I = 0; I < NumScalars; ++I) {
5343         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5344         DemandedElts.setBit(InsertIdx);
5345         IsIdentity &= InsertIdx - Offset == I;
5346         Mask[InsertIdx - Offset] = I;
5347       }
5348       assert(Offset < NumElts && "Failed to find vector index offset");
5349 
5350       InstructionCost Cost = 0;
5351       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5352                                             /*Insert*/ true, /*Extract*/ false);
5353 
5354       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5355         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5356         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5357         Cost += TTI->getShuffleCost(
5358             TargetTransformInfo::SK_PermuteSingleSrc,
5359             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5360       } else if (!IsIdentity) {
5361         auto *FirstInsert =
5362             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5363               return !is_contained(E->Scalars,
5364                                    cast<Instruction>(V)->getOperand(0));
5365             }));
5366         if (isUndefVector(FirstInsert->getOperand(0))) {
5367           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5368         } else {
5369           SmallVector<int> InsertMask(NumElts);
5370           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5371           for (unsigned I = 0; I < NumElts; I++) {
5372             if (Mask[I] != UndefMaskElem)
5373               InsertMask[Offset + I] = NumElts + I;
5374           }
5375           Cost +=
5376               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5377         }
5378       }
5379 
5380       return Cost;
5381     }
5382     case Instruction::ZExt:
5383     case Instruction::SExt:
5384     case Instruction::FPToUI:
5385     case Instruction::FPToSI:
5386     case Instruction::FPExt:
5387     case Instruction::PtrToInt:
5388     case Instruction::IntToPtr:
5389     case Instruction::SIToFP:
5390     case Instruction::UIToFP:
5391     case Instruction::Trunc:
5392     case Instruction::FPTrunc:
5393     case Instruction::BitCast: {
5394       Type *SrcTy = VL0->getOperand(0)->getType();
5395       InstructionCost ScalarEltCost =
5396           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5397                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5398       if (NeedToShuffleReuses) {
5399         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5400       }
5401 
5402       // Calculate the cost of this instruction.
5403       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5404 
5405       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5406       InstructionCost VecCost = 0;
5407       // Check if the values are candidates to demote.
5408       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5409         VecCost = CommonCost + TTI->getCastInstrCost(
5410                                    E->getOpcode(), VecTy, SrcVecTy,
5411                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5412       }
5413       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5414       return VecCost - ScalarCost;
5415     }
5416     case Instruction::FCmp:
5417     case Instruction::ICmp:
5418     case Instruction::Select: {
5419       // Calculate the cost of this instruction.
5420       InstructionCost ScalarEltCost =
5421           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5422                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5423       if (NeedToShuffleReuses) {
5424         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5425       }
5426       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5427       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5428 
5429       // Check if all entries in VL are either compares or selects with compares
5430       // as condition that have the same predicates.
5431       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5432       bool First = true;
5433       for (auto *V : VL) {
5434         CmpInst::Predicate CurrentPred;
5435         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5436         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5437              !match(V, MatchCmp)) ||
5438             (!First && VecPred != CurrentPred)) {
5439           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5440           break;
5441         }
5442         First = false;
5443         VecPred = CurrentPred;
5444       }
5445 
5446       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5447           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5448       // Check if it is possible and profitable to use min/max for selects in
5449       // VL.
5450       //
5451       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5452       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5453         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5454                                           {VecTy, VecTy});
5455         InstructionCost IntrinsicCost =
5456             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5457         // If the selects are the only uses of the compares, they will be dead
5458         // and we can adjust the cost by removing their cost.
5459         if (IntrinsicAndUse.second)
5460           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5461                                                    MaskTy, VecPred, CostKind);
5462         VecCost = std::min(VecCost, IntrinsicCost);
5463       }
5464       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5465       return CommonCost + VecCost - ScalarCost;
5466     }
5467     case Instruction::FNeg:
5468     case Instruction::Add:
5469     case Instruction::FAdd:
5470     case Instruction::Sub:
5471     case Instruction::FSub:
5472     case Instruction::Mul:
5473     case Instruction::FMul:
5474     case Instruction::UDiv:
5475     case Instruction::SDiv:
5476     case Instruction::FDiv:
5477     case Instruction::URem:
5478     case Instruction::SRem:
5479     case Instruction::FRem:
5480     case Instruction::Shl:
5481     case Instruction::LShr:
5482     case Instruction::AShr:
5483     case Instruction::And:
5484     case Instruction::Or:
5485     case Instruction::Xor: {
5486       // Certain instructions can be cheaper to vectorize if they have a
5487       // constant second vector operand.
5488       TargetTransformInfo::OperandValueKind Op1VK =
5489           TargetTransformInfo::OK_AnyValue;
5490       TargetTransformInfo::OperandValueKind Op2VK =
5491           TargetTransformInfo::OK_UniformConstantValue;
5492       TargetTransformInfo::OperandValueProperties Op1VP =
5493           TargetTransformInfo::OP_None;
5494       TargetTransformInfo::OperandValueProperties Op2VP =
5495           TargetTransformInfo::OP_PowerOf2;
5496 
5497       // If all operands are exactly the same ConstantInt then set the
5498       // operand kind to OK_UniformConstantValue.
5499       // If instead not all operands are constants, then set the operand kind
5500       // to OK_AnyValue. If all operands are constants but not the same,
5501       // then set the operand kind to OK_NonUniformConstantValue.
5502       ConstantInt *CInt0 = nullptr;
5503       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5504         const Instruction *I = cast<Instruction>(VL[i]);
5505         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5506         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5507         if (!CInt) {
5508           Op2VK = TargetTransformInfo::OK_AnyValue;
5509           Op2VP = TargetTransformInfo::OP_None;
5510           break;
5511         }
5512         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5513             !CInt->getValue().isPowerOf2())
5514           Op2VP = TargetTransformInfo::OP_None;
5515         if (i == 0) {
5516           CInt0 = CInt;
5517           continue;
5518         }
5519         if (CInt0 != CInt)
5520           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5521       }
5522 
5523       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5524       InstructionCost ScalarEltCost =
5525           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5526                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5527       if (NeedToShuffleReuses) {
5528         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5529       }
5530       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5531       InstructionCost VecCost =
5532           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5533                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5534       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5535       return CommonCost + VecCost - ScalarCost;
5536     }
5537     case Instruction::GetElementPtr: {
5538       TargetTransformInfo::OperandValueKind Op1VK =
5539           TargetTransformInfo::OK_AnyValue;
5540       TargetTransformInfo::OperandValueKind Op2VK =
5541           TargetTransformInfo::OK_UniformConstantValue;
5542 
5543       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5544           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5545       if (NeedToShuffleReuses) {
5546         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5547       }
5548       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5549       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5550           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5551       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5552       return CommonCost + VecCost - ScalarCost;
5553     }
5554     case Instruction::Load: {
5555       // Cost of wide load - cost of scalar loads.
5556       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5557       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5558           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5559       if (NeedToShuffleReuses) {
5560         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5561       }
5562       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5563       InstructionCost VecLdCost;
5564       if (E->State == TreeEntry::Vectorize) {
5565         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5566                                          CostKind, VL0);
5567       } else {
5568         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5569         Align CommonAlignment = Alignment;
5570         for (Value *V : VL)
5571           CommonAlignment =
5572               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5573         VecLdCost = TTI->getGatherScatterOpCost(
5574             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5575             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5576       }
5577       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5578       return CommonCost + VecLdCost - ScalarLdCost;
5579     }
5580     case Instruction::Store: {
5581       // We know that we can merge the stores. Calculate the cost.
5582       bool IsReorder = !E->ReorderIndices.empty();
5583       auto *SI =
5584           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5585       Align Alignment = SI->getAlign();
5586       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5587           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5588       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5589       InstructionCost VecStCost = TTI->getMemoryOpCost(
5590           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5591       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5592       return CommonCost + VecStCost - ScalarStCost;
5593     }
5594     case Instruction::Call: {
5595       CallInst *CI = cast<CallInst>(VL0);
5596       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5597 
5598       // Calculate the cost of the scalar and vector calls.
5599       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5600       InstructionCost ScalarEltCost =
5601           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5602       if (NeedToShuffleReuses) {
5603         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5604       }
5605       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5606 
5607       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5608       InstructionCost VecCallCost =
5609           std::min(VecCallCosts.first, VecCallCosts.second);
5610 
5611       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5612                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5613                         << " for " << *CI << "\n");
5614 
5615       return CommonCost + VecCallCost - ScalarCallCost;
5616     }
5617     case Instruction::ShuffleVector: {
5618       assert(E->isAltShuffle() &&
5619              ((Instruction::isBinaryOp(E->getOpcode()) &&
5620                Instruction::isBinaryOp(E->getAltOpcode())) ||
5621               (Instruction::isCast(E->getOpcode()) &&
5622                Instruction::isCast(E->getAltOpcode())) ||
5623               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5624              "Invalid Shuffle Vector Operand");
5625       InstructionCost ScalarCost = 0;
5626       if (NeedToShuffleReuses) {
5627         for (unsigned Idx : E->ReuseShuffleIndices) {
5628           Instruction *I = cast<Instruction>(VL[Idx]);
5629           CommonCost -= TTI->getInstructionCost(I, CostKind);
5630         }
5631         for (Value *V : VL) {
5632           Instruction *I = cast<Instruction>(V);
5633           CommonCost += TTI->getInstructionCost(I, CostKind);
5634         }
5635       }
5636       for (Value *V : VL) {
5637         Instruction *I = cast<Instruction>(V);
5638         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5639         ScalarCost += TTI->getInstructionCost(I, CostKind);
5640       }
5641       // VecCost is equal to sum of the cost of creating 2 vectors
5642       // and the cost of creating shuffle.
5643       InstructionCost VecCost = 0;
5644       // Try to find the previous shuffle node with the same operands and same
5645       // main/alternate ops.
5646       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5647         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5648           if (TE.get() == E)
5649             break;
5650           if (TE->isAltShuffle() &&
5651               ((TE->getOpcode() == E->getOpcode() &&
5652                 TE->getAltOpcode() == E->getAltOpcode()) ||
5653                (TE->getOpcode() == E->getAltOpcode() &&
5654                 TE->getAltOpcode() == E->getOpcode())) &&
5655               TE->hasEqualOperands(*E))
5656             return true;
5657         }
5658         return false;
5659       };
5660       if (TryFindNodeWithEqualOperands()) {
5661         LLVM_DEBUG({
5662           dbgs() << "SLP: diamond match for alternate node found.\n";
5663           E->dump();
5664         });
5665         // No need to add new vector costs here since we're going to reuse
5666         // same main/alternate vector ops, just do different shuffling.
5667       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5668         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5669         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5670                                                CostKind);
5671       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5672         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5673                                           Builder.getInt1Ty(),
5674                                           CI0->getPredicate(), CostKind, VL0);
5675         VecCost += TTI->getCmpSelInstrCost(
5676             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5677             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5678             E->getAltOp());
5679       } else {
5680         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5681         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5682         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5683         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5684         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5685                                         TTI::CastContextHint::None, CostKind);
5686         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5687                                          TTI::CastContextHint::None, CostKind);
5688       }
5689 
5690       SmallVector<int> Mask;
5691       buildShuffleEntryMask(
5692           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5693           [E](Instruction *I) {
5694             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5695             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5696           },
5697           Mask);
5698       CommonCost =
5699           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5700       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5701       return CommonCost + VecCost - ScalarCost;
5702     }
5703     default:
5704       llvm_unreachable("Unknown instruction");
5705   }
5706 }
5707 
5708 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5709   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5710                     << VectorizableTree.size() << " is fully vectorizable .\n");
5711 
5712   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5713     SmallVector<int> Mask;
5714     return TE->State == TreeEntry::NeedToGather &&
5715            !any_of(TE->Scalars,
5716                    [this](Value *V) { return EphValues.contains(V); }) &&
5717            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5718             TE->Scalars.size() < Limit ||
5719             ((TE->getOpcode() == Instruction::ExtractElement ||
5720               all_of(TE->Scalars,
5721                      [](Value *V) {
5722                        return isa<ExtractElementInst, UndefValue>(V);
5723                      })) &&
5724              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5725             (TE->State == TreeEntry::NeedToGather &&
5726              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5727   };
5728 
5729   // We only handle trees of heights 1 and 2.
5730   if (VectorizableTree.size() == 1 &&
5731       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5732        (ForReduction &&
5733         AreVectorizableGathers(VectorizableTree[0].get(),
5734                                VectorizableTree[0]->Scalars.size()) &&
5735         VectorizableTree[0]->getVectorFactor() > 2)))
5736     return true;
5737 
5738   if (VectorizableTree.size() != 2)
5739     return false;
5740 
5741   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5742   // with the second gather nodes if they have less scalar operands rather than
5743   // the initial tree element (may be profitable to shuffle the second gather)
5744   // or they are extractelements, which form shuffle.
5745   SmallVector<int> Mask;
5746   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5747       AreVectorizableGathers(VectorizableTree[1].get(),
5748                              VectorizableTree[0]->Scalars.size()))
5749     return true;
5750 
5751   // Gathering cost would be too much for tiny trees.
5752   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5753       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5754        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5755     return false;
5756 
5757   return true;
5758 }
5759 
5760 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5761                                        TargetTransformInfo *TTI,
5762                                        bool MustMatchOrInst) {
5763   // Look past the root to find a source value. Arbitrarily follow the
5764   // path through operand 0 of any 'or'. Also, peek through optional
5765   // shift-left-by-multiple-of-8-bits.
5766   Value *ZextLoad = Root;
5767   const APInt *ShAmtC;
5768   bool FoundOr = false;
5769   while (!isa<ConstantExpr>(ZextLoad) &&
5770          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5771           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5772            ShAmtC->urem(8) == 0))) {
5773     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5774     ZextLoad = BinOp->getOperand(0);
5775     if (BinOp->getOpcode() == Instruction::Or)
5776       FoundOr = true;
5777   }
5778   // Check if the input is an extended load of the required or/shift expression.
5779   Value *Load;
5780   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5781       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5782     return false;
5783 
5784   // Require that the total load bit width is a legal integer type.
5785   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5786   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5787   Type *SrcTy = Load->getType();
5788   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5789   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5790     return false;
5791 
5792   // Everything matched - assume that we can fold the whole sequence using
5793   // load combining.
5794   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5795              << *(cast<Instruction>(Root)) << "\n");
5796 
5797   return true;
5798 }
5799 
5800 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5801   if (RdxKind != RecurKind::Or)
5802     return false;
5803 
5804   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5805   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5806   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5807                                     /* MatchOr */ false);
5808 }
5809 
5810 bool BoUpSLP::isLoadCombineCandidate() const {
5811   // Peek through a final sequence of stores and check if all operations are
5812   // likely to be load-combined.
5813   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5814   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5815     Value *X;
5816     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5817         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5818       return false;
5819   }
5820   return true;
5821 }
5822 
5823 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5824   // No need to vectorize inserts of gathered values.
5825   if (VectorizableTree.size() == 2 &&
5826       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5827       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5828     return true;
5829 
5830   // We can vectorize the tree if its size is greater than or equal to the
5831   // minimum size specified by the MinTreeSize command line option.
5832   if (VectorizableTree.size() >= MinTreeSize)
5833     return false;
5834 
5835   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5836   // can vectorize it if we can prove it fully vectorizable.
5837   if (isFullyVectorizableTinyTree(ForReduction))
5838     return false;
5839 
5840   assert(VectorizableTree.empty()
5841              ? ExternalUses.empty()
5842              : true && "We shouldn't have any external users");
5843 
5844   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5845   // vectorizable.
5846   return true;
5847 }
5848 
5849 InstructionCost BoUpSLP::getSpillCost() const {
5850   // Walk from the bottom of the tree to the top, tracking which values are
5851   // live. When we see a call instruction that is not part of our tree,
5852   // query TTI to see if there is a cost to keeping values live over it
5853   // (for example, if spills and fills are required).
5854   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5855   InstructionCost Cost = 0;
5856 
5857   SmallPtrSet<Instruction*, 4> LiveValues;
5858   Instruction *PrevInst = nullptr;
5859 
5860   // The entries in VectorizableTree are not necessarily ordered by their
5861   // position in basic blocks. Collect them and order them by dominance so later
5862   // instructions are guaranteed to be visited first. For instructions in
5863   // different basic blocks, we only scan to the beginning of the block, so
5864   // their order does not matter, as long as all instructions in a basic block
5865   // are grouped together. Using dominance ensures a deterministic order.
5866   SmallVector<Instruction *, 16> OrderedScalars;
5867   for (const auto &TEPtr : VectorizableTree) {
5868     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5869     if (!Inst)
5870       continue;
5871     OrderedScalars.push_back(Inst);
5872   }
5873   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5874     auto *NodeA = DT->getNode(A->getParent());
5875     auto *NodeB = DT->getNode(B->getParent());
5876     assert(NodeA && "Should only process reachable instructions");
5877     assert(NodeB && "Should only process reachable instructions");
5878     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5879            "Different nodes should have different DFS numbers");
5880     if (NodeA != NodeB)
5881       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5882     return B->comesBefore(A);
5883   });
5884 
5885   for (Instruction *Inst : OrderedScalars) {
5886     if (!PrevInst) {
5887       PrevInst = Inst;
5888       continue;
5889     }
5890 
5891     // Update LiveValues.
5892     LiveValues.erase(PrevInst);
5893     for (auto &J : PrevInst->operands()) {
5894       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5895         LiveValues.insert(cast<Instruction>(&*J));
5896     }
5897 
5898     LLVM_DEBUG({
5899       dbgs() << "SLP: #LV: " << LiveValues.size();
5900       for (auto *X : LiveValues)
5901         dbgs() << " " << X->getName();
5902       dbgs() << ", Looking at ";
5903       Inst->dump();
5904     });
5905 
5906     // Now find the sequence of instructions between PrevInst and Inst.
5907     unsigned NumCalls = 0;
5908     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5909                                  PrevInstIt =
5910                                      PrevInst->getIterator().getReverse();
5911     while (InstIt != PrevInstIt) {
5912       if (PrevInstIt == PrevInst->getParent()->rend()) {
5913         PrevInstIt = Inst->getParent()->rbegin();
5914         continue;
5915       }
5916 
5917       // Debug information does not impact spill cost.
5918       if ((isa<CallInst>(&*PrevInstIt) &&
5919            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5920           &*PrevInstIt != PrevInst)
5921         NumCalls++;
5922 
5923       ++PrevInstIt;
5924     }
5925 
5926     if (NumCalls) {
5927       SmallVector<Type*, 4> V;
5928       for (auto *II : LiveValues) {
5929         auto *ScalarTy = II->getType();
5930         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5931           ScalarTy = VectorTy->getElementType();
5932         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5933       }
5934       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5935     }
5936 
5937     PrevInst = Inst;
5938   }
5939 
5940   return Cost;
5941 }
5942 
5943 /// Check if two insertelement instructions are from the same buildvector.
5944 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5945                                             InsertElementInst *V) {
5946   // Instructions must be from the same basic blocks.
5947   if (VU->getParent() != V->getParent())
5948     return false;
5949   // Checks if 2 insertelements are from the same buildvector.
5950   if (VU->getType() != V->getType())
5951     return false;
5952   // Multiple used inserts are separate nodes.
5953   if (!VU->hasOneUse() && !V->hasOneUse())
5954     return false;
5955   auto *IE1 = VU;
5956   auto *IE2 = V;
5957   // Go through the vector operand of insertelement instructions trying to find
5958   // either VU as the original vector for IE2 or V as the original vector for
5959   // IE1.
5960   do {
5961     if (IE2 == VU || IE1 == V)
5962       return true;
5963     if (IE1) {
5964       if (IE1 != VU && !IE1->hasOneUse())
5965         IE1 = nullptr;
5966       else
5967         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5968     }
5969     if (IE2) {
5970       if (IE2 != V && !IE2->hasOneUse())
5971         IE2 = nullptr;
5972       else
5973         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5974     }
5975   } while (IE1 || IE2);
5976   return false;
5977 }
5978 
5979 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5980   InstructionCost Cost = 0;
5981   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5982                     << VectorizableTree.size() << ".\n");
5983 
5984   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5985 
5986   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5987     TreeEntry &TE = *VectorizableTree[I].get();
5988 
5989     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5990     Cost += C;
5991     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5992                       << " for bundle that starts with " << *TE.Scalars[0]
5993                       << ".\n"
5994                       << "SLP: Current total cost = " << Cost << "\n");
5995   }
5996 
5997   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5998   InstructionCost ExtractCost = 0;
5999   SmallVector<unsigned> VF;
6000   SmallVector<SmallVector<int>> ShuffleMask;
6001   SmallVector<Value *> FirstUsers;
6002   SmallVector<APInt> DemandedElts;
6003   for (ExternalUser &EU : ExternalUses) {
6004     // We only add extract cost once for the same scalar.
6005     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6006         !ExtractCostCalculated.insert(EU.Scalar).second)
6007       continue;
6008 
6009     // Uses by ephemeral values are free (because the ephemeral value will be
6010     // removed prior to code generation, and so the extraction will be
6011     // removed as well).
6012     if (EphValues.count(EU.User))
6013       continue;
6014 
6015     // No extract cost for vector "scalar"
6016     if (isa<FixedVectorType>(EU.Scalar->getType()))
6017       continue;
6018 
6019     // Already counted the cost for external uses when tried to adjust the cost
6020     // for extractelements, no need to add it again.
6021     if (isa<ExtractElementInst>(EU.Scalar))
6022       continue;
6023 
6024     // If found user is an insertelement, do not calculate extract cost but try
6025     // to detect it as a final shuffled/identity match.
6026     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6027       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6028         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6029         if (InsertIdx) {
6030           auto *It = find_if(FirstUsers, [VU](Value *V) {
6031             return areTwoInsertFromSameBuildVector(VU,
6032                                                    cast<InsertElementInst>(V));
6033           });
6034           int VecId = -1;
6035           if (It == FirstUsers.end()) {
6036             VF.push_back(FTy->getNumElements());
6037             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6038             // Find the insertvector, vectorized in tree, if any.
6039             Value *Base = VU;
6040             while (isa<InsertElementInst>(Base)) {
6041               // Build the mask for the vectorized insertelement instructions.
6042               if (const TreeEntry *E = getTreeEntry(Base)) {
6043                 VU = cast<InsertElementInst>(Base);
6044                 do {
6045                   int Idx = E->findLaneForValue(Base);
6046                   ShuffleMask.back()[Idx] = Idx;
6047                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6048                 } while (E == getTreeEntry(Base));
6049                 break;
6050               }
6051               Base = cast<InsertElementInst>(Base)->getOperand(0);
6052             }
6053             FirstUsers.push_back(VU);
6054             DemandedElts.push_back(APInt::getZero(VF.back()));
6055             VecId = FirstUsers.size() - 1;
6056           } else {
6057             VecId = std::distance(FirstUsers.begin(), It);
6058           }
6059           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6060           DemandedElts[VecId].setBit(*InsertIdx);
6061           continue;
6062         }
6063       }
6064     }
6065 
6066     // If we plan to rewrite the tree in a smaller type, we will need to sign
6067     // extend the extracted value back to the original type. Here, we account
6068     // for the extract and the added cost of the sign extend if needed.
6069     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6070     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6071     if (MinBWs.count(ScalarRoot)) {
6072       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6073       auto Extend =
6074           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6075       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6076       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6077                                                    VecTy, EU.Lane);
6078     } else {
6079       ExtractCost +=
6080           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6081     }
6082   }
6083 
6084   InstructionCost SpillCost = getSpillCost();
6085   Cost += SpillCost + ExtractCost;
6086   if (FirstUsers.size() == 1) {
6087     int Limit = ShuffleMask.front().size() * 2;
6088     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6089         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6090       InstructionCost C = TTI->getShuffleCost(
6091           TTI::SK_PermuteSingleSrc,
6092           cast<FixedVectorType>(FirstUsers.front()->getType()),
6093           ShuffleMask.front());
6094       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6095                         << " for final shuffle of insertelement external users "
6096                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6097                         << "SLP: Current total cost = " << Cost << "\n");
6098       Cost += C;
6099     }
6100     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6101         cast<FixedVectorType>(FirstUsers.front()->getType()),
6102         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6103     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6104                       << " for insertelements gather.\n"
6105                       << "SLP: Current total cost = " << Cost << "\n");
6106     Cost -= InsertCost;
6107   } else if (FirstUsers.size() >= 2) {
6108     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6109     // Combined masks of the first 2 vectors.
6110     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6111     copy(ShuffleMask.front(), CombinedMask.begin());
6112     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6113     auto *VecTy = FixedVectorType::get(
6114         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6115         MaxVF);
6116     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6117       if (ShuffleMask[1][I] != UndefMaskElem) {
6118         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6119         CombinedDemandedElts.setBit(I);
6120       }
6121     }
6122     InstructionCost C =
6123         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6124     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6125                       << " for final shuffle of vector node and external "
6126                          "insertelement users "
6127                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6128                       << "SLP: Current total cost = " << Cost << "\n");
6129     Cost += C;
6130     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6131         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6132     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6133                       << " for insertelements gather.\n"
6134                       << "SLP: Current total cost = " << Cost << "\n");
6135     Cost -= InsertCost;
6136     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6137       // Other elements - permutation of 2 vectors (the initial one and the
6138       // next Ith incoming vector).
6139       unsigned VF = ShuffleMask[I].size();
6140       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6141         int Mask = ShuffleMask[I][Idx];
6142         if (Mask != UndefMaskElem)
6143           CombinedMask[Idx] = MaxVF + Mask;
6144         else if (CombinedMask[Idx] != UndefMaskElem)
6145           CombinedMask[Idx] = Idx;
6146       }
6147       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6148         if (CombinedMask[Idx] != UndefMaskElem)
6149           CombinedMask[Idx] = Idx;
6150       InstructionCost C =
6151           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6152       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6153                         << " for final shuffle of vector node and external "
6154                            "insertelement users "
6155                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6156                         << "SLP: Current total cost = " << Cost << "\n");
6157       Cost += C;
6158       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6159           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6160           /*Insert*/ true, /*Extract*/ false);
6161       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6162                         << " for insertelements gather.\n"
6163                         << "SLP: Current total cost = " << Cost << "\n");
6164       Cost -= InsertCost;
6165     }
6166   }
6167 
6168 #ifndef NDEBUG
6169   SmallString<256> Str;
6170   {
6171     raw_svector_ostream OS(Str);
6172     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6173        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6174        << "SLP: Total Cost = " << Cost << ".\n";
6175   }
6176   LLVM_DEBUG(dbgs() << Str);
6177   if (ViewSLPTree)
6178     ViewGraph(this, "SLP" + F->getName(), false, Str);
6179 #endif
6180 
6181   return Cost;
6182 }
6183 
6184 Optional<TargetTransformInfo::ShuffleKind>
6185 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6186                                SmallVectorImpl<const TreeEntry *> &Entries) {
6187   // TODO: currently checking only for Scalars in the tree entry, need to count
6188   // reused elements too for better cost estimation.
6189   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6190   Entries.clear();
6191   // Build a lists of values to tree entries.
6192   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6193   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6194     if (EntryPtr.get() == TE)
6195       break;
6196     if (EntryPtr->State != TreeEntry::NeedToGather)
6197       continue;
6198     for (Value *V : EntryPtr->Scalars)
6199       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6200   }
6201   // Find all tree entries used by the gathered values. If no common entries
6202   // found - not a shuffle.
6203   // Here we build a set of tree nodes for each gathered value and trying to
6204   // find the intersection between these sets. If we have at least one common
6205   // tree node for each gathered value - we have just a permutation of the
6206   // single vector. If we have 2 different sets, we're in situation where we
6207   // have a permutation of 2 input vectors.
6208   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6209   DenseMap<Value *, int> UsedValuesEntry;
6210   for (Value *V : TE->Scalars) {
6211     if (isa<UndefValue>(V))
6212       continue;
6213     // Build a list of tree entries where V is used.
6214     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6215     auto It = ValueToTEs.find(V);
6216     if (It != ValueToTEs.end())
6217       VToTEs = It->second;
6218     if (const TreeEntry *VTE = getTreeEntry(V))
6219       VToTEs.insert(VTE);
6220     if (VToTEs.empty())
6221       return None;
6222     if (UsedTEs.empty()) {
6223       // The first iteration, just insert the list of nodes to vector.
6224       UsedTEs.push_back(VToTEs);
6225     } else {
6226       // Need to check if there are any previously used tree nodes which use V.
6227       // If there are no such nodes, consider that we have another one input
6228       // vector.
6229       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6230       unsigned Idx = 0;
6231       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6232         // Do we have a non-empty intersection of previously listed tree entries
6233         // and tree entries using current V?
6234         set_intersect(VToTEs, Set);
6235         if (!VToTEs.empty()) {
6236           // Yes, write the new subset and continue analysis for the next
6237           // scalar.
6238           Set.swap(VToTEs);
6239           break;
6240         }
6241         VToTEs = SavedVToTEs;
6242         ++Idx;
6243       }
6244       // No non-empty intersection found - need to add a second set of possible
6245       // source vectors.
6246       if (Idx == UsedTEs.size()) {
6247         // If the number of input vectors is greater than 2 - not a permutation,
6248         // fallback to the regular gather.
6249         if (UsedTEs.size() == 2)
6250           return None;
6251         UsedTEs.push_back(SavedVToTEs);
6252         Idx = UsedTEs.size() - 1;
6253       }
6254       UsedValuesEntry.try_emplace(V, Idx);
6255     }
6256   }
6257 
6258   unsigned VF = 0;
6259   if (UsedTEs.size() == 1) {
6260     // Try to find the perfect match in another gather node at first.
6261     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6262       return EntryPtr->isSame(TE->Scalars);
6263     });
6264     if (It != UsedTEs.front().end()) {
6265       Entries.push_back(*It);
6266       std::iota(Mask.begin(), Mask.end(), 0);
6267       return TargetTransformInfo::SK_PermuteSingleSrc;
6268     }
6269     // No perfect match, just shuffle, so choose the first tree node.
6270     Entries.push_back(*UsedTEs.front().begin());
6271   } else {
6272     // Try to find nodes with the same vector factor.
6273     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6274     DenseMap<int, const TreeEntry *> VFToTE;
6275     for (const TreeEntry *TE : UsedTEs.front())
6276       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6277     for (const TreeEntry *TE : UsedTEs.back()) {
6278       auto It = VFToTE.find(TE->getVectorFactor());
6279       if (It != VFToTE.end()) {
6280         VF = It->first;
6281         Entries.push_back(It->second);
6282         Entries.push_back(TE);
6283         break;
6284       }
6285     }
6286     // No 2 source vectors with the same vector factor - give up and do regular
6287     // gather.
6288     if (Entries.empty())
6289       return None;
6290   }
6291 
6292   // Build a shuffle mask for better cost estimation and vector emission.
6293   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6294     Value *V = TE->Scalars[I];
6295     if (isa<UndefValue>(V))
6296       continue;
6297     unsigned Idx = UsedValuesEntry.lookup(V);
6298     const TreeEntry *VTE = Entries[Idx];
6299     int FoundLane = VTE->findLaneForValue(V);
6300     Mask[I] = Idx * VF + FoundLane;
6301     // Extra check required by isSingleSourceMaskImpl function (called by
6302     // ShuffleVectorInst::isSingleSourceMask).
6303     if (Mask[I] >= 2 * E)
6304       return None;
6305   }
6306   switch (Entries.size()) {
6307   case 1:
6308     return TargetTransformInfo::SK_PermuteSingleSrc;
6309   case 2:
6310     return TargetTransformInfo::SK_PermuteTwoSrc;
6311   default:
6312     break;
6313   }
6314   return None;
6315 }
6316 
6317 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6318                                        const APInt &ShuffledIndices,
6319                                        bool NeedToShuffle) const {
6320   InstructionCost Cost =
6321       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6322                                     /*Extract*/ false);
6323   if (NeedToShuffle)
6324     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6325   return Cost;
6326 }
6327 
6328 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6329   // Find the type of the operands in VL.
6330   Type *ScalarTy = VL[0]->getType();
6331   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6332     ScalarTy = SI->getValueOperand()->getType();
6333   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6334   bool DuplicateNonConst = false;
6335   // Find the cost of inserting/extracting values from the vector.
6336   // Check if the same elements are inserted several times and count them as
6337   // shuffle candidates.
6338   APInt ShuffledElements = APInt::getZero(VL.size());
6339   DenseSet<Value *> UniqueElements;
6340   // Iterate in reverse order to consider insert elements with the high cost.
6341   for (unsigned I = VL.size(); I > 0; --I) {
6342     unsigned Idx = I - 1;
6343     // No need to shuffle duplicates for constants.
6344     if (isConstant(VL[Idx])) {
6345       ShuffledElements.setBit(Idx);
6346       continue;
6347     }
6348     if (!UniqueElements.insert(VL[Idx]).second) {
6349       DuplicateNonConst = true;
6350       ShuffledElements.setBit(Idx);
6351     }
6352   }
6353   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6354 }
6355 
6356 // Perform operand reordering on the instructions in VL and return the reordered
6357 // operands in Left and Right.
6358 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6359                                              SmallVectorImpl<Value *> &Left,
6360                                              SmallVectorImpl<Value *> &Right,
6361                                              const DataLayout &DL,
6362                                              ScalarEvolution &SE,
6363                                              const BoUpSLP &R) {
6364   if (VL.empty())
6365     return;
6366   VLOperands Ops(VL, DL, SE, R);
6367   // Reorder the operands in place.
6368   Ops.reorder();
6369   Left = Ops.getVL(0);
6370   Right = Ops.getVL(1);
6371 }
6372 
6373 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6374   // Get the basic block this bundle is in. All instructions in the bundle
6375   // should be in this block.
6376   auto *Front = E->getMainOp();
6377   auto *BB = Front->getParent();
6378   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6379     auto *I = cast<Instruction>(V);
6380     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6381   }));
6382 
6383   // The last instruction in the bundle in program order.
6384   Instruction *LastInst = nullptr;
6385 
6386   // Find the last instruction. The common case should be that BB has been
6387   // scheduled, and the last instruction is VL.back(). So we start with
6388   // VL.back() and iterate over schedule data until we reach the end of the
6389   // bundle. The end of the bundle is marked by null ScheduleData.
6390   if (BlocksSchedules.count(BB)) {
6391     auto *Bundle =
6392         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6393     if (Bundle && Bundle->isPartOfBundle())
6394       for (; Bundle; Bundle = Bundle->NextInBundle)
6395         if (Bundle->OpValue == Bundle->Inst)
6396           LastInst = Bundle->Inst;
6397   }
6398 
6399   // LastInst can still be null at this point if there's either not an entry
6400   // for BB in BlocksSchedules or there's no ScheduleData available for
6401   // VL.back(). This can be the case if buildTree_rec aborts for various
6402   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6403   // size is reached, etc.). ScheduleData is initialized in the scheduling
6404   // "dry-run".
6405   //
6406   // If this happens, we can still find the last instruction by brute force. We
6407   // iterate forwards from Front (inclusive) until we either see all
6408   // instructions in the bundle or reach the end of the block. If Front is the
6409   // last instruction in program order, LastInst will be set to Front, and we
6410   // will visit all the remaining instructions in the block.
6411   //
6412   // One of the reasons we exit early from buildTree_rec is to place an upper
6413   // bound on compile-time. Thus, taking an additional compile-time hit here is
6414   // not ideal. However, this should be exceedingly rare since it requires that
6415   // we both exit early from buildTree_rec and that the bundle be out-of-order
6416   // (causing us to iterate all the way to the end of the block).
6417   if (!LastInst) {
6418     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6419     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6420       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6421         LastInst = &I;
6422       if (Bundle.empty())
6423         break;
6424     }
6425   }
6426   assert(LastInst && "Failed to find last instruction in bundle");
6427 
6428   // Set the insertion point after the last instruction in the bundle. Set the
6429   // debug location to Front.
6430   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6431   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6432 }
6433 
6434 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6435   // List of instructions/lanes from current block and/or the blocks which are
6436   // part of the current loop. These instructions will be inserted at the end to
6437   // make it possible to optimize loops and hoist invariant instructions out of
6438   // the loops body with better chances for success.
6439   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6440   SmallSet<int, 4> PostponedIndices;
6441   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6442   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6443     SmallPtrSet<BasicBlock *, 4> Visited;
6444     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6445       InsertBB = InsertBB->getSinglePredecessor();
6446     return InsertBB && InsertBB == InstBB;
6447   };
6448   for (int I = 0, E = VL.size(); I < E; ++I) {
6449     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6450       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6451            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6452           PostponedIndices.insert(I).second)
6453         PostponedInsts.emplace_back(Inst, I);
6454   }
6455 
6456   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6457     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6458     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6459     if (!InsElt)
6460       return Vec;
6461     GatherShuffleSeq.insert(InsElt);
6462     CSEBlocks.insert(InsElt->getParent());
6463     // Add to our 'need-to-extract' list.
6464     if (TreeEntry *Entry = getTreeEntry(V)) {
6465       // Find which lane we need to extract.
6466       unsigned FoundLane = Entry->findLaneForValue(V);
6467       ExternalUses.emplace_back(V, InsElt, FoundLane);
6468     }
6469     return Vec;
6470   };
6471   Value *Val0 =
6472       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6473   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6474   Value *Vec = PoisonValue::get(VecTy);
6475   SmallVector<int> NonConsts;
6476   // Insert constant values at first.
6477   for (int I = 0, E = VL.size(); I < E; ++I) {
6478     if (PostponedIndices.contains(I))
6479       continue;
6480     if (!isConstant(VL[I])) {
6481       NonConsts.push_back(I);
6482       continue;
6483     }
6484     Vec = CreateInsertElement(Vec, VL[I], I);
6485   }
6486   // Insert non-constant values.
6487   for (int I : NonConsts)
6488     Vec = CreateInsertElement(Vec, VL[I], I);
6489   // Append instructions, which are/may be part of the loop, in the end to make
6490   // it possible to hoist non-loop-based instructions.
6491   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6492     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6493 
6494   return Vec;
6495 }
6496 
6497 namespace {
6498 /// Merges shuffle masks and emits final shuffle instruction, if required.
6499 class ShuffleInstructionBuilder {
6500   IRBuilderBase &Builder;
6501   const unsigned VF = 0;
6502   bool IsFinalized = false;
6503   SmallVector<int, 4> Mask;
6504   /// Holds all of the instructions that we gathered.
6505   SetVector<Instruction *> &GatherShuffleSeq;
6506   /// A list of blocks that we are going to CSE.
6507   SetVector<BasicBlock *> &CSEBlocks;
6508 
6509 public:
6510   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6511                             SetVector<Instruction *> &GatherShuffleSeq,
6512                             SetVector<BasicBlock *> &CSEBlocks)
6513       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6514         CSEBlocks(CSEBlocks) {}
6515 
6516   /// Adds a mask, inverting it before applying.
6517   void addInversedMask(ArrayRef<unsigned> SubMask) {
6518     if (SubMask.empty())
6519       return;
6520     SmallVector<int, 4> NewMask;
6521     inversePermutation(SubMask, NewMask);
6522     addMask(NewMask);
6523   }
6524 
6525   /// Functions adds masks, merging them into  single one.
6526   void addMask(ArrayRef<unsigned> SubMask) {
6527     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6528     addMask(NewMask);
6529   }
6530 
6531   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6532 
6533   Value *finalize(Value *V) {
6534     IsFinalized = true;
6535     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6536     if (VF == ValueVF && Mask.empty())
6537       return V;
6538     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6539     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6540     addMask(NormalizedMask);
6541 
6542     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6543       return V;
6544     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6545     if (auto *I = dyn_cast<Instruction>(Vec)) {
6546       GatherShuffleSeq.insert(I);
6547       CSEBlocks.insert(I->getParent());
6548     }
6549     return Vec;
6550   }
6551 
6552   ~ShuffleInstructionBuilder() {
6553     assert((IsFinalized || Mask.empty()) &&
6554            "Shuffle construction must be finalized.");
6555   }
6556 };
6557 } // namespace
6558 
6559 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6560   unsigned VF = VL.size();
6561   InstructionsState S = getSameOpcode(VL);
6562   if (S.getOpcode()) {
6563     if (TreeEntry *E = getTreeEntry(S.OpValue))
6564       if (E->isSame(VL)) {
6565         Value *V = vectorizeTree(E);
6566         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6567           if (!E->ReuseShuffleIndices.empty()) {
6568             // Reshuffle to get only unique values.
6569             // If some of the scalars are duplicated in the vectorization tree
6570             // entry, we do not vectorize them but instead generate a mask for
6571             // the reuses. But if there are several users of the same entry,
6572             // they may have different vectorization factors. This is especially
6573             // important for PHI nodes. In this case, we need to adapt the
6574             // resulting instruction for the user vectorization factor and have
6575             // to reshuffle it again to take only unique elements of the vector.
6576             // Without this code the function incorrectly returns reduced vector
6577             // instruction with the same elements, not with the unique ones.
6578 
6579             // block:
6580             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6581             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6582             // ... (use %2)
6583             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6584             // br %block
6585             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6586             SmallSet<int, 4> UsedIdxs;
6587             int Pos = 0;
6588             int Sz = VL.size();
6589             for (int Idx : E->ReuseShuffleIndices) {
6590               if (Idx != Sz && Idx != UndefMaskElem &&
6591                   UsedIdxs.insert(Idx).second)
6592                 UniqueIdxs[Idx] = Pos;
6593               ++Pos;
6594             }
6595             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6596                                             "less than original vector size.");
6597             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6598             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6599           } else {
6600             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6601                    "Expected vectorization factor less "
6602                    "than original vector size.");
6603             SmallVector<int> UniformMask(VF, 0);
6604             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6605             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6606           }
6607           if (auto *I = dyn_cast<Instruction>(V)) {
6608             GatherShuffleSeq.insert(I);
6609             CSEBlocks.insert(I->getParent());
6610           }
6611         }
6612         return V;
6613       }
6614   }
6615 
6616   // Check that every instruction appears once in this bundle.
6617   SmallVector<int> ReuseShuffleIndicies;
6618   SmallVector<Value *> UniqueValues;
6619   if (VL.size() > 2) {
6620     DenseMap<Value *, unsigned> UniquePositions;
6621     unsigned NumValues =
6622         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6623                                     return !isa<UndefValue>(V);
6624                                   }).base());
6625     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6626     int UniqueVals = 0;
6627     for (Value *V : VL.drop_back(VL.size() - VF)) {
6628       if (isa<UndefValue>(V)) {
6629         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6630         continue;
6631       }
6632       if (isConstant(V)) {
6633         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6634         UniqueValues.emplace_back(V);
6635         continue;
6636       }
6637       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6638       ReuseShuffleIndicies.emplace_back(Res.first->second);
6639       if (Res.second) {
6640         UniqueValues.emplace_back(V);
6641         ++UniqueVals;
6642       }
6643     }
6644     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6645       // Emit pure splat vector.
6646       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6647                                   UndefMaskElem);
6648     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6649       ReuseShuffleIndicies.clear();
6650       UniqueValues.clear();
6651       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6652     }
6653     UniqueValues.append(VF - UniqueValues.size(),
6654                         PoisonValue::get(VL[0]->getType()));
6655     VL = UniqueValues;
6656   }
6657 
6658   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6659                                            CSEBlocks);
6660   Value *Vec = gather(VL);
6661   if (!ReuseShuffleIndicies.empty()) {
6662     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6663     Vec = ShuffleBuilder.finalize(Vec);
6664   }
6665   return Vec;
6666 }
6667 
6668 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6669   IRBuilder<>::InsertPointGuard Guard(Builder);
6670 
6671   if (E->VectorizedValue) {
6672     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6673     return E->VectorizedValue;
6674   }
6675 
6676   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6677   unsigned VF = E->getVectorFactor();
6678   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6679                                            CSEBlocks);
6680   if (E->State == TreeEntry::NeedToGather) {
6681     if (E->getMainOp())
6682       setInsertPointAfterBundle(E);
6683     Value *Vec;
6684     SmallVector<int> Mask;
6685     SmallVector<const TreeEntry *> Entries;
6686     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6687         isGatherShuffledEntry(E, Mask, Entries);
6688     if (Shuffle.hasValue()) {
6689       assert((Entries.size() == 1 || Entries.size() == 2) &&
6690              "Expected shuffle of 1 or 2 entries.");
6691       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6692                                         Entries.back()->VectorizedValue, Mask);
6693       if (auto *I = dyn_cast<Instruction>(Vec)) {
6694         GatherShuffleSeq.insert(I);
6695         CSEBlocks.insert(I->getParent());
6696       }
6697     } else {
6698       Vec = gather(E->Scalars);
6699     }
6700     if (NeedToShuffleReuses) {
6701       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6702       Vec = ShuffleBuilder.finalize(Vec);
6703     }
6704     E->VectorizedValue = Vec;
6705     return Vec;
6706   }
6707 
6708   assert((E->State == TreeEntry::Vectorize ||
6709           E->State == TreeEntry::ScatterVectorize) &&
6710          "Unhandled state");
6711   unsigned ShuffleOrOp =
6712       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6713   Instruction *VL0 = E->getMainOp();
6714   Type *ScalarTy = VL0->getType();
6715   if (auto *Store = dyn_cast<StoreInst>(VL0))
6716     ScalarTy = Store->getValueOperand()->getType();
6717   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6718     ScalarTy = IE->getOperand(1)->getType();
6719   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6720   switch (ShuffleOrOp) {
6721     case Instruction::PHI: {
6722       assert(
6723           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6724           "PHI reordering is free.");
6725       auto *PH = cast<PHINode>(VL0);
6726       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6727       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6728       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6729       Value *V = NewPhi;
6730 
6731       // Adjust insertion point once all PHI's have been generated.
6732       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6733       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6734 
6735       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6736       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6737       V = ShuffleBuilder.finalize(V);
6738 
6739       E->VectorizedValue = V;
6740 
6741       // PHINodes may have multiple entries from the same block. We want to
6742       // visit every block once.
6743       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6744 
6745       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6746         ValueList Operands;
6747         BasicBlock *IBB = PH->getIncomingBlock(i);
6748 
6749         if (!VisitedBBs.insert(IBB).second) {
6750           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6751           continue;
6752         }
6753 
6754         Builder.SetInsertPoint(IBB->getTerminator());
6755         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6756         Value *Vec = vectorizeTree(E->getOperand(i));
6757         NewPhi->addIncoming(Vec, IBB);
6758       }
6759 
6760       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6761              "Invalid number of incoming values");
6762       return V;
6763     }
6764 
6765     case Instruction::ExtractElement: {
6766       Value *V = E->getSingleOperand(0);
6767       Builder.SetInsertPoint(VL0);
6768       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6769       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6770       V = ShuffleBuilder.finalize(V);
6771       E->VectorizedValue = V;
6772       return V;
6773     }
6774     case Instruction::ExtractValue: {
6775       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6776       Builder.SetInsertPoint(LI);
6777       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6778       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6779       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6780       Value *NewV = propagateMetadata(V, E->Scalars);
6781       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6782       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6783       NewV = ShuffleBuilder.finalize(NewV);
6784       E->VectorizedValue = NewV;
6785       return NewV;
6786     }
6787     case Instruction::InsertElement: {
6788       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6789       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6790       Value *V = vectorizeTree(E->getOperand(1));
6791 
6792       // Create InsertVector shuffle if necessary
6793       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6794         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6795       }));
6796       const unsigned NumElts =
6797           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6798       const unsigned NumScalars = E->Scalars.size();
6799 
6800       unsigned Offset = *getInsertIndex(VL0);
6801       assert(Offset < NumElts && "Failed to find vector index offset");
6802 
6803       // Create shuffle to resize vector
6804       SmallVector<int> Mask;
6805       if (!E->ReorderIndices.empty()) {
6806         inversePermutation(E->ReorderIndices, Mask);
6807         Mask.append(NumElts - NumScalars, UndefMaskElem);
6808       } else {
6809         Mask.assign(NumElts, UndefMaskElem);
6810         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6811       }
6812       // Create InsertVector shuffle if necessary
6813       bool IsIdentity = true;
6814       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6815       Mask.swap(PrevMask);
6816       for (unsigned I = 0; I < NumScalars; ++I) {
6817         Value *Scalar = E->Scalars[PrevMask[I]];
6818         unsigned InsertIdx = *getInsertIndex(Scalar);
6819         IsIdentity &= InsertIdx - Offset == I;
6820         Mask[InsertIdx - Offset] = I;
6821       }
6822       if (!IsIdentity || NumElts != NumScalars) {
6823         V = Builder.CreateShuffleVector(V, Mask);
6824         if (auto *I = dyn_cast<Instruction>(V)) {
6825           GatherShuffleSeq.insert(I);
6826           CSEBlocks.insert(I->getParent());
6827         }
6828       }
6829 
6830       if ((!IsIdentity || Offset != 0 ||
6831            !isUndefVector(FirstInsert->getOperand(0))) &&
6832           NumElts != NumScalars) {
6833         SmallVector<int> InsertMask(NumElts);
6834         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6835         for (unsigned I = 0; I < NumElts; I++) {
6836           if (Mask[I] != UndefMaskElem)
6837             InsertMask[Offset + I] = NumElts + I;
6838         }
6839 
6840         V = Builder.CreateShuffleVector(
6841             FirstInsert->getOperand(0), V, InsertMask,
6842             cast<Instruction>(E->Scalars.back())->getName());
6843         if (auto *I = dyn_cast<Instruction>(V)) {
6844           GatherShuffleSeq.insert(I);
6845           CSEBlocks.insert(I->getParent());
6846         }
6847       }
6848 
6849       ++NumVectorInstructions;
6850       E->VectorizedValue = V;
6851       return V;
6852     }
6853     case Instruction::ZExt:
6854     case Instruction::SExt:
6855     case Instruction::FPToUI:
6856     case Instruction::FPToSI:
6857     case Instruction::FPExt:
6858     case Instruction::PtrToInt:
6859     case Instruction::IntToPtr:
6860     case Instruction::SIToFP:
6861     case Instruction::UIToFP:
6862     case Instruction::Trunc:
6863     case Instruction::FPTrunc:
6864     case Instruction::BitCast: {
6865       setInsertPointAfterBundle(E);
6866 
6867       Value *InVec = vectorizeTree(E->getOperand(0));
6868 
6869       if (E->VectorizedValue) {
6870         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6871         return E->VectorizedValue;
6872       }
6873 
6874       auto *CI = cast<CastInst>(VL0);
6875       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6876       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6877       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6878       V = ShuffleBuilder.finalize(V);
6879 
6880       E->VectorizedValue = V;
6881       ++NumVectorInstructions;
6882       return V;
6883     }
6884     case Instruction::FCmp:
6885     case Instruction::ICmp: {
6886       setInsertPointAfterBundle(E);
6887 
6888       Value *L = vectorizeTree(E->getOperand(0));
6889       Value *R = vectorizeTree(E->getOperand(1));
6890 
6891       if (E->VectorizedValue) {
6892         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6893         return E->VectorizedValue;
6894       }
6895 
6896       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6897       Value *V = Builder.CreateCmp(P0, L, R);
6898       propagateIRFlags(V, E->Scalars, VL0);
6899       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6900       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6901       V = ShuffleBuilder.finalize(V);
6902 
6903       E->VectorizedValue = V;
6904       ++NumVectorInstructions;
6905       return V;
6906     }
6907     case Instruction::Select: {
6908       setInsertPointAfterBundle(E);
6909 
6910       Value *Cond = vectorizeTree(E->getOperand(0));
6911       Value *True = vectorizeTree(E->getOperand(1));
6912       Value *False = vectorizeTree(E->getOperand(2));
6913 
6914       if (E->VectorizedValue) {
6915         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6916         return E->VectorizedValue;
6917       }
6918 
6919       Value *V = Builder.CreateSelect(Cond, True, False);
6920       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6921       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6922       V = ShuffleBuilder.finalize(V);
6923 
6924       E->VectorizedValue = V;
6925       ++NumVectorInstructions;
6926       return V;
6927     }
6928     case Instruction::FNeg: {
6929       setInsertPointAfterBundle(E);
6930 
6931       Value *Op = vectorizeTree(E->getOperand(0));
6932 
6933       if (E->VectorizedValue) {
6934         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6935         return E->VectorizedValue;
6936       }
6937 
6938       Value *V = Builder.CreateUnOp(
6939           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6940       propagateIRFlags(V, E->Scalars, VL0);
6941       if (auto *I = dyn_cast<Instruction>(V))
6942         V = propagateMetadata(I, E->Scalars);
6943 
6944       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6945       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6946       V = ShuffleBuilder.finalize(V);
6947 
6948       E->VectorizedValue = V;
6949       ++NumVectorInstructions;
6950 
6951       return V;
6952     }
6953     case Instruction::Add:
6954     case Instruction::FAdd:
6955     case Instruction::Sub:
6956     case Instruction::FSub:
6957     case Instruction::Mul:
6958     case Instruction::FMul:
6959     case Instruction::UDiv:
6960     case Instruction::SDiv:
6961     case Instruction::FDiv:
6962     case Instruction::URem:
6963     case Instruction::SRem:
6964     case Instruction::FRem:
6965     case Instruction::Shl:
6966     case Instruction::LShr:
6967     case Instruction::AShr:
6968     case Instruction::And:
6969     case Instruction::Or:
6970     case Instruction::Xor: {
6971       setInsertPointAfterBundle(E);
6972 
6973       Value *LHS = vectorizeTree(E->getOperand(0));
6974       Value *RHS = vectorizeTree(E->getOperand(1));
6975 
6976       if (E->VectorizedValue) {
6977         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6978         return E->VectorizedValue;
6979       }
6980 
6981       Value *V = Builder.CreateBinOp(
6982           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6983           RHS);
6984       propagateIRFlags(V, E->Scalars, VL0);
6985       if (auto *I = dyn_cast<Instruction>(V))
6986         V = propagateMetadata(I, E->Scalars);
6987 
6988       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6989       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6990       V = ShuffleBuilder.finalize(V);
6991 
6992       E->VectorizedValue = V;
6993       ++NumVectorInstructions;
6994 
6995       return V;
6996     }
6997     case Instruction::Load: {
6998       // Loads are inserted at the head of the tree because we don't want to
6999       // sink them all the way down past store instructions.
7000       setInsertPointAfterBundle(E);
7001 
7002       LoadInst *LI = cast<LoadInst>(VL0);
7003       Instruction *NewLI;
7004       unsigned AS = LI->getPointerAddressSpace();
7005       Value *PO = LI->getPointerOperand();
7006       if (E->State == TreeEntry::Vectorize) {
7007 
7008         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7009 
7010         // The pointer operand uses an in-tree scalar so we add the new BitCast
7011         // to ExternalUses list to make sure that an extract will be generated
7012         // in the future.
7013         if (TreeEntry *Entry = getTreeEntry(PO)) {
7014           // Find which lane we need to extract.
7015           unsigned FoundLane = Entry->findLaneForValue(PO);
7016           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
7017         }
7018 
7019         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7020       } else {
7021         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7022         Value *VecPtr = vectorizeTree(E->getOperand(0));
7023         // Use the minimum alignment of the gathered loads.
7024         Align CommonAlignment = LI->getAlign();
7025         for (Value *V : E->Scalars)
7026           CommonAlignment =
7027               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7028         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7029       }
7030       Value *V = propagateMetadata(NewLI, E->Scalars);
7031 
7032       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7033       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7034       V = ShuffleBuilder.finalize(V);
7035       E->VectorizedValue = V;
7036       ++NumVectorInstructions;
7037       return V;
7038     }
7039     case Instruction::Store: {
7040       auto *SI = cast<StoreInst>(VL0);
7041       unsigned AS = SI->getPointerAddressSpace();
7042 
7043       setInsertPointAfterBundle(E);
7044 
7045       Value *VecValue = vectorizeTree(E->getOperand(0));
7046       ShuffleBuilder.addMask(E->ReorderIndices);
7047       VecValue = ShuffleBuilder.finalize(VecValue);
7048 
7049       Value *ScalarPtr = SI->getPointerOperand();
7050       Value *VecPtr = Builder.CreateBitCast(
7051           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7052       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
7053                                                  SI->getAlign());
7054 
7055       // The pointer operand uses an in-tree scalar, so add the new BitCast to
7056       // ExternalUses to make sure that an extract will be generated in the
7057       // future.
7058       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7059         // Find which lane we need to extract.
7060         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7061         ExternalUses.push_back(
7062             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
7063       }
7064 
7065       Value *V = propagateMetadata(ST, E->Scalars);
7066 
7067       E->VectorizedValue = V;
7068       ++NumVectorInstructions;
7069       return V;
7070     }
7071     case Instruction::GetElementPtr: {
7072       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7073       setInsertPointAfterBundle(E);
7074 
7075       Value *Op0 = vectorizeTree(E->getOperand(0));
7076 
7077       SmallVector<Value *> OpVecs;
7078       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7079         Value *OpVec = vectorizeTree(E->getOperand(J));
7080         OpVecs.push_back(OpVec);
7081       }
7082 
7083       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7084       if (Instruction *I = dyn_cast<Instruction>(V))
7085         V = propagateMetadata(I, E->Scalars);
7086 
7087       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7088       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7089       V = ShuffleBuilder.finalize(V);
7090 
7091       E->VectorizedValue = V;
7092       ++NumVectorInstructions;
7093 
7094       return V;
7095     }
7096     case Instruction::Call: {
7097       CallInst *CI = cast<CallInst>(VL0);
7098       setInsertPointAfterBundle(E);
7099 
7100       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7101       if (Function *FI = CI->getCalledFunction())
7102         IID = FI->getIntrinsicID();
7103 
7104       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7105 
7106       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7107       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7108                           VecCallCosts.first <= VecCallCosts.second;
7109 
7110       Value *ScalarArg = nullptr;
7111       std::vector<Value *> OpVecs;
7112       SmallVector<Type *, 2> TysForDecl =
7113           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7114       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7115         ValueList OpVL;
7116         // Some intrinsics have scalar arguments. This argument should not be
7117         // vectorized.
7118         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7119           CallInst *CEI = cast<CallInst>(VL0);
7120           ScalarArg = CEI->getArgOperand(j);
7121           OpVecs.push_back(CEI->getArgOperand(j));
7122           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7123             TysForDecl.push_back(ScalarArg->getType());
7124           continue;
7125         }
7126 
7127         Value *OpVec = vectorizeTree(E->getOperand(j));
7128         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7129         OpVecs.push_back(OpVec);
7130       }
7131 
7132       Function *CF;
7133       if (!UseIntrinsic) {
7134         VFShape Shape =
7135             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7136                                   VecTy->getNumElements())),
7137                          false /*HasGlobalPred*/);
7138         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7139       } else {
7140         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7141       }
7142 
7143       SmallVector<OperandBundleDef, 1> OpBundles;
7144       CI->getOperandBundlesAsDefs(OpBundles);
7145       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7146 
7147       // The scalar argument uses an in-tree scalar so we add the new vectorized
7148       // call to ExternalUses list to make sure that an extract will be
7149       // generated in the future.
7150       if (ScalarArg) {
7151         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7152           // Find which lane we need to extract.
7153           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7154           ExternalUses.push_back(
7155               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7156         }
7157       }
7158 
7159       propagateIRFlags(V, E->Scalars, VL0);
7160       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7161       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7162       V = ShuffleBuilder.finalize(V);
7163 
7164       E->VectorizedValue = V;
7165       ++NumVectorInstructions;
7166       return V;
7167     }
7168     case Instruction::ShuffleVector: {
7169       assert(E->isAltShuffle() &&
7170              ((Instruction::isBinaryOp(E->getOpcode()) &&
7171                Instruction::isBinaryOp(E->getAltOpcode())) ||
7172               (Instruction::isCast(E->getOpcode()) &&
7173                Instruction::isCast(E->getAltOpcode())) ||
7174               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7175              "Invalid Shuffle Vector Operand");
7176 
7177       Value *LHS = nullptr, *RHS = nullptr;
7178       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7179         setInsertPointAfterBundle(E);
7180         LHS = vectorizeTree(E->getOperand(0));
7181         RHS = vectorizeTree(E->getOperand(1));
7182       } else {
7183         setInsertPointAfterBundle(E);
7184         LHS = vectorizeTree(E->getOperand(0));
7185       }
7186 
7187       if (E->VectorizedValue) {
7188         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7189         return E->VectorizedValue;
7190       }
7191 
7192       Value *V0, *V1;
7193       if (Instruction::isBinaryOp(E->getOpcode())) {
7194         V0 = Builder.CreateBinOp(
7195             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7196         V1 = Builder.CreateBinOp(
7197             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7198       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7199         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7200         auto *AltCI = cast<CmpInst>(E->getAltOp());
7201         CmpInst::Predicate AltPred = AltCI->getPredicate();
7202         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7203       } else {
7204         V0 = Builder.CreateCast(
7205             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7206         V1 = Builder.CreateCast(
7207             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7208       }
7209       // Add V0 and V1 to later analysis to try to find and remove matching
7210       // instruction, if any.
7211       for (Value *V : {V0, V1}) {
7212         if (auto *I = dyn_cast<Instruction>(V)) {
7213           GatherShuffleSeq.insert(I);
7214           CSEBlocks.insert(I->getParent());
7215         }
7216       }
7217 
7218       // Create shuffle to take alternate operations from the vector.
7219       // Also, gather up main and alt scalar ops to propagate IR flags to
7220       // each vector operation.
7221       ValueList OpScalars, AltScalars;
7222       SmallVector<int> Mask;
7223       buildShuffleEntryMask(
7224           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7225           [E](Instruction *I) {
7226             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7227             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7228           },
7229           Mask, &OpScalars, &AltScalars);
7230 
7231       propagateIRFlags(V0, OpScalars);
7232       propagateIRFlags(V1, AltScalars);
7233 
7234       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7235       if (auto *I = dyn_cast<Instruction>(V)) {
7236         V = propagateMetadata(I, E->Scalars);
7237         GatherShuffleSeq.insert(I);
7238         CSEBlocks.insert(I->getParent());
7239       }
7240       V = ShuffleBuilder.finalize(V);
7241 
7242       E->VectorizedValue = V;
7243       ++NumVectorInstructions;
7244 
7245       return V;
7246     }
7247     default:
7248     llvm_unreachable("unknown inst");
7249   }
7250   return nullptr;
7251 }
7252 
7253 Value *BoUpSLP::vectorizeTree() {
7254   ExtraValueToDebugLocsMap ExternallyUsedValues;
7255   return vectorizeTree(ExternallyUsedValues);
7256 }
7257 
7258 Value *
7259 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7260   // All blocks must be scheduled before any instructions are inserted.
7261   for (auto &BSIter : BlocksSchedules) {
7262     scheduleBlock(BSIter.second.get());
7263   }
7264 
7265   Builder.SetInsertPoint(&F->getEntryBlock().front());
7266   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7267 
7268   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7269   // vectorized root. InstCombine will then rewrite the entire expression. We
7270   // sign extend the extracted values below.
7271   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7272   if (MinBWs.count(ScalarRoot)) {
7273     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7274       // If current instr is a phi and not the last phi, insert it after the
7275       // last phi node.
7276       if (isa<PHINode>(I))
7277         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7278       else
7279         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7280     }
7281     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7282     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7283     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7284     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7285     VectorizableTree[0]->VectorizedValue = Trunc;
7286   }
7287 
7288   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7289                     << " values .\n");
7290 
7291   // Extract all of the elements with the external uses.
7292   for (const auto &ExternalUse : ExternalUses) {
7293     Value *Scalar = ExternalUse.Scalar;
7294     llvm::User *User = ExternalUse.User;
7295 
7296     // Skip users that we already RAUW. This happens when one instruction
7297     // has multiple uses of the same value.
7298     if (User && !is_contained(Scalar->users(), User))
7299       continue;
7300     TreeEntry *E = getTreeEntry(Scalar);
7301     assert(E && "Invalid scalar");
7302     assert(E->State != TreeEntry::NeedToGather &&
7303            "Extracting from a gather list");
7304 
7305     Value *Vec = E->VectorizedValue;
7306     assert(Vec && "Can't find vectorizable value");
7307 
7308     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7309     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7310       if (Scalar->getType() != Vec->getType()) {
7311         Value *Ex;
7312         // "Reuse" the existing extract to improve final codegen.
7313         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7314           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7315                                             ES->getOperand(1));
7316         } else {
7317           Ex = Builder.CreateExtractElement(Vec, Lane);
7318         }
7319         // If necessary, sign-extend or zero-extend ScalarRoot
7320         // to the larger type.
7321         if (!MinBWs.count(ScalarRoot))
7322           return Ex;
7323         if (MinBWs[ScalarRoot].second)
7324           return Builder.CreateSExt(Ex, Scalar->getType());
7325         return Builder.CreateZExt(Ex, Scalar->getType());
7326       }
7327       assert(isa<FixedVectorType>(Scalar->getType()) &&
7328              isa<InsertElementInst>(Scalar) &&
7329              "In-tree scalar of vector type is not insertelement?");
7330       return Vec;
7331     };
7332     // If User == nullptr, the Scalar is used as extra arg. Generate
7333     // ExtractElement instruction and update the record for this scalar in
7334     // ExternallyUsedValues.
7335     if (!User) {
7336       assert(ExternallyUsedValues.count(Scalar) &&
7337              "Scalar with nullptr as an external user must be registered in "
7338              "ExternallyUsedValues map");
7339       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7340         Builder.SetInsertPoint(VecI->getParent(),
7341                                std::next(VecI->getIterator()));
7342       } else {
7343         Builder.SetInsertPoint(&F->getEntryBlock().front());
7344       }
7345       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7346       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7347       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7348       auto It = ExternallyUsedValues.find(Scalar);
7349       assert(It != ExternallyUsedValues.end() &&
7350              "Externally used scalar is not found in ExternallyUsedValues");
7351       NewInstLocs.append(It->second);
7352       ExternallyUsedValues.erase(Scalar);
7353       // Required to update internally referenced instructions.
7354       Scalar->replaceAllUsesWith(NewInst);
7355       continue;
7356     }
7357 
7358     // Generate extracts for out-of-tree users.
7359     // Find the insertion point for the extractelement lane.
7360     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7361       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7362         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7363           if (PH->getIncomingValue(i) == Scalar) {
7364             Instruction *IncomingTerminator =
7365                 PH->getIncomingBlock(i)->getTerminator();
7366             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7367               Builder.SetInsertPoint(VecI->getParent(),
7368                                      std::next(VecI->getIterator()));
7369             } else {
7370               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7371             }
7372             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7373             CSEBlocks.insert(PH->getIncomingBlock(i));
7374             PH->setOperand(i, NewInst);
7375           }
7376         }
7377       } else {
7378         Builder.SetInsertPoint(cast<Instruction>(User));
7379         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7380         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7381         User->replaceUsesOfWith(Scalar, NewInst);
7382       }
7383     } else {
7384       Builder.SetInsertPoint(&F->getEntryBlock().front());
7385       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7386       CSEBlocks.insert(&F->getEntryBlock());
7387       User->replaceUsesOfWith(Scalar, NewInst);
7388     }
7389 
7390     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7391   }
7392 
7393   // For each vectorized value:
7394   for (auto &TEPtr : VectorizableTree) {
7395     TreeEntry *Entry = TEPtr.get();
7396 
7397     // No need to handle users of gathered values.
7398     if (Entry->State == TreeEntry::NeedToGather)
7399       continue;
7400 
7401     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7402 
7403     // For each lane:
7404     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7405       Value *Scalar = Entry->Scalars[Lane];
7406 
7407 #ifndef NDEBUG
7408       Type *Ty = Scalar->getType();
7409       if (!Ty->isVoidTy()) {
7410         for (User *U : Scalar->users()) {
7411           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7412 
7413           // It is legal to delete users in the ignorelist.
7414           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7415                   (isa_and_nonnull<Instruction>(U) &&
7416                    isDeleted(cast<Instruction>(U)))) &&
7417                  "Deleting out-of-tree value");
7418         }
7419       }
7420 #endif
7421       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7422       eraseInstruction(cast<Instruction>(Scalar));
7423     }
7424   }
7425 
7426   Builder.ClearInsertionPoint();
7427   InstrElementSize.clear();
7428 
7429   return VectorizableTree[0]->VectorizedValue;
7430 }
7431 
7432 void BoUpSLP::optimizeGatherSequence() {
7433   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7434                     << " gather sequences instructions.\n");
7435   // LICM InsertElementInst sequences.
7436   for (Instruction *I : GatherShuffleSeq) {
7437     if (isDeleted(I))
7438       continue;
7439 
7440     // Check if this block is inside a loop.
7441     Loop *L = LI->getLoopFor(I->getParent());
7442     if (!L)
7443       continue;
7444 
7445     // Check if it has a preheader.
7446     BasicBlock *PreHeader = L->getLoopPreheader();
7447     if (!PreHeader)
7448       continue;
7449 
7450     // If the vector or the element that we insert into it are
7451     // instructions that are defined in this basic block then we can't
7452     // hoist this instruction.
7453     if (any_of(I->operands(), [L](Value *V) {
7454           auto *OpI = dyn_cast<Instruction>(V);
7455           return OpI && L->contains(OpI);
7456         }))
7457       continue;
7458 
7459     // We can hoist this instruction. Move it to the pre-header.
7460     I->moveBefore(PreHeader->getTerminator());
7461   }
7462 
7463   // Make a list of all reachable blocks in our CSE queue.
7464   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7465   CSEWorkList.reserve(CSEBlocks.size());
7466   for (BasicBlock *BB : CSEBlocks)
7467     if (DomTreeNode *N = DT->getNode(BB)) {
7468       assert(DT->isReachableFromEntry(N));
7469       CSEWorkList.push_back(N);
7470     }
7471 
7472   // Sort blocks by domination. This ensures we visit a block after all blocks
7473   // dominating it are visited.
7474   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7475     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7476            "Different nodes should have different DFS numbers");
7477     return A->getDFSNumIn() < B->getDFSNumIn();
7478   });
7479 
7480   // Less defined shuffles can be replaced by the more defined copies.
7481   // Between two shuffles one is less defined if it has the same vector operands
7482   // and its mask indeces are the same as in the first one or undefs. E.g.
7483   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7484   // poison, <0, 0, 0, 0>.
7485   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7486                                            SmallVectorImpl<int> &NewMask) {
7487     if (I1->getType() != I2->getType())
7488       return false;
7489     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7490     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7491     if (!SI1 || !SI2)
7492       return I1->isIdenticalTo(I2);
7493     if (SI1->isIdenticalTo(SI2))
7494       return true;
7495     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7496       if (SI1->getOperand(I) != SI2->getOperand(I))
7497         return false;
7498     // Check if the second instruction is more defined than the first one.
7499     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7500     ArrayRef<int> SM1 = SI1->getShuffleMask();
7501     // Count trailing undefs in the mask to check the final number of used
7502     // registers.
7503     unsigned LastUndefsCnt = 0;
7504     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7505       if (SM1[I] == UndefMaskElem)
7506         ++LastUndefsCnt;
7507       else
7508         LastUndefsCnt = 0;
7509       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7510           NewMask[I] != SM1[I])
7511         return false;
7512       if (NewMask[I] == UndefMaskElem)
7513         NewMask[I] = SM1[I];
7514     }
7515     // Check if the last undefs actually change the final number of used vector
7516     // registers.
7517     return SM1.size() - LastUndefsCnt > 1 &&
7518            TTI->getNumberOfParts(SI1->getType()) ==
7519                TTI->getNumberOfParts(
7520                    FixedVectorType::get(SI1->getType()->getElementType(),
7521                                         SM1.size() - LastUndefsCnt));
7522   };
7523   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7524   // instructions. TODO: We can further optimize this scan if we split the
7525   // instructions into different buckets based on the insert lane.
7526   SmallVector<Instruction *, 16> Visited;
7527   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7528     assert(*I &&
7529            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7530            "Worklist not sorted properly!");
7531     BasicBlock *BB = (*I)->getBlock();
7532     // For all instructions in blocks containing gather sequences:
7533     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7534       if (isDeleted(&In))
7535         continue;
7536       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7537           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7538         continue;
7539 
7540       // Check if we can replace this instruction with any of the
7541       // visited instructions.
7542       bool Replaced = false;
7543       for (Instruction *&V : Visited) {
7544         SmallVector<int> NewMask;
7545         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7546             DT->dominates(V->getParent(), In.getParent())) {
7547           In.replaceAllUsesWith(V);
7548           eraseInstruction(&In);
7549           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7550             if (!NewMask.empty())
7551               SI->setShuffleMask(NewMask);
7552           Replaced = true;
7553           break;
7554         }
7555         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7556             GatherShuffleSeq.contains(V) &&
7557             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7558             DT->dominates(In.getParent(), V->getParent())) {
7559           In.moveAfter(V);
7560           V->replaceAllUsesWith(&In);
7561           eraseInstruction(V);
7562           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7563             if (!NewMask.empty())
7564               SI->setShuffleMask(NewMask);
7565           V = &In;
7566           Replaced = true;
7567           break;
7568         }
7569       }
7570       if (!Replaced) {
7571         assert(!is_contained(Visited, &In));
7572         Visited.push_back(&In);
7573       }
7574     }
7575   }
7576   CSEBlocks.clear();
7577   GatherShuffleSeq.clear();
7578 }
7579 
7580 BoUpSLP::ScheduleData *
7581 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7582   ScheduleData *Bundle = nullptr;
7583   ScheduleData *PrevInBundle = nullptr;
7584   for (Value *V : VL) {
7585     ScheduleData *BundleMember = getScheduleData(V);
7586     assert(BundleMember &&
7587            "no ScheduleData for bundle member "
7588            "(maybe not in same basic block)");
7589     assert(BundleMember->isSchedulingEntity() &&
7590            "bundle member already part of other bundle");
7591     if (PrevInBundle) {
7592       PrevInBundle->NextInBundle = BundleMember;
7593     } else {
7594       Bundle = BundleMember;
7595     }
7596 
7597     // Group the instructions to a bundle.
7598     BundleMember->FirstInBundle = Bundle;
7599     PrevInBundle = BundleMember;
7600   }
7601   assert(Bundle && "Failed to find schedule bundle");
7602   return Bundle;
7603 }
7604 
7605 // Groups the instructions to a bundle (which is then a single scheduling entity)
7606 // and schedules instructions until the bundle gets ready.
7607 Optional<BoUpSLP::ScheduleData *>
7608 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7609                                             const InstructionsState &S) {
7610   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7611   // instructions.
7612   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7613     return nullptr;
7614 
7615   // Initialize the instruction bundle.
7616   Instruction *OldScheduleEnd = ScheduleEnd;
7617   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7618 
7619   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7620                                                          ScheduleData *Bundle) {
7621     // The scheduling region got new instructions at the lower end (or it is a
7622     // new region for the first bundle). This makes it necessary to
7623     // recalculate all dependencies.
7624     // It is seldom that this needs to be done a second time after adding the
7625     // initial bundle to the region.
7626     if (ScheduleEnd != OldScheduleEnd) {
7627       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7628         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7629       ReSchedule = true;
7630     }
7631     if (Bundle) {
7632       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7633                         << " in block " << BB->getName() << "\n");
7634       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7635     }
7636 
7637     if (ReSchedule) {
7638       resetSchedule();
7639       initialFillReadyList(ReadyInsts);
7640     }
7641 
7642     // Now try to schedule the new bundle or (if no bundle) just calculate
7643     // dependencies. As soon as the bundle is "ready" it means that there are no
7644     // cyclic dependencies and we can schedule it. Note that's important that we
7645     // don't "schedule" the bundle yet (see cancelScheduling).
7646     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7647            !ReadyInsts.empty()) {
7648       ScheduleData *Picked = ReadyInsts.pop_back_val();
7649       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7650              "must be ready to schedule");
7651       schedule(Picked, ReadyInsts);
7652     }
7653   };
7654 
7655   // Make sure that the scheduling region contains all
7656   // instructions of the bundle.
7657   for (Value *V : VL) {
7658     if (!extendSchedulingRegion(V, S)) {
7659       // If the scheduling region got new instructions at the lower end (or it
7660       // is a new region for the first bundle). This makes it necessary to
7661       // recalculate all dependencies.
7662       // Otherwise the compiler may crash trying to incorrectly calculate
7663       // dependencies and emit instruction in the wrong order at the actual
7664       // scheduling.
7665       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7666       return None;
7667     }
7668   }
7669 
7670   bool ReSchedule = false;
7671   for (Value *V : VL) {
7672     ScheduleData *BundleMember = getScheduleData(V);
7673     assert(BundleMember &&
7674            "no ScheduleData for bundle member (maybe not in same basic block)");
7675 
7676     // Make sure we don't leave the pieces of the bundle in the ready list when
7677     // whole bundle might not be ready.
7678     ReadyInsts.remove(BundleMember);
7679 
7680     if (!BundleMember->IsScheduled)
7681       continue;
7682     // A bundle member was scheduled as single instruction before and now
7683     // needs to be scheduled as part of the bundle. We just get rid of the
7684     // existing schedule.
7685     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7686                       << " was already scheduled\n");
7687     ReSchedule = true;
7688   }
7689 
7690   auto *Bundle = buildBundle(VL);
7691   TryScheduleBundleImpl(ReSchedule, Bundle);
7692   if (!Bundle->isReady()) {
7693     cancelScheduling(VL, S.OpValue);
7694     return None;
7695   }
7696   return Bundle;
7697 }
7698 
7699 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7700                                                 Value *OpValue) {
7701   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7702     return;
7703 
7704   ScheduleData *Bundle = getScheduleData(OpValue);
7705   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7706   assert(!Bundle->IsScheduled &&
7707          "Can't cancel bundle which is already scheduled");
7708   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7709          "tried to unbundle something which is not a bundle");
7710 
7711   // Remove the bundle from the ready list.
7712   if (Bundle->isReady())
7713     ReadyInsts.remove(Bundle);
7714 
7715   // Un-bundle: make single instructions out of the bundle.
7716   ScheduleData *BundleMember = Bundle;
7717   while (BundleMember) {
7718     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7719     BundleMember->FirstInBundle = BundleMember;
7720     ScheduleData *Next = BundleMember->NextInBundle;
7721     BundleMember->NextInBundle = nullptr;
7722     if (BundleMember->unscheduledDepsInBundle() == 0) {
7723       ReadyInsts.insert(BundleMember);
7724     }
7725     BundleMember = Next;
7726   }
7727 }
7728 
7729 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7730   // Allocate a new ScheduleData for the instruction.
7731   if (ChunkPos >= ChunkSize) {
7732     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7733     ChunkPos = 0;
7734   }
7735   return &(ScheduleDataChunks.back()[ChunkPos++]);
7736 }
7737 
7738 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7739                                                       const InstructionsState &S) {
7740   if (getScheduleData(V, isOneOf(S, V)))
7741     return true;
7742   Instruction *I = dyn_cast<Instruction>(V);
7743   assert(I && "bundle member must be an instruction");
7744   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7745          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7746          "be scheduled");
7747   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7748     ScheduleData *ISD = getScheduleData(I);
7749     if (!ISD)
7750       return false;
7751     assert(isInSchedulingRegion(ISD) &&
7752            "ScheduleData not in scheduling region");
7753     ScheduleData *SD = allocateScheduleDataChunks();
7754     SD->Inst = I;
7755     SD->init(SchedulingRegionID, S.OpValue);
7756     ExtraScheduleDataMap[I][S.OpValue] = SD;
7757     return true;
7758   };
7759   if (CheckSheduleForI(I))
7760     return true;
7761   if (!ScheduleStart) {
7762     // It's the first instruction in the new region.
7763     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7764     ScheduleStart = I;
7765     ScheduleEnd = I->getNextNode();
7766     if (isOneOf(S, I) != I)
7767       CheckSheduleForI(I);
7768     assert(ScheduleEnd && "tried to vectorize a terminator?");
7769     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7770     return true;
7771   }
7772   // Search up and down at the same time, because we don't know if the new
7773   // instruction is above or below the existing scheduling region.
7774   BasicBlock::reverse_iterator UpIter =
7775       ++ScheduleStart->getIterator().getReverse();
7776   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7777   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7778   BasicBlock::iterator LowerEnd = BB->end();
7779   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7780          &*DownIter != I) {
7781     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7782       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7783       return false;
7784     }
7785 
7786     ++UpIter;
7787     ++DownIter;
7788   }
7789   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7790     assert(I->getParent() == ScheduleStart->getParent() &&
7791            "Instruction is in wrong basic block.");
7792     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7793     ScheduleStart = I;
7794     if (isOneOf(S, I) != I)
7795       CheckSheduleForI(I);
7796     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7797                       << "\n");
7798     return true;
7799   }
7800   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7801          "Expected to reach top of the basic block or instruction down the "
7802          "lower end.");
7803   assert(I->getParent() == ScheduleEnd->getParent() &&
7804          "Instruction is in wrong basic block.");
7805   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7806                    nullptr);
7807   ScheduleEnd = I->getNextNode();
7808   if (isOneOf(S, I) != I)
7809     CheckSheduleForI(I);
7810   assert(ScheduleEnd && "tried to vectorize a terminator?");
7811   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7812   return true;
7813 }
7814 
7815 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7816                                                 Instruction *ToI,
7817                                                 ScheduleData *PrevLoadStore,
7818                                                 ScheduleData *NextLoadStore) {
7819   ScheduleData *CurrentLoadStore = PrevLoadStore;
7820   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7821     ScheduleData *SD = ScheduleDataMap[I];
7822     if (!SD) {
7823       SD = allocateScheduleDataChunks();
7824       ScheduleDataMap[I] = SD;
7825       SD->Inst = I;
7826     }
7827     assert(!isInSchedulingRegion(SD) &&
7828            "new ScheduleData already in scheduling region");
7829     SD->init(SchedulingRegionID, I);
7830 
7831     if (I->mayReadOrWriteMemory() &&
7832         (!isa<IntrinsicInst>(I) ||
7833          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7834           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7835               Intrinsic::pseudoprobe))) {
7836       // Update the linked list of memory accessing instructions.
7837       if (CurrentLoadStore) {
7838         CurrentLoadStore->NextLoadStore = SD;
7839       } else {
7840         FirstLoadStoreInRegion = SD;
7841       }
7842       CurrentLoadStore = SD;
7843     }
7844   }
7845   if (NextLoadStore) {
7846     if (CurrentLoadStore)
7847       CurrentLoadStore->NextLoadStore = NextLoadStore;
7848   } else {
7849     LastLoadStoreInRegion = CurrentLoadStore;
7850   }
7851 }
7852 
7853 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7854                                                      bool InsertInReadyList,
7855                                                      BoUpSLP *SLP) {
7856   assert(SD->isSchedulingEntity());
7857 
7858   SmallVector<ScheduleData *, 10> WorkList;
7859   WorkList.push_back(SD);
7860 
7861   while (!WorkList.empty()) {
7862     ScheduleData *SD = WorkList.pop_back_val();
7863     for (ScheduleData *BundleMember = SD; BundleMember;
7864          BundleMember = BundleMember->NextInBundle) {
7865       assert(isInSchedulingRegion(BundleMember));
7866       if (BundleMember->hasValidDependencies())
7867         continue;
7868 
7869       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7870                  << "\n");
7871       BundleMember->Dependencies = 0;
7872       BundleMember->resetUnscheduledDeps();
7873 
7874       // Handle def-use chain dependencies.
7875       if (BundleMember->OpValue != BundleMember->Inst) {
7876         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
7877           BundleMember->Dependencies++;
7878           ScheduleData *DestBundle = UseSD->FirstInBundle;
7879           if (!DestBundle->IsScheduled)
7880             BundleMember->incrementUnscheduledDeps(1);
7881           if (!DestBundle->hasValidDependencies())
7882             WorkList.push_back(DestBundle);
7883         }
7884       } else {
7885         for (User *U : BundleMember->Inst->users()) {
7886           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
7887             BundleMember->Dependencies++;
7888             ScheduleData *DestBundle = UseSD->FirstInBundle;
7889             if (!DestBundle->IsScheduled)
7890               BundleMember->incrementUnscheduledDeps(1);
7891             if (!DestBundle->hasValidDependencies())
7892               WorkList.push_back(DestBundle);
7893           }
7894         }
7895       }
7896 
7897       // Handle the memory dependencies (if any).
7898       ScheduleData *DepDest = BundleMember->NextLoadStore;
7899       if (!DepDest)
7900         continue;
7901       Instruction *SrcInst = BundleMember->Inst;
7902       assert(SrcInst->mayReadOrWriteMemory() &&
7903              "NextLoadStore list for non memory effecting bundle?");
7904       MemoryLocation SrcLoc = getLocation(SrcInst);
7905       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7906       unsigned numAliased = 0;
7907       unsigned DistToSrc = 1;
7908 
7909       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7910         assert(isInSchedulingRegion(DepDest));
7911 
7912         // We have two limits to reduce the complexity:
7913         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7914         //    SLP->isAliased (which is the expensive part in this loop).
7915         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7916         //    the whole loop (even if the loop is fast, it's quadratic).
7917         //    It's important for the loop break condition (see below) to
7918         //    check this limit even between two read-only instructions.
7919         if (DistToSrc >= MaxMemDepDistance ||
7920             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7921              (numAliased >= AliasedCheckLimit ||
7922               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7923 
7924           // We increment the counter only if the locations are aliased
7925           // (instead of counting all alias checks). This gives a better
7926           // balance between reduced runtime and accurate dependencies.
7927           numAliased++;
7928 
7929           DepDest->MemoryDependencies.push_back(BundleMember);
7930           BundleMember->Dependencies++;
7931           ScheduleData *DestBundle = DepDest->FirstInBundle;
7932           if (!DestBundle->IsScheduled) {
7933             BundleMember->incrementUnscheduledDeps(1);
7934           }
7935           if (!DestBundle->hasValidDependencies()) {
7936             WorkList.push_back(DestBundle);
7937           }
7938         }
7939 
7940         // Example, explaining the loop break condition: Let's assume our
7941         // starting instruction is i0 and MaxMemDepDistance = 3.
7942         //
7943         //                      +--------v--v--v
7944         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7945         //             +--------^--^--^
7946         //
7947         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7948         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7949         // Previously we already added dependencies from i3 to i6,i7,i8
7950         // (because of MaxMemDepDistance). As we added a dependency from
7951         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7952         // and we can abort this loop at i6.
7953         if (DistToSrc >= 2 * MaxMemDepDistance)
7954           break;
7955         DistToSrc++;
7956       }
7957     }
7958     if (InsertInReadyList && SD->isReady()) {
7959       ReadyInsts.insert(SD);
7960       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7961                         << "\n");
7962     }
7963   }
7964 }
7965 
7966 void BoUpSLP::BlockScheduling::resetSchedule() {
7967   assert(ScheduleStart &&
7968          "tried to reset schedule on block which has not been scheduled");
7969   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7970     doForAllOpcodes(I, [&](ScheduleData *SD) {
7971       assert(isInSchedulingRegion(SD) &&
7972              "ScheduleData not in scheduling region");
7973       SD->IsScheduled = false;
7974       SD->resetUnscheduledDeps();
7975     });
7976   }
7977   ReadyInsts.clear();
7978 }
7979 
7980 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7981   if (!BS->ScheduleStart)
7982     return;
7983 
7984   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7985 
7986   BS->resetSchedule();
7987 
7988   // For the real scheduling we use a more sophisticated ready-list: it is
7989   // sorted by the original instruction location. This lets the final schedule
7990   // be as  close as possible to the original instruction order.
7991   struct ScheduleDataCompare {
7992     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7993       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7994     }
7995   };
7996   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7997 
7998   // Ensure that all dependency data is updated and fill the ready-list with
7999   // initial instructions.
8000   int Idx = 0;
8001   int NumToSchedule = 0;
8002   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8003        I = I->getNextNode()) {
8004     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8005       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8006               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
8007              "scheduler and vectorizer bundle mismatch");
8008       SD->FirstInBundle->SchedulingPriority = Idx++;
8009       if (SD->isSchedulingEntity()) {
8010         BS->calculateDependencies(SD, false, this);
8011         NumToSchedule++;
8012       }
8013     });
8014   }
8015   BS->initialFillReadyList(ReadyInsts);
8016 
8017   Instruction *LastScheduledInst = BS->ScheduleEnd;
8018 
8019   // Do the "real" scheduling.
8020   while (!ReadyInsts.empty()) {
8021     ScheduleData *picked = *ReadyInsts.begin();
8022     ReadyInsts.erase(ReadyInsts.begin());
8023 
8024     // Move the scheduled instruction(s) to their dedicated places, if not
8025     // there yet.
8026     for (ScheduleData *BundleMember = picked; BundleMember;
8027          BundleMember = BundleMember->NextInBundle) {
8028       Instruction *pickedInst = BundleMember->Inst;
8029       if (pickedInst->getNextNode() != LastScheduledInst)
8030         pickedInst->moveBefore(LastScheduledInst);
8031       LastScheduledInst = pickedInst;
8032     }
8033 
8034     BS->schedule(picked, ReadyInsts);
8035     NumToSchedule--;
8036   }
8037   assert(NumToSchedule == 0 && "could not schedule all instructions");
8038 
8039   // Check that we didn't break any of our invariants.
8040 #ifdef EXPENSIVE_CHECKS
8041   BS->verify();
8042 #endif
8043 
8044 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8045   // Check that all schedulable entities got scheduled
8046   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8047     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8048       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8049         assert(SD->IsScheduled && "must be scheduled at this point");
8050       }
8051     });
8052   }
8053 #endif
8054 
8055   // Avoid duplicate scheduling of the block.
8056   BS->ScheduleStart = nullptr;
8057 }
8058 
8059 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8060   // If V is a store, just return the width of the stored value (or value
8061   // truncated just before storing) without traversing the expression tree.
8062   // This is the common case.
8063   if (auto *Store = dyn_cast<StoreInst>(V)) {
8064     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8065       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8066     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8067   }
8068 
8069   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8070     return getVectorElementSize(IEI->getOperand(1));
8071 
8072   auto E = InstrElementSize.find(V);
8073   if (E != InstrElementSize.end())
8074     return E->second;
8075 
8076   // If V is not a store, we can traverse the expression tree to find loads
8077   // that feed it. The type of the loaded value may indicate a more suitable
8078   // width than V's type. We want to base the vector element size on the width
8079   // of memory operations where possible.
8080   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8081   SmallPtrSet<Instruction *, 16> Visited;
8082   if (auto *I = dyn_cast<Instruction>(V)) {
8083     Worklist.emplace_back(I, I->getParent());
8084     Visited.insert(I);
8085   }
8086 
8087   // Traverse the expression tree in bottom-up order looking for loads. If we
8088   // encounter an instruction we don't yet handle, we give up.
8089   auto Width = 0u;
8090   while (!Worklist.empty()) {
8091     Instruction *I;
8092     BasicBlock *Parent;
8093     std::tie(I, Parent) = Worklist.pop_back_val();
8094 
8095     // We should only be looking at scalar instructions here. If the current
8096     // instruction has a vector type, skip.
8097     auto *Ty = I->getType();
8098     if (isa<VectorType>(Ty))
8099       continue;
8100 
8101     // If the current instruction is a load, update MaxWidth to reflect the
8102     // width of the loaded value.
8103     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8104         isa<ExtractValueInst>(I))
8105       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8106 
8107     // Otherwise, we need to visit the operands of the instruction. We only
8108     // handle the interesting cases from buildTree here. If an operand is an
8109     // instruction we haven't yet visited and from the same basic block as the
8110     // user or the use is a PHI node, we add it to the worklist.
8111     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8112              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8113              isa<UnaryOperator>(I)) {
8114       for (Use &U : I->operands())
8115         if (auto *J = dyn_cast<Instruction>(U.get()))
8116           if (Visited.insert(J).second &&
8117               (isa<PHINode>(I) || J->getParent() == Parent))
8118             Worklist.emplace_back(J, J->getParent());
8119     } else {
8120       break;
8121     }
8122   }
8123 
8124   // If we didn't encounter a memory access in the expression tree, or if we
8125   // gave up for some reason, just return the width of V. Otherwise, return the
8126   // maximum width we found.
8127   if (!Width) {
8128     if (auto *CI = dyn_cast<CmpInst>(V))
8129       V = CI->getOperand(0);
8130     Width = DL->getTypeSizeInBits(V->getType());
8131   }
8132 
8133   for (Instruction *I : Visited)
8134     InstrElementSize[I] = Width;
8135 
8136   return Width;
8137 }
8138 
8139 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8140 // smaller type with a truncation. We collect the values that will be demoted
8141 // in ToDemote and additional roots that require investigating in Roots.
8142 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8143                                   SmallVectorImpl<Value *> &ToDemote,
8144                                   SmallVectorImpl<Value *> &Roots) {
8145   // We can always demote constants.
8146   if (isa<Constant>(V)) {
8147     ToDemote.push_back(V);
8148     return true;
8149   }
8150 
8151   // If the value is not an instruction in the expression with only one use, it
8152   // cannot be demoted.
8153   auto *I = dyn_cast<Instruction>(V);
8154   if (!I || !I->hasOneUse() || !Expr.count(I))
8155     return false;
8156 
8157   switch (I->getOpcode()) {
8158 
8159   // We can always demote truncations and extensions. Since truncations can
8160   // seed additional demotion, we save the truncated value.
8161   case Instruction::Trunc:
8162     Roots.push_back(I->getOperand(0));
8163     break;
8164   case Instruction::ZExt:
8165   case Instruction::SExt:
8166     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8167         isa<InsertElementInst>(I->getOperand(0)))
8168       return false;
8169     break;
8170 
8171   // We can demote certain binary operations if we can demote both of their
8172   // operands.
8173   case Instruction::Add:
8174   case Instruction::Sub:
8175   case Instruction::Mul:
8176   case Instruction::And:
8177   case Instruction::Or:
8178   case Instruction::Xor:
8179     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8180         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8181       return false;
8182     break;
8183 
8184   // We can demote selects if we can demote their true and false values.
8185   case Instruction::Select: {
8186     SelectInst *SI = cast<SelectInst>(I);
8187     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8188         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8189       return false;
8190     break;
8191   }
8192 
8193   // We can demote phis if we can demote all their incoming operands. Note that
8194   // we don't need to worry about cycles since we ensure single use above.
8195   case Instruction::PHI: {
8196     PHINode *PN = cast<PHINode>(I);
8197     for (Value *IncValue : PN->incoming_values())
8198       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8199         return false;
8200     break;
8201   }
8202 
8203   // Otherwise, conservatively give up.
8204   default:
8205     return false;
8206   }
8207 
8208   // Record the value that we can demote.
8209   ToDemote.push_back(V);
8210   return true;
8211 }
8212 
8213 void BoUpSLP::computeMinimumValueSizes() {
8214   // If there are no external uses, the expression tree must be rooted by a
8215   // store. We can't demote in-memory values, so there is nothing to do here.
8216   if (ExternalUses.empty())
8217     return;
8218 
8219   // We only attempt to truncate integer expressions.
8220   auto &TreeRoot = VectorizableTree[0]->Scalars;
8221   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8222   if (!TreeRootIT)
8223     return;
8224 
8225   // If the expression is not rooted by a store, these roots should have
8226   // external uses. We will rely on InstCombine to rewrite the expression in
8227   // the narrower type. However, InstCombine only rewrites single-use values.
8228   // This means that if a tree entry other than a root is used externally, it
8229   // must have multiple uses and InstCombine will not rewrite it. The code
8230   // below ensures that only the roots are used externally.
8231   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8232   for (auto &EU : ExternalUses)
8233     if (!Expr.erase(EU.Scalar))
8234       return;
8235   if (!Expr.empty())
8236     return;
8237 
8238   // Collect the scalar values of the vectorizable expression. We will use this
8239   // context to determine which values can be demoted. If we see a truncation,
8240   // we mark it as seeding another demotion.
8241   for (auto &EntryPtr : VectorizableTree)
8242     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8243 
8244   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8245   // have a single external user that is not in the vectorizable tree.
8246   for (auto *Root : TreeRoot)
8247     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8248       return;
8249 
8250   // Conservatively determine if we can actually truncate the roots of the
8251   // expression. Collect the values that can be demoted in ToDemote and
8252   // additional roots that require investigating in Roots.
8253   SmallVector<Value *, 32> ToDemote;
8254   SmallVector<Value *, 4> Roots;
8255   for (auto *Root : TreeRoot)
8256     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8257       return;
8258 
8259   // The maximum bit width required to represent all the values that can be
8260   // demoted without loss of precision. It would be safe to truncate the roots
8261   // of the expression to this width.
8262   auto MaxBitWidth = 8u;
8263 
8264   // We first check if all the bits of the roots are demanded. If they're not,
8265   // we can truncate the roots to this narrower type.
8266   for (auto *Root : TreeRoot) {
8267     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8268     MaxBitWidth = std::max<unsigned>(
8269         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8270   }
8271 
8272   // True if the roots can be zero-extended back to their original type, rather
8273   // than sign-extended. We know that if the leading bits are not demanded, we
8274   // can safely zero-extend. So we initialize IsKnownPositive to True.
8275   bool IsKnownPositive = true;
8276 
8277   // If all the bits of the roots are demanded, we can try a little harder to
8278   // compute a narrower type. This can happen, for example, if the roots are
8279   // getelementptr indices. InstCombine promotes these indices to the pointer
8280   // width. Thus, all their bits are technically demanded even though the
8281   // address computation might be vectorized in a smaller type.
8282   //
8283   // We start by looking at each entry that can be demoted. We compute the
8284   // maximum bit width required to store the scalar by using ValueTracking to
8285   // compute the number of high-order bits we can truncate.
8286   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8287       llvm::all_of(TreeRoot, [](Value *R) {
8288         assert(R->hasOneUse() && "Root should have only one use!");
8289         return isa<GetElementPtrInst>(R->user_back());
8290       })) {
8291     MaxBitWidth = 8u;
8292 
8293     // Determine if the sign bit of all the roots is known to be zero. If not,
8294     // IsKnownPositive is set to False.
8295     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8296       KnownBits Known = computeKnownBits(R, *DL);
8297       return Known.isNonNegative();
8298     });
8299 
8300     // Determine the maximum number of bits required to store the scalar
8301     // values.
8302     for (auto *Scalar : ToDemote) {
8303       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8304       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8305       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8306     }
8307 
8308     // If we can't prove that the sign bit is zero, we must add one to the
8309     // maximum bit width to account for the unknown sign bit. This preserves
8310     // the existing sign bit so we can safely sign-extend the root back to the
8311     // original type. Otherwise, if we know the sign bit is zero, we will
8312     // zero-extend the root instead.
8313     //
8314     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8315     //        one to the maximum bit width will yield a larger-than-necessary
8316     //        type. In general, we need to add an extra bit only if we can't
8317     //        prove that the upper bit of the original type is equal to the
8318     //        upper bit of the proposed smaller type. If these two bits are the
8319     //        same (either zero or one) we know that sign-extending from the
8320     //        smaller type will result in the same value. Here, since we can't
8321     //        yet prove this, we are just making the proposed smaller type
8322     //        larger to ensure correctness.
8323     if (!IsKnownPositive)
8324       ++MaxBitWidth;
8325   }
8326 
8327   // Round MaxBitWidth up to the next power-of-two.
8328   if (!isPowerOf2_64(MaxBitWidth))
8329     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8330 
8331   // If the maximum bit width we compute is less than the with of the roots'
8332   // type, we can proceed with the narrowing. Otherwise, do nothing.
8333   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8334     return;
8335 
8336   // If we can truncate the root, we must collect additional values that might
8337   // be demoted as a result. That is, those seeded by truncations we will
8338   // modify.
8339   while (!Roots.empty())
8340     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8341 
8342   // Finally, map the values we can demote to the maximum bit with we computed.
8343   for (auto *Scalar : ToDemote)
8344     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8345 }
8346 
8347 namespace {
8348 
8349 /// The SLPVectorizer Pass.
8350 struct SLPVectorizer : public FunctionPass {
8351   SLPVectorizerPass Impl;
8352 
8353   /// Pass identification, replacement for typeid
8354   static char ID;
8355 
8356   explicit SLPVectorizer() : FunctionPass(ID) {
8357     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8358   }
8359 
8360   bool doInitialization(Module &M) override { return false; }
8361 
8362   bool runOnFunction(Function &F) override {
8363     if (skipFunction(F))
8364       return false;
8365 
8366     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8367     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8368     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8369     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8370     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8371     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8372     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8373     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8374     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8375     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8376 
8377     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8378   }
8379 
8380   void getAnalysisUsage(AnalysisUsage &AU) const override {
8381     FunctionPass::getAnalysisUsage(AU);
8382     AU.addRequired<AssumptionCacheTracker>();
8383     AU.addRequired<ScalarEvolutionWrapperPass>();
8384     AU.addRequired<AAResultsWrapperPass>();
8385     AU.addRequired<TargetTransformInfoWrapperPass>();
8386     AU.addRequired<LoopInfoWrapperPass>();
8387     AU.addRequired<DominatorTreeWrapperPass>();
8388     AU.addRequired<DemandedBitsWrapperPass>();
8389     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8390     AU.addRequired<InjectTLIMappingsLegacy>();
8391     AU.addPreserved<LoopInfoWrapperPass>();
8392     AU.addPreserved<DominatorTreeWrapperPass>();
8393     AU.addPreserved<AAResultsWrapperPass>();
8394     AU.addPreserved<GlobalsAAWrapperPass>();
8395     AU.setPreservesCFG();
8396   }
8397 };
8398 
8399 } // end anonymous namespace
8400 
8401 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8402   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8403   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8404   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8405   auto *AA = &AM.getResult<AAManager>(F);
8406   auto *LI = &AM.getResult<LoopAnalysis>(F);
8407   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8408   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8409   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8410   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8411 
8412   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8413   if (!Changed)
8414     return PreservedAnalyses::all();
8415 
8416   PreservedAnalyses PA;
8417   PA.preserveSet<CFGAnalyses>();
8418   return PA;
8419 }
8420 
8421 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8422                                 TargetTransformInfo *TTI_,
8423                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8424                                 LoopInfo *LI_, DominatorTree *DT_,
8425                                 AssumptionCache *AC_, DemandedBits *DB_,
8426                                 OptimizationRemarkEmitter *ORE_) {
8427   if (!RunSLPVectorization)
8428     return false;
8429   SE = SE_;
8430   TTI = TTI_;
8431   TLI = TLI_;
8432   AA = AA_;
8433   LI = LI_;
8434   DT = DT_;
8435   AC = AC_;
8436   DB = DB_;
8437   DL = &F.getParent()->getDataLayout();
8438 
8439   Stores.clear();
8440   GEPs.clear();
8441   bool Changed = false;
8442 
8443   // If the target claims to have no vector registers don't attempt
8444   // vectorization.
8445   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8446     LLVM_DEBUG(
8447         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8448     return false;
8449   }
8450 
8451   // Don't vectorize when the attribute NoImplicitFloat is used.
8452   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8453     return false;
8454 
8455   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8456 
8457   // Use the bottom up slp vectorizer to construct chains that start with
8458   // store instructions.
8459   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8460 
8461   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8462   // delete instructions.
8463 
8464   // Update DFS numbers now so that we can use them for ordering.
8465   DT->updateDFSNumbers();
8466 
8467   // Scan the blocks in the function in post order.
8468   for (auto BB : post_order(&F.getEntryBlock())) {
8469     collectSeedInstructions(BB);
8470 
8471     // Vectorize trees that end at stores.
8472     if (!Stores.empty()) {
8473       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8474                         << " underlying objects.\n");
8475       Changed |= vectorizeStoreChains(R);
8476     }
8477 
8478     // Vectorize trees that end at reductions.
8479     Changed |= vectorizeChainsInBlock(BB, R);
8480 
8481     // Vectorize the index computations of getelementptr instructions. This
8482     // is primarily intended to catch gather-like idioms ending at
8483     // non-consecutive loads.
8484     if (!GEPs.empty()) {
8485       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8486                         << " underlying objects.\n");
8487       Changed |= vectorizeGEPIndices(BB, R);
8488     }
8489   }
8490 
8491   if (Changed) {
8492     R.optimizeGatherSequence();
8493     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8494   }
8495   return Changed;
8496 }
8497 
8498 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8499                                             unsigned Idx) {
8500   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8501                     << "\n");
8502   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8503   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8504   unsigned VF = Chain.size();
8505 
8506   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8507     return false;
8508 
8509   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8510                     << "\n");
8511 
8512   R.buildTree(Chain);
8513   if (R.isTreeTinyAndNotFullyVectorizable())
8514     return false;
8515   if (R.isLoadCombineCandidate())
8516     return false;
8517   R.reorderTopToBottom();
8518   R.reorderBottomToTop();
8519   R.buildExternalUses();
8520 
8521   R.computeMinimumValueSizes();
8522 
8523   InstructionCost Cost = R.getTreeCost();
8524 
8525   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8526   if (Cost < -SLPCostThreshold) {
8527     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8528 
8529     using namespace ore;
8530 
8531     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8532                                         cast<StoreInst>(Chain[0]))
8533                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8534                      << " and with tree size "
8535                      << NV("TreeSize", R.getTreeSize()));
8536 
8537     R.vectorizeTree();
8538     return true;
8539   }
8540 
8541   return false;
8542 }
8543 
8544 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8545                                         BoUpSLP &R) {
8546   // We may run into multiple chains that merge into a single chain. We mark the
8547   // stores that we vectorized so that we don't visit the same store twice.
8548   BoUpSLP::ValueSet VectorizedStores;
8549   bool Changed = false;
8550 
8551   int E = Stores.size();
8552   SmallBitVector Tails(E, false);
8553   int MaxIter = MaxStoreLookup.getValue();
8554   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8555       E, std::make_pair(E, INT_MAX));
8556   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8557   int IterCnt;
8558   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8559                                   &CheckedPairs,
8560                                   &ConsecutiveChain](int K, int Idx) {
8561     if (IterCnt >= MaxIter)
8562       return true;
8563     if (CheckedPairs[Idx].test(K))
8564       return ConsecutiveChain[K].second == 1 &&
8565              ConsecutiveChain[K].first == Idx;
8566     ++IterCnt;
8567     CheckedPairs[Idx].set(K);
8568     CheckedPairs[K].set(Idx);
8569     Optional<int> Diff = getPointersDiff(
8570         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8571         Stores[Idx]->getValueOperand()->getType(),
8572         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8573     if (!Diff || *Diff == 0)
8574       return false;
8575     int Val = *Diff;
8576     if (Val < 0) {
8577       if (ConsecutiveChain[Idx].second > -Val) {
8578         Tails.set(K);
8579         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8580       }
8581       return false;
8582     }
8583     if (ConsecutiveChain[K].second <= Val)
8584       return false;
8585 
8586     Tails.set(Idx);
8587     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8588     return Val == 1;
8589   };
8590   // Do a quadratic search on all of the given stores in reverse order and find
8591   // all of the pairs of stores that follow each other.
8592   for (int Idx = E - 1; Idx >= 0; --Idx) {
8593     // If a store has multiple consecutive store candidates, search according
8594     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8595     // This is because usually pairing with immediate succeeding or preceding
8596     // candidate create the best chance to find slp vectorization opportunity.
8597     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8598     IterCnt = 0;
8599     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8600       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8601           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8602         break;
8603   }
8604 
8605   // Tracks if we tried to vectorize stores starting from the given tail
8606   // already.
8607   SmallBitVector TriedTails(E, false);
8608   // For stores that start but don't end a link in the chain:
8609   for (int Cnt = E; Cnt > 0; --Cnt) {
8610     int I = Cnt - 1;
8611     if (ConsecutiveChain[I].first == E || Tails.test(I))
8612       continue;
8613     // We found a store instr that starts a chain. Now follow the chain and try
8614     // to vectorize it.
8615     BoUpSLP::ValueList Operands;
8616     // Collect the chain into a list.
8617     while (I != E && !VectorizedStores.count(Stores[I])) {
8618       Operands.push_back(Stores[I]);
8619       Tails.set(I);
8620       if (ConsecutiveChain[I].second != 1) {
8621         // Mark the new end in the chain and go back, if required. It might be
8622         // required if the original stores come in reversed order, for example.
8623         if (ConsecutiveChain[I].first != E &&
8624             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8625             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8626           TriedTails.set(I);
8627           Tails.reset(ConsecutiveChain[I].first);
8628           if (Cnt < ConsecutiveChain[I].first + 2)
8629             Cnt = ConsecutiveChain[I].first + 2;
8630         }
8631         break;
8632       }
8633       // Move to the next value in the chain.
8634       I = ConsecutiveChain[I].first;
8635     }
8636     assert(!Operands.empty() && "Expected non-empty list of stores.");
8637 
8638     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8639     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8640     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8641 
8642     unsigned MinVF = R.getMinVF(EltSize);
8643     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8644                               MaxElts);
8645 
8646     // FIXME: Is division-by-2 the correct step? Should we assert that the
8647     // register size is a power-of-2?
8648     unsigned StartIdx = 0;
8649     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8650       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8651         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8652         if (!VectorizedStores.count(Slice.front()) &&
8653             !VectorizedStores.count(Slice.back()) &&
8654             vectorizeStoreChain(Slice, R, Cnt)) {
8655           // Mark the vectorized stores so that we don't vectorize them again.
8656           VectorizedStores.insert(Slice.begin(), Slice.end());
8657           Changed = true;
8658           // If we vectorized initial block, no need to try to vectorize it
8659           // again.
8660           if (Cnt == StartIdx)
8661             StartIdx += Size;
8662           Cnt += Size;
8663           continue;
8664         }
8665         ++Cnt;
8666       }
8667       // Check if the whole array was vectorized already - exit.
8668       if (StartIdx >= Operands.size())
8669         break;
8670     }
8671   }
8672 
8673   return Changed;
8674 }
8675 
8676 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8677   // Initialize the collections. We will make a single pass over the block.
8678   Stores.clear();
8679   GEPs.clear();
8680 
8681   // Visit the store and getelementptr instructions in BB and organize them in
8682   // Stores and GEPs according to the underlying objects of their pointer
8683   // operands.
8684   for (Instruction &I : *BB) {
8685     // Ignore store instructions that are volatile or have a pointer operand
8686     // that doesn't point to a scalar type.
8687     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8688       if (!SI->isSimple())
8689         continue;
8690       if (!isValidElementType(SI->getValueOperand()->getType()))
8691         continue;
8692       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8693     }
8694 
8695     // Ignore getelementptr instructions that have more than one index, a
8696     // constant index, or a pointer operand that doesn't point to a scalar
8697     // type.
8698     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8699       auto Idx = GEP->idx_begin()->get();
8700       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8701         continue;
8702       if (!isValidElementType(Idx->getType()))
8703         continue;
8704       if (GEP->getType()->isVectorTy())
8705         continue;
8706       GEPs[GEP->getPointerOperand()].push_back(GEP);
8707     }
8708   }
8709 }
8710 
8711 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8712   if (!A || !B)
8713     return false;
8714   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8715     return false;
8716   Value *VL[] = {A, B};
8717   return tryToVectorizeList(VL, R);
8718 }
8719 
8720 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8721                                            bool LimitForRegisterSize) {
8722   if (VL.size() < 2)
8723     return false;
8724 
8725   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8726                     << VL.size() << ".\n");
8727 
8728   // Check that all of the parts are instructions of the same type,
8729   // we permit an alternate opcode via InstructionsState.
8730   InstructionsState S = getSameOpcode(VL);
8731   if (!S.getOpcode())
8732     return false;
8733 
8734   Instruction *I0 = cast<Instruction>(S.OpValue);
8735   // Make sure invalid types (including vector type) are rejected before
8736   // determining vectorization factor for scalar instructions.
8737   for (Value *V : VL) {
8738     Type *Ty = V->getType();
8739     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8740       // NOTE: the following will give user internal llvm type name, which may
8741       // not be useful.
8742       R.getORE()->emit([&]() {
8743         std::string type_str;
8744         llvm::raw_string_ostream rso(type_str);
8745         Ty->print(rso);
8746         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8747                << "Cannot SLP vectorize list: type "
8748                << rso.str() + " is unsupported by vectorizer";
8749       });
8750       return false;
8751     }
8752   }
8753 
8754   unsigned Sz = R.getVectorElementSize(I0);
8755   unsigned MinVF = R.getMinVF(Sz);
8756   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8757   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8758   if (MaxVF < 2) {
8759     R.getORE()->emit([&]() {
8760       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8761              << "Cannot SLP vectorize list: vectorization factor "
8762              << "less than 2 is not supported";
8763     });
8764     return false;
8765   }
8766 
8767   bool Changed = false;
8768   bool CandidateFound = false;
8769   InstructionCost MinCost = SLPCostThreshold.getValue();
8770   Type *ScalarTy = VL[0]->getType();
8771   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8772     ScalarTy = IE->getOperand(1)->getType();
8773 
8774   unsigned NextInst = 0, MaxInst = VL.size();
8775   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8776     // No actual vectorization should happen, if number of parts is the same as
8777     // provided vectorization factor (i.e. the scalar type is used for vector
8778     // code during codegen).
8779     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8780     if (TTI->getNumberOfParts(VecTy) == VF)
8781       continue;
8782     for (unsigned I = NextInst; I < MaxInst; ++I) {
8783       unsigned OpsWidth = 0;
8784 
8785       if (I + VF > MaxInst)
8786         OpsWidth = MaxInst - I;
8787       else
8788         OpsWidth = VF;
8789 
8790       if (!isPowerOf2_32(OpsWidth))
8791         continue;
8792 
8793       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8794           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8795         break;
8796 
8797       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8798       // Check that a previous iteration of this loop did not delete the Value.
8799       if (llvm::any_of(Ops, [&R](Value *V) {
8800             auto *I = dyn_cast<Instruction>(V);
8801             return I && R.isDeleted(I);
8802           }))
8803         continue;
8804 
8805       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8806                         << "\n");
8807 
8808       R.buildTree(Ops);
8809       if (R.isTreeTinyAndNotFullyVectorizable())
8810         continue;
8811       R.reorderTopToBottom();
8812       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8813       R.buildExternalUses();
8814 
8815       R.computeMinimumValueSizes();
8816       InstructionCost Cost = R.getTreeCost();
8817       CandidateFound = true;
8818       MinCost = std::min(MinCost, Cost);
8819 
8820       if (Cost < -SLPCostThreshold) {
8821         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8822         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8823                                                     cast<Instruction>(Ops[0]))
8824                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8825                                  << " and with tree size "
8826                                  << ore::NV("TreeSize", R.getTreeSize()));
8827 
8828         R.vectorizeTree();
8829         // Move to the next bundle.
8830         I += VF - 1;
8831         NextInst = I + 1;
8832         Changed = true;
8833       }
8834     }
8835   }
8836 
8837   if (!Changed && CandidateFound) {
8838     R.getORE()->emit([&]() {
8839       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8840              << "List vectorization was possible but not beneficial with cost "
8841              << ore::NV("Cost", MinCost) << " >= "
8842              << ore::NV("Treshold", -SLPCostThreshold);
8843     });
8844   } else if (!Changed) {
8845     R.getORE()->emit([&]() {
8846       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8847              << "Cannot SLP vectorize list: vectorization was impossible"
8848              << " with available vectorization factors";
8849     });
8850   }
8851   return Changed;
8852 }
8853 
8854 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8855   if (!I)
8856     return false;
8857 
8858   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8859     return false;
8860 
8861   Value *P = I->getParent();
8862 
8863   // Vectorize in current basic block only.
8864   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8865   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8866   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8867     return false;
8868 
8869   // Try to vectorize V.
8870   if (tryToVectorizePair(Op0, Op1, R))
8871     return true;
8872 
8873   auto *A = dyn_cast<BinaryOperator>(Op0);
8874   auto *B = dyn_cast<BinaryOperator>(Op1);
8875   // Try to skip B.
8876   if (B && B->hasOneUse()) {
8877     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8878     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8879     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8880       return true;
8881     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8882       return true;
8883   }
8884 
8885   // Try to skip A.
8886   if (A && A->hasOneUse()) {
8887     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8888     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8889     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8890       return true;
8891     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8892       return true;
8893   }
8894   return false;
8895 }
8896 
8897 namespace {
8898 
8899 /// Model horizontal reductions.
8900 ///
8901 /// A horizontal reduction is a tree of reduction instructions that has values
8902 /// that can be put into a vector as its leaves. For example:
8903 ///
8904 /// mul mul mul mul
8905 ///  \  /    \  /
8906 ///   +       +
8907 ///    \     /
8908 ///       +
8909 /// This tree has "mul" as its leaf values and "+" as its reduction
8910 /// instructions. A reduction can feed into a store or a binary operation
8911 /// feeding a phi.
8912 ///    ...
8913 ///    \  /
8914 ///     +
8915 ///     |
8916 ///  phi +=
8917 ///
8918 ///  Or:
8919 ///    ...
8920 ///    \  /
8921 ///     +
8922 ///     |
8923 ///   *p =
8924 ///
8925 class HorizontalReduction {
8926   using ReductionOpsType = SmallVector<Value *, 16>;
8927   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8928   ReductionOpsListType ReductionOps;
8929   SmallVector<Value *, 32> ReducedVals;
8930   // Use map vector to make stable output.
8931   MapVector<Instruction *, Value *> ExtraArgs;
8932   WeakTrackingVH ReductionRoot;
8933   /// The type of reduction operation.
8934   RecurKind RdxKind;
8935 
8936   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8937 
8938   static bool isCmpSelMinMax(Instruction *I) {
8939     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8940            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8941   }
8942 
8943   // And/or are potentially poison-safe logical patterns like:
8944   // select x, y, false
8945   // select x, true, y
8946   static bool isBoolLogicOp(Instruction *I) {
8947     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8948            match(I, m_LogicalOr(m_Value(), m_Value()));
8949   }
8950 
8951   /// Checks if instruction is associative and can be vectorized.
8952   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8953     if (Kind == RecurKind::None)
8954       return false;
8955 
8956     // Integer ops that map to select instructions or intrinsics are fine.
8957     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8958         isBoolLogicOp(I))
8959       return true;
8960 
8961     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8962       // FP min/max are associative except for NaN and -0.0. We do not
8963       // have to rule out -0.0 here because the intrinsic semantics do not
8964       // specify a fixed result for it.
8965       return I->getFastMathFlags().noNaNs();
8966     }
8967 
8968     return I->isAssociative();
8969   }
8970 
8971   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8972     // Poison-safe 'or' takes the form: select X, true, Y
8973     // To make that work with the normal operand processing, we skip the
8974     // true value operand.
8975     // TODO: Change the code and data structures to handle this without a hack.
8976     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8977       return I->getOperand(2);
8978     return I->getOperand(Index);
8979   }
8980 
8981   /// Checks if the ParentStackElem.first should be marked as a reduction
8982   /// operation with an extra argument or as extra argument itself.
8983   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8984                     Value *ExtraArg) {
8985     if (ExtraArgs.count(ParentStackElem.first)) {
8986       ExtraArgs[ParentStackElem.first] = nullptr;
8987       // We ran into something like:
8988       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8989       // The whole ParentStackElem.first should be considered as an extra value
8990       // in this case.
8991       // Do not perform analysis of remaining operands of ParentStackElem.first
8992       // instruction, this whole instruction is an extra argument.
8993       ParentStackElem.second = INVALID_OPERAND_INDEX;
8994     } else {
8995       // We ran into something like:
8996       // ParentStackElem.first += ... + ExtraArg + ...
8997       ExtraArgs[ParentStackElem.first] = ExtraArg;
8998     }
8999   }
9000 
9001   /// Creates reduction operation with the current opcode.
9002   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9003                          Value *RHS, const Twine &Name, bool UseSelect) {
9004     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9005     switch (Kind) {
9006     case RecurKind::Or:
9007       if (UseSelect &&
9008           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9009         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9010       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9011                                  Name);
9012     case RecurKind::And:
9013       if (UseSelect &&
9014           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9015         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9016       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9017                                  Name);
9018     case RecurKind::Add:
9019     case RecurKind::Mul:
9020     case RecurKind::Xor:
9021     case RecurKind::FAdd:
9022     case RecurKind::FMul:
9023       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9024                                  Name);
9025     case RecurKind::FMax:
9026       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9027     case RecurKind::FMin:
9028       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9029     case RecurKind::SMax:
9030       if (UseSelect) {
9031         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9032         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9033       }
9034       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9035     case RecurKind::SMin:
9036       if (UseSelect) {
9037         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9038         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9039       }
9040       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9041     case RecurKind::UMax:
9042       if (UseSelect) {
9043         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9044         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9045       }
9046       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9047     case RecurKind::UMin:
9048       if (UseSelect) {
9049         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9050         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9051       }
9052       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9053     default:
9054       llvm_unreachable("Unknown reduction operation.");
9055     }
9056   }
9057 
9058   /// Creates reduction operation with the current opcode with the IR flags
9059   /// from \p ReductionOps.
9060   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9061                          Value *RHS, const Twine &Name,
9062                          const ReductionOpsListType &ReductionOps) {
9063     bool UseSelect = ReductionOps.size() == 2 ||
9064                      // Logical or/and.
9065                      (ReductionOps.size() == 1 &&
9066                       isa<SelectInst>(ReductionOps.front().front()));
9067     assert((!UseSelect || ReductionOps.size() != 2 ||
9068             isa<SelectInst>(ReductionOps[1][0])) &&
9069            "Expected cmp + select pairs for reduction");
9070     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9071     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9072       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9073         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9074         propagateIRFlags(Op, ReductionOps[1]);
9075         return Op;
9076       }
9077     }
9078     propagateIRFlags(Op, ReductionOps[0]);
9079     return Op;
9080   }
9081 
9082   /// Creates reduction operation with the current opcode with the IR flags
9083   /// from \p I.
9084   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9085                          Value *RHS, const Twine &Name, Instruction *I) {
9086     auto *SelI = dyn_cast<SelectInst>(I);
9087     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9088     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9089       if (auto *Sel = dyn_cast<SelectInst>(Op))
9090         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9091     }
9092     propagateIRFlags(Op, I);
9093     return Op;
9094   }
9095 
9096   static RecurKind getRdxKind(Instruction *I) {
9097     assert(I && "Expected instruction for reduction matching");
9098     if (match(I, m_Add(m_Value(), m_Value())))
9099       return RecurKind::Add;
9100     if (match(I, m_Mul(m_Value(), m_Value())))
9101       return RecurKind::Mul;
9102     if (match(I, m_And(m_Value(), m_Value())) ||
9103         match(I, m_LogicalAnd(m_Value(), m_Value())))
9104       return RecurKind::And;
9105     if (match(I, m_Or(m_Value(), m_Value())) ||
9106         match(I, m_LogicalOr(m_Value(), m_Value())))
9107       return RecurKind::Or;
9108     if (match(I, m_Xor(m_Value(), m_Value())))
9109       return RecurKind::Xor;
9110     if (match(I, m_FAdd(m_Value(), m_Value())))
9111       return RecurKind::FAdd;
9112     if (match(I, m_FMul(m_Value(), m_Value())))
9113       return RecurKind::FMul;
9114 
9115     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9116       return RecurKind::FMax;
9117     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9118       return RecurKind::FMin;
9119 
9120     // This matches either cmp+select or intrinsics. SLP is expected to handle
9121     // either form.
9122     // TODO: If we are canonicalizing to intrinsics, we can remove several
9123     //       special-case paths that deal with selects.
9124     if (match(I, m_SMax(m_Value(), m_Value())))
9125       return RecurKind::SMax;
9126     if (match(I, m_SMin(m_Value(), m_Value())))
9127       return RecurKind::SMin;
9128     if (match(I, m_UMax(m_Value(), m_Value())))
9129       return RecurKind::UMax;
9130     if (match(I, m_UMin(m_Value(), m_Value())))
9131       return RecurKind::UMin;
9132 
9133     if (auto *Select = dyn_cast<SelectInst>(I)) {
9134       // Try harder: look for min/max pattern based on instructions producing
9135       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9136       // During the intermediate stages of SLP, it's very common to have
9137       // pattern like this (since optimizeGatherSequence is run only once
9138       // at the end):
9139       // %1 = extractelement <2 x i32> %a, i32 0
9140       // %2 = extractelement <2 x i32> %a, i32 1
9141       // %cond = icmp sgt i32 %1, %2
9142       // %3 = extractelement <2 x i32> %a, i32 0
9143       // %4 = extractelement <2 x i32> %a, i32 1
9144       // %select = select i1 %cond, i32 %3, i32 %4
9145       CmpInst::Predicate Pred;
9146       Instruction *L1;
9147       Instruction *L2;
9148 
9149       Value *LHS = Select->getTrueValue();
9150       Value *RHS = Select->getFalseValue();
9151       Value *Cond = Select->getCondition();
9152 
9153       // TODO: Support inverse predicates.
9154       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9155         if (!isa<ExtractElementInst>(RHS) ||
9156             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9157           return RecurKind::None;
9158       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9159         if (!isa<ExtractElementInst>(LHS) ||
9160             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9161           return RecurKind::None;
9162       } else {
9163         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9164           return RecurKind::None;
9165         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9166             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9167             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9168           return RecurKind::None;
9169       }
9170 
9171       switch (Pred) {
9172       default:
9173         return RecurKind::None;
9174       case CmpInst::ICMP_SGT:
9175       case CmpInst::ICMP_SGE:
9176         return RecurKind::SMax;
9177       case CmpInst::ICMP_SLT:
9178       case CmpInst::ICMP_SLE:
9179         return RecurKind::SMin;
9180       case CmpInst::ICMP_UGT:
9181       case CmpInst::ICMP_UGE:
9182         return RecurKind::UMax;
9183       case CmpInst::ICMP_ULT:
9184       case CmpInst::ICMP_ULE:
9185         return RecurKind::UMin;
9186       }
9187     }
9188     return RecurKind::None;
9189   }
9190 
9191   /// Get the index of the first operand.
9192   static unsigned getFirstOperandIndex(Instruction *I) {
9193     return isCmpSelMinMax(I) ? 1 : 0;
9194   }
9195 
9196   /// Total number of operands in the reduction operation.
9197   static unsigned getNumberOfOperands(Instruction *I) {
9198     return isCmpSelMinMax(I) ? 3 : 2;
9199   }
9200 
9201   /// Checks if the instruction is in basic block \p BB.
9202   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9203   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9204     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9205       auto *Sel = cast<SelectInst>(I);
9206       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9207       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9208     }
9209     return I->getParent() == BB;
9210   }
9211 
9212   /// Expected number of uses for reduction operations/reduced values.
9213   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9214     if (IsCmpSelMinMax) {
9215       // SelectInst must be used twice while the condition op must have single
9216       // use only.
9217       if (auto *Sel = dyn_cast<SelectInst>(I))
9218         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9219       return I->hasNUses(2);
9220     }
9221 
9222     // Arithmetic reduction operation must be used once only.
9223     return I->hasOneUse();
9224   }
9225 
9226   /// Initializes the list of reduction operations.
9227   void initReductionOps(Instruction *I) {
9228     if (isCmpSelMinMax(I))
9229       ReductionOps.assign(2, ReductionOpsType());
9230     else
9231       ReductionOps.assign(1, ReductionOpsType());
9232   }
9233 
9234   /// Add all reduction operations for the reduction instruction \p I.
9235   void addReductionOps(Instruction *I) {
9236     if (isCmpSelMinMax(I)) {
9237       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9238       ReductionOps[1].emplace_back(I);
9239     } else {
9240       ReductionOps[0].emplace_back(I);
9241     }
9242   }
9243 
9244   static Value *getLHS(RecurKind Kind, Instruction *I) {
9245     if (Kind == RecurKind::None)
9246       return nullptr;
9247     return I->getOperand(getFirstOperandIndex(I));
9248   }
9249   static Value *getRHS(RecurKind Kind, Instruction *I) {
9250     if (Kind == RecurKind::None)
9251       return nullptr;
9252     return I->getOperand(getFirstOperandIndex(I) + 1);
9253   }
9254 
9255 public:
9256   HorizontalReduction() = default;
9257 
9258   /// Try to find a reduction tree.
9259   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9260     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9261            "Phi needs to use the binary operator");
9262     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9263             isa<IntrinsicInst>(Inst)) &&
9264            "Expected binop, select, or intrinsic for reduction matching");
9265     RdxKind = getRdxKind(Inst);
9266 
9267     // We could have a initial reductions that is not an add.
9268     //  r *= v1 + v2 + v3 + v4
9269     // In such a case start looking for a tree rooted in the first '+'.
9270     if (Phi) {
9271       if (getLHS(RdxKind, Inst) == Phi) {
9272         Phi = nullptr;
9273         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9274         if (!Inst)
9275           return false;
9276         RdxKind = getRdxKind(Inst);
9277       } else if (getRHS(RdxKind, Inst) == Phi) {
9278         Phi = nullptr;
9279         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9280         if (!Inst)
9281           return false;
9282         RdxKind = getRdxKind(Inst);
9283       }
9284     }
9285 
9286     if (!isVectorizable(RdxKind, Inst))
9287       return false;
9288 
9289     // Analyze "regular" integer/FP types for reductions - no target-specific
9290     // types or pointers.
9291     Type *Ty = Inst->getType();
9292     if (!isValidElementType(Ty) || Ty->isPointerTy())
9293       return false;
9294 
9295     // Though the ultimate reduction may have multiple uses, its condition must
9296     // have only single use.
9297     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9298       if (!Sel->getCondition()->hasOneUse())
9299         return false;
9300 
9301     ReductionRoot = Inst;
9302 
9303     // The opcode for leaf values that we perform a reduction on.
9304     // For example: load(x) + load(y) + load(z) + fptoui(w)
9305     // The leaf opcode for 'w' does not match, so we don't include it as a
9306     // potential candidate for the reduction.
9307     unsigned LeafOpcode = 0;
9308 
9309     // Post-order traverse the reduction tree starting at Inst. We only handle
9310     // true trees containing binary operators or selects.
9311     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9312     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9313     initReductionOps(Inst);
9314     while (!Stack.empty()) {
9315       Instruction *TreeN = Stack.back().first;
9316       unsigned EdgeToVisit = Stack.back().second++;
9317       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9318       bool IsReducedValue = TreeRdxKind != RdxKind;
9319 
9320       // Postorder visit.
9321       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9322         if (IsReducedValue)
9323           ReducedVals.push_back(TreeN);
9324         else {
9325           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9326           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9327             // Check if TreeN is an extra argument of its parent operation.
9328             if (Stack.size() <= 1) {
9329               // TreeN can't be an extra argument as it is a root reduction
9330               // operation.
9331               return false;
9332             }
9333             // Yes, TreeN is an extra argument, do not add it to a list of
9334             // reduction operations.
9335             // Stack[Stack.size() - 2] always points to the parent operation.
9336             markExtraArg(Stack[Stack.size() - 2], TreeN);
9337             ExtraArgs.erase(TreeN);
9338           } else
9339             addReductionOps(TreeN);
9340         }
9341         // Retract.
9342         Stack.pop_back();
9343         continue;
9344       }
9345 
9346       // Visit operands.
9347       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9348       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9349       if (!EdgeInst) {
9350         // Edge value is not a reduction instruction or a leaf instruction.
9351         // (It may be a constant, function argument, or something else.)
9352         markExtraArg(Stack.back(), EdgeVal);
9353         continue;
9354       }
9355       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9356       // Continue analysis if the next operand is a reduction operation or
9357       // (possibly) a leaf value. If the leaf value opcode is not set,
9358       // the first met operation != reduction operation is considered as the
9359       // leaf opcode.
9360       // Only handle trees in the current basic block.
9361       // Each tree node needs to have minimal number of users except for the
9362       // ultimate reduction.
9363       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9364       if (EdgeInst != Phi && EdgeInst != Inst &&
9365           hasSameParent(EdgeInst, Inst->getParent()) &&
9366           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9367           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9368         if (IsRdxInst) {
9369           // We need to be able to reassociate the reduction operations.
9370           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9371             // I is an extra argument for TreeN (its parent operation).
9372             markExtraArg(Stack.back(), EdgeInst);
9373             continue;
9374           }
9375         } else if (!LeafOpcode) {
9376           LeafOpcode = EdgeInst->getOpcode();
9377         }
9378         Stack.push_back(
9379             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9380         continue;
9381       }
9382       // I is an extra argument for TreeN (its parent operation).
9383       markExtraArg(Stack.back(), EdgeInst);
9384     }
9385     return true;
9386   }
9387 
9388   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9389   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9390     // If there are a sufficient number of reduction values, reduce
9391     // to a nearby power-of-2. We can safely generate oversized
9392     // vectors and rely on the backend to split them to legal sizes.
9393     unsigned NumReducedVals = ReducedVals.size();
9394     if (NumReducedVals < 4)
9395       return nullptr;
9396 
9397     // Intersect the fast-math-flags from all reduction operations.
9398     FastMathFlags RdxFMF;
9399     RdxFMF.set();
9400     for (ReductionOpsType &RdxOp : ReductionOps) {
9401       for (Value *RdxVal : RdxOp) {
9402         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9403           RdxFMF &= FPMO->getFastMathFlags();
9404       }
9405     }
9406 
9407     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9408     Builder.setFastMathFlags(RdxFMF);
9409 
9410     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9411     // The same extra argument may be used several times, so log each attempt
9412     // to use it.
9413     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9414       assert(Pair.first && "DebugLoc must be set.");
9415       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9416     }
9417 
9418     // The compare instruction of a min/max is the insertion point for new
9419     // instructions and may be replaced with a new compare instruction.
9420     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9421       assert(isa<SelectInst>(RdxRootInst) &&
9422              "Expected min/max reduction to have select root instruction");
9423       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9424       assert(isa<Instruction>(ScalarCond) &&
9425              "Expected min/max reduction to have compare condition");
9426       return cast<Instruction>(ScalarCond);
9427     };
9428 
9429     // The reduction root is used as the insertion point for new instructions,
9430     // so set it as externally used to prevent it from being deleted.
9431     ExternallyUsedValues[ReductionRoot];
9432     SmallVector<Value *, 16> IgnoreList;
9433     for (ReductionOpsType &RdxOp : ReductionOps)
9434       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9435 
9436     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9437     if (NumReducedVals > ReduxWidth) {
9438       // In the loop below, we are building a tree based on a window of
9439       // 'ReduxWidth' values.
9440       // If the operands of those values have common traits (compare predicate,
9441       // constant operand, etc), then we want to group those together to
9442       // minimize the cost of the reduction.
9443 
9444       // TODO: This should be extended to count common operands for
9445       //       compares and binops.
9446 
9447       // Step 1: Count the number of times each compare predicate occurs.
9448       SmallDenseMap<unsigned, unsigned> PredCountMap;
9449       for (Value *RdxVal : ReducedVals) {
9450         CmpInst::Predicate Pred;
9451         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9452           ++PredCountMap[Pred];
9453       }
9454       // Step 2: Sort the values so the most common predicates come first.
9455       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9456         CmpInst::Predicate PredA, PredB;
9457         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9458             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9459           return PredCountMap[PredA] > PredCountMap[PredB];
9460         }
9461         return false;
9462       });
9463     }
9464 
9465     Value *VectorizedTree = nullptr;
9466     unsigned i = 0;
9467     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9468       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9469       V.buildTree(VL, IgnoreList);
9470       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9471         break;
9472       if (V.isLoadCombineReductionCandidate(RdxKind))
9473         break;
9474       V.reorderTopToBottom();
9475       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9476       V.buildExternalUses(ExternallyUsedValues);
9477 
9478       // For a poison-safe boolean logic reduction, do not replace select
9479       // instructions with logic ops. All reduced values will be frozen (see
9480       // below) to prevent leaking poison.
9481       if (isa<SelectInst>(ReductionRoot) &&
9482           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9483           NumReducedVals != ReduxWidth)
9484         break;
9485 
9486       V.computeMinimumValueSizes();
9487 
9488       // Estimate cost.
9489       InstructionCost TreeCost =
9490           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9491       InstructionCost ReductionCost =
9492           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9493       InstructionCost Cost = TreeCost + ReductionCost;
9494       if (!Cost.isValid()) {
9495         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9496         return nullptr;
9497       }
9498       if (Cost >= -SLPCostThreshold) {
9499         V.getORE()->emit([&]() {
9500           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9501                                           cast<Instruction>(VL[0]))
9502                  << "Vectorizing horizontal reduction is possible"
9503                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9504                  << " and threshold "
9505                  << ore::NV("Threshold", -SLPCostThreshold);
9506         });
9507         break;
9508       }
9509 
9510       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9511                         << Cost << ". (HorRdx)\n");
9512       V.getORE()->emit([&]() {
9513         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9514                                   cast<Instruction>(VL[0]))
9515                << "Vectorized horizontal reduction with cost "
9516                << ore::NV("Cost", Cost) << " and with tree size "
9517                << ore::NV("TreeSize", V.getTreeSize());
9518       });
9519 
9520       // Vectorize a tree.
9521       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9522       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9523 
9524       // Emit a reduction. If the root is a select (min/max idiom), the insert
9525       // point is the compare condition of that select.
9526       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9527       if (isCmpSelMinMax(RdxRootInst))
9528         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9529       else
9530         Builder.SetInsertPoint(RdxRootInst);
9531 
9532       // To prevent poison from leaking across what used to be sequential, safe,
9533       // scalar boolean logic operations, the reduction operand must be frozen.
9534       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9535         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9536 
9537       Value *ReducedSubTree =
9538           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9539 
9540       if (!VectorizedTree) {
9541         // Initialize the final value in the reduction.
9542         VectorizedTree = ReducedSubTree;
9543       } else {
9544         // Update the final value in the reduction.
9545         Builder.SetCurrentDebugLocation(Loc);
9546         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9547                                   ReducedSubTree, "op.rdx", ReductionOps);
9548       }
9549       i += ReduxWidth;
9550       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9551     }
9552 
9553     if (VectorizedTree) {
9554       // Finish the reduction.
9555       for (; i < NumReducedVals; ++i) {
9556         auto *I = cast<Instruction>(ReducedVals[i]);
9557         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9558         VectorizedTree =
9559             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9560       }
9561       for (auto &Pair : ExternallyUsedValues) {
9562         // Add each externally used value to the final reduction.
9563         for (auto *I : Pair.second) {
9564           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9565           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9566                                     Pair.first, "op.extra", I);
9567         }
9568       }
9569 
9570       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9571 
9572       // Mark all scalar reduction ops for deletion, they are replaced by the
9573       // vector reductions.
9574       V.eraseInstructions(IgnoreList);
9575     }
9576     return VectorizedTree;
9577   }
9578 
9579   unsigned numReductionValues() const { return ReducedVals.size(); }
9580 
9581 private:
9582   /// Calculate the cost of a reduction.
9583   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9584                                    Value *FirstReducedVal, unsigned ReduxWidth,
9585                                    FastMathFlags FMF) {
9586     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9587     Type *ScalarTy = FirstReducedVal->getType();
9588     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9589     InstructionCost VectorCost, ScalarCost;
9590     switch (RdxKind) {
9591     case RecurKind::Add:
9592     case RecurKind::Mul:
9593     case RecurKind::Or:
9594     case RecurKind::And:
9595     case RecurKind::Xor:
9596     case RecurKind::FAdd:
9597     case RecurKind::FMul: {
9598       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9599       VectorCost =
9600           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9601       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9602       break;
9603     }
9604     case RecurKind::FMax:
9605     case RecurKind::FMin: {
9606       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9607       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9608       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9609                                                /*IsUnsigned=*/false, CostKind);
9610       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9611       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9612                                            SclCondTy, RdxPred, CostKind) +
9613                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9614                                            SclCondTy, RdxPred, CostKind);
9615       break;
9616     }
9617     case RecurKind::SMax:
9618     case RecurKind::SMin:
9619     case RecurKind::UMax:
9620     case RecurKind::UMin: {
9621       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9622       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9623       bool IsUnsigned =
9624           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9625       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9626                                                CostKind);
9627       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9628       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9629                                            SclCondTy, RdxPred, CostKind) +
9630                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9631                                            SclCondTy, RdxPred, CostKind);
9632       break;
9633     }
9634     default:
9635       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9636     }
9637 
9638     // Scalar cost is repeated for N-1 elements.
9639     ScalarCost *= (ReduxWidth - 1);
9640     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9641                       << " for reduction that starts with " << *FirstReducedVal
9642                       << " (It is a splitting reduction)\n");
9643     return VectorCost - ScalarCost;
9644   }
9645 
9646   /// Emit a horizontal reduction of the vectorized value.
9647   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9648                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9649     assert(VectorizedValue && "Need to have a vectorized tree node");
9650     assert(isPowerOf2_32(ReduxWidth) &&
9651            "We only handle power-of-two reductions for now");
9652     assert(RdxKind != RecurKind::FMulAdd &&
9653            "A call to the llvm.fmuladd intrinsic is not handled yet");
9654 
9655     ++NumVectorInstructions;
9656     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9657   }
9658 };
9659 
9660 } // end anonymous namespace
9661 
9662 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9663   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9664     return cast<FixedVectorType>(IE->getType())->getNumElements();
9665 
9666   unsigned AggregateSize = 1;
9667   auto *IV = cast<InsertValueInst>(InsertInst);
9668   Type *CurrentType = IV->getType();
9669   do {
9670     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9671       for (auto *Elt : ST->elements())
9672         if (Elt != ST->getElementType(0)) // check homogeneity
9673           return None;
9674       AggregateSize *= ST->getNumElements();
9675       CurrentType = ST->getElementType(0);
9676     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9677       AggregateSize *= AT->getNumElements();
9678       CurrentType = AT->getElementType();
9679     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9680       AggregateSize *= VT->getNumElements();
9681       return AggregateSize;
9682     } else if (CurrentType->isSingleValueType()) {
9683       return AggregateSize;
9684     } else {
9685       return None;
9686     }
9687   } while (true);
9688 }
9689 
9690 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9691                                    TargetTransformInfo *TTI,
9692                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9693                                    SmallVectorImpl<Value *> &InsertElts,
9694                                    unsigned OperandOffset) {
9695   do {
9696     Value *InsertedOperand = LastInsertInst->getOperand(1);
9697     Optional<unsigned> OperandIndex =
9698         getInsertIndex(LastInsertInst, OperandOffset);
9699     if (!OperandIndex)
9700       return;
9701     if (isa<InsertElementInst>(InsertedOperand) ||
9702         isa<InsertValueInst>(InsertedOperand)) {
9703       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9704                              BuildVectorOpds, InsertElts, *OperandIndex);
9705 
9706     } else {
9707       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9708       InsertElts[*OperandIndex] = LastInsertInst;
9709     }
9710     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9711   } while (LastInsertInst != nullptr &&
9712            (isa<InsertValueInst>(LastInsertInst) ||
9713             isa<InsertElementInst>(LastInsertInst)) &&
9714            LastInsertInst->hasOneUse());
9715 }
9716 
9717 /// Recognize construction of vectors like
9718 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9719 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9720 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9721 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9722 ///  starting from the last insertelement or insertvalue instruction.
9723 ///
9724 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9725 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9726 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9727 ///
9728 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9729 ///
9730 /// \return true if it matches.
9731 static bool findBuildAggregate(Instruction *LastInsertInst,
9732                                TargetTransformInfo *TTI,
9733                                SmallVectorImpl<Value *> &BuildVectorOpds,
9734                                SmallVectorImpl<Value *> &InsertElts) {
9735 
9736   assert((isa<InsertElementInst>(LastInsertInst) ||
9737           isa<InsertValueInst>(LastInsertInst)) &&
9738          "Expected insertelement or insertvalue instruction!");
9739 
9740   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9741          "Expected empty result vectors!");
9742 
9743   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9744   if (!AggregateSize)
9745     return false;
9746   BuildVectorOpds.resize(*AggregateSize);
9747   InsertElts.resize(*AggregateSize);
9748 
9749   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9750   llvm::erase_value(BuildVectorOpds, nullptr);
9751   llvm::erase_value(InsertElts, nullptr);
9752   if (BuildVectorOpds.size() >= 2)
9753     return true;
9754 
9755   return false;
9756 }
9757 
9758 /// Try and get a reduction value from a phi node.
9759 ///
9760 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9761 /// if they come from either \p ParentBB or a containing loop latch.
9762 ///
9763 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9764 /// if not possible.
9765 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9766                                 BasicBlock *ParentBB, LoopInfo *LI) {
9767   // There are situations where the reduction value is not dominated by the
9768   // reduction phi. Vectorizing such cases has been reported to cause
9769   // miscompiles. See PR25787.
9770   auto DominatedReduxValue = [&](Value *R) {
9771     return isa<Instruction>(R) &&
9772            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9773   };
9774 
9775   Value *Rdx = nullptr;
9776 
9777   // Return the incoming value if it comes from the same BB as the phi node.
9778   if (P->getIncomingBlock(0) == ParentBB) {
9779     Rdx = P->getIncomingValue(0);
9780   } else if (P->getIncomingBlock(1) == ParentBB) {
9781     Rdx = P->getIncomingValue(1);
9782   }
9783 
9784   if (Rdx && DominatedReduxValue(Rdx))
9785     return Rdx;
9786 
9787   // Otherwise, check whether we have a loop latch to look at.
9788   Loop *BBL = LI->getLoopFor(ParentBB);
9789   if (!BBL)
9790     return nullptr;
9791   BasicBlock *BBLatch = BBL->getLoopLatch();
9792   if (!BBLatch)
9793     return nullptr;
9794 
9795   // There is a loop latch, return the incoming value if it comes from
9796   // that. This reduction pattern occasionally turns up.
9797   if (P->getIncomingBlock(0) == BBLatch) {
9798     Rdx = P->getIncomingValue(0);
9799   } else if (P->getIncomingBlock(1) == BBLatch) {
9800     Rdx = P->getIncomingValue(1);
9801   }
9802 
9803   if (Rdx && DominatedReduxValue(Rdx))
9804     return Rdx;
9805 
9806   return nullptr;
9807 }
9808 
9809 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9810   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9811     return true;
9812   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9813     return true;
9814   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9815     return true;
9816   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9817     return true;
9818   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9819     return true;
9820   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9821     return true;
9822   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9823     return true;
9824   return false;
9825 }
9826 
9827 /// Attempt to reduce a horizontal reduction.
9828 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9829 /// with reduction operators \a Root (or one of its operands) in a basic block
9830 /// \a BB, then check if it can be done. If horizontal reduction is not found
9831 /// and root instruction is a binary operation, vectorization of the operands is
9832 /// attempted.
9833 /// \returns true if a horizontal reduction was matched and reduced or operands
9834 /// of one of the binary instruction were vectorized.
9835 /// \returns false if a horizontal reduction was not matched (or not possible)
9836 /// or no vectorization of any binary operation feeding \a Root instruction was
9837 /// performed.
9838 static bool tryToVectorizeHorReductionOrInstOperands(
9839     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9840     TargetTransformInfo *TTI,
9841     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9842   if (!ShouldVectorizeHor)
9843     return false;
9844 
9845   if (!Root)
9846     return false;
9847 
9848   if (Root->getParent() != BB || isa<PHINode>(Root))
9849     return false;
9850   // Start analysis starting from Root instruction. If horizontal reduction is
9851   // found, try to vectorize it. If it is not a horizontal reduction or
9852   // vectorization is not possible or not effective, and currently analyzed
9853   // instruction is a binary operation, try to vectorize the operands, using
9854   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9855   // the same procedure considering each operand as a possible root of the
9856   // horizontal reduction.
9857   // Interrupt the process if the Root instruction itself was vectorized or all
9858   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9859   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9860   // CmpInsts so we can skip extra attempts in
9861   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9862   std::queue<std::pair<Instruction *, unsigned>> Stack;
9863   Stack.emplace(Root, 0);
9864   SmallPtrSet<Value *, 8> VisitedInstrs;
9865   SmallVector<WeakTrackingVH> PostponedInsts;
9866   bool Res = false;
9867   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9868                                      Value *&B1) -> Value * {
9869     bool IsBinop = matchRdxBop(Inst, B0, B1);
9870     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9871     if (IsBinop || IsSelect) {
9872       HorizontalReduction HorRdx;
9873       if (HorRdx.matchAssociativeReduction(P, Inst))
9874         return HorRdx.tryToReduce(R, TTI);
9875     }
9876     return nullptr;
9877   };
9878   while (!Stack.empty()) {
9879     Instruction *Inst;
9880     unsigned Level;
9881     std::tie(Inst, Level) = Stack.front();
9882     Stack.pop();
9883     // Do not try to analyze instruction that has already been vectorized.
9884     // This may happen when we vectorize instruction operands on a previous
9885     // iteration while stack was populated before that happened.
9886     if (R.isDeleted(Inst))
9887       continue;
9888     Value *B0 = nullptr, *B1 = nullptr;
9889     if (Value *V = TryToReduce(Inst, B0, B1)) {
9890       Res = true;
9891       // Set P to nullptr to avoid re-analysis of phi node in
9892       // matchAssociativeReduction function unless this is the root node.
9893       P = nullptr;
9894       if (auto *I = dyn_cast<Instruction>(V)) {
9895         // Try to find another reduction.
9896         Stack.emplace(I, Level);
9897         continue;
9898       }
9899     } else {
9900       bool IsBinop = B0 && B1;
9901       if (P && IsBinop) {
9902         Inst = dyn_cast<Instruction>(B0);
9903         if (Inst == P)
9904           Inst = dyn_cast<Instruction>(B1);
9905         if (!Inst) {
9906           // Set P to nullptr to avoid re-analysis of phi node in
9907           // matchAssociativeReduction function unless this is the root node.
9908           P = nullptr;
9909           continue;
9910         }
9911       }
9912       // Set P to nullptr to avoid re-analysis of phi node in
9913       // matchAssociativeReduction function unless this is the root node.
9914       P = nullptr;
9915       // Do not try to vectorize CmpInst operands, this is done separately.
9916       // Final attempt for binop args vectorization should happen after the loop
9917       // to try to find reductions.
9918       if (!isa<CmpInst>(Inst))
9919         PostponedInsts.push_back(Inst);
9920     }
9921 
9922     // Try to vectorize operands.
9923     // Continue analysis for the instruction from the same basic block only to
9924     // save compile time.
9925     if (++Level < RecursionMaxDepth)
9926       for (auto *Op : Inst->operand_values())
9927         if (VisitedInstrs.insert(Op).second)
9928           if (auto *I = dyn_cast<Instruction>(Op))
9929             // Do not try to vectorize CmpInst operands,  this is done
9930             // separately.
9931             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9932                 I->getParent() == BB)
9933               Stack.emplace(I, Level);
9934   }
9935   // Try to vectorized binops where reductions were not found.
9936   for (Value *V : PostponedInsts)
9937     if (auto *Inst = dyn_cast<Instruction>(V))
9938       if (!R.isDeleted(Inst))
9939         Res |= Vectorize(Inst, R);
9940   return Res;
9941 }
9942 
9943 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9944                                                  BasicBlock *BB, BoUpSLP &R,
9945                                                  TargetTransformInfo *TTI) {
9946   auto *I = dyn_cast_or_null<Instruction>(V);
9947   if (!I)
9948     return false;
9949 
9950   if (!isa<BinaryOperator>(I))
9951     P = nullptr;
9952   // Try to match and vectorize a horizontal reduction.
9953   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9954     return tryToVectorize(I, R);
9955   };
9956   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9957                                                   ExtraVectorization);
9958 }
9959 
9960 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9961                                                  BasicBlock *BB, BoUpSLP &R) {
9962   const DataLayout &DL = BB->getModule()->getDataLayout();
9963   if (!R.canMapToVector(IVI->getType(), DL))
9964     return false;
9965 
9966   SmallVector<Value *, 16> BuildVectorOpds;
9967   SmallVector<Value *, 16> BuildVectorInsts;
9968   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9969     return false;
9970 
9971   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9972   // Aggregate value is unlikely to be processed in vector register.
9973   return tryToVectorizeList(BuildVectorOpds, R);
9974 }
9975 
9976 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9977                                                    BasicBlock *BB, BoUpSLP &R) {
9978   SmallVector<Value *, 16> BuildVectorInsts;
9979   SmallVector<Value *, 16> BuildVectorOpds;
9980   SmallVector<int> Mask;
9981   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9982       (llvm::all_of(
9983            BuildVectorOpds,
9984            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9985        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9986     return false;
9987 
9988   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9989   return tryToVectorizeList(BuildVectorInsts, R);
9990 }
9991 
9992 template <typename T>
9993 static bool
9994 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9995                        function_ref<unsigned(T *)> Limit,
9996                        function_ref<bool(T *, T *)> Comparator,
9997                        function_ref<bool(T *, T *)> AreCompatible,
9998                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9999                        bool LimitForRegisterSize) {
10000   bool Changed = false;
10001   // Sort by type, parent, operands.
10002   stable_sort(Incoming, Comparator);
10003 
10004   // Try to vectorize elements base on their type.
10005   SmallVector<T *> Candidates;
10006   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10007     // Look for the next elements with the same type, parent and operand
10008     // kinds.
10009     auto *SameTypeIt = IncIt;
10010     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10011       ++SameTypeIt;
10012 
10013     // Try to vectorize them.
10014     unsigned NumElts = (SameTypeIt - IncIt);
10015     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10016                       << NumElts << ")\n");
10017     // The vectorization is a 3-state attempt:
10018     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10019     // size of maximal register at first.
10020     // 2. Try to vectorize remaining instructions with the same type, if
10021     // possible. This may result in the better vectorization results rather than
10022     // if we try just to vectorize instructions with the same/alternate opcodes.
10023     // 3. Final attempt to try to vectorize all instructions with the
10024     // same/alternate ops only, this may result in some extra final
10025     // vectorization.
10026     if (NumElts > 1 &&
10027         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10028       // Success start over because instructions might have been changed.
10029       Changed = true;
10030     } else if (NumElts < Limit(*IncIt) &&
10031                (Candidates.empty() ||
10032                 Candidates.front()->getType() == (*IncIt)->getType())) {
10033       Candidates.append(IncIt, std::next(IncIt, NumElts));
10034     }
10035     // Final attempt to vectorize instructions with the same types.
10036     if (Candidates.size() > 1 &&
10037         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10038       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10039         // Success start over because instructions might have been changed.
10040         Changed = true;
10041       } else if (LimitForRegisterSize) {
10042         // Try to vectorize using small vectors.
10043         for (auto *It = Candidates.begin(), *End = Candidates.end();
10044              It != End;) {
10045           auto *SameTypeIt = It;
10046           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10047             ++SameTypeIt;
10048           unsigned NumElts = (SameTypeIt - It);
10049           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10050                                             /*LimitForRegisterSize=*/false))
10051             Changed = true;
10052           It = SameTypeIt;
10053         }
10054       }
10055       Candidates.clear();
10056     }
10057 
10058     // Start over at the next instruction of a different type (or the end).
10059     IncIt = SameTypeIt;
10060   }
10061   return Changed;
10062 }
10063 
10064 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10065 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10066 /// operands. If IsCompatibility is false, function implements strict weak
10067 /// ordering relation between two cmp instructions, returning true if the first
10068 /// instruction is "less" than the second, i.e. its predicate is less than the
10069 /// predicate of the second or the operands IDs are less than the operands IDs
10070 /// of the second cmp instruction.
10071 template <bool IsCompatibility>
10072 static bool compareCmp(Value *V, Value *V2,
10073                        function_ref<bool(Instruction *)> IsDeleted) {
10074   auto *CI1 = cast<CmpInst>(V);
10075   auto *CI2 = cast<CmpInst>(V2);
10076   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10077     return false;
10078   if (CI1->getOperand(0)->getType()->getTypeID() <
10079       CI2->getOperand(0)->getType()->getTypeID())
10080     return !IsCompatibility;
10081   if (CI1->getOperand(0)->getType()->getTypeID() >
10082       CI2->getOperand(0)->getType()->getTypeID())
10083     return false;
10084   CmpInst::Predicate Pred1 = CI1->getPredicate();
10085   CmpInst::Predicate Pred2 = CI2->getPredicate();
10086   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10087   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10088   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10089   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10090   if (BasePred1 < BasePred2)
10091     return !IsCompatibility;
10092   if (BasePred1 > BasePred2)
10093     return false;
10094   // Compare operands.
10095   bool LEPreds = Pred1 <= Pred2;
10096   bool GEPreds = Pred1 >= Pred2;
10097   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10098     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10099     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10100     if (Op1->getValueID() < Op2->getValueID())
10101       return !IsCompatibility;
10102     if (Op1->getValueID() > Op2->getValueID())
10103       return false;
10104     if (auto *I1 = dyn_cast<Instruction>(Op1))
10105       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10106         if (I1->getParent() != I2->getParent())
10107           return false;
10108         InstructionsState S = getSameOpcode({I1, I2});
10109         if (S.getOpcode())
10110           continue;
10111         return false;
10112       }
10113   }
10114   return IsCompatibility;
10115 }
10116 
10117 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10118     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10119     bool AtTerminator) {
10120   bool OpsChanged = false;
10121   SmallVector<Instruction *, 4> PostponedCmps;
10122   for (auto *I : reverse(Instructions)) {
10123     if (R.isDeleted(I))
10124       continue;
10125     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10126       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10127     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10128       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10129     else if (isa<CmpInst>(I))
10130       PostponedCmps.push_back(I);
10131   }
10132   if (AtTerminator) {
10133     // Try to find reductions first.
10134     for (Instruction *I : PostponedCmps) {
10135       if (R.isDeleted(I))
10136         continue;
10137       for (Value *Op : I->operands())
10138         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10139     }
10140     // Try to vectorize operands as vector bundles.
10141     for (Instruction *I : PostponedCmps) {
10142       if (R.isDeleted(I))
10143         continue;
10144       OpsChanged |= tryToVectorize(I, R);
10145     }
10146     // Try to vectorize list of compares.
10147     // Sort by type, compare predicate, etc.
10148     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10149       return compareCmp<false>(V, V2,
10150                                [&R](Instruction *I) { return R.isDeleted(I); });
10151     };
10152 
10153     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10154       if (V1 == V2)
10155         return true;
10156       return compareCmp<true>(V1, V2,
10157                               [&R](Instruction *I) { return R.isDeleted(I); });
10158     };
10159     auto Limit = [&R](Value *V) {
10160       unsigned EltSize = R.getVectorElementSize(V);
10161       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10162     };
10163 
10164     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10165     OpsChanged |= tryToVectorizeSequence<Value>(
10166         Vals, Limit, CompareSorter, AreCompatibleCompares,
10167         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10168           // Exclude possible reductions from other blocks.
10169           bool ArePossiblyReducedInOtherBlock =
10170               any_of(Candidates, [](Value *V) {
10171                 return any_of(V->users(), [V](User *U) {
10172                   return isa<SelectInst>(U) &&
10173                          cast<SelectInst>(U)->getParent() !=
10174                              cast<Instruction>(V)->getParent();
10175                 });
10176               });
10177           if (ArePossiblyReducedInOtherBlock)
10178             return false;
10179           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10180         },
10181         /*LimitForRegisterSize=*/true);
10182     Instructions.clear();
10183   } else {
10184     // Insert in reverse order since the PostponedCmps vector was filled in
10185     // reverse order.
10186     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10187   }
10188   return OpsChanged;
10189 }
10190 
10191 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10192   bool Changed = false;
10193   SmallVector<Value *, 4> Incoming;
10194   SmallPtrSet<Value *, 16> VisitedInstrs;
10195   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10196   // node. Allows better to identify the chains that can be vectorized in the
10197   // better way.
10198   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10199   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10200     assert(isValidElementType(V1->getType()) &&
10201            isValidElementType(V2->getType()) &&
10202            "Expected vectorizable types only.");
10203     // It is fine to compare type IDs here, since we expect only vectorizable
10204     // types, like ints, floats and pointers, we don't care about other type.
10205     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10206       return true;
10207     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10208       return false;
10209     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10210     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10211     if (Opcodes1.size() < Opcodes2.size())
10212       return true;
10213     if (Opcodes1.size() > Opcodes2.size())
10214       return false;
10215     Optional<bool> ConstOrder;
10216     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10217       // Undefs are compatible with any other value.
10218       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10219         if (!ConstOrder)
10220           ConstOrder =
10221               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10222         continue;
10223       }
10224       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10225         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10226           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10227           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10228           if (!NodeI1)
10229             return NodeI2 != nullptr;
10230           if (!NodeI2)
10231             return false;
10232           assert((NodeI1 == NodeI2) ==
10233                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10234                  "Different nodes should have different DFS numbers");
10235           if (NodeI1 != NodeI2)
10236             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10237           InstructionsState S = getSameOpcode({I1, I2});
10238           if (S.getOpcode())
10239             continue;
10240           return I1->getOpcode() < I2->getOpcode();
10241         }
10242       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10243         if (!ConstOrder)
10244           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10245         continue;
10246       }
10247       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10248         return true;
10249       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10250         return false;
10251     }
10252     return ConstOrder && *ConstOrder;
10253   };
10254   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10255     if (V1 == V2)
10256       return true;
10257     if (V1->getType() != V2->getType())
10258       return false;
10259     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10260     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10261     if (Opcodes1.size() != Opcodes2.size())
10262       return false;
10263     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10264       // Undefs are compatible with any other value.
10265       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10266         continue;
10267       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10268         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10269           if (I1->getParent() != I2->getParent())
10270             return false;
10271           InstructionsState S = getSameOpcode({I1, I2});
10272           if (S.getOpcode())
10273             continue;
10274           return false;
10275         }
10276       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10277         continue;
10278       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10279         return false;
10280     }
10281     return true;
10282   };
10283   auto Limit = [&R](Value *V) {
10284     unsigned EltSize = R.getVectorElementSize(V);
10285     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10286   };
10287 
10288   bool HaveVectorizedPhiNodes = false;
10289   do {
10290     // Collect the incoming values from the PHIs.
10291     Incoming.clear();
10292     for (Instruction &I : *BB) {
10293       PHINode *P = dyn_cast<PHINode>(&I);
10294       if (!P)
10295         break;
10296 
10297       // No need to analyze deleted, vectorized and non-vectorizable
10298       // instructions.
10299       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10300           isValidElementType(P->getType()))
10301         Incoming.push_back(P);
10302     }
10303 
10304     // Find the corresponding non-phi nodes for better matching when trying to
10305     // build the tree.
10306     for (Value *V : Incoming) {
10307       SmallVectorImpl<Value *> &Opcodes =
10308           PHIToOpcodes.try_emplace(V).first->getSecond();
10309       if (!Opcodes.empty())
10310         continue;
10311       SmallVector<Value *, 4> Nodes(1, V);
10312       SmallPtrSet<Value *, 4> Visited;
10313       while (!Nodes.empty()) {
10314         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10315         if (!Visited.insert(PHI).second)
10316           continue;
10317         for (Value *V : PHI->incoming_values()) {
10318           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10319             Nodes.push_back(PHI1);
10320             continue;
10321           }
10322           Opcodes.emplace_back(V);
10323         }
10324       }
10325     }
10326 
10327     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10328         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10329         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10330           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10331         },
10332         /*LimitForRegisterSize=*/true);
10333     Changed |= HaveVectorizedPhiNodes;
10334     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10335   } while (HaveVectorizedPhiNodes);
10336 
10337   VisitedInstrs.clear();
10338 
10339   SmallVector<Instruction *, 8> PostProcessInstructions;
10340   SmallDenseSet<Instruction *, 4> KeyNodes;
10341   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10342     // Skip instructions with scalable type. The num of elements is unknown at
10343     // compile-time for scalable type.
10344     if (isa<ScalableVectorType>(it->getType()))
10345       continue;
10346 
10347     // Skip instructions marked for the deletion.
10348     if (R.isDeleted(&*it))
10349       continue;
10350     // We may go through BB multiple times so skip the one we have checked.
10351     if (!VisitedInstrs.insert(&*it).second) {
10352       if (it->use_empty() && KeyNodes.contains(&*it) &&
10353           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10354                                       it->isTerminator())) {
10355         // We would like to start over since some instructions are deleted
10356         // and the iterator may become invalid value.
10357         Changed = true;
10358         it = BB->begin();
10359         e = BB->end();
10360       }
10361       continue;
10362     }
10363 
10364     if (isa<DbgInfoIntrinsic>(it))
10365       continue;
10366 
10367     // Try to vectorize reductions that use PHINodes.
10368     if (PHINode *P = dyn_cast<PHINode>(it)) {
10369       // Check that the PHI is a reduction PHI.
10370       if (P->getNumIncomingValues() == 2) {
10371         // Try to match and vectorize a horizontal reduction.
10372         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10373                                      TTI)) {
10374           Changed = true;
10375           it = BB->begin();
10376           e = BB->end();
10377           continue;
10378         }
10379       }
10380       // Try to vectorize the incoming values of the PHI, to catch reductions
10381       // that feed into PHIs.
10382       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10383         // Skip if the incoming block is the current BB for now. Also, bypass
10384         // unreachable IR for efficiency and to avoid crashing.
10385         // TODO: Collect the skipped incoming values and try to vectorize them
10386         // after processing BB.
10387         if (BB == P->getIncomingBlock(I) ||
10388             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10389           continue;
10390 
10391         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10392                                             P->getIncomingBlock(I), R, TTI);
10393       }
10394       continue;
10395     }
10396 
10397     // Ran into an instruction without users, like terminator, or function call
10398     // with ignored return value, store. Ignore unused instructions (basing on
10399     // instruction type, except for CallInst and InvokeInst).
10400     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10401                             isa<InvokeInst>(it))) {
10402       KeyNodes.insert(&*it);
10403       bool OpsChanged = false;
10404       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10405         for (auto *V : it->operand_values()) {
10406           // Try to match and vectorize a horizontal reduction.
10407           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10408         }
10409       }
10410       // Start vectorization of post-process list of instructions from the
10411       // top-tree instructions to try to vectorize as many instructions as
10412       // possible.
10413       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10414                                                 it->isTerminator());
10415       if (OpsChanged) {
10416         // We would like to start over since some instructions are deleted
10417         // and the iterator may become invalid value.
10418         Changed = true;
10419         it = BB->begin();
10420         e = BB->end();
10421         continue;
10422       }
10423     }
10424 
10425     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10426         isa<InsertValueInst>(it))
10427       PostProcessInstructions.push_back(&*it);
10428   }
10429 
10430   return Changed;
10431 }
10432 
10433 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10434   auto Changed = false;
10435   for (auto &Entry : GEPs) {
10436     // If the getelementptr list has fewer than two elements, there's nothing
10437     // to do.
10438     if (Entry.second.size() < 2)
10439       continue;
10440 
10441     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10442                       << Entry.second.size() << ".\n");
10443 
10444     // Process the GEP list in chunks suitable for the target's supported
10445     // vector size. If a vector register can't hold 1 element, we are done. We
10446     // are trying to vectorize the index computations, so the maximum number of
10447     // elements is based on the size of the index expression, rather than the
10448     // size of the GEP itself (the target's pointer size).
10449     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10450     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10451     if (MaxVecRegSize < EltSize)
10452       continue;
10453 
10454     unsigned MaxElts = MaxVecRegSize / EltSize;
10455     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10456       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10457       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10458 
10459       // Initialize a set a candidate getelementptrs. Note that we use a
10460       // SetVector here to preserve program order. If the index computations
10461       // are vectorizable and begin with loads, we want to minimize the chance
10462       // of having to reorder them later.
10463       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10464 
10465       // Some of the candidates may have already been vectorized after we
10466       // initially collected them. If so, they are marked as deleted, so remove
10467       // them from the set of candidates.
10468       Candidates.remove_if(
10469           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10470 
10471       // Remove from the set of candidates all pairs of getelementptrs with
10472       // constant differences. Such getelementptrs are likely not good
10473       // candidates for vectorization in a bottom-up phase since one can be
10474       // computed from the other. We also ensure all candidate getelementptr
10475       // indices are unique.
10476       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10477         auto *GEPI = GEPList[I];
10478         if (!Candidates.count(GEPI))
10479           continue;
10480         auto *SCEVI = SE->getSCEV(GEPList[I]);
10481         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10482           auto *GEPJ = GEPList[J];
10483           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10484           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10485             Candidates.remove(GEPI);
10486             Candidates.remove(GEPJ);
10487           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10488             Candidates.remove(GEPJ);
10489           }
10490         }
10491       }
10492 
10493       // We break out of the above computation as soon as we know there are
10494       // fewer than two candidates remaining.
10495       if (Candidates.size() < 2)
10496         continue;
10497 
10498       // Add the single, non-constant index of each candidate to the bundle. We
10499       // ensured the indices met these constraints when we originally collected
10500       // the getelementptrs.
10501       SmallVector<Value *, 16> Bundle(Candidates.size());
10502       auto BundleIndex = 0u;
10503       for (auto *V : Candidates) {
10504         auto *GEP = cast<GetElementPtrInst>(V);
10505         auto *GEPIdx = GEP->idx_begin()->get();
10506         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10507         Bundle[BundleIndex++] = GEPIdx;
10508       }
10509 
10510       // Try and vectorize the indices. We are currently only interested in
10511       // gather-like cases of the form:
10512       //
10513       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10514       //
10515       // where the loads of "a", the loads of "b", and the subtractions can be
10516       // performed in parallel. It's likely that detecting this pattern in a
10517       // bottom-up phase will be simpler and less costly than building a
10518       // full-blown top-down phase beginning at the consecutive loads.
10519       Changed |= tryToVectorizeList(Bundle, R);
10520     }
10521   }
10522   return Changed;
10523 }
10524 
10525 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10526   bool Changed = false;
10527   // Sort by type, base pointers and values operand. Value operands must be
10528   // compatible (have the same opcode, same parent), otherwise it is
10529   // definitely not profitable to try to vectorize them.
10530   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10531     if (V->getPointerOperandType()->getTypeID() <
10532         V2->getPointerOperandType()->getTypeID())
10533       return true;
10534     if (V->getPointerOperandType()->getTypeID() >
10535         V2->getPointerOperandType()->getTypeID())
10536       return false;
10537     // UndefValues are compatible with all other values.
10538     if (isa<UndefValue>(V->getValueOperand()) ||
10539         isa<UndefValue>(V2->getValueOperand()))
10540       return false;
10541     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10542       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10543         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10544             DT->getNode(I1->getParent());
10545         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10546             DT->getNode(I2->getParent());
10547         assert(NodeI1 && "Should only process reachable instructions");
10548         assert(NodeI1 && "Should only process reachable instructions");
10549         assert((NodeI1 == NodeI2) ==
10550                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10551                "Different nodes should have different DFS numbers");
10552         if (NodeI1 != NodeI2)
10553           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10554         InstructionsState S = getSameOpcode({I1, I2});
10555         if (S.getOpcode())
10556           return false;
10557         return I1->getOpcode() < I2->getOpcode();
10558       }
10559     if (isa<Constant>(V->getValueOperand()) &&
10560         isa<Constant>(V2->getValueOperand()))
10561       return false;
10562     return V->getValueOperand()->getValueID() <
10563            V2->getValueOperand()->getValueID();
10564   };
10565 
10566   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10567     if (V1 == V2)
10568       return true;
10569     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10570       return false;
10571     // Undefs are compatible with any other value.
10572     if (isa<UndefValue>(V1->getValueOperand()) ||
10573         isa<UndefValue>(V2->getValueOperand()))
10574       return true;
10575     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10576       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10577         if (I1->getParent() != I2->getParent())
10578           return false;
10579         InstructionsState S = getSameOpcode({I1, I2});
10580         return S.getOpcode() > 0;
10581       }
10582     if (isa<Constant>(V1->getValueOperand()) &&
10583         isa<Constant>(V2->getValueOperand()))
10584       return true;
10585     return V1->getValueOperand()->getValueID() ==
10586            V2->getValueOperand()->getValueID();
10587   };
10588   auto Limit = [&R, this](StoreInst *SI) {
10589     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10590     return R.getMinVF(EltSize);
10591   };
10592 
10593   // Attempt to sort and vectorize each of the store-groups.
10594   for (auto &Pair : Stores) {
10595     if (Pair.second.size() < 2)
10596       continue;
10597 
10598     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10599                       << Pair.second.size() << ".\n");
10600 
10601     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10602       continue;
10603 
10604     Changed |= tryToVectorizeSequence<StoreInst>(
10605         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10606         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10607           return vectorizeStores(Candidates, R);
10608         },
10609         /*LimitForRegisterSize=*/false);
10610   }
10611   return Changed;
10612 }
10613 
10614 char SLPVectorizer::ID = 0;
10615 
10616 static const char lv_name[] = "SLP Vectorizer";
10617 
10618 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10619 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10620 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10621 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10622 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10623 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10624 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10625 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10626 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10627 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10628 
10629 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10630