1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 /// Checks if the provided value does not require scheduling. It does not
776 /// require scheduling if this is not an instruction or it is an instruction
777 /// that does not read/write memory and all operands are either not instructions
778 /// or phi nodes or instructions from different blocks.
779 static bool areAllOperandsNonInsts(Value *V) {
780   auto *I = dyn_cast<Instruction>(V);
781   if (!I)
782     return true;
783   return !mayHaveNonDefUseDependency(*I) &&
784     all_of(I->operands(), [I](Value *V) {
785       auto *IO = dyn_cast<Instruction>(V);
786       if (!IO)
787         return true;
788       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
789     });
790 }
791 
792 /// Checks if the provided value does not require scheduling. It does not
793 /// require scheduling if this is not an instruction or it is an instruction
794 /// that does not read/write memory and all users are phi nodes or instructions
795 /// from the different blocks.
796 static bool isUsedOutsideBlock(Value *V) {
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800   // Limits the number of uses to save compile time.
801   constexpr int UsesLimit = 8;
802   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
803          all_of(I->users(), [I](User *U) {
804            auto *IU = dyn_cast<Instruction>(U);
805            if (!IU)
806              return true;
807            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
808          });
809 }
810 
811 /// Checks if the specified value does not require scheduling. It does not
812 /// require scheduling if all operands and all users do not need to be scheduled
813 /// in the current basic block.
814 static bool doesNotNeedToBeScheduled(Value *V) {
815   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
816 }
817 
818 /// Checks if the specified array of instructions does not require scheduling.
819 /// It is so if all either instructions have operands that do not require
820 /// scheduling or their users do not require scheduling since they are phis or
821 /// in other basic blocks.
822 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
823   return !VL.empty() &&
824          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
825 }
826 
827 namespace slpvectorizer {
828 
829 /// Bottom Up SLP Vectorizer.
830 class BoUpSLP {
831   struct TreeEntry;
832   struct ScheduleData;
833 
834 public:
835   using ValueList = SmallVector<Value *, 8>;
836   using InstrList = SmallVector<Instruction *, 16>;
837   using ValueSet = SmallPtrSet<Value *, 16>;
838   using StoreList = SmallVector<StoreInst *, 8>;
839   using ExtraValueToDebugLocsMap =
840       MapVector<Value *, SmallVector<Instruction *, 2>>;
841   using OrdersType = SmallVector<unsigned, 4>;
842 
843   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
844           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
845           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
846           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
847       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
848         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
849     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
850     // Use the vector register size specified by the target unless overridden
851     // by a command-line option.
852     // TODO: It would be better to limit the vectorization factor based on
853     //       data type rather than just register size. For example, x86 AVX has
854     //       256-bit registers, but it does not support integer operations
855     //       at that width (that requires AVX2).
856     if (MaxVectorRegSizeOption.getNumOccurrences())
857       MaxVecRegSize = MaxVectorRegSizeOption;
858     else
859       MaxVecRegSize =
860           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
861               .getFixedSize();
862 
863     if (MinVectorRegSizeOption.getNumOccurrences())
864       MinVecRegSize = MinVectorRegSizeOption;
865     else
866       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
867   }
868 
869   /// Vectorize the tree that starts with the elements in \p VL.
870   /// Returns the vectorized root.
871   Value *vectorizeTree();
872 
873   /// Vectorize the tree but with the list of externally used values \p
874   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
875   /// generated extractvalue instructions.
876   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
877 
878   /// \returns the cost incurred by unwanted spills and fills, caused by
879   /// holding live values over call sites.
880   InstructionCost getSpillCost() const;
881 
882   /// \returns the vectorization cost of the subtree that starts at \p VL.
883   /// A negative number means that this is profitable.
884   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
885 
886   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
887   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
888   void buildTree(ArrayRef<Value *> Roots,
889                  ArrayRef<Value *> UserIgnoreLst = None);
890 
891   /// Builds external uses of the vectorized scalars, i.e. the list of
892   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
893   /// ExternallyUsedValues contains additional list of external uses to handle
894   /// vectorization of reductions.
895   void
896   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
897 
898   /// Clear the internal data structures that are created by 'buildTree'.
899   void deleteTree() {
900     VectorizableTree.clear();
901     ScalarToTreeEntry.clear();
902     MustGather.clear();
903     ExternalUses.clear();
904     for (auto &Iter : BlocksSchedules) {
905       BlockScheduling *BS = Iter.second.get();
906       BS->clear();
907     }
908     MinBWs.clear();
909     InstrElementSize.clear();
910   }
911 
912   unsigned getTreeSize() const { return VectorizableTree.size(); }
913 
914   /// Perform LICM and CSE on the newly generated gather sequences.
915   void optimizeGatherSequence();
916 
917   /// Checks if the specified gather tree entry \p TE can be represented as a
918   /// shuffled vector entry + (possibly) permutation with other gathers. It
919   /// implements the checks only for possibly ordered scalars (Loads,
920   /// ExtractElement, ExtractValue), which can be part of the graph.
921   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
922 
923   /// Gets reordering data for the given tree entry. If the entry is vectorized
924   /// - just return ReorderIndices, otherwise check if the scalars can be
925   /// reordered and return the most optimal order.
926   /// \param TopToBottom If true, include the order of vectorized stores and
927   /// insertelement nodes, otherwise skip them.
928   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
929 
930   /// Reorders the current graph to the most profitable order starting from the
931   /// root node to the leaf nodes. The best order is chosen only from the nodes
932   /// of the same size (vectorization factor). Smaller nodes are considered
933   /// parts of subgraph with smaller VF and they are reordered independently. We
934   /// can make it because we still need to extend smaller nodes to the wider VF
935   /// and we can merge reordering shuffles with the widening shuffles.
936   void reorderTopToBottom();
937 
938   /// Reorders the current graph to the most profitable order starting from
939   /// leaves to the root. It allows to rotate small subgraphs and reduce the
940   /// number of reshuffles if the leaf nodes use the same order. In this case we
941   /// can merge the orders and just shuffle user node instead of shuffling its
942   /// operands. Plus, even the leaf nodes have different orders, it allows to
943   /// sink reordering in the graph closer to the root node and merge it later
944   /// during analysis.
945   void reorderBottomToTop(bool IgnoreReorder = false);
946 
947   /// \return The vector element size in bits to use when vectorizing the
948   /// expression tree ending at \p V. If V is a store, the size is the width of
949   /// the stored value. Otherwise, the size is the width of the largest loaded
950   /// value reaching V. This method is used by the vectorizer to calculate
951   /// vectorization factors.
952   unsigned getVectorElementSize(Value *V);
953 
954   /// Compute the minimum type sizes required to represent the entries in a
955   /// vectorizable tree.
956   void computeMinimumValueSizes();
957 
958   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
959   unsigned getMaxVecRegSize() const {
960     return MaxVecRegSize;
961   }
962 
963   // \returns minimum vector register size as set by cl::opt.
964   unsigned getMinVecRegSize() const {
965     return MinVecRegSize;
966   }
967 
968   unsigned getMinVF(unsigned Sz) const {
969     return std::max(2U, getMinVecRegSize() / Sz);
970   }
971 
972   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
973     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
974       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
975     return MaxVF ? MaxVF : UINT_MAX;
976   }
977 
978   /// Check if homogeneous aggregate is isomorphic to some VectorType.
979   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
980   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
981   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
982   ///
983   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
984   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
985 
986   /// \returns True if the VectorizableTree is both tiny and not fully
987   /// vectorizable. We do not vectorize such trees.
988   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
989 
990   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
991   /// can be load combined in the backend. Load combining may not be allowed in
992   /// the IR optimizer, so we do not want to alter the pattern. For example,
993   /// partially transforming a scalar bswap() pattern into vector code is
994   /// effectively impossible for the backend to undo.
995   /// TODO: If load combining is allowed in the IR optimizer, this analysis
996   ///       may not be necessary.
997   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
998 
999   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineCandidate() const;
1007 
1008   OptimizationRemarkEmitter *getORE() { return ORE; }
1009 
1010   /// This structure holds any data we need about the edges being traversed
1011   /// during buildTree_rec(). We keep track of:
1012   /// (i) the user TreeEntry index, and
1013   /// (ii) the index of the edge.
1014   struct EdgeInfo {
1015     EdgeInfo() = default;
1016     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1017         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1018     /// The user TreeEntry.
1019     TreeEntry *UserTE = nullptr;
1020     /// The operand index of the use.
1021     unsigned EdgeIdx = UINT_MAX;
1022 #ifndef NDEBUG
1023     friend inline raw_ostream &operator<<(raw_ostream &OS,
1024                                           const BoUpSLP::EdgeInfo &EI) {
1025       EI.dump(OS);
1026       return OS;
1027     }
1028     /// Debug print.
1029     void dump(raw_ostream &OS) const {
1030       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1031          << " EdgeIdx:" << EdgeIdx << "}";
1032     }
1033     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1034 #endif
1035   };
1036 
1037   /// A helper data structure to hold the operands of a vector of instructions.
1038   /// This supports a fixed vector length for all operand vectors.
1039   class VLOperands {
1040     /// For each operand we need (i) the value, and (ii) the opcode that it
1041     /// would be attached to if the expression was in a left-linearized form.
1042     /// This is required to avoid illegal operand reordering.
1043     /// For example:
1044     /// \verbatim
1045     ///                         0 Op1
1046     ///                         |/
1047     /// Op1 Op2   Linearized    + Op2
1048     ///   \ /     ---------->   |/
1049     ///    -                    -
1050     ///
1051     /// Op1 - Op2            (0 + Op1) - Op2
1052     /// \endverbatim
1053     ///
1054     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1055     ///
1056     /// Another way to think of this is to track all the operations across the
1057     /// path from the operand all the way to the root of the tree and to
1058     /// calculate the operation that corresponds to this path. For example, the
1059     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1060     /// corresponding operation is a '-' (which matches the one in the
1061     /// linearized tree, as shown above).
1062     ///
1063     /// For lack of a better term, we refer to this operation as Accumulated
1064     /// Path Operation (APO).
1065     struct OperandData {
1066       OperandData() = default;
1067       OperandData(Value *V, bool APO, bool IsUsed)
1068           : V(V), APO(APO), IsUsed(IsUsed) {}
1069       /// The operand value.
1070       Value *V = nullptr;
1071       /// TreeEntries only allow a single opcode, or an alternate sequence of
1072       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1073       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1074       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1075       /// (e.g., Add/Mul)
1076       bool APO = false;
1077       /// Helper data for the reordering function.
1078       bool IsUsed = false;
1079     };
1080 
1081     /// During operand reordering, we are trying to select the operand at lane
1082     /// that matches best with the operand at the neighboring lane. Our
1083     /// selection is based on the type of value we are looking for. For example,
1084     /// if the neighboring lane has a load, we need to look for a load that is
1085     /// accessing a consecutive address. These strategies are summarized in the
1086     /// 'ReorderingMode' enumerator.
1087     enum class ReorderingMode {
1088       Load,     ///< Matching loads to consecutive memory addresses
1089       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1090       Constant, ///< Matching constants
1091       Splat,    ///< Matching the same instruction multiple times (broadcast)
1092       Failed,   ///< We failed to create a vectorizable group
1093     };
1094 
1095     using OperandDataVec = SmallVector<OperandData, 2>;
1096 
1097     /// A vector of operand vectors.
1098     SmallVector<OperandDataVec, 4> OpsVec;
1099 
1100     const DataLayout &DL;
1101     ScalarEvolution &SE;
1102     const BoUpSLP &R;
1103 
1104     /// \returns the operand data at \p OpIdx and \p Lane.
1105     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1106       return OpsVec[OpIdx][Lane];
1107     }
1108 
1109     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1110     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1111       return OpsVec[OpIdx][Lane];
1112     }
1113 
1114     /// Clears the used flag for all entries.
1115     void clearUsed() {
1116       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1117            OpIdx != NumOperands; ++OpIdx)
1118         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1119              ++Lane)
1120           OpsVec[OpIdx][Lane].IsUsed = false;
1121     }
1122 
1123     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1124     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1125       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1126     }
1127 
1128     // The hard-coded scores listed here are not very important, though it shall
1129     // be higher for better matches to improve the resulting cost. When
1130     // computing the scores of matching one sub-tree with another, we are
1131     // basically counting the number of values that are matching. So even if all
1132     // scores are set to 1, we would still get a decent matching result.
1133     // However, sometimes we have to break ties. For example we may have to
1134     // choose between matching loads vs matching opcodes. This is what these
1135     // scores are helping us with: they provide the order of preference. Also,
1136     // this is important if the scalar is externally used or used in another
1137     // tree entry node in the different lane.
1138 
1139     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1140     static const int ScoreConsecutiveLoads = 4;
1141     /// The same load multiple times. This should have a better score than
1142     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1143     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1144     /// a vector load and 1.0 for a broadcast.
1145     static const int ScoreSplatLoads = 3;
1146     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1147     static const int ScoreReversedLoads = 3;
1148     /// ExtractElementInst from same vector and consecutive indexes.
1149     static const int ScoreConsecutiveExtracts = 4;
1150     /// ExtractElementInst from same vector and reversed indices.
1151     static const int ScoreReversedExtracts = 3;
1152     /// Constants.
1153     static const int ScoreConstants = 2;
1154     /// Instructions with the same opcode.
1155     static const int ScoreSameOpcode = 2;
1156     /// Instructions with alt opcodes (e.g, add + sub).
1157     static const int ScoreAltOpcodes = 1;
1158     /// Identical instructions (a.k.a. splat or broadcast).
1159     static const int ScoreSplat = 1;
1160     /// Matching with an undef is preferable to failing.
1161     static const int ScoreUndef = 1;
1162     /// Score for failing to find a decent match.
1163     static const int ScoreFail = 0;
1164     /// Score if all users are vectorized.
1165     static const int ScoreAllUserVectorized = 1;
1166 
1167     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1168     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1169     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1170     /// MainAltOps.
1171     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1172                         const DataLayout &DL, ScalarEvolution &SE, int NumLanes,
1173                         ArrayRef<Value *> MainAltOps) {
1174       if (V1 == V2) {
1175         if (isa<LoadInst>(V1)) {
1176           // Retruns true if the users of V1 and V2 won't need to be extracted.
1177           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1178             // Bail out if we have too many uses to save compilation time.
1179             static constexpr unsigned Limit = 8;
1180             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1181               return false;
1182 
1183             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1184               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1185                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1186               });
1187             };
1188             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1189           };
1190           // A broadcast of a load can be cheaper on some targets.
1191           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1192                                           ElementCount::getFixed(NumLanes)) &&
1193               ((int)V1->getNumUses() == NumLanes ||
1194                AllUsersAreInternal(V1, V2)))
1195             return VLOperands::ScoreSplatLoads;
1196         }
1197         return VLOperands::ScoreSplat;
1198       }
1199 
1200       auto *LI1 = dyn_cast<LoadInst>(V1);
1201       auto *LI2 = dyn_cast<LoadInst>(V2);
1202       if (LI1 && LI2) {
1203         if (LI1->getParent() != LI2->getParent())
1204           return VLOperands::ScoreFail;
1205 
1206         Optional<int> Dist = getPointersDiff(
1207             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1208             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1209         if (!Dist || *Dist == 0)
1210           return VLOperands::ScoreFail;
1211         // The distance is too large - still may be profitable to use masked
1212         // loads/gathers.
1213         if (std::abs(*Dist) > NumLanes / 2)
1214           return VLOperands::ScoreAltOpcodes;
1215         // This still will detect consecutive loads, but we might have "holes"
1216         // in some cases. It is ok for non-power-2 vectorization and may produce
1217         // better results. It should not affect current vectorization.
1218         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1219                            : VLOperands::ScoreReversedLoads;
1220       }
1221 
1222       auto *C1 = dyn_cast<Constant>(V1);
1223       auto *C2 = dyn_cast<Constant>(V2);
1224       if (C1 && C2)
1225         return VLOperands::ScoreConstants;
1226 
1227       // Extracts from consecutive indexes of the same vector better score as
1228       // the extracts could be optimized away.
1229       Value *EV1;
1230       ConstantInt *Ex1Idx;
1231       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1232         // Undefs are always profitable for extractelements.
1233         if (isa<UndefValue>(V2))
1234           return VLOperands::ScoreConsecutiveExtracts;
1235         Value *EV2 = nullptr;
1236         ConstantInt *Ex2Idx = nullptr;
1237         if (match(V2,
1238                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1239                                                          m_Undef())))) {
1240           // Undefs are always profitable for extractelements.
1241           if (!Ex2Idx)
1242             return VLOperands::ScoreConsecutiveExtracts;
1243           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1244             return VLOperands::ScoreConsecutiveExtracts;
1245           if (EV2 == EV1) {
1246             int Idx1 = Ex1Idx->getZExtValue();
1247             int Idx2 = Ex2Idx->getZExtValue();
1248             int Dist = Idx2 - Idx1;
1249             // The distance is too large - still may be profitable to use
1250             // shuffles.
1251             if (std::abs(Dist) == 0)
1252               return VLOperands::ScoreSplat;
1253             if (std::abs(Dist) > NumLanes / 2)
1254               return VLOperands::ScoreSameOpcode;
1255             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1256                               : VLOperands::ScoreReversedExtracts;
1257           }
1258           return VLOperands::ScoreAltOpcodes;
1259         }
1260         return VLOperands::ScoreFail;
1261       }
1262 
1263       auto *I1 = dyn_cast<Instruction>(V1);
1264       auto *I2 = dyn_cast<Instruction>(V2);
1265       if (I1 && I2) {
1266         if (I1->getParent() != I2->getParent())
1267           return VLOperands::ScoreFail;
1268         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1269         Ops.push_back(I1);
1270         Ops.push_back(I2);
1271         InstructionsState S = getSameOpcode(Ops);
1272         // Note: Only consider instructions with <= 2 operands to avoid
1273         // complexity explosion.
1274         if (S.getOpcode() &&
1275             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1276              !S.isAltShuffle()) &&
1277             all_of(Ops, [&S](Value *V) {
1278               return cast<Instruction>(V)->getNumOperands() ==
1279                      S.MainOp->getNumOperands();
1280             }))
1281           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1282                                   : VLOperands::ScoreSameOpcode;
1283       }
1284 
1285       if (isa<UndefValue>(V2))
1286         return VLOperands::ScoreUndef;
1287 
1288       return VLOperands::ScoreFail;
1289     }
1290 
1291     /// \param Lane lane of the operands under analysis.
1292     /// \param OpIdx operand index in \p Lane lane we're looking the best
1293     /// candidate for.
1294     /// \param Idx operand index of the current candidate value.
1295     /// \returns The additional score due to possible broadcasting of the
1296     /// elements in the lane. It is more profitable to have power-of-2 unique
1297     /// elements in the lane, it will be vectorized with higher probability
1298     /// after removing duplicates. Currently the SLP vectorizer supports only
1299     /// vectorization of the power-of-2 number of unique scalars.
1300     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1301       Value *IdxLaneV = getData(Idx, Lane).V;
1302       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1303         return 0;
1304       SmallPtrSet<Value *, 4> Uniques;
1305       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1306         if (Ln == Lane)
1307           continue;
1308         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1309         if (!isa<Instruction>(OpIdxLnV))
1310           return 0;
1311         Uniques.insert(OpIdxLnV);
1312       }
1313       int UniquesCount = Uniques.size();
1314       int UniquesCntWithIdxLaneV =
1315           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1316       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1317       int UniquesCntWithOpIdxLaneV =
1318           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1319       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1320         return 0;
1321       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1322               UniquesCntWithOpIdxLaneV) -
1323              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1324     }
1325 
1326     /// \param Lane lane of the operands under analysis.
1327     /// \param OpIdx operand index in \p Lane lane we're looking the best
1328     /// candidate for.
1329     /// \param Idx operand index of the current candidate value.
1330     /// \returns The additional score for the scalar which users are all
1331     /// vectorized.
1332     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1333       Value *IdxLaneV = getData(Idx, Lane).V;
1334       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1335       // Do not care about number of uses for vector-like instructions
1336       // (extractelement/extractvalue with constant indices), they are extracts
1337       // themselves and already externally used. Vectorization of such
1338       // instructions does not add extra extractelement instruction, just may
1339       // remove it.
1340       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1341           isVectorLikeInstWithConstOps(OpIdxLaneV))
1342         return VLOperands::ScoreAllUserVectorized;
1343       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1344       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1345         return 0;
1346       return R.areAllUsersVectorized(IdxLaneI, None)
1347                  ? VLOperands::ScoreAllUserVectorized
1348                  : 0;
1349     }
1350 
1351     /// Go through the operands of \p LHS and \p RHS recursively until \p
1352     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1353     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1354     /// of \p U1 and \p U2), except at the beginning of the recursion where
1355     /// these are set to nullptr.
1356     ///
1357     /// For example:
1358     /// \verbatim
1359     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1360     ///     \ /         \ /         \ /        \ /
1361     ///      +           +           +          +
1362     ///     G1          G2          G3         G4
1363     /// \endverbatim
1364     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1365     /// each level recursively, accumulating the score. It starts from matching
1366     /// the additions at level 0, then moves on to the loads (level 1). The
1367     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1368     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1369     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1370     /// Please note that the order of the operands does not matter, as we
1371     /// evaluate the score of all profitable combinations of operands. In
1372     /// other words the score of G1 and G4 is the same as G1 and G2. This
1373     /// heuristic is based on ideas described in:
1374     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1375     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1376     ///   Luís F. W. Góes
1377     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1378                            Instruction *U2, int CurrLevel, int MaxLevel,
1379                            ArrayRef<Value *> MainAltOps) {
1380 
1381       // Get the shallow score of V1 and V2.
1382       int ShallowScoreAtThisLevel =
1383           getShallowScore(LHS, RHS, U1, U2, DL, SE, getNumLanes(), MainAltOps);
1384 
1385       // If reached MaxLevel,
1386       //  or if V1 and V2 are not instructions,
1387       //  or if they are SPLAT,
1388       //  or if they are not consecutive,
1389       //  or if profitable to vectorize loads or extractelements, early return
1390       //  the current cost.
1391       auto *I1 = dyn_cast<Instruction>(LHS);
1392       auto *I2 = dyn_cast<Instruction>(RHS);
1393       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1394           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1395           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1396             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1397             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1398            ShallowScoreAtThisLevel))
1399         return ShallowScoreAtThisLevel;
1400       assert(I1 && I2 && "Should have early exited.");
1401 
1402       // Contains the I2 operand indexes that got matched with I1 operands.
1403       SmallSet<unsigned, 4> Op2Used;
1404 
1405       // Recursion towards the operands of I1 and I2. We are trying all possible
1406       // operand pairs, and keeping track of the best score.
1407       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1408            OpIdx1 != NumOperands1; ++OpIdx1) {
1409         // Try to pair op1I with the best operand of I2.
1410         int MaxTmpScore = 0;
1411         unsigned MaxOpIdx2 = 0;
1412         bool FoundBest = false;
1413         // If I2 is commutative try all combinations.
1414         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1415         unsigned ToIdx = isCommutative(I2)
1416                              ? I2->getNumOperands()
1417                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1418         assert(FromIdx <= ToIdx && "Bad index");
1419         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1420           // Skip operands already paired with OpIdx1.
1421           if (Op2Used.count(OpIdx2))
1422             continue;
1423           // Recursively calculate the cost at each level
1424           int TmpScore =
1425               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1426                                  I1, I2, CurrLevel + 1, MaxLevel, None);
1427           // Look for the best score.
1428           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1429             MaxTmpScore = TmpScore;
1430             MaxOpIdx2 = OpIdx2;
1431             FoundBest = true;
1432           }
1433         }
1434         if (FoundBest) {
1435           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1436           Op2Used.insert(MaxOpIdx2);
1437           ShallowScoreAtThisLevel += MaxTmpScore;
1438         }
1439       }
1440       return ShallowScoreAtThisLevel;
1441     }
1442 
1443     /// Score scaling factor for fully compatible instructions but with
1444     /// different number of external uses. Allows better selection of the
1445     /// instructions with less external uses.
1446     static const int ScoreScaleFactor = 10;
1447 
1448     /// \Returns the look-ahead score, which tells us how much the sub-trees
1449     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1450     /// score. This helps break ties in an informed way when we cannot decide on
1451     /// the order of the operands by just considering the immediate
1452     /// predecessors.
1453     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1454                           int Lane, unsigned OpIdx, unsigned Idx,
1455                           bool &IsUsed) {
1456       // Keep track of the instruction stack as we recurse into the operands
1457       // during the look-ahead score exploration.
1458       int Score = getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1459                                      1, LookAheadMaxDepth, MainAltOps);
1460       if (Score) {
1461         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1462         if (Score <= -SplatScore) {
1463           // Set the minimum score for splat-like sequence to avoid setting
1464           // failed state.
1465           Score = 1;
1466         } else {
1467           Score += SplatScore;
1468           // Scale score to see the difference between different operands
1469           // and similar operands but all vectorized/not all vectorized
1470           // uses. It does not affect actual selection of the best
1471           // compatible operand in general, just allows to select the
1472           // operand with all vectorized uses.
1473           Score *= ScoreScaleFactor;
1474           Score += getExternalUseScore(Lane, OpIdx, Idx);
1475           IsUsed = true;
1476         }
1477       }
1478       return Score;
1479     }
1480 
1481     /// Best defined scores per lanes between the passes. Used to choose the
1482     /// best operand (with the highest score) between the passes.
1483     /// The key - {Operand Index, Lane}.
1484     /// The value - the best score between the passes for the lane and the
1485     /// operand.
1486     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1487         BestScoresPerLanes;
1488 
1489     // Search all operands in Ops[*][Lane] for the one that matches best
1490     // Ops[OpIdx][LastLane] and return its opreand index.
1491     // If no good match can be found, return None.
1492     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1493                                       ArrayRef<ReorderingMode> ReorderingModes,
1494                                       ArrayRef<Value *> MainAltOps) {
1495       unsigned NumOperands = getNumOperands();
1496 
1497       // The operand of the previous lane at OpIdx.
1498       Value *OpLastLane = getData(OpIdx, LastLane).V;
1499 
1500       // Our strategy mode for OpIdx.
1501       ReorderingMode RMode = ReorderingModes[OpIdx];
1502       if (RMode == ReorderingMode::Failed)
1503         return None;
1504 
1505       // The linearized opcode of the operand at OpIdx, Lane.
1506       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1507 
1508       // The best operand index and its score.
1509       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1510       // are using the score to differentiate between the two.
1511       struct BestOpData {
1512         Optional<unsigned> Idx = None;
1513         unsigned Score = 0;
1514       } BestOp;
1515       BestOp.Score =
1516           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1517               .first->second;
1518 
1519       // Track if the operand must be marked as used. If the operand is set to
1520       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1521       // want to reestimate the operands again on the following iterations).
1522       bool IsUsed =
1523           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1524       // Iterate through all unused operands and look for the best.
1525       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1526         // Get the operand at Idx and Lane.
1527         OperandData &OpData = getData(Idx, Lane);
1528         Value *Op = OpData.V;
1529         bool OpAPO = OpData.APO;
1530 
1531         // Skip already selected operands.
1532         if (OpData.IsUsed)
1533           continue;
1534 
1535         // Skip if we are trying to move the operand to a position with a
1536         // different opcode in the linearized tree form. This would break the
1537         // semantics.
1538         if (OpAPO != OpIdxAPO)
1539           continue;
1540 
1541         // Look for an operand that matches the current mode.
1542         switch (RMode) {
1543         case ReorderingMode::Load:
1544         case ReorderingMode::Constant:
1545         case ReorderingMode::Opcode: {
1546           bool LeftToRight = Lane > LastLane;
1547           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1548           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1549           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1550                                         OpIdx, Idx, IsUsed);
1551           if (Score > static_cast<int>(BestOp.Score)) {
1552             BestOp.Idx = Idx;
1553             BestOp.Score = Score;
1554             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1555           }
1556           break;
1557         }
1558         case ReorderingMode::Splat:
1559           if (Op == OpLastLane)
1560             BestOp.Idx = Idx;
1561           break;
1562         case ReorderingMode::Failed:
1563           llvm_unreachable("Not expected Failed reordering mode.");
1564         }
1565       }
1566 
1567       if (BestOp.Idx) {
1568         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1569         return BestOp.Idx;
1570       }
1571       // If we could not find a good match return None.
1572       return None;
1573     }
1574 
1575     /// Helper for reorderOperandVecs.
1576     /// \returns the lane that we should start reordering from. This is the one
1577     /// which has the least number of operands that can freely move about or
1578     /// less profitable because it already has the most optimal set of operands.
1579     unsigned getBestLaneToStartReordering() const {
1580       unsigned Min = UINT_MAX;
1581       unsigned SameOpNumber = 0;
1582       // std::pair<unsigned, unsigned> is used to implement a simple voting
1583       // algorithm and choose the lane with the least number of operands that
1584       // can freely move about or less profitable because it already has the
1585       // most optimal set of operands. The first unsigned is a counter for
1586       // voting, the second unsigned is the counter of lanes with instructions
1587       // with same/alternate opcodes and same parent basic block.
1588       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1589       // Try to be closer to the original results, if we have multiple lanes
1590       // with same cost. If 2 lanes have the same cost, use the one with the
1591       // lowest index.
1592       for (int I = getNumLanes(); I > 0; --I) {
1593         unsigned Lane = I - 1;
1594         OperandsOrderData NumFreeOpsHash =
1595             getMaxNumOperandsThatCanBeReordered(Lane);
1596         // Compare the number of operands that can move and choose the one with
1597         // the least number.
1598         if (NumFreeOpsHash.NumOfAPOs < Min) {
1599           Min = NumFreeOpsHash.NumOfAPOs;
1600           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1601           HashMap.clear();
1602           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1603         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1604                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1605           // Select the most optimal lane in terms of number of operands that
1606           // should be moved around.
1607           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1608           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1609         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1610                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1611           auto It = HashMap.find(NumFreeOpsHash.Hash);
1612           if (It == HashMap.end())
1613             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1614           else
1615             ++It->second.first;
1616         }
1617       }
1618       // Select the lane with the minimum counter.
1619       unsigned BestLane = 0;
1620       unsigned CntMin = UINT_MAX;
1621       for (const auto &Data : reverse(HashMap)) {
1622         if (Data.second.first < CntMin) {
1623           CntMin = Data.second.first;
1624           BestLane = Data.second.second;
1625         }
1626       }
1627       return BestLane;
1628     }
1629 
1630     /// Data structure that helps to reorder operands.
1631     struct OperandsOrderData {
1632       /// The best number of operands with the same APOs, which can be
1633       /// reordered.
1634       unsigned NumOfAPOs = UINT_MAX;
1635       /// Number of operands with the same/alternate instruction opcode and
1636       /// parent.
1637       unsigned NumOpsWithSameOpcodeParent = 0;
1638       /// Hash for the actual operands ordering.
1639       /// Used to count operands, actually their position id and opcode
1640       /// value. It is used in the voting mechanism to find the lane with the
1641       /// least number of operands that can freely move about or less profitable
1642       /// because it already has the most optimal set of operands. Can be
1643       /// replaced with SmallVector<unsigned> instead but hash code is faster
1644       /// and requires less memory.
1645       unsigned Hash = 0;
1646     };
1647     /// \returns the maximum number of operands that are allowed to be reordered
1648     /// for \p Lane and the number of compatible instructions(with the same
1649     /// parent/opcode). This is used as a heuristic for selecting the first lane
1650     /// to start operand reordering.
1651     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1652       unsigned CntTrue = 0;
1653       unsigned NumOperands = getNumOperands();
1654       // Operands with the same APO can be reordered. We therefore need to count
1655       // how many of them we have for each APO, like this: Cnt[APO] = x.
1656       // Since we only have two APOs, namely true and false, we can avoid using
1657       // a map. Instead we can simply count the number of operands that
1658       // correspond to one of them (in this case the 'true' APO), and calculate
1659       // the other by subtracting it from the total number of operands.
1660       // Operands with the same instruction opcode and parent are more
1661       // profitable since we don't need to move them in many cases, with a high
1662       // probability such lane already can be vectorized effectively.
1663       bool AllUndefs = true;
1664       unsigned NumOpsWithSameOpcodeParent = 0;
1665       Instruction *OpcodeI = nullptr;
1666       BasicBlock *Parent = nullptr;
1667       unsigned Hash = 0;
1668       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1669         const OperandData &OpData = getData(OpIdx, Lane);
1670         if (OpData.APO)
1671           ++CntTrue;
1672         // Use Boyer-Moore majority voting for finding the majority opcode and
1673         // the number of times it occurs.
1674         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1675           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1676               I->getParent() != Parent) {
1677             if (NumOpsWithSameOpcodeParent == 0) {
1678               NumOpsWithSameOpcodeParent = 1;
1679               OpcodeI = I;
1680               Parent = I->getParent();
1681             } else {
1682               --NumOpsWithSameOpcodeParent;
1683             }
1684           } else {
1685             ++NumOpsWithSameOpcodeParent;
1686           }
1687         }
1688         Hash = hash_combine(
1689             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1690         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1691       }
1692       if (AllUndefs)
1693         return {};
1694       OperandsOrderData Data;
1695       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1696       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1697       Data.Hash = Hash;
1698       return Data;
1699     }
1700 
1701     /// Go through the instructions in VL and append their operands.
1702     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1703       assert(!VL.empty() && "Bad VL");
1704       assert((empty() || VL.size() == getNumLanes()) &&
1705              "Expected same number of lanes");
1706       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1707       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1708       OpsVec.resize(NumOperands);
1709       unsigned NumLanes = VL.size();
1710       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1711         OpsVec[OpIdx].resize(NumLanes);
1712         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1713           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1714           // Our tree has just 3 nodes: the root and two operands.
1715           // It is therefore trivial to get the APO. We only need to check the
1716           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1717           // RHS operand. The LHS operand of both add and sub is never attached
1718           // to an inversese operation in the linearized form, therefore its APO
1719           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1720 
1721           // Since operand reordering is performed on groups of commutative
1722           // operations or alternating sequences (e.g., +, -), we can safely
1723           // tell the inverse operations by checking commutativity.
1724           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1725           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1726           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1727                                  APO, false};
1728         }
1729       }
1730     }
1731 
1732     /// \returns the number of operands.
1733     unsigned getNumOperands() const { return OpsVec.size(); }
1734 
1735     /// \returns the number of lanes.
1736     unsigned getNumLanes() const { return OpsVec[0].size(); }
1737 
1738     /// \returns the operand value at \p OpIdx and \p Lane.
1739     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1740       return getData(OpIdx, Lane).V;
1741     }
1742 
1743     /// \returns true if the data structure is empty.
1744     bool empty() const { return OpsVec.empty(); }
1745 
1746     /// Clears the data.
1747     void clear() { OpsVec.clear(); }
1748 
1749     /// \Returns true if there are enough operands identical to \p Op to fill
1750     /// the whole vector.
1751     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1752     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1753       bool OpAPO = getData(OpIdx, Lane).APO;
1754       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1755         if (Ln == Lane)
1756           continue;
1757         // This is set to true if we found a candidate for broadcast at Lane.
1758         bool FoundCandidate = false;
1759         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1760           OperandData &Data = getData(OpI, Ln);
1761           if (Data.APO != OpAPO || Data.IsUsed)
1762             continue;
1763           if (Data.V == Op) {
1764             FoundCandidate = true;
1765             Data.IsUsed = true;
1766             break;
1767           }
1768         }
1769         if (!FoundCandidate)
1770           return false;
1771       }
1772       return true;
1773     }
1774 
1775   public:
1776     /// Initialize with all the operands of the instruction vector \p RootVL.
1777     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1778                ScalarEvolution &SE, const BoUpSLP &R)
1779         : DL(DL), SE(SE), R(R) {
1780       // Append all the operands of RootVL.
1781       appendOperandsOfVL(RootVL);
1782     }
1783 
1784     /// \Returns a value vector with the operands across all lanes for the
1785     /// opearnd at \p OpIdx.
1786     ValueList getVL(unsigned OpIdx) const {
1787       ValueList OpVL(OpsVec[OpIdx].size());
1788       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1789              "Expected same num of lanes across all operands");
1790       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1791         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1792       return OpVL;
1793     }
1794 
1795     // Performs operand reordering for 2 or more operands.
1796     // The original operands are in OrigOps[OpIdx][Lane].
1797     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1798     void reorder() {
1799       unsigned NumOperands = getNumOperands();
1800       unsigned NumLanes = getNumLanes();
1801       // Each operand has its own mode. We are using this mode to help us select
1802       // the instructions for each lane, so that they match best with the ones
1803       // we have selected so far.
1804       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1805 
1806       // This is a greedy single-pass algorithm. We are going over each lane
1807       // once and deciding on the best order right away with no back-tracking.
1808       // However, in order to increase its effectiveness, we start with the lane
1809       // that has operands that can move the least. For example, given the
1810       // following lanes:
1811       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1812       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1813       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1814       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1815       // we will start at Lane 1, since the operands of the subtraction cannot
1816       // be reordered. Then we will visit the rest of the lanes in a circular
1817       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1818 
1819       // Find the first lane that we will start our search from.
1820       unsigned FirstLane = getBestLaneToStartReordering();
1821 
1822       // Initialize the modes.
1823       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1824         Value *OpLane0 = getValue(OpIdx, FirstLane);
1825         // Keep track if we have instructions with all the same opcode on one
1826         // side.
1827         if (isa<LoadInst>(OpLane0))
1828           ReorderingModes[OpIdx] = ReorderingMode::Load;
1829         else if (isa<Instruction>(OpLane0)) {
1830           // Check if OpLane0 should be broadcast.
1831           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1832             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1833           else
1834             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1835         }
1836         else if (isa<Constant>(OpLane0))
1837           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1838         else if (isa<Argument>(OpLane0))
1839           // Our best hope is a Splat. It may save some cost in some cases.
1840           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1841         else
1842           // NOTE: This should be unreachable.
1843           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1844       }
1845 
1846       // Check that we don't have same operands. No need to reorder if operands
1847       // are just perfect diamond or shuffled diamond match. Do not do it only
1848       // for possible broadcasts or non-power of 2 number of scalars (just for
1849       // now).
1850       auto &&SkipReordering = [this]() {
1851         SmallPtrSet<Value *, 4> UniqueValues;
1852         ArrayRef<OperandData> Op0 = OpsVec.front();
1853         for (const OperandData &Data : Op0)
1854           UniqueValues.insert(Data.V);
1855         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1856           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1857                 return !UniqueValues.contains(Data.V);
1858               }))
1859             return false;
1860         }
1861         // TODO: Check if we can remove a check for non-power-2 number of
1862         // scalars after full support of non-power-2 vectorization.
1863         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1864       };
1865 
1866       // If the initial strategy fails for any of the operand indexes, then we
1867       // perform reordering again in a second pass. This helps avoid assigning
1868       // high priority to the failed strategy, and should improve reordering for
1869       // the non-failed operand indexes.
1870       for (int Pass = 0; Pass != 2; ++Pass) {
1871         // Check if no need to reorder operands since they're are perfect or
1872         // shuffled diamond match.
1873         // Need to to do it to avoid extra external use cost counting for
1874         // shuffled matches, which may cause regressions.
1875         if (SkipReordering())
1876           break;
1877         // Skip the second pass if the first pass did not fail.
1878         bool StrategyFailed = false;
1879         // Mark all operand data as free to use.
1880         clearUsed();
1881         // We keep the original operand order for the FirstLane, so reorder the
1882         // rest of the lanes. We are visiting the nodes in a circular fashion,
1883         // using FirstLane as the center point and increasing the radius
1884         // distance.
1885         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1886         for (unsigned I = 0; I < NumOperands; ++I)
1887           MainAltOps[I].push_back(getData(I, FirstLane).V);
1888 
1889         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1890           // Visit the lane on the right and then the lane on the left.
1891           for (int Direction : {+1, -1}) {
1892             int Lane = FirstLane + Direction * Distance;
1893             if (Lane < 0 || Lane >= (int)NumLanes)
1894               continue;
1895             int LastLane = Lane - Direction;
1896             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1897                    "Out of bounds");
1898             // Look for a good match for each operand.
1899             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1900               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1901               Optional<unsigned> BestIdx = getBestOperand(
1902                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1903               // By not selecting a value, we allow the operands that follow to
1904               // select a better matching value. We will get a non-null value in
1905               // the next run of getBestOperand().
1906               if (BestIdx) {
1907                 // Swap the current operand with the one returned by
1908                 // getBestOperand().
1909                 swap(OpIdx, BestIdx.getValue(), Lane);
1910               } else {
1911                 // We failed to find a best operand, set mode to 'Failed'.
1912                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1913                 // Enable the second pass.
1914                 StrategyFailed = true;
1915               }
1916               // Try to get the alternate opcode and follow it during analysis.
1917               if (MainAltOps[OpIdx].size() != 2) {
1918                 OperandData &AltOp = getData(OpIdx, Lane);
1919                 InstructionsState OpS =
1920                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1921                 if (OpS.getOpcode() && OpS.isAltShuffle())
1922                   MainAltOps[OpIdx].push_back(AltOp.V);
1923               }
1924             }
1925           }
1926         }
1927         // Skip second pass if the strategy did not fail.
1928         if (!StrategyFailed)
1929           break;
1930       }
1931     }
1932 
1933 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1934     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1935       switch (RMode) {
1936       case ReorderingMode::Load:
1937         return "Load";
1938       case ReorderingMode::Opcode:
1939         return "Opcode";
1940       case ReorderingMode::Constant:
1941         return "Constant";
1942       case ReorderingMode::Splat:
1943         return "Splat";
1944       case ReorderingMode::Failed:
1945         return "Failed";
1946       }
1947       llvm_unreachable("Unimplemented Reordering Type");
1948     }
1949 
1950     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1951                                                    raw_ostream &OS) {
1952       return OS << getModeStr(RMode);
1953     }
1954 
1955     /// Debug print.
1956     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1957       printMode(RMode, dbgs());
1958     }
1959 
1960     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1961       return printMode(RMode, OS);
1962     }
1963 
1964     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1965       const unsigned Indent = 2;
1966       unsigned Cnt = 0;
1967       for (const OperandDataVec &OpDataVec : OpsVec) {
1968         OS << "Operand " << Cnt++ << "\n";
1969         for (const OperandData &OpData : OpDataVec) {
1970           OS.indent(Indent) << "{";
1971           if (Value *V = OpData.V)
1972             OS << *V;
1973           else
1974             OS << "null";
1975           OS << ", APO:" << OpData.APO << "}\n";
1976         }
1977         OS << "\n";
1978       }
1979       return OS;
1980     }
1981 
1982     /// Debug print.
1983     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1984 #endif
1985   };
1986 
1987   /// Checks if the instruction is marked for deletion.
1988   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1989 
1990   /// Removes an instruction from its block and eventually deletes it.
1991   /// It's like Instruction::eraseFromParent() except that the actual deletion
1992   /// is delayed until BoUpSLP is destructed.
1993   void eraseInstruction(Instruction *I) {
1994     DeletedInstructions.insert(I);
1995   }
1996 
1997   ~BoUpSLP();
1998 
1999 private:
2000   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2001   /// reordering (i.e. the operands can be reordered because they have only one
2002   /// user and reordarable).
2003   /// \param ReorderableGathers List of all gather nodes that require reordering
2004   /// (e.g., gather of extractlements or partially vectorizable loads).
2005   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2006   /// reordering, subset of \p NonVectorized.
2007   bool
2008   canReorderOperands(TreeEntry *UserTE,
2009                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2010                      ArrayRef<TreeEntry *> ReorderableGathers,
2011                      SmallVectorImpl<TreeEntry *> &GatherOps);
2012 
2013   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2014   /// if any. If it is not vectorized (gather node), returns nullptr.
2015   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2016     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2017     TreeEntry *TE = nullptr;
2018     const auto *It = find_if(VL, [this, &TE](Value *V) {
2019       TE = getTreeEntry(V);
2020       return TE;
2021     });
2022     if (It != VL.end() && TE->isSame(VL))
2023       return TE;
2024     return nullptr;
2025   }
2026 
2027   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2028   /// if any. If it is not vectorized (gather node), returns nullptr.
2029   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2030                                         unsigned OpIdx) const {
2031     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2032         const_cast<TreeEntry *>(UserTE), OpIdx);
2033   }
2034 
2035   /// Checks if all users of \p I are the part of the vectorization tree.
2036   bool areAllUsersVectorized(Instruction *I,
2037                              ArrayRef<Value *> VectorizedVals) const;
2038 
2039   /// \returns the cost of the vectorizable entry.
2040   InstructionCost getEntryCost(const TreeEntry *E,
2041                                ArrayRef<Value *> VectorizedVals);
2042 
2043   /// This is the recursive part of buildTree.
2044   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2045                      const EdgeInfo &EI);
2046 
2047   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2048   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2049   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2050   /// returns false, setting \p CurrentOrder to either an empty vector or a
2051   /// non-identity permutation that allows to reuse extract instructions.
2052   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2053                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2054 
2055   /// Vectorize a single entry in the tree.
2056   Value *vectorizeTree(TreeEntry *E);
2057 
2058   /// Vectorize a single entry in the tree, starting in \p VL.
2059   Value *vectorizeTree(ArrayRef<Value *> VL);
2060 
2061   /// Create a new vector from a list of scalar values.  Produces a sequence
2062   /// which exploits values reused across lanes, and arranges the inserts
2063   /// for ease of later optimization.
2064   Value *createBuildVector(ArrayRef<Value *> VL);
2065 
2066   /// \returns the scalarization cost for this type. Scalarization in this
2067   /// context means the creation of vectors from a group of scalars. If \p
2068   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2069   /// vector elements.
2070   InstructionCost getGatherCost(FixedVectorType *Ty,
2071                                 const APInt &ShuffledIndices,
2072                                 bool NeedToShuffle) const;
2073 
2074   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2075   /// tree entries.
2076   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2077   /// previous tree entries. \p Mask is filled with the shuffle mask.
2078   Optional<TargetTransformInfo::ShuffleKind>
2079   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2080                         SmallVectorImpl<const TreeEntry *> &Entries);
2081 
2082   /// \returns the scalarization cost for this list of values. Assuming that
2083   /// this subtree gets vectorized, we may need to extract the values from the
2084   /// roots. This method calculates the cost of extracting the values.
2085   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2086 
2087   /// Set the Builder insert point to one after the last instruction in
2088   /// the bundle
2089   void setInsertPointAfterBundle(const TreeEntry *E);
2090 
2091   /// \returns a vector from a collection of scalars in \p VL.
2092   Value *gather(ArrayRef<Value *> VL);
2093 
2094   /// \returns whether the VectorizableTree is fully vectorizable and will
2095   /// be beneficial even the tree height is tiny.
2096   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2097 
2098   /// Reorder commutative or alt operands to get better probability of
2099   /// generating vectorized code.
2100   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2101                                              SmallVectorImpl<Value *> &Left,
2102                                              SmallVectorImpl<Value *> &Right,
2103                                              const DataLayout &DL,
2104                                              ScalarEvolution &SE,
2105                                              const BoUpSLP &R);
2106   struct TreeEntry {
2107     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2108     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2109 
2110     /// \returns true if the scalars in VL are equal to this entry.
2111     bool isSame(ArrayRef<Value *> VL) const {
2112       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2113         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2114           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2115         return VL.size() == Mask.size() &&
2116                std::equal(VL.begin(), VL.end(), Mask.begin(),
2117                           [Scalars](Value *V, int Idx) {
2118                             return (isa<UndefValue>(V) &&
2119                                     Idx == UndefMaskElem) ||
2120                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2121                           });
2122       };
2123       if (!ReorderIndices.empty()) {
2124         // TODO: implement matching if the nodes are just reordered, still can
2125         // treat the vector as the same if the list of scalars matches VL
2126         // directly, without reordering.
2127         SmallVector<int> Mask;
2128         inversePermutation(ReorderIndices, Mask);
2129         if (VL.size() == Scalars.size())
2130           return IsSame(Scalars, Mask);
2131         if (VL.size() == ReuseShuffleIndices.size()) {
2132           ::addMask(Mask, ReuseShuffleIndices);
2133           return IsSame(Scalars, Mask);
2134         }
2135         return false;
2136       }
2137       return IsSame(Scalars, ReuseShuffleIndices);
2138     }
2139 
2140     /// \returns true if current entry has same operands as \p TE.
2141     bool hasEqualOperands(const TreeEntry &TE) const {
2142       if (TE.getNumOperands() != getNumOperands())
2143         return false;
2144       SmallBitVector Used(getNumOperands());
2145       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2146         unsigned PrevCount = Used.count();
2147         for (unsigned K = 0; K < E; ++K) {
2148           if (Used.test(K))
2149             continue;
2150           if (getOperand(K) == TE.getOperand(I)) {
2151             Used.set(K);
2152             break;
2153           }
2154         }
2155         // Check if we actually found the matching operand.
2156         if (PrevCount == Used.count())
2157           return false;
2158       }
2159       return true;
2160     }
2161 
2162     /// \return Final vectorization factor for the node. Defined by the total
2163     /// number of vectorized scalars, including those, used several times in the
2164     /// entry and counted in the \a ReuseShuffleIndices, if any.
2165     unsigned getVectorFactor() const {
2166       if (!ReuseShuffleIndices.empty())
2167         return ReuseShuffleIndices.size();
2168       return Scalars.size();
2169     };
2170 
2171     /// A vector of scalars.
2172     ValueList Scalars;
2173 
2174     /// The Scalars are vectorized into this value. It is initialized to Null.
2175     Value *VectorizedValue = nullptr;
2176 
2177     /// Do we need to gather this sequence or vectorize it
2178     /// (either with vector instruction or with scatter/gather
2179     /// intrinsics for store/load)?
2180     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2181     EntryState State;
2182 
2183     /// Does this sequence require some shuffling?
2184     SmallVector<int, 4> ReuseShuffleIndices;
2185 
2186     /// Does this entry require reordering?
2187     SmallVector<unsigned, 4> ReorderIndices;
2188 
2189     /// Points back to the VectorizableTree.
2190     ///
2191     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2192     /// to be a pointer and needs to be able to initialize the child iterator.
2193     /// Thus we need a reference back to the container to translate the indices
2194     /// to entries.
2195     VecTreeTy &Container;
2196 
2197     /// The TreeEntry index containing the user of this entry.  We can actually
2198     /// have multiple users so the data structure is not truly a tree.
2199     SmallVector<EdgeInfo, 1> UserTreeIndices;
2200 
2201     /// The index of this treeEntry in VectorizableTree.
2202     int Idx = -1;
2203 
2204   private:
2205     /// The operands of each instruction in each lane Operands[op_index][lane].
2206     /// Note: This helps avoid the replication of the code that performs the
2207     /// reordering of operands during buildTree_rec() and vectorizeTree().
2208     SmallVector<ValueList, 2> Operands;
2209 
2210     /// The main/alternate instruction.
2211     Instruction *MainOp = nullptr;
2212     Instruction *AltOp = nullptr;
2213 
2214   public:
2215     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2216     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2217       if (Operands.size() < OpIdx + 1)
2218         Operands.resize(OpIdx + 1);
2219       assert(Operands[OpIdx].empty() && "Already resized?");
2220       assert(OpVL.size() <= Scalars.size() &&
2221              "Number of operands is greater than the number of scalars.");
2222       Operands[OpIdx].resize(OpVL.size());
2223       copy(OpVL, Operands[OpIdx].begin());
2224     }
2225 
2226     /// Set the operands of this bundle in their original order.
2227     void setOperandsInOrder() {
2228       assert(Operands.empty() && "Already initialized?");
2229       auto *I0 = cast<Instruction>(Scalars[0]);
2230       Operands.resize(I0->getNumOperands());
2231       unsigned NumLanes = Scalars.size();
2232       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2233            OpIdx != NumOperands; ++OpIdx) {
2234         Operands[OpIdx].resize(NumLanes);
2235         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2236           auto *I = cast<Instruction>(Scalars[Lane]);
2237           assert(I->getNumOperands() == NumOperands &&
2238                  "Expected same number of operands");
2239           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2240         }
2241       }
2242     }
2243 
2244     /// Reorders operands of the node to the given mask \p Mask.
2245     void reorderOperands(ArrayRef<int> Mask) {
2246       for (ValueList &Operand : Operands)
2247         reorderScalars(Operand, Mask);
2248     }
2249 
2250     /// \returns the \p OpIdx operand of this TreeEntry.
2251     ValueList &getOperand(unsigned OpIdx) {
2252       assert(OpIdx < Operands.size() && "Off bounds");
2253       return Operands[OpIdx];
2254     }
2255 
2256     /// \returns the \p OpIdx operand of this TreeEntry.
2257     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2258       assert(OpIdx < Operands.size() && "Off bounds");
2259       return Operands[OpIdx];
2260     }
2261 
2262     /// \returns the number of operands.
2263     unsigned getNumOperands() const { return Operands.size(); }
2264 
2265     /// \return the single \p OpIdx operand.
2266     Value *getSingleOperand(unsigned OpIdx) const {
2267       assert(OpIdx < Operands.size() && "Off bounds");
2268       assert(!Operands[OpIdx].empty() && "No operand available");
2269       return Operands[OpIdx][0];
2270     }
2271 
2272     /// Some of the instructions in the list have alternate opcodes.
2273     bool isAltShuffle() const { return MainOp != AltOp; }
2274 
2275     bool isOpcodeOrAlt(Instruction *I) const {
2276       unsigned CheckedOpcode = I->getOpcode();
2277       return (getOpcode() == CheckedOpcode ||
2278               getAltOpcode() == CheckedOpcode);
2279     }
2280 
2281     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2282     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2283     /// \p OpValue.
2284     Value *isOneOf(Value *Op) const {
2285       auto *I = dyn_cast<Instruction>(Op);
2286       if (I && isOpcodeOrAlt(I))
2287         return Op;
2288       return MainOp;
2289     }
2290 
2291     void setOperations(const InstructionsState &S) {
2292       MainOp = S.MainOp;
2293       AltOp = S.AltOp;
2294     }
2295 
2296     Instruction *getMainOp() const {
2297       return MainOp;
2298     }
2299 
2300     Instruction *getAltOp() const {
2301       return AltOp;
2302     }
2303 
2304     /// The main/alternate opcodes for the list of instructions.
2305     unsigned getOpcode() const {
2306       return MainOp ? MainOp->getOpcode() : 0;
2307     }
2308 
2309     unsigned getAltOpcode() const {
2310       return AltOp ? AltOp->getOpcode() : 0;
2311     }
2312 
2313     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2314     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2315     int findLaneForValue(Value *V) const {
2316       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2317       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2318       if (!ReorderIndices.empty())
2319         FoundLane = ReorderIndices[FoundLane];
2320       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2321       if (!ReuseShuffleIndices.empty()) {
2322         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2323                                   find(ReuseShuffleIndices, FoundLane));
2324       }
2325       return FoundLane;
2326     }
2327 
2328 #ifndef NDEBUG
2329     /// Debug printer.
2330     LLVM_DUMP_METHOD void dump() const {
2331       dbgs() << Idx << ".\n";
2332       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2333         dbgs() << "Operand " << OpI << ":\n";
2334         for (const Value *V : Operands[OpI])
2335           dbgs().indent(2) << *V << "\n";
2336       }
2337       dbgs() << "Scalars: \n";
2338       for (Value *V : Scalars)
2339         dbgs().indent(2) << *V << "\n";
2340       dbgs() << "State: ";
2341       switch (State) {
2342       case Vectorize:
2343         dbgs() << "Vectorize\n";
2344         break;
2345       case ScatterVectorize:
2346         dbgs() << "ScatterVectorize\n";
2347         break;
2348       case NeedToGather:
2349         dbgs() << "NeedToGather\n";
2350         break;
2351       }
2352       dbgs() << "MainOp: ";
2353       if (MainOp)
2354         dbgs() << *MainOp << "\n";
2355       else
2356         dbgs() << "NULL\n";
2357       dbgs() << "AltOp: ";
2358       if (AltOp)
2359         dbgs() << *AltOp << "\n";
2360       else
2361         dbgs() << "NULL\n";
2362       dbgs() << "VectorizedValue: ";
2363       if (VectorizedValue)
2364         dbgs() << *VectorizedValue << "\n";
2365       else
2366         dbgs() << "NULL\n";
2367       dbgs() << "ReuseShuffleIndices: ";
2368       if (ReuseShuffleIndices.empty())
2369         dbgs() << "Empty";
2370       else
2371         for (int ReuseIdx : ReuseShuffleIndices)
2372           dbgs() << ReuseIdx << ", ";
2373       dbgs() << "\n";
2374       dbgs() << "ReorderIndices: ";
2375       for (unsigned ReorderIdx : ReorderIndices)
2376         dbgs() << ReorderIdx << ", ";
2377       dbgs() << "\n";
2378       dbgs() << "UserTreeIndices: ";
2379       for (const auto &EInfo : UserTreeIndices)
2380         dbgs() << EInfo << ", ";
2381       dbgs() << "\n";
2382     }
2383 #endif
2384   };
2385 
2386 #ifndef NDEBUG
2387   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2388                      InstructionCost VecCost,
2389                      InstructionCost ScalarCost) const {
2390     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2391     dbgs() << "SLP: Costs:\n";
2392     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2393     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2394     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2395     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2396                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2397   }
2398 #endif
2399 
2400   /// Create a new VectorizableTree entry.
2401   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2402                           const InstructionsState &S,
2403                           const EdgeInfo &UserTreeIdx,
2404                           ArrayRef<int> ReuseShuffleIndices = None,
2405                           ArrayRef<unsigned> ReorderIndices = None) {
2406     TreeEntry::EntryState EntryState =
2407         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2408     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2409                         ReuseShuffleIndices, ReorderIndices);
2410   }
2411 
2412   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2413                           TreeEntry::EntryState EntryState,
2414                           Optional<ScheduleData *> Bundle,
2415                           const InstructionsState &S,
2416                           const EdgeInfo &UserTreeIdx,
2417                           ArrayRef<int> ReuseShuffleIndices = None,
2418                           ArrayRef<unsigned> ReorderIndices = None) {
2419     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2420             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2421            "Need to vectorize gather entry?");
2422     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2423     TreeEntry *Last = VectorizableTree.back().get();
2424     Last->Idx = VectorizableTree.size() - 1;
2425     Last->State = EntryState;
2426     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2427                                      ReuseShuffleIndices.end());
2428     if (ReorderIndices.empty()) {
2429       Last->Scalars.assign(VL.begin(), VL.end());
2430       Last->setOperations(S);
2431     } else {
2432       // Reorder scalars and build final mask.
2433       Last->Scalars.assign(VL.size(), nullptr);
2434       transform(ReorderIndices, Last->Scalars.begin(),
2435                 [VL](unsigned Idx) -> Value * {
2436                   if (Idx >= VL.size())
2437                     return UndefValue::get(VL.front()->getType());
2438                   return VL[Idx];
2439                 });
2440       InstructionsState S = getSameOpcode(Last->Scalars);
2441       Last->setOperations(S);
2442       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2443     }
2444     if (Last->State != TreeEntry::NeedToGather) {
2445       for (Value *V : VL) {
2446         assert(!getTreeEntry(V) && "Scalar already in tree!");
2447         ScalarToTreeEntry[V] = Last;
2448       }
2449       // Update the scheduler bundle to point to this TreeEntry.
2450       ScheduleData *BundleMember = Bundle.getValue();
2451       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2452               isVectorLikeInstWithConstOps(S.MainOp) ||
2453               doesNotNeedToSchedule(VL)) &&
2454              "Bundle and VL out of sync");
2455       if (BundleMember) {
2456         for (Value *V : VL) {
2457           if (doesNotNeedToBeScheduled(V))
2458             continue;
2459           assert(BundleMember && "Unexpected end of bundle.");
2460           BundleMember->TE = Last;
2461           BundleMember = BundleMember->NextInBundle;
2462         }
2463       }
2464       assert(!BundleMember && "Bundle and VL out of sync");
2465     } else {
2466       MustGather.insert(VL.begin(), VL.end());
2467     }
2468 
2469     if (UserTreeIdx.UserTE)
2470       Last->UserTreeIndices.push_back(UserTreeIdx);
2471 
2472     return Last;
2473   }
2474 
2475   /// -- Vectorization State --
2476   /// Holds all of the tree entries.
2477   TreeEntry::VecTreeTy VectorizableTree;
2478 
2479 #ifndef NDEBUG
2480   /// Debug printer.
2481   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2482     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2483       VectorizableTree[Id]->dump();
2484       dbgs() << "\n";
2485     }
2486   }
2487 #endif
2488 
2489   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2490 
2491   const TreeEntry *getTreeEntry(Value *V) const {
2492     return ScalarToTreeEntry.lookup(V);
2493   }
2494 
2495   /// Maps a specific scalar to its tree entry.
2496   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2497 
2498   /// Maps a value to the proposed vectorizable size.
2499   SmallDenseMap<Value *, unsigned> InstrElementSize;
2500 
2501   /// A list of scalars that we found that we need to keep as scalars.
2502   ValueSet MustGather;
2503 
2504   /// This POD struct describes one external user in the vectorized tree.
2505   struct ExternalUser {
2506     ExternalUser(Value *S, llvm::User *U, int L)
2507         : Scalar(S), User(U), Lane(L) {}
2508 
2509     // Which scalar in our function.
2510     Value *Scalar;
2511 
2512     // Which user that uses the scalar.
2513     llvm::User *User;
2514 
2515     // Which lane does the scalar belong to.
2516     int Lane;
2517   };
2518   using UserList = SmallVector<ExternalUser, 16>;
2519 
2520   /// Checks if two instructions may access the same memory.
2521   ///
2522   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2523   /// is invariant in the calling loop.
2524   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2525                  Instruction *Inst2) {
2526     // First check if the result is already in the cache.
2527     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2528     Optional<bool> &result = AliasCache[key];
2529     if (result.hasValue()) {
2530       return result.getValue();
2531     }
2532     bool aliased = true;
2533     if (Loc1.Ptr && isSimple(Inst1))
2534       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2535     // Store the result in the cache.
2536     result = aliased;
2537     return aliased;
2538   }
2539 
2540   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2541 
2542   /// Cache for alias results.
2543   /// TODO: consider moving this to the AliasAnalysis itself.
2544   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2545 
2546   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2547   // globally through SLP because we don't perform any action which
2548   // invalidates capture results.
2549   BatchAAResults BatchAA;
2550 
2551   /// Temporary store for deleted instructions. Instructions will be deleted
2552   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2553   /// ensure that there are no incorrect collisions in the AliasCache, which
2554   /// can happen if a new instruction is allocated at the same address as a
2555   /// previously deleted instruction.
2556   DenseSet<Instruction *> DeletedInstructions;
2557 
2558   /// A list of values that need to extracted out of the tree.
2559   /// This list holds pairs of (Internal Scalar : External User). External User
2560   /// can be nullptr, it means that this Internal Scalar will be used later,
2561   /// after vectorization.
2562   UserList ExternalUses;
2563 
2564   /// Values used only by @llvm.assume calls.
2565   SmallPtrSet<const Value *, 32> EphValues;
2566 
2567   /// Holds all of the instructions that we gathered.
2568   SetVector<Instruction *> GatherShuffleSeq;
2569 
2570   /// A list of blocks that we are going to CSE.
2571   SetVector<BasicBlock *> CSEBlocks;
2572 
2573   /// Contains all scheduling relevant data for an instruction.
2574   /// A ScheduleData either represents a single instruction or a member of an
2575   /// instruction bundle (= a group of instructions which is combined into a
2576   /// vector instruction).
2577   struct ScheduleData {
2578     // The initial value for the dependency counters. It means that the
2579     // dependencies are not calculated yet.
2580     enum { InvalidDeps = -1 };
2581 
2582     ScheduleData() = default;
2583 
2584     void init(int BlockSchedulingRegionID, Value *OpVal) {
2585       FirstInBundle = this;
2586       NextInBundle = nullptr;
2587       NextLoadStore = nullptr;
2588       IsScheduled = false;
2589       SchedulingRegionID = BlockSchedulingRegionID;
2590       clearDependencies();
2591       OpValue = OpVal;
2592       TE = nullptr;
2593     }
2594 
2595     /// Verify basic self consistency properties
2596     void verify() {
2597       if (hasValidDependencies()) {
2598         assert(UnscheduledDeps <= Dependencies && "invariant");
2599       } else {
2600         assert(UnscheduledDeps == Dependencies && "invariant");
2601       }
2602 
2603       if (IsScheduled) {
2604         assert(isSchedulingEntity() &&
2605                 "unexpected scheduled state");
2606         for (const ScheduleData *BundleMember = this; BundleMember;
2607              BundleMember = BundleMember->NextInBundle) {
2608           assert(BundleMember->hasValidDependencies() &&
2609                  BundleMember->UnscheduledDeps == 0 &&
2610                  "unexpected scheduled state");
2611           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2612                  "only bundle is marked scheduled");
2613         }
2614       }
2615 
2616       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2617              "all bundle members must be in same basic block");
2618     }
2619 
2620     /// Returns true if the dependency information has been calculated.
2621     /// Note that depenendency validity can vary between instructions within
2622     /// a single bundle.
2623     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2624 
2625     /// Returns true for single instructions and for bundle representatives
2626     /// (= the head of a bundle).
2627     bool isSchedulingEntity() const { return FirstInBundle == this; }
2628 
2629     /// Returns true if it represents an instruction bundle and not only a
2630     /// single instruction.
2631     bool isPartOfBundle() const {
2632       return NextInBundle != nullptr || FirstInBundle != this || TE;
2633     }
2634 
2635     /// Returns true if it is ready for scheduling, i.e. it has no more
2636     /// unscheduled depending instructions/bundles.
2637     bool isReady() const {
2638       assert(isSchedulingEntity() &&
2639              "can't consider non-scheduling entity for ready list");
2640       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2641     }
2642 
2643     /// Modifies the number of unscheduled dependencies for this instruction,
2644     /// and returns the number of remaining dependencies for the containing
2645     /// bundle.
2646     int incrementUnscheduledDeps(int Incr) {
2647       assert(hasValidDependencies() &&
2648              "increment of unscheduled deps would be meaningless");
2649       UnscheduledDeps += Incr;
2650       return FirstInBundle->unscheduledDepsInBundle();
2651     }
2652 
2653     /// Sets the number of unscheduled dependencies to the number of
2654     /// dependencies.
2655     void resetUnscheduledDeps() {
2656       UnscheduledDeps = Dependencies;
2657     }
2658 
2659     /// Clears all dependency information.
2660     void clearDependencies() {
2661       Dependencies = InvalidDeps;
2662       resetUnscheduledDeps();
2663       MemoryDependencies.clear();
2664       ControlDependencies.clear();
2665     }
2666 
2667     int unscheduledDepsInBundle() const {
2668       assert(isSchedulingEntity() && "only meaningful on the bundle");
2669       int Sum = 0;
2670       for (const ScheduleData *BundleMember = this; BundleMember;
2671            BundleMember = BundleMember->NextInBundle) {
2672         if (BundleMember->UnscheduledDeps == InvalidDeps)
2673           return InvalidDeps;
2674         Sum += BundleMember->UnscheduledDeps;
2675       }
2676       return Sum;
2677     }
2678 
2679     void dump(raw_ostream &os) const {
2680       if (!isSchedulingEntity()) {
2681         os << "/ " << *Inst;
2682       } else if (NextInBundle) {
2683         os << '[' << *Inst;
2684         ScheduleData *SD = NextInBundle;
2685         while (SD) {
2686           os << ';' << *SD->Inst;
2687           SD = SD->NextInBundle;
2688         }
2689         os << ']';
2690       } else {
2691         os << *Inst;
2692       }
2693     }
2694 
2695     Instruction *Inst = nullptr;
2696 
2697     /// Opcode of the current instruction in the schedule data.
2698     Value *OpValue = nullptr;
2699 
2700     /// The TreeEntry that this instruction corresponds to.
2701     TreeEntry *TE = nullptr;
2702 
2703     /// Points to the head in an instruction bundle (and always to this for
2704     /// single instructions).
2705     ScheduleData *FirstInBundle = nullptr;
2706 
2707     /// Single linked list of all instructions in a bundle. Null if it is a
2708     /// single instruction.
2709     ScheduleData *NextInBundle = nullptr;
2710 
2711     /// Single linked list of all memory instructions (e.g. load, store, call)
2712     /// in the block - until the end of the scheduling region.
2713     ScheduleData *NextLoadStore = nullptr;
2714 
2715     /// The dependent memory instructions.
2716     /// This list is derived on demand in calculateDependencies().
2717     SmallVector<ScheduleData *, 4> MemoryDependencies;
2718 
2719     /// List of instructions which this instruction could be control dependent
2720     /// on.  Allowing such nodes to be scheduled below this one could introduce
2721     /// a runtime fault which didn't exist in the original program.
2722     /// ex: this is a load or udiv following a readonly call which inf loops
2723     SmallVector<ScheduleData *, 4> ControlDependencies;
2724 
2725     /// This ScheduleData is in the current scheduling region if this matches
2726     /// the current SchedulingRegionID of BlockScheduling.
2727     int SchedulingRegionID = 0;
2728 
2729     /// Used for getting a "good" final ordering of instructions.
2730     int SchedulingPriority = 0;
2731 
2732     /// The number of dependencies. Constitutes of the number of users of the
2733     /// instruction plus the number of dependent memory instructions (if any).
2734     /// This value is calculated on demand.
2735     /// If InvalidDeps, the number of dependencies is not calculated yet.
2736     int Dependencies = InvalidDeps;
2737 
2738     /// The number of dependencies minus the number of dependencies of scheduled
2739     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2740     /// for scheduling.
2741     /// Note that this is negative as long as Dependencies is not calculated.
2742     int UnscheduledDeps = InvalidDeps;
2743 
2744     /// True if this instruction is scheduled (or considered as scheduled in the
2745     /// dry-run).
2746     bool IsScheduled = false;
2747   };
2748 
2749 #ifndef NDEBUG
2750   friend inline raw_ostream &operator<<(raw_ostream &os,
2751                                         const BoUpSLP::ScheduleData &SD) {
2752     SD.dump(os);
2753     return os;
2754   }
2755 #endif
2756 
2757   friend struct GraphTraits<BoUpSLP *>;
2758   friend struct DOTGraphTraits<BoUpSLP *>;
2759 
2760   /// Contains all scheduling data for a basic block.
2761   /// It does not schedules instructions, which are not memory read/write
2762   /// instructions and their operands are either constants, or arguments, or
2763   /// phis, or instructions from others blocks, or their users are phis or from
2764   /// the other blocks. The resulting vector instructions can be placed at the
2765   /// beginning of the basic block without scheduling (if operands does not need
2766   /// to be scheduled) or at the end of the block (if users are outside of the
2767   /// block). It allows to save some compile time and memory used by the
2768   /// compiler.
2769   /// ScheduleData is assigned for each instruction in between the boundaries of
2770   /// the tree entry, even for those, which are not part of the graph. It is
2771   /// required to correctly follow the dependencies between the instructions and
2772   /// their correct scheduling. The ScheduleData is not allocated for the
2773   /// instructions, which do not require scheduling, like phis, nodes with
2774   /// extractelements/insertelements only or nodes with instructions, with
2775   /// uses/operands outside of the block.
2776   struct BlockScheduling {
2777     BlockScheduling(BasicBlock *BB)
2778         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2779 
2780     void clear() {
2781       ReadyInsts.clear();
2782       ScheduleStart = nullptr;
2783       ScheduleEnd = nullptr;
2784       FirstLoadStoreInRegion = nullptr;
2785       LastLoadStoreInRegion = nullptr;
2786       RegionHasStackSave = false;
2787 
2788       // Reduce the maximum schedule region size by the size of the
2789       // previous scheduling run.
2790       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2791       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2792         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2793       ScheduleRegionSize = 0;
2794 
2795       // Make a new scheduling region, i.e. all existing ScheduleData is not
2796       // in the new region yet.
2797       ++SchedulingRegionID;
2798     }
2799 
2800     ScheduleData *getScheduleData(Instruction *I) {
2801       if (BB != I->getParent())
2802         // Avoid lookup if can't possibly be in map.
2803         return nullptr;
2804       ScheduleData *SD = ScheduleDataMap.lookup(I);
2805       if (SD && isInSchedulingRegion(SD))
2806         return SD;
2807       return nullptr;
2808     }
2809 
2810     ScheduleData *getScheduleData(Value *V) {
2811       if (auto *I = dyn_cast<Instruction>(V))
2812         return getScheduleData(I);
2813       return nullptr;
2814     }
2815 
2816     ScheduleData *getScheduleData(Value *V, Value *Key) {
2817       if (V == Key)
2818         return getScheduleData(V);
2819       auto I = ExtraScheduleDataMap.find(V);
2820       if (I != ExtraScheduleDataMap.end()) {
2821         ScheduleData *SD = I->second.lookup(Key);
2822         if (SD && isInSchedulingRegion(SD))
2823           return SD;
2824       }
2825       return nullptr;
2826     }
2827 
2828     bool isInSchedulingRegion(ScheduleData *SD) const {
2829       return SD->SchedulingRegionID == SchedulingRegionID;
2830     }
2831 
2832     /// Marks an instruction as scheduled and puts all dependent ready
2833     /// instructions into the ready-list.
2834     template <typename ReadyListType>
2835     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2836       SD->IsScheduled = true;
2837       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2838 
2839       for (ScheduleData *BundleMember = SD; BundleMember;
2840            BundleMember = BundleMember->NextInBundle) {
2841         if (BundleMember->Inst != BundleMember->OpValue)
2842           continue;
2843 
2844         // Handle the def-use chain dependencies.
2845 
2846         // Decrement the unscheduled counter and insert to ready list if ready.
2847         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2848           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2849             if (OpDef && OpDef->hasValidDependencies() &&
2850                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2851               // There are no more unscheduled dependencies after
2852               // decrementing, so we can put the dependent instruction
2853               // into the ready list.
2854               ScheduleData *DepBundle = OpDef->FirstInBundle;
2855               assert(!DepBundle->IsScheduled &&
2856                      "already scheduled bundle gets ready");
2857               ReadyList.insert(DepBundle);
2858               LLVM_DEBUG(dbgs()
2859                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2860             }
2861           });
2862         };
2863 
2864         // If BundleMember is a vector bundle, its operands may have been
2865         // reordered during buildTree(). We therefore need to get its operands
2866         // through the TreeEntry.
2867         if (TreeEntry *TE = BundleMember->TE) {
2868           // Need to search for the lane since the tree entry can be reordered.
2869           int Lane = std::distance(TE->Scalars.begin(),
2870                                    find(TE->Scalars, BundleMember->Inst));
2871           assert(Lane >= 0 && "Lane not set");
2872 
2873           // Since vectorization tree is being built recursively this assertion
2874           // ensures that the tree entry has all operands set before reaching
2875           // this code. Couple of exceptions known at the moment are extracts
2876           // where their second (immediate) operand is not added. Since
2877           // immediates do not affect scheduler behavior this is considered
2878           // okay.
2879           auto *In = BundleMember->Inst;
2880           assert(In &&
2881                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2882                   In->getNumOperands() == TE->getNumOperands()) &&
2883                  "Missed TreeEntry operands?");
2884           (void)In; // fake use to avoid build failure when assertions disabled
2885 
2886           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2887                OpIdx != NumOperands; ++OpIdx)
2888             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2889               DecrUnsched(I);
2890         } else {
2891           // If BundleMember is a stand-alone instruction, no operand reordering
2892           // has taken place, so we directly access its operands.
2893           for (Use &U : BundleMember->Inst->operands())
2894             if (auto *I = dyn_cast<Instruction>(U.get()))
2895               DecrUnsched(I);
2896         }
2897         // Handle the memory dependencies.
2898         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2899           if (MemoryDepSD->hasValidDependencies() &&
2900               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2901             // There are no more unscheduled dependencies after decrementing,
2902             // so we can put the dependent instruction into the ready list.
2903             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2904             assert(!DepBundle->IsScheduled &&
2905                    "already scheduled bundle gets ready");
2906             ReadyList.insert(DepBundle);
2907             LLVM_DEBUG(dbgs()
2908                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2909           }
2910         }
2911         // Handle the control dependencies.
2912         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2913           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2914             // There are no more unscheduled dependencies after decrementing,
2915             // so we can put the dependent instruction into the ready list.
2916             ScheduleData *DepBundle = DepSD->FirstInBundle;
2917             assert(!DepBundle->IsScheduled &&
2918                    "already scheduled bundle gets ready");
2919             ReadyList.insert(DepBundle);
2920             LLVM_DEBUG(dbgs()
2921                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2922           }
2923         }
2924 
2925       }
2926     }
2927 
2928     /// Verify basic self consistency properties of the data structure.
2929     void verify() {
2930       if (!ScheduleStart)
2931         return;
2932 
2933       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2934              ScheduleStart->comesBefore(ScheduleEnd) &&
2935              "Not a valid scheduling region?");
2936 
2937       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2938         auto *SD = getScheduleData(I);
2939         if (!SD)
2940           continue;
2941         assert(isInSchedulingRegion(SD) &&
2942                "primary schedule data not in window?");
2943         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2944                "entire bundle in window!");
2945         (void)SD;
2946         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2947       }
2948 
2949       for (auto *SD : ReadyInsts) {
2950         assert(SD->isSchedulingEntity() && SD->isReady() &&
2951                "item in ready list not ready?");
2952         (void)SD;
2953       }
2954     }
2955 
2956     void doForAllOpcodes(Value *V,
2957                          function_ref<void(ScheduleData *SD)> Action) {
2958       if (ScheduleData *SD = getScheduleData(V))
2959         Action(SD);
2960       auto I = ExtraScheduleDataMap.find(V);
2961       if (I != ExtraScheduleDataMap.end())
2962         for (auto &P : I->second)
2963           if (isInSchedulingRegion(P.second))
2964             Action(P.second);
2965     }
2966 
2967     /// Put all instructions into the ReadyList which are ready for scheduling.
2968     template <typename ReadyListType>
2969     void initialFillReadyList(ReadyListType &ReadyList) {
2970       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2971         doForAllOpcodes(I, [&](ScheduleData *SD) {
2972           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2973               SD->isReady()) {
2974             ReadyList.insert(SD);
2975             LLVM_DEBUG(dbgs()
2976                        << "SLP:    initially in ready list: " << *SD << "\n");
2977           }
2978         });
2979       }
2980     }
2981 
2982     /// Build a bundle from the ScheduleData nodes corresponding to the
2983     /// scalar instruction for each lane.
2984     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2985 
2986     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2987     /// cyclic dependencies. This is only a dry-run, no instructions are
2988     /// actually moved at this stage.
2989     /// \returns the scheduling bundle. The returned Optional value is non-None
2990     /// if \p VL is allowed to be scheduled.
2991     Optional<ScheduleData *>
2992     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2993                       const InstructionsState &S);
2994 
2995     /// Un-bundles a group of instructions.
2996     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2997 
2998     /// Allocates schedule data chunk.
2999     ScheduleData *allocateScheduleDataChunks();
3000 
3001     /// Extends the scheduling region so that V is inside the region.
3002     /// \returns true if the region size is within the limit.
3003     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3004 
3005     /// Initialize the ScheduleData structures for new instructions in the
3006     /// scheduling region.
3007     void initScheduleData(Instruction *FromI, Instruction *ToI,
3008                           ScheduleData *PrevLoadStore,
3009                           ScheduleData *NextLoadStore);
3010 
3011     /// Updates the dependency information of a bundle and of all instructions/
3012     /// bundles which depend on the original bundle.
3013     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3014                                BoUpSLP *SLP);
3015 
3016     /// Sets all instruction in the scheduling region to un-scheduled.
3017     void resetSchedule();
3018 
3019     BasicBlock *BB;
3020 
3021     /// Simple memory allocation for ScheduleData.
3022     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3023 
3024     /// The size of a ScheduleData array in ScheduleDataChunks.
3025     int ChunkSize;
3026 
3027     /// The allocator position in the current chunk, which is the last entry
3028     /// of ScheduleDataChunks.
3029     int ChunkPos;
3030 
3031     /// Attaches ScheduleData to Instruction.
3032     /// Note that the mapping survives during all vectorization iterations, i.e.
3033     /// ScheduleData structures are recycled.
3034     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3035 
3036     /// Attaches ScheduleData to Instruction with the leading key.
3037     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3038         ExtraScheduleDataMap;
3039 
3040     /// The ready-list for scheduling (only used for the dry-run).
3041     SetVector<ScheduleData *> ReadyInsts;
3042 
3043     /// The first instruction of the scheduling region.
3044     Instruction *ScheduleStart = nullptr;
3045 
3046     /// The first instruction _after_ the scheduling region.
3047     Instruction *ScheduleEnd = nullptr;
3048 
3049     /// The first memory accessing instruction in the scheduling region
3050     /// (can be null).
3051     ScheduleData *FirstLoadStoreInRegion = nullptr;
3052 
3053     /// The last memory accessing instruction in the scheduling region
3054     /// (can be null).
3055     ScheduleData *LastLoadStoreInRegion = nullptr;
3056 
3057     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3058     /// region?  Used to optimize the dependence calculation for the
3059     /// common case where there isn't.
3060     bool RegionHasStackSave = false;
3061 
3062     /// The current size of the scheduling region.
3063     int ScheduleRegionSize = 0;
3064 
3065     /// The maximum size allowed for the scheduling region.
3066     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3067 
3068     /// The ID of the scheduling region. For a new vectorization iteration this
3069     /// is incremented which "removes" all ScheduleData from the region.
3070     /// Make sure that the initial SchedulingRegionID is greater than the
3071     /// initial SchedulingRegionID in ScheduleData (which is 0).
3072     int SchedulingRegionID = 1;
3073   };
3074 
3075   /// Attaches the BlockScheduling structures to basic blocks.
3076   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3077 
3078   /// Performs the "real" scheduling. Done before vectorization is actually
3079   /// performed in a basic block.
3080   void scheduleBlock(BlockScheduling *BS);
3081 
3082   /// List of users to ignore during scheduling and that don't need extracting.
3083   ArrayRef<Value *> UserIgnoreList;
3084 
3085   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3086   /// sorted SmallVectors of unsigned.
3087   struct OrdersTypeDenseMapInfo {
3088     static OrdersType getEmptyKey() {
3089       OrdersType V;
3090       V.push_back(~1U);
3091       return V;
3092     }
3093 
3094     static OrdersType getTombstoneKey() {
3095       OrdersType V;
3096       V.push_back(~2U);
3097       return V;
3098     }
3099 
3100     static unsigned getHashValue(const OrdersType &V) {
3101       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3102     }
3103 
3104     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3105       return LHS == RHS;
3106     }
3107   };
3108 
3109   // Analysis and block reference.
3110   Function *F;
3111   ScalarEvolution *SE;
3112   TargetTransformInfo *TTI;
3113   TargetLibraryInfo *TLI;
3114   LoopInfo *LI;
3115   DominatorTree *DT;
3116   AssumptionCache *AC;
3117   DemandedBits *DB;
3118   const DataLayout *DL;
3119   OptimizationRemarkEmitter *ORE;
3120 
3121   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3122   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3123 
3124   /// Instruction builder to construct the vectorized tree.
3125   IRBuilder<> Builder;
3126 
3127   /// A map of scalar integer values to the smallest bit width with which they
3128   /// can legally be represented. The values map to (width, signed) pairs,
3129   /// where "width" indicates the minimum bit width and "signed" is True if the
3130   /// value must be signed-extended, rather than zero-extended, back to its
3131   /// original width.
3132   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3133 };
3134 
3135 } // end namespace slpvectorizer
3136 
3137 template <> struct GraphTraits<BoUpSLP *> {
3138   using TreeEntry = BoUpSLP::TreeEntry;
3139 
3140   /// NodeRef has to be a pointer per the GraphWriter.
3141   using NodeRef = TreeEntry *;
3142 
3143   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3144 
3145   /// Add the VectorizableTree to the index iterator to be able to return
3146   /// TreeEntry pointers.
3147   struct ChildIteratorType
3148       : public iterator_adaptor_base<
3149             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3150     ContainerTy &VectorizableTree;
3151 
3152     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3153                       ContainerTy &VT)
3154         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3155 
3156     NodeRef operator*() { return I->UserTE; }
3157   };
3158 
3159   static NodeRef getEntryNode(BoUpSLP &R) {
3160     return R.VectorizableTree[0].get();
3161   }
3162 
3163   static ChildIteratorType child_begin(NodeRef N) {
3164     return {N->UserTreeIndices.begin(), N->Container};
3165   }
3166 
3167   static ChildIteratorType child_end(NodeRef N) {
3168     return {N->UserTreeIndices.end(), N->Container};
3169   }
3170 
3171   /// For the node iterator we just need to turn the TreeEntry iterator into a
3172   /// TreeEntry* iterator so that it dereferences to NodeRef.
3173   class nodes_iterator {
3174     using ItTy = ContainerTy::iterator;
3175     ItTy It;
3176 
3177   public:
3178     nodes_iterator(const ItTy &It2) : It(It2) {}
3179     NodeRef operator*() { return It->get(); }
3180     nodes_iterator operator++() {
3181       ++It;
3182       return *this;
3183     }
3184     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3185   };
3186 
3187   static nodes_iterator nodes_begin(BoUpSLP *R) {
3188     return nodes_iterator(R->VectorizableTree.begin());
3189   }
3190 
3191   static nodes_iterator nodes_end(BoUpSLP *R) {
3192     return nodes_iterator(R->VectorizableTree.end());
3193   }
3194 
3195   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3196 };
3197 
3198 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3199   using TreeEntry = BoUpSLP::TreeEntry;
3200 
3201   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3202 
3203   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3204     std::string Str;
3205     raw_string_ostream OS(Str);
3206     if (isSplat(Entry->Scalars))
3207       OS << "<splat> ";
3208     for (auto V : Entry->Scalars) {
3209       OS << *V;
3210       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3211             return EU.Scalar == V;
3212           }))
3213         OS << " <extract>";
3214       OS << "\n";
3215     }
3216     return Str;
3217   }
3218 
3219   static std::string getNodeAttributes(const TreeEntry *Entry,
3220                                        const BoUpSLP *) {
3221     if (Entry->State == TreeEntry::NeedToGather)
3222       return "color=red";
3223     return "";
3224   }
3225 };
3226 
3227 } // end namespace llvm
3228 
3229 BoUpSLP::~BoUpSLP() {
3230   SmallVector<WeakTrackingVH> DeadInsts;
3231   for (auto *I : DeletedInstructions) {
3232     for (Use &U : I->operands()) {
3233       auto *Op = dyn_cast<Instruction>(U.get());
3234       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3235           wouldInstructionBeTriviallyDead(Op, TLI))
3236         DeadInsts.emplace_back(Op);
3237     }
3238     I->dropAllReferences();
3239   }
3240   for (auto *I : DeletedInstructions) {
3241     assert(I->use_empty() &&
3242            "trying to erase instruction with users.");
3243     I->eraseFromParent();
3244   }
3245 
3246   // Cleanup any dead scalar code feeding the vectorized instructions
3247   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3248 
3249 #ifdef EXPENSIVE_CHECKS
3250   // If we could guarantee that this call is not extremely slow, we could
3251   // remove the ifdef limitation (see PR47712).
3252   assert(!verifyFunction(*F, &dbgs()));
3253 #endif
3254 }
3255 
3256 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3257 /// contains original mask for the scalars reused in the node. Procedure
3258 /// transform this mask in accordance with the given \p Mask.
3259 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3260   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3261          "Expected non-empty mask.");
3262   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3263   Prev.swap(Reuses);
3264   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3265     if (Mask[I] != UndefMaskElem)
3266       Reuses[Mask[I]] = Prev[I];
3267 }
3268 
3269 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3270 /// the original order of the scalars. Procedure transforms the provided order
3271 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3272 /// identity order, \p Order is cleared.
3273 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3274   assert(!Mask.empty() && "Expected non-empty mask.");
3275   SmallVector<int> MaskOrder;
3276   if (Order.empty()) {
3277     MaskOrder.resize(Mask.size());
3278     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3279   } else {
3280     inversePermutation(Order, MaskOrder);
3281   }
3282   reorderReuses(MaskOrder, Mask);
3283   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3284     Order.clear();
3285     return;
3286   }
3287   Order.assign(Mask.size(), Mask.size());
3288   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3289     if (MaskOrder[I] != UndefMaskElem)
3290       Order[MaskOrder[I]] = I;
3291   fixupOrderingIndices(Order);
3292 }
3293 
3294 Optional<BoUpSLP::OrdersType>
3295 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3296   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3297   unsigned NumScalars = TE.Scalars.size();
3298   OrdersType CurrentOrder(NumScalars, NumScalars);
3299   SmallVector<int> Positions;
3300   SmallBitVector UsedPositions(NumScalars);
3301   const TreeEntry *STE = nullptr;
3302   // Try to find all gathered scalars that are gets vectorized in other
3303   // vectorize node. Here we can have only one single tree vector node to
3304   // correctly identify order of the gathered scalars.
3305   for (unsigned I = 0; I < NumScalars; ++I) {
3306     Value *V = TE.Scalars[I];
3307     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3308       continue;
3309     if (const auto *LocalSTE = getTreeEntry(V)) {
3310       if (!STE)
3311         STE = LocalSTE;
3312       else if (STE != LocalSTE)
3313         // Take the order only from the single vector node.
3314         return None;
3315       unsigned Lane =
3316           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3317       if (Lane >= NumScalars)
3318         return None;
3319       if (CurrentOrder[Lane] != NumScalars) {
3320         if (Lane != I)
3321           continue;
3322         UsedPositions.reset(CurrentOrder[Lane]);
3323       }
3324       // The partial identity (where only some elements of the gather node are
3325       // in the identity order) is good.
3326       CurrentOrder[Lane] = I;
3327       UsedPositions.set(I);
3328     }
3329   }
3330   // Need to keep the order if we have a vector entry and at least 2 scalars or
3331   // the vectorized entry has just 2 scalars.
3332   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3333     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3334       for (unsigned I = 0; I < NumScalars; ++I)
3335         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3336           return false;
3337       return true;
3338     };
3339     if (IsIdentityOrder(CurrentOrder)) {
3340       CurrentOrder.clear();
3341       return CurrentOrder;
3342     }
3343     auto *It = CurrentOrder.begin();
3344     for (unsigned I = 0; I < NumScalars;) {
3345       if (UsedPositions.test(I)) {
3346         ++I;
3347         continue;
3348       }
3349       if (*It == NumScalars) {
3350         *It = I;
3351         ++I;
3352       }
3353       ++It;
3354     }
3355     return CurrentOrder;
3356   }
3357   return None;
3358 }
3359 
3360 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3361                                                          bool TopToBottom) {
3362   // No need to reorder if need to shuffle reuses, still need to shuffle the
3363   // node.
3364   if (!TE.ReuseShuffleIndices.empty())
3365     return None;
3366   if (TE.State == TreeEntry::Vectorize &&
3367       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3368        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3369       !TE.isAltShuffle())
3370     return TE.ReorderIndices;
3371   if (TE.State == TreeEntry::NeedToGather) {
3372     // TODO: add analysis of other gather nodes with extractelement
3373     // instructions and other values/instructions, not only undefs.
3374     if (((TE.getOpcode() == Instruction::ExtractElement &&
3375           !TE.isAltShuffle()) ||
3376          (all_of(TE.Scalars,
3377                  [](Value *V) {
3378                    return isa<UndefValue, ExtractElementInst>(V);
3379                  }) &&
3380           any_of(TE.Scalars,
3381                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3382         all_of(TE.Scalars,
3383                [](Value *V) {
3384                  auto *EE = dyn_cast<ExtractElementInst>(V);
3385                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3386                }) &&
3387         allSameType(TE.Scalars)) {
3388       // Check that gather of extractelements can be represented as
3389       // just a shuffle of a single vector.
3390       OrdersType CurrentOrder;
3391       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3392       if (Reuse || !CurrentOrder.empty()) {
3393         if (!CurrentOrder.empty())
3394           fixupOrderingIndices(CurrentOrder);
3395         return CurrentOrder;
3396       }
3397     }
3398     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3399       return CurrentOrder;
3400   }
3401   return None;
3402 }
3403 
3404 void BoUpSLP::reorderTopToBottom() {
3405   // Maps VF to the graph nodes.
3406   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3407   // ExtractElement gather nodes which can be vectorized and need to handle
3408   // their ordering.
3409   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3410   // Find all reorderable nodes with the given VF.
3411   // Currently the are vectorized stores,loads,extracts + some gathering of
3412   // extracts.
3413   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3414                                  const std::unique_ptr<TreeEntry> &TE) {
3415     if (Optional<OrdersType> CurrentOrder =
3416             getReorderingData(*TE, /*TopToBottom=*/true)) {
3417       // Do not include ordering for nodes used in the alt opcode vectorization,
3418       // better to reorder them during bottom-to-top stage. If follow the order
3419       // here, it causes reordering of the whole graph though actually it is
3420       // profitable just to reorder the subgraph that starts from the alternate
3421       // opcode vectorization node. Such nodes already end-up with the shuffle
3422       // instruction and it is just enough to change this shuffle rather than
3423       // rotate the scalars for the whole graph.
3424       unsigned Cnt = 0;
3425       const TreeEntry *UserTE = TE.get();
3426       while (UserTE && Cnt < RecursionMaxDepth) {
3427         if (UserTE->UserTreeIndices.size() != 1)
3428           break;
3429         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3430               return EI.UserTE->State == TreeEntry::Vectorize &&
3431                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3432             }))
3433           return;
3434         if (UserTE->UserTreeIndices.empty())
3435           UserTE = nullptr;
3436         else
3437           UserTE = UserTE->UserTreeIndices.back().UserTE;
3438         ++Cnt;
3439       }
3440       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3441       if (TE->State != TreeEntry::Vectorize)
3442         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3443     }
3444   });
3445 
3446   // Reorder the graph nodes according to their vectorization factor.
3447   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3448        VF /= 2) {
3449     auto It = VFToOrderedEntries.find(VF);
3450     if (It == VFToOrderedEntries.end())
3451       continue;
3452     // Try to find the most profitable order. We just are looking for the most
3453     // used order and reorder scalar elements in the nodes according to this
3454     // mostly used order.
3455     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3456     // All operands are reordered and used only in this node - propagate the
3457     // most used order to the user node.
3458     MapVector<OrdersType, unsigned,
3459               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3460         OrdersUses;
3461     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3462     for (const TreeEntry *OpTE : OrderedEntries) {
3463       // No need to reorder this nodes, still need to extend and to use shuffle,
3464       // just need to merge reordering shuffle and the reuse shuffle.
3465       if (!OpTE->ReuseShuffleIndices.empty())
3466         continue;
3467       // Count number of orders uses.
3468       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3469         if (OpTE->State == TreeEntry::NeedToGather)
3470           return GathersToOrders.find(OpTE)->second;
3471         return OpTE->ReorderIndices;
3472       }();
3473       // Stores actually store the mask, not the order, need to invert.
3474       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3475           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3476         SmallVector<int> Mask;
3477         inversePermutation(Order, Mask);
3478         unsigned E = Order.size();
3479         OrdersType CurrentOrder(E, E);
3480         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3481           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3482         });
3483         fixupOrderingIndices(CurrentOrder);
3484         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3485       } else {
3486         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3487       }
3488     }
3489     // Set order of the user node.
3490     if (OrdersUses.empty())
3491       continue;
3492     // Choose the most used order.
3493     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3494     unsigned Cnt = OrdersUses.front().second;
3495     for (const auto &Pair : drop_begin(OrdersUses)) {
3496       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3497         BestOrder = Pair.first;
3498         Cnt = Pair.second;
3499       }
3500     }
3501     // Set order of the user node.
3502     if (BestOrder.empty())
3503       continue;
3504     SmallVector<int> Mask;
3505     inversePermutation(BestOrder, Mask);
3506     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3507     unsigned E = BestOrder.size();
3508     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3509       return I < E ? static_cast<int>(I) : UndefMaskElem;
3510     });
3511     // Do an actual reordering, if profitable.
3512     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3513       // Just do the reordering for the nodes with the given VF.
3514       if (TE->Scalars.size() != VF) {
3515         if (TE->ReuseShuffleIndices.size() == VF) {
3516           // Need to reorder the reuses masks of the operands with smaller VF to
3517           // be able to find the match between the graph nodes and scalar
3518           // operands of the given node during vectorization/cost estimation.
3519           assert(all_of(TE->UserTreeIndices,
3520                         [VF, &TE](const EdgeInfo &EI) {
3521                           return EI.UserTE->Scalars.size() == VF ||
3522                                  EI.UserTE->Scalars.size() ==
3523                                      TE->Scalars.size();
3524                         }) &&
3525                  "All users must be of VF size.");
3526           // Update ordering of the operands with the smaller VF than the given
3527           // one.
3528           reorderReuses(TE->ReuseShuffleIndices, Mask);
3529         }
3530         continue;
3531       }
3532       if (TE->State == TreeEntry::Vectorize &&
3533           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3534               InsertElementInst>(TE->getMainOp()) &&
3535           !TE->isAltShuffle()) {
3536         // Build correct orders for extract{element,value}, loads and
3537         // stores.
3538         reorderOrder(TE->ReorderIndices, Mask);
3539         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3540           TE->reorderOperands(Mask);
3541       } else {
3542         // Reorder the node and its operands.
3543         TE->reorderOperands(Mask);
3544         assert(TE->ReorderIndices.empty() &&
3545                "Expected empty reorder sequence.");
3546         reorderScalars(TE->Scalars, Mask);
3547       }
3548       if (!TE->ReuseShuffleIndices.empty()) {
3549         // Apply reversed order to keep the original ordering of the reused
3550         // elements to avoid extra reorder indices shuffling.
3551         OrdersType CurrentOrder;
3552         reorderOrder(CurrentOrder, MaskOrder);
3553         SmallVector<int> NewReuses;
3554         inversePermutation(CurrentOrder, NewReuses);
3555         addMask(NewReuses, TE->ReuseShuffleIndices);
3556         TE->ReuseShuffleIndices.swap(NewReuses);
3557       }
3558     }
3559   }
3560 }
3561 
3562 bool BoUpSLP::canReorderOperands(
3563     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3564     ArrayRef<TreeEntry *> ReorderableGathers,
3565     SmallVectorImpl<TreeEntry *> &GatherOps) {
3566   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3567     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3568           return OpData.first == I &&
3569                  OpData.second->State == TreeEntry::Vectorize;
3570         }))
3571       continue;
3572     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3573       // Do not reorder if operand node is used by many user nodes.
3574       if (any_of(TE->UserTreeIndices,
3575                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3576         return false;
3577       // Add the node to the list of the ordered nodes with the identity
3578       // order.
3579       Edges.emplace_back(I, TE);
3580       continue;
3581     }
3582     ArrayRef<Value *> VL = UserTE->getOperand(I);
3583     TreeEntry *Gather = nullptr;
3584     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3585           assert(TE->State != TreeEntry::Vectorize &&
3586                  "Only non-vectorized nodes are expected.");
3587           if (TE->isSame(VL)) {
3588             Gather = TE;
3589             return true;
3590           }
3591           return false;
3592         }) > 1)
3593       return false;
3594     if (Gather)
3595       GatherOps.push_back(Gather);
3596   }
3597   return true;
3598 }
3599 
3600 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3601   SetVector<TreeEntry *> OrderedEntries;
3602   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3603   // Find all reorderable leaf nodes with the given VF.
3604   // Currently the are vectorized loads,extracts without alternate operands +
3605   // some gathering of extracts.
3606   SmallVector<TreeEntry *> NonVectorized;
3607   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3608                               &NonVectorized](
3609                                  const std::unique_ptr<TreeEntry> &TE) {
3610     if (TE->State != TreeEntry::Vectorize)
3611       NonVectorized.push_back(TE.get());
3612     if (Optional<OrdersType> CurrentOrder =
3613             getReorderingData(*TE, /*TopToBottom=*/false)) {
3614       OrderedEntries.insert(TE.get());
3615       if (TE->State != TreeEntry::Vectorize)
3616         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3617     }
3618   });
3619 
3620   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3621   // I.e., if the node has operands, that are reordered, try to make at least
3622   // one operand order in the natural order and reorder others + reorder the
3623   // user node itself.
3624   SmallPtrSet<const TreeEntry *, 4> Visited;
3625   while (!OrderedEntries.empty()) {
3626     // 1. Filter out only reordered nodes.
3627     // 2. If the entry has multiple uses - skip it and jump to the next node.
3628     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3629     SmallVector<TreeEntry *> Filtered;
3630     for (TreeEntry *TE : OrderedEntries) {
3631       if (!(TE->State == TreeEntry::Vectorize ||
3632             (TE->State == TreeEntry::NeedToGather &&
3633              GathersToOrders.count(TE))) ||
3634           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3635           !all_of(drop_begin(TE->UserTreeIndices),
3636                   [TE](const EdgeInfo &EI) {
3637                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3638                   }) ||
3639           !Visited.insert(TE).second) {
3640         Filtered.push_back(TE);
3641         continue;
3642       }
3643       // Build a map between user nodes and their operands order to speedup
3644       // search. The graph currently does not provide this dependency directly.
3645       for (EdgeInfo &EI : TE->UserTreeIndices) {
3646         TreeEntry *UserTE = EI.UserTE;
3647         auto It = Users.find(UserTE);
3648         if (It == Users.end())
3649           It = Users.insert({UserTE, {}}).first;
3650         It->second.emplace_back(EI.EdgeIdx, TE);
3651       }
3652     }
3653     // Erase filtered entries.
3654     for_each(Filtered,
3655              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3656     for (auto &Data : Users) {
3657       // Check that operands are used only in the User node.
3658       SmallVector<TreeEntry *> GatherOps;
3659       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3660                               GatherOps)) {
3661         for_each(Data.second,
3662                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3663                    OrderedEntries.remove(Op.second);
3664                  });
3665         continue;
3666       }
3667       // All operands are reordered and used only in this node - propagate the
3668       // most used order to the user node.
3669       MapVector<OrdersType, unsigned,
3670                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3671           OrdersUses;
3672       // Do the analysis for each tree entry only once, otherwise the order of
3673       // the same node my be considered several times, though might be not
3674       // profitable.
3675       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3676       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3677       for (const auto &Op : Data.second) {
3678         TreeEntry *OpTE = Op.second;
3679         if (!VisitedOps.insert(OpTE).second)
3680           continue;
3681         if (!OpTE->ReuseShuffleIndices.empty() ||
3682             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3683           continue;
3684         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3685           if (OpTE->State == TreeEntry::NeedToGather)
3686             return GathersToOrders.find(OpTE)->second;
3687           return OpTE->ReorderIndices;
3688         }();
3689         unsigned NumOps = count_if(
3690             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3691               return P.second == OpTE;
3692             });
3693         // Stores actually store the mask, not the order, need to invert.
3694         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3695             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3696           SmallVector<int> Mask;
3697           inversePermutation(Order, Mask);
3698           unsigned E = Order.size();
3699           OrdersType CurrentOrder(E, E);
3700           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3701             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3702           });
3703           fixupOrderingIndices(CurrentOrder);
3704           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3705               NumOps;
3706         } else {
3707           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3708         }
3709         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3710         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3711                                             const TreeEntry *TE) {
3712           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3713               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3714               (IgnoreReorder && TE->Idx == 0))
3715             return true;
3716           if (TE->State == TreeEntry::NeedToGather) {
3717             auto It = GathersToOrders.find(TE);
3718             if (It != GathersToOrders.end())
3719               return !It->second.empty();
3720             return true;
3721           }
3722           return false;
3723         };
3724         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3725           TreeEntry *UserTE = EI.UserTE;
3726           if (!VisitedUsers.insert(UserTE).second)
3727             continue;
3728           // May reorder user node if it requires reordering, has reused
3729           // scalars, is an alternate op vectorize node or its op nodes require
3730           // reordering.
3731           if (AllowsReordering(UserTE))
3732             continue;
3733           // Check if users allow reordering.
3734           // Currently look up just 1 level of operands to avoid increase of
3735           // the compile time.
3736           // Profitable to reorder if definitely more operands allow
3737           // reordering rather than those with natural order.
3738           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3739           if (static_cast<unsigned>(count_if(
3740                   Ops, [UserTE, &AllowsReordering](
3741                            const std::pair<unsigned, TreeEntry *> &Op) {
3742                     return AllowsReordering(Op.second) &&
3743                            all_of(Op.second->UserTreeIndices,
3744                                   [UserTE](const EdgeInfo &EI) {
3745                                     return EI.UserTE == UserTE;
3746                                   });
3747                   })) <= Ops.size() / 2)
3748             ++Res.first->second;
3749         }
3750       }
3751       // If no orders - skip current nodes and jump to the next one, if any.
3752       if (OrdersUses.empty()) {
3753         for_each(Data.second,
3754                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3755                    OrderedEntries.remove(Op.second);
3756                  });
3757         continue;
3758       }
3759       // Choose the best order.
3760       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3761       unsigned Cnt = OrdersUses.front().second;
3762       for (const auto &Pair : drop_begin(OrdersUses)) {
3763         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3764           BestOrder = Pair.first;
3765           Cnt = Pair.second;
3766         }
3767       }
3768       // Set order of the user node (reordering of operands and user nodes).
3769       if (BestOrder.empty()) {
3770         for_each(Data.second,
3771                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3772                    OrderedEntries.remove(Op.second);
3773                  });
3774         continue;
3775       }
3776       // Erase operands from OrderedEntries list and adjust their orders.
3777       VisitedOps.clear();
3778       SmallVector<int> Mask;
3779       inversePermutation(BestOrder, Mask);
3780       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3781       unsigned E = BestOrder.size();
3782       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3783         return I < E ? static_cast<int>(I) : UndefMaskElem;
3784       });
3785       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3786         TreeEntry *TE = Op.second;
3787         OrderedEntries.remove(TE);
3788         if (!VisitedOps.insert(TE).second)
3789           continue;
3790         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3791           // Just reorder reuses indices.
3792           reorderReuses(TE->ReuseShuffleIndices, Mask);
3793           continue;
3794         }
3795         // Gathers are processed separately.
3796         if (TE->State != TreeEntry::Vectorize)
3797           continue;
3798         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3799                 TE->ReorderIndices.empty()) &&
3800                "Non-matching sizes of user/operand entries.");
3801         reorderOrder(TE->ReorderIndices, Mask);
3802       }
3803       // For gathers just need to reorder its scalars.
3804       for (TreeEntry *Gather : GatherOps) {
3805         assert(Gather->ReorderIndices.empty() &&
3806                "Unexpected reordering of gathers.");
3807         if (!Gather->ReuseShuffleIndices.empty()) {
3808           // Just reorder reuses indices.
3809           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3810           continue;
3811         }
3812         reorderScalars(Gather->Scalars, Mask);
3813         OrderedEntries.remove(Gather);
3814       }
3815       // Reorder operands of the user node and set the ordering for the user
3816       // node itself.
3817       if (Data.first->State != TreeEntry::Vectorize ||
3818           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3819               Data.first->getMainOp()) ||
3820           Data.first->isAltShuffle())
3821         Data.first->reorderOperands(Mask);
3822       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3823           Data.first->isAltShuffle()) {
3824         reorderScalars(Data.first->Scalars, Mask);
3825         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3826         if (Data.first->ReuseShuffleIndices.empty() &&
3827             !Data.first->ReorderIndices.empty() &&
3828             !Data.first->isAltShuffle()) {
3829           // Insert user node to the list to try to sink reordering deeper in
3830           // the graph.
3831           OrderedEntries.insert(Data.first);
3832         }
3833       } else {
3834         reorderOrder(Data.first->ReorderIndices, Mask);
3835       }
3836     }
3837   }
3838   // If the reordering is unnecessary, just remove the reorder.
3839   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3840       VectorizableTree.front()->ReuseShuffleIndices.empty())
3841     VectorizableTree.front()->ReorderIndices.clear();
3842 }
3843 
3844 void BoUpSLP::buildExternalUses(
3845     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3846   // Collect the values that we need to extract from the tree.
3847   for (auto &TEPtr : VectorizableTree) {
3848     TreeEntry *Entry = TEPtr.get();
3849 
3850     // No need to handle users of gathered values.
3851     if (Entry->State == TreeEntry::NeedToGather)
3852       continue;
3853 
3854     // For each lane:
3855     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3856       Value *Scalar = Entry->Scalars[Lane];
3857       int FoundLane = Entry->findLaneForValue(Scalar);
3858 
3859       // Check if the scalar is externally used as an extra arg.
3860       auto ExtI = ExternallyUsedValues.find(Scalar);
3861       if (ExtI != ExternallyUsedValues.end()) {
3862         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3863                           << Lane << " from " << *Scalar << ".\n");
3864         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3865       }
3866       for (User *U : Scalar->users()) {
3867         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3868 
3869         Instruction *UserInst = dyn_cast<Instruction>(U);
3870         if (!UserInst)
3871           continue;
3872 
3873         if (isDeleted(UserInst))
3874           continue;
3875 
3876         // Skip in-tree scalars that become vectors
3877         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3878           Value *UseScalar = UseEntry->Scalars[0];
3879           // Some in-tree scalars will remain as scalar in vectorized
3880           // instructions. If that is the case, the one in Lane 0 will
3881           // be used.
3882           if (UseScalar != U ||
3883               UseEntry->State == TreeEntry::ScatterVectorize ||
3884               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3885             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3886                               << ".\n");
3887             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3888             continue;
3889           }
3890         }
3891 
3892         // Ignore users in the user ignore list.
3893         if (is_contained(UserIgnoreList, UserInst))
3894           continue;
3895 
3896         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3897                           << Lane << " from " << *Scalar << ".\n");
3898         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3899       }
3900     }
3901   }
3902 }
3903 
3904 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3905                         ArrayRef<Value *> UserIgnoreLst) {
3906   deleteTree();
3907   UserIgnoreList = UserIgnoreLst;
3908   if (!allSameType(Roots))
3909     return;
3910   buildTree_rec(Roots, 0, EdgeInfo());
3911 }
3912 
3913 namespace {
3914 /// Tracks the state we can represent the loads in the given sequence.
3915 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3916 } // anonymous namespace
3917 
3918 /// Checks if the given array of loads can be represented as a vectorized,
3919 /// scatter or just simple gather.
3920 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3921                                     const TargetTransformInfo &TTI,
3922                                     const DataLayout &DL, ScalarEvolution &SE,
3923                                     SmallVectorImpl<unsigned> &Order,
3924                                     SmallVectorImpl<Value *> &PointerOps) {
3925   // Check that a vectorized load would load the same memory as a scalar
3926   // load. For example, we don't want to vectorize loads that are smaller
3927   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3928   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3929   // from such a struct, we read/write packed bits disagreeing with the
3930   // unvectorized version.
3931   Type *ScalarTy = VL0->getType();
3932 
3933   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3934     return LoadsState::Gather;
3935 
3936   // Make sure all loads in the bundle are simple - we can't vectorize
3937   // atomic or volatile loads.
3938   PointerOps.clear();
3939   PointerOps.resize(VL.size());
3940   auto *POIter = PointerOps.begin();
3941   for (Value *V : VL) {
3942     auto *L = cast<LoadInst>(V);
3943     if (!L->isSimple())
3944       return LoadsState::Gather;
3945     *POIter = L->getPointerOperand();
3946     ++POIter;
3947   }
3948 
3949   Order.clear();
3950   // Check the order of pointer operands.
3951   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3952     Value *Ptr0;
3953     Value *PtrN;
3954     if (Order.empty()) {
3955       Ptr0 = PointerOps.front();
3956       PtrN = PointerOps.back();
3957     } else {
3958       Ptr0 = PointerOps[Order.front()];
3959       PtrN = PointerOps[Order.back()];
3960     }
3961     Optional<int> Diff =
3962         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3963     // Check that the sorted loads are consecutive.
3964     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3965       return LoadsState::Vectorize;
3966     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3967     for (Value *V : VL)
3968       CommonAlignment =
3969           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3970     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3971                                 CommonAlignment))
3972       return LoadsState::ScatterVectorize;
3973   }
3974 
3975   return LoadsState::Gather;
3976 }
3977 
3978 /// \return true if the specified list of values has only one instruction that
3979 /// requires scheduling, false otherwise.
3980 #ifndef NDEBUG
3981 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3982   Value *NeedsScheduling = nullptr;
3983   for (Value *V : VL) {
3984     if (doesNotNeedToBeScheduled(V))
3985       continue;
3986     if (!NeedsScheduling) {
3987       NeedsScheduling = V;
3988       continue;
3989     }
3990     return false;
3991   }
3992   return NeedsScheduling;
3993 }
3994 #endif
3995 
3996 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3997                             const EdgeInfo &UserTreeIdx) {
3998   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3999 
4000   SmallVector<int> ReuseShuffleIndicies;
4001   SmallVector<Value *> UniqueValues;
4002   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4003                                 &UserTreeIdx,
4004                                 this](const InstructionsState &S) {
4005     // Check that every instruction appears once in this bundle.
4006     DenseMap<Value *, unsigned> UniquePositions;
4007     for (Value *V : VL) {
4008       if (isConstant(V)) {
4009         ReuseShuffleIndicies.emplace_back(
4010             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4011         UniqueValues.emplace_back(V);
4012         continue;
4013       }
4014       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4015       ReuseShuffleIndicies.emplace_back(Res.first->second);
4016       if (Res.second)
4017         UniqueValues.emplace_back(V);
4018     }
4019     size_t NumUniqueScalarValues = UniqueValues.size();
4020     if (NumUniqueScalarValues == VL.size()) {
4021       ReuseShuffleIndicies.clear();
4022     } else {
4023       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4024       if (NumUniqueScalarValues <= 1 ||
4025           (UniquePositions.size() == 1 && all_of(UniqueValues,
4026                                                  [](Value *V) {
4027                                                    return isa<UndefValue>(V) ||
4028                                                           !isConstant(V);
4029                                                  })) ||
4030           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4031         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4032         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4033         return false;
4034       }
4035       VL = UniqueValues;
4036     }
4037     return true;
4038   };
4039 
4040   InstructionsState S = getSameOpcode(VL);
4041   if (Depth == RecursionMaxDepth) {
4042     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4043     if (TryToFindDuplicates(S))
4044       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4045                    ReuseShuffleIndicies);
4046     return;
4047   }
4048 
4049   // Don't handle scalable vectors
4050   if (S.getOpcode() == Instruction::ExtractElement &&
4051       isa<ScalableVectorType>(
4052           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4053     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4054     if (TryToFindDuplicates(S))
4055       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4056                    ReuseShuffleIndicies);
4057     return;
4058   }
4059 
4060   // Don't handle vectors.
4061   if (S.OpValue->getType()->isVectorTy() &&
4062       !isa<InsertElementInst>(S.OpValue)) {
4063     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4064     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4065     return;
4066   }
4067 
4068   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4069     if (SI->getValueOperand()->getType()->isVectorTy()) {
4070       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4071       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4072       return;
4073     }
4074 
4075   // If all of the operands are identical or constant we have a simple solution.
4076   // If we deal with insert/extract instructions, they all must have constant
4077   // indices, otherwise we should gather them, not try to vectorize.
4078   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4079       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4080        !all_of(VL, isVectorLikeInstWithConstOps))) {
4081     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4082     if (TryToFindDuplicates(S))
4083       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4084                    ReuseShuffleIndicies);
4085     return;
4086   }
4087 
4088   // We now know that this is a vector of instructions of the same type from
4089   // the same block.
4090 
4091   // Don't vectorize ephemeral values.
4092   for (Value *V : VL) {
4093     if (EphValues.count(V)) {
4094       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4095                         << ") is ephemeral.\n");
4096       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4097       return;
4098     }
4099   }
4100 
4101   // Check if this is a duplicate of another entry.
4102   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4103     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4104     if (!E->isSame(VL)) {
4105       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4106       if (TryToFindDuplicates(S))
4107         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4108                      ReuseShuffleIndicies);
4109       return;
4110     }
4111     // Record the reuse of the tree node.  FIXME, currently this is only used to
4112     // properly draw the graph rather than for the actual vectorization.
4113     E->UserTreeIndices.push_back(UserTreeIdx);
4114     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4115                       << ".\n");
4116     return;
4117   }
4118 
4119   // Check that none of the instructions in the bundle are already in the tree.
4120   for (Value *V : VL) {
4121     auto *I = dyn_cast<Instruction>(V);
4122     if (!I)
4123       continue;
4124     if (getTreeEntry(I)) {
4125       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4126                         << ") is already in tree.\n");
4127       if (TryToFindDuplicates(S))
4128         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4129                      ReuseShuffleIndicies);
4130       return;
4131     }
4132   }
4133 
4134   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4135   for (Value *V : VL) {
4136     if (is_contained(UserIgnoreList, V)) {
4137       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4138       if (TryToFindDuplicates(S))
4139         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4140                      ReuseShuffleIndicies);
4141       return;
4142     }
4143   }
4144 
4145   // Check that all of the users of the scalars that we want to vectorize are
4146   // schedulable.
4147   auto *VL0 = cast<Instruction>(S.OpValue);
4148   BasicBlock *BB = VL0->getParent();
4149 
4150   if (!DT->isReachableFromEntry(BB)) {
4151     // Don't go into unreachable blocks. They may contain instructions with
4152     // dependency cycles which confuse the final scheduling.
4153     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4154     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4155     return;
4156   }
4157 
4158   // Check that every instruction appears once in this bundle.
4159   if (!TryToFindDuplicates(S))
4160     return;
4161 
4162   auto &BSRef = BlocksSchedules[BB];
4163   if (!BSRef)
4164     BSRef = std::make_unique<BlockScheduling>(BB);
4165 
4166   BlockScheduling &BS = *BSRef;
4167 
4168   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4169 #ifdef EXPENSIVE_CHECKS
4170   // Make sure we didn't break any internal invariants
4171   BS.verify();
4172 #endif
4173   if (!Bundle) {
4174     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4175     assert((!BS.getScheduleData(VL0) ||
4176             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4177            "tryScheduleBundle should cancelScheduling on failure");
4178     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4179                  ReuseShuffleIndicies);
4180     return;
4181   }
4182   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4183 
4184   unsigned ShuffleOrOp = S.isAltShuffle() ?
4185                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4186   switch (ShuffleOrOp) {
4187     case Instruction::PHI: {
4188       auto *PH = cast<PHINode>(VL0);
4189 
4190       // Check for terminator values (e.g. invoke).
4191       for (Value *V : VL)
4192         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4193           Instruction *Term = dyn_cast<Instruction>(Incoming);
4194           if (Term && Term->isTerminator()) {
4195             LLVM_DEBUG(dbgs()
4196                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4197             BS.cancelScheduling(VL, VL0);
4198             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4199                          ReuseShuffleIndicies);
4200             return;
4201           }
4202         }
4203 
4204       TreeEntry *TE =
4205           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4206       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4207 
4208       // Keeps the reordered operands to avoid code duplication.
4209       SmallVector<ValueList, 2> OperandsVec;
4210       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4211         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4212           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4213           TE->setOperand(I, Operands);
4214           OperandsVec.push_back(Operands);
4215           continue;
4216         }
4217         ValueList Operands;
4218         // Prepare the operand vector.
4219         for (Value *V : VL)
4220           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4221               PH->getIncomingBlock(I)));
4222         TE->setOperand(I, Operands);
4223         OperandsVec.push_back(Operands);
4224       }
4225       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4226         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4227       return;
4228     }
4229     case Instruction::ExtractValue:
4230     case Instruction::ExtractElement: {
4231       OrdersType CurrentOrder;
4232       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4233       if (Reuse) {
4234         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4235         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4236                      ReuseShuffleIndicies);
4237         // This is a special case, as it does not gather, but at the same time
4238         // we are not extending buildTree_rec() towards the operands.
4239         ValueList Op0;
4240         Op0.assign(VL.size(), VL0->getOperand(0));
4241         VectorizableTree.back()->setOperand(0, Op0);
4242         return;
4243       }
4244       if (!CurrentOrder.empty()) {
4245         LLVM_DEBUG({
4246           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4247                     "with order";
4248           for (unsigned Idx : CurrentOrder)
4249             dbgs() << " " << Idx;
4250           dbgs() << "\n";
4251         });
4252         fixupOrderingIndices(CurrentOrder);
4253         // Insert new order with initial value 0, if it does not exist,
4254         // otherwise return the iterator to the existing one.
4255         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4256                      ReuseShuffleIndicies, CurrentOrder);
4257         // This is a special case, as it does not gather, but at the same time
4258         // we are not extending buildTree_rec() towards the operands.
4259         ValueList Op0;
4260         Op0.assign(VL.size(), VL0->getOperand(0));
4261         VectorizableTree.back()->setOperand(0, Op0);
4262         return;
4263       }
4264       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4265       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4266                    ReuseShuffleIndicies);
4267       BS.cancelScheduling(VL, VL0);
4268       return;
4269     }
4270     case Instruction::InsertElement: {
4271       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4272 
4273       // Check that we have a buildvector and not a shuffle of 2 or more
4274       // different vectors.
4275       ValueSet SourceVectors;
4276       for (Value *V : VL) {
4277         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4278         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4279       }
4280 
4281       if (count_if(VL, [&SourceVectors](Value *V) {
4282             return !SourceVectors.contains(V);
4283           }) >= 2) {
4284         // Found 2nd source vector - cancel.
4285         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4286                              "different source vectors.\n");
4287         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4288         BS.cancelScheduling(VL, VL0);
4289         return;
4290       }
4291 
4292       auto OrdCompare = [](const std::pair<int, int> &P1,
4293                            const std::pair<int, int> &P2) {
4294         return P1.first > P2.first;
4295       };
4296       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4297                     decltype(OrdCompare)>
4298           Indices(OrdCompare);
4299       for (int I = 0, E = VL.size(); I < E; ++I) {
4300         unsigned Idx = *getInsertIndex(VL[I]);
4301         Indices.emplace(Idx, I);
4302       }
4303       OrdersType CurrentOrder(VL.size(), VL.size());
4304       bool IsIdentity = true;
4305       for (int I = 0, E = VL.size(); I < E; ++I) {
4306         CurrentOrder[Indices.top().second] = I;
4307         IsIdentity &= Indices.top().second == I;
4308         Indices.pop();
4309       }
4310       if (IsIdentity)
4311         CurrentOrder.clear();
4312       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4313                                    None, CurrentOrder);
4314       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4315 
4316       constexpr int NumOps = 2;
4317       ValueList VectorOperands[NumOps];
4318       for (int I = 0; I < NumOps; ++I) {
4319         for (Value *V : VL)
4320           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4321 
4322         TE->setOperand(I, VectorOperands[I]);
4323       }
4324       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4325       return;
4326     }
4327     case Instruction::Load: {
4328       // Check that a vectorized load would load the same memory as a scalar
4329       // load. For example, we don't want to vectorize loads that are smaller
4330       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4331       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4332       // from such a struct, we read/write packed bits disagreeing with the
4333       // unvectorized version.
4334       SmallVector<Value *> PointerOps;
4335       OrdersType CurrentOrder;
4336       TreeEntry *TE = nullptr;
4337       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4338                                 PointerOps)) {
4339       case LoadsState::Vectorize:
4340         if (CurrentOrder.empty()) {
4341           // Original loads are consecutive and does not require reordering.
4342           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4343                             ReuseShuffleIndicies);
4344           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4345         } else {
4346           fixupOrderingIndices(CurrentOrder);
4347           // Need to reorder.
4348           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4349                             ReuseShuffleIndicies, CurrentOrder);
4350           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4351         }
4352         TE->setOperandsInOrder();
4353         break;
4354       case LoadsState::ScatterVectorize:
4355         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4356         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4357                           UserTreeIdx, ReuseShuffleIndicies);
4358         TE->setOperandsInOrder();
4359         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4360         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4361         break;
4362       case LoadsState::Gather:
4363         BS.cancelScheduling(VL, VL0);
4364         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4365                      ReuseShuffleIndicies);
4366 #ifndef NDEBUG
4367         Type *ScalarTy = VL0->getType();
4368         if (DL->getTypeSizeInBits(ScalarTy) !=
4369             DL->getTypeAllocSizeInBits(ScalarTy))
4370           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4371         else if (any_of(VL, [](Value *V) {
4372                    return !cast<LoadInst>(V)->isSimple();
4373                  }))
4374           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4375         else
4376           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4377 #endif // NDEBUG
4378         break;
4379       }
4380       return;
4381     }
4382     case Instruction::ZExt:
4383     case Instruction::SExt:
4384     case Instruction::FPToUI:
4385     case Instruction::FPToSI:
4386     case Instruction::FPExt:
4387     case Instruction::PtrToInt:
4388     case Instruction::IntToPtr:
4389     case Instruction::SIToFP:
4390     case Instruction::UIToFP:
4391     case Instruction::Trunc:
4392     case Instruction::FPTrunc:
4393     case Instruction::BitCast: {
4394       Type *SrcTy = VL0->getOperand(0)->getType();
4395       for (Value *V : VL) {
4396         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4397         if (Ty != SrcTy || !isValidElementType(Ty)) {
4398           BS.cancelScheduling(VL, VL0);
4399           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4400                        ReuseShuffleIndicies);
4401           LLVM_DEBUG(dbgs()
4402                      << "SLP: Gathering casts with different src types.\n");
4403           return;
4404         }
4405       }
4406       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4407                                    ReuseShuffleIndicies);
4408       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4409 
4410       TE->setOperandsInOrder();
4411       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4412         ValueList Operands;
4413         // Prepare the operand vector.
4414         for (Value *V : VL)
4415           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4416 
4417         buildTree_rec(Operands, Depth + 1, {TE, i});
4418       }
4419       return;
4420     }
4421     case Instruction::ICmp:
4422     case Instruction::FCmp: {
4423       // Check that all of the compares have the same predicate.
4424       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4425       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4426       Type *ComparedTy = VL0->getOperand(0)->getType();
4427       for (Value *V : VL) {
4428         CmpInst *Cmp = cast<CmpInst>(V);
4429         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4430             Cmp->getOperand(0)->getType() != ComparedTy) {
4431           BS.cancelScheduling(VL, VL0);
4432           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4433                        ReuseShuffleIndicies);
4434           LLVM_DEBUG(dbgs()
4435                      << "SLP: Gathering cmp with different predicate.\n");
4436           return;
4437         }
4438       }
4439 
4440       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4441                                    ReuseShuffleIndicies);
4442       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4443 
4444       ValueList Left, Right;
4445       if (cast<CmpInst>(VL0)->isCommutative()) {
4446         // Commutative predicate - collect + sort operands of the instructions
4447         // so that each side is more likely to have the same opcode.
4448         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4449         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4450       } else {
4451         // Collect operands - commute if it uses the swapped predicate.
4452         for (Value *V : VL) {
4453           auto *Cmp = cast<CmpInst>(V);
4454           Value *LHS = Cmp->getOperand(0);
4455           Value *RHS = Cmp->getOperand(1);
4456           if (Cmp->getPredicate() != P0)
4457             std::swap(LHS, RHS);
4458           Left.push_back(LHS);
4459           Right.push_back(RHS);
4460         }
4461       }
4462       TE->setOperand(0, Left);
4463       TE->setOperand(1, Right);
4464       buildTree_rec(Left, Depth + 1, {TE, 0});
4465       buildTree_rec(Right, Depth + 1, {TE, 1});
4466       return;
4467     }
4468     case Instruction::Select:
4469     case Instruction::FNeg:
4470     case Instruction::Add:
4471     case Instruction::FAdd:
4472     case Instruction::Sub:
4473     case Instruction::FSub:
4474     case Instruction::Mul:
4475     case Instruction::FMul:
4476     case Instruction::UDiv:
4477     case Instruction::SDiv:
4478     case Instruction::FDiv:
4479     case Instruction::URem:
4480     case Instruction::SRem:
4481     case Instruction::FRem:
4482     case Instruction::Shl:
4483     case Instruction::LShr:
4484     case Instruction::AShr:
4485     case Instruction::And:
4486     case Instruction::Or:
4487     case Instruction::Xor: {
4488       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4489                                    ReuseShuffleIndicies);
4490       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4491 
4492       // Sort operands of the instructions so that each side is more likely to
4493       // have the same opcode.
4494       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4495         ValueList Left, Right;
4496         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4497         TE->setOperand(0, Left);
4498         TE->setOperand(1, Right);
4499         buildTree_rec(Left, Depth + 1, {TE, 0});
4500         buildTree_rec(Right, Depth + 1, {TE, 1});
4501         return;
4502       }
4503 
4504       TE->setOperandsInOrder();
4505       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4506         ValueList Operands;
4507         // Prepare the operand vector.
4508         for (Value *V : VL)
4509           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4510 
4511         buildTree_rec(Operands, Depth + 1, {TE, i});
4512       }
4513       return;
4514     }
4515     case Instruction::GetElementPtr: {
4516       // We don't combine GEPs with complicated (nested) indexing.
4517       for (Value *V : VL) {
4518         if (cast<Instruction>(V)->getNumOperands() != 2) {
4519           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4520           BS.cancelScheduling(VL, VL0);
4521           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4522                        ReuseShuffleIndicies);
4523           return;
4524         }
4525       }
4526 
4527       // We can't combine several GEPs into one vector if they operate on
4528       // different types.
4529       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4530       for (Value *V : VL) {
4531         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4532         if (Ty0 != CurTy) {
4533           LLVM_DEBUG(dbgs()
4534                      << "SLP: not-vectorizable GEP (different types).\n");
4535           BS.cancelScheduling(VL, VL0);
4536           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4537                        ReuseShuffleIndicies);
4538           return;
4539         }
4540       }
4541 
4542       // We don't combine GEPs with non-constant indexes.
4543       Type *Ty1 = VL0->getOperand(1)->getType();
4544       for (Value *V : VL) {
4545         auto Op = cast<Instruction>(V)->getOperand(1);
4546         if (!isa<ConstantInt>(Op) ||
4547             (Op->getType() != Ty1 &&
4548              Op->getType()->getScalarSizeInBits() >
4549                  DL->getIndexSizeInBits(
4550                      V->getType()->getPointerAddressSpace()))) {
4551           LLVM_DEBUG(dbgs()
4552                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4553           BS.cancelScheduling(VL, VL0);
4554           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4555                        ReuseShuffleIndicies);
4556           return;
4557         }
4558       }
4559 
4560       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4561                                    ReuseShuffleIndicies);
4562       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4563       SmallVector<ValueList, 2> Operands(2);
4564       // Prepare the operand vector for pointer operands.
4565       for (Value *V : VL)
4566         Operands.front().push_back(
4567             cast<GetElementPtrInst>(V)->getPointerOperand());
4568       TE->setOperand(0, Operands.front());
4569       // Need to cast all indices to the same type before vectorization to
4570       // avoid crash.
4571       // Required to be able to find correct matches between different gather
4572       // nodes and reuse the vectorized values rather than trying to gather them
4573       // again.
4574       int IndexIdx = 1;
4575       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4576       Type *Ty = all_of(VL,
4577                         [VL0Ty, IndexIdx](Value *V) {
4578                           return VL0Ty == cast<GetElementPtrInst>(V)
4579                                               ->getOperand(IndexIdx)
4580                                               ->getType();
4581                         })
4582                      ? VL0Ty
4583                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4584                                             ->getPointerOperandType()
4585                                             ->getScalarType());
4586       // Prepare the operand vector.
4587       for (Value *V : VL) {
4588         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4589         auto *CI = cast<ConstantInt>(Op);
4590         Operands.back().push_back(ConstantExpr::getIntegerCast(
4591             CI, Ty, CI->getValue().isSignBitSet()));
4592       }
4593       TE->setOperand(IndexIdx, Operands.back());
4594 
4595       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4596         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4597       return;
4598     }
4599     case Instruction::Store: {
4600       // Check if the stores are consecutive or if we need to swizzle them.
4601       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4602       // Avoid types that are padded when being allocated as scalars, while
4603       // being packed together in a vector (such as i1).
4604       if (DL->getTypeSizeInBits(ScalarTy) !=
4605           DL->getTypeAllocSizeInBits(ScalarTy)) {
4606         BS.cancelScheduling(VL, VL0);
4607         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4608                      ReuseShuffleIndicies);
4609         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4610         return;
4611       }
4612       // Make sure all stores in the bundle are simple - we can't vectorize
4613       // atomic or volatile stores.
4614       SmallVector<Value *, 4> PointerOps(VL.size());
4615       ValueList Operands(VL.size());
4616       auto POIter = PointerOps.begin();
4617       auto OIter = Operands.begin();
4618       for (Value *V : VL) {
4619         auto *SI = cast<StoreInst>(V);
4620         if (!SI->isSimple()) {
4621           BS.cancelScheduling(VL, VL0);
4622           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4623                        ReuseShuffleIndicies);
4624           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4625           return;
4626         }
4627         *POIter = SI->getPointerOperand();
4628         *OIter = SI->getValueOperand();
4629         ++POIter;
4630         ++OIter;
4631       }
4632 
4633       OrdersType CurrentOrder;
4634       // Check the order of pointer operands.
4635       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4636         Value *Ptr0;
4637         Value *PtrN;
4638         if (CurrentOrder.empty()) {
4639           Ptr0 = PointerOps.front();
4640           PtrN = PointerOps.back();
4641         } else {
4642           Ptr0 = PointerOps[CurrentOrder.front()];
4643           PtrN = PointerOps[CurrentOrder.back()];
4644         }
4645         Optional<int> Dist =
4646             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4647         // Check that the sorted pointer operands are consecutive.
4648         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4649           if (CurrentOrder.empty()) {
4650             // Original stores are consecutive and does not require reordering.
4651             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4652                                          UserTreeIdx, ReuseShuffleIndicies);
4653             TE->setOperandsInOrder();
4654             buildTree_rec(Operands, Depth + 1, {TE, 0});
4655             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4656           } else {
4657             fixupOrderingIndices(CurrentOrder);
4658             TreeEntry *TE =
4659                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4660                              ReuseShuffleIndicies, CurrentOrder);
4661             TE->setOperandsInOrder();
4662             buildTree_rec(Operands, Depth + 1, {TE, 0});
4663             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4664           }
4665           return;
4666         }
4667       }
4668 
4669       BS.cancelScheduling(VL, VL0);
4670       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4671                    ReuseShuffleIndicies);
4672       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4673       return;
4674     }
4675     case Instruction::Call: {
4676       // Check if the calls are all to the same vectorizable intrinsic or
4677       // library function.
4678       CallInst *CI = cast<CallInst>(VL0);
4679       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4680 
4681       VFShape Shape = VFShape::get(
4682           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4683           false /*HasGlobalPred*/);
4684       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4685 
4686       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4687         BS.cancelScheduling(VL, VL0);
4688         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4689                      ReuseShuffleIndicies);
4690         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4691         return;
4692       }
4693       Function *F = CI->getCalledFunction();
4694       unsigned NumArgs = CI->arg_size();
4695       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4696       for (unsigned j = 0; j != NumArgs; ++j)
4697         if (hasVectorInstrinsicScalarOpd(ID, j))
4698           ScalarArgs[j] = CI->getArgOperand(j);
4699       for (Value *V : VL) {
4700         CallInst *CI2 = dyn_cast<CallInst>(V);
4701         if (!CI2 || CI2->getCalledFunction() != F ||
4702             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4703             (VecFunc &&
4704              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4705             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4706           BS.cancelScheduling(VL, VL0);
4707           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4708                        ReuseShuffleIndicies);
4709           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4710                             << "\n");
4711           return;
4712         }
4713         // Some intrinsics have scalar arguments and should be same in order for
4714         // them to be vectorized.
4715         for (unsigned j = 0; j != NumArgs; ++j) {
4716           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4717             Value *A1J = CI2->getArgOperand(j);
4718             if (ScalarArgs[j] != A1J) {
4719               BS.cancelScheduling(VL, VL0);
4720               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4721                            ReuseShuffleIndicies);
4722               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4723                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4724                                 << "\n");
4725               return;
4726             }
4727           }
4728         }
4729         // Verify that the bundle operands are identical between the two calls.
4730         if (CI->hasOperandBundles() &&
4731             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4732                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4733                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4734           BS.cancelScheduling(VL, VL0);
4735           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4736                        ReuseShuffleIndicies);
4737           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4738                             << *CI << "!=" << *V << '\n');
4739           return;
4740         }
4741       }
4742 
4743       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4744                                    ReuseShuffleIndicies);
4745       TE->setOperandsInOrder();
4746       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4747         // For scalar operands no need to to create an entry since no need to
4748         // vectorize it.
4749         if (hasVectorInstrinsicScalarOpd(ID, i))
4750           continue;
4751         ValueList Operands;
4752         // Prepare the operand vector.
4753         for (Value *V : VL) {
4754           auto *CI2 = cast<CallInst>(V);
4755           Operands.push_back(CI2->getArgOperand(i));
4756         }
4757         buildTree_rec(Operands, Depth + 1, {TE, i});
4758       }
4759       return;
4760     }
4761     case Instruction::ShuffleVector: {
4762       // If this is not an alternate sequence of opcode like add-sub
4763       // then do not vectorize this instruction.
4764       if (!S.isAltShuffle()) {
4765         BS.cancelScheduling(VL, VL0);
4766         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4767                      ReuseShuffleIndicies);
4768         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4769         return;
4770       }
4771       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4772                                    ReuseShuffleIndicies);
4773       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4774 
4775       // Reorder operands if reordering would enable vectorization.
4776       auto *CI = dyn_cast<CmpInst>(VL0);
4777       if (isa<BinaryOperator>(VL0) || CI) {
4778         ValueList Left, Right;
4779         if (!CI || all_of(VL, [](Value *V) {
4780               return cast<CmpInst>(V)->isCommutative();
4781             })) {
4782           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4783         } else {
4784           CmpInst::Predicate P0 = CI->getPredicate();
4785           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4786           assert(P0 != AltP0 &&
4787                  "Expected different main/alternate predicates.");
4788           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4789           Value *BaseOp0 = VL0->getOperand(0);
4790           Value *BaseOp1 = VL0->getOperand(1);
4791           // Collect operands - commute if it uses the swapped predicate or
4792           // alternate operation.
4793           for (Value *V : VL) {
4794             auto *Cmp = cast<CmpInst>(V);
4795             Value *LHS = Cmp->getOperand(0);
4796             Value *RHS = Cmp->getOperand(1);
4797             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4798             if (P0 == AltP0Swapped) {
4799               if (CI != Cmp && S.AltOp != Cmp &&
4800                   ((P0 == CurrentPred &&
4801                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4802                    (AltP0 == CurrentPred &&
4803                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4804                 std::swap(LHS, RHS);
4805             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4806               std::swap(LHS, RHS);
4807             }
4808             Left.push_back(LHS);
4809             Right.push_back(RHS);
4810           }
4811         }
4812         TE->setOperand(0, Left);
4813         TE->setOperand(1, Right);
4814         buildTree_rec(Left, Depth + 1, {TE, 0});
4815         buildTree_rec(Right, Depth + 1, {TE, 1});
4816         return;
4817       }
4818 
4819       TE->setOperandsInOrder();
4820       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4821         ValueList Operands;
4822         // Prepare the operand vector.
4823         for (Value *V : VL)
4824           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4825 
4826         buildTree_rec(Operands, Depth + 1, {TE, i});
4827       }
4828       return;
4829     }
4830     default:
4831       BS.cancelScheduling(VL, VL0);
4832       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4833                    ReuseShuffleIndicies);
4834       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4835       return;
4836   }
4837 }
4838 
4839 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4840   unsigned N = 1;
4841   Type *EltTy = T;
4842 
4843   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4844          isa<VectorType>(EltTy)) {
4845     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4846       // Check that struct is homogeneous.
4847       for (const auto *Ty : ST->elements())
4848         if (Ty != *ST->element_begin())
4849           return 0;
4850       N *= ST->getNumElements();
4851       EltTy = *ST->element_begin();
4852     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4853       N *= AT->getNumElements();
4854       EltTy = AT->getElementType();
4855     } else {
4856       auto *VT = cast<FixedVectorType>(EltTy);
4857       N *= VT->getNumElements();
4858       EltTy = VT->getElementType();
4859     }
4860   }
4861 
4862   if (!isValidElementType(EltTy))
4863     return 0;
4864   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4865   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4866     return 0;
4867   return N;
4868 }
4869 
4870 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4871                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4872   const auto *It = find_if(VL, [](Value *V) {
4873     return isa<ExtractElementInst, ExtractValueInst>(V);
4874   });
4875   assert(It != VL.end() && "Expected at least one extract instruction.");
4876   auto *E0 = cast<Instruction>(*It);
4877   assert(all_of(VL,
4878                 [](Value *V) {
4879                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4880                       V);
4881                 }) &&
4882          "Invalid opcode");
4883   // Check if all of the extracts come from the same vector and from the
4884   // correct offset.
4885   Value *Vec = E0->getOperand(0);
4886 
4887   CurrentOrder.clear();
4888 
4889   // We have to extract from a vector/aggregate with the same number of elements.
4890   unsigned NElts;
4891   if (E0->getOpcode() == Instruction::ExtractValue) {
4892     const DataLayout &DL = E0->getModule()->getDataLayout();
4893     NElts = canMapToVector(Vec->getType(), DL);
4894     if (!NElts)
4895       return false;
4896     // Check if load can be rewritten as load of vector.
4897     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4898     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4899       return false;
4900   } else {
4901     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4902   }
4903 
4904   if (NElts != VL.size())
4905     return false;
4906 
4907   // Check that all of the indices extract from the correct offset.
4908   bool ShouldKeepOrder = true;
4909   unsigned E = VL.size();
4910   // Assign to all items the initial value E + 1 so we can check if the extract
4911   // instruction index was used already.
4912   // Also, later we can check that all the indices are used and we have a
4913   // consecutive access in the extract instructions, by checking that no
4914   // element of CurrentOrder still has value E + 1.
4915   CurrentOrder.assign(E, E);
4916   unsigned I = 0;
4917   for (; I < E; ++I) {
4918     auto *Inst = dyn_cast<Instruction>(VL[I]);
4919     if (!Inst)
4920       continue;
4921     if (Inst->getOperand(0) != Vec)
4922       break;
4923     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4924       if (isa<UndefValue>(EE->getIndexOperand()))
4925         continue;
4926     Optional<unsigned> Idx = getExtractIndex(Inst);
4927     if (!Idx)
4928       break;
4929     const unsigned ExtIdx = *Idx;
4930     if (ExtIdx != I) {
4931       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4932         break;
4933       ShouldKeepOrder = false;
4934       CurrentOrder[ExtIdx] = I;
4935     } else {
4936       if (CurrentOrder[I] != E)
4937         break;
4938       CurrentOrder[I] = I;
4939     }
4940   }
4941   if (I < E) {
4942     CurrentOrder.clear();
4943     return false;
4944   }
4945   if (ShouldKeepOrder)
4946     CurrentOrder.clear();
4947 
4948   return ShouldKeepOrder;
4949 }
4950 
4951 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4952                                     ArrayRef<Value *> VectorizedVals) const {
4953   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4954          all_of(I->users(), [this](User *U) {
4955            return ScalarToTreeEntry.count(U) > 0 ||
4956                   isVectorLikeInstWithConstOps(U) ||
4957                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4958          });
4959 }
4960 
4961 static std::pair<InstructionCost, InstructionCost>
4962 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4963                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4964   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4965 
4966   // Calculate the cost of the scalar and vector calls.
4967   SmallVector<Type *, 4> VecTys;
4968   for (Use &Arg : CI->args())
4969     VecTys.push_back(
4970         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4971   FastMathFlags FMF;
4972   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4973     FMF = FPCI->getFastMathFlags();
4974   SmallVector<const Value *> Arguments(CI->args());
4975   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4976                                     dyn_cast<IntrinsicInst>(CI));
4977   auto IntrinsicCost =
4978     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4979 
4980   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4981                                      VecTy->getNumElements())),
4982                             false /*HasGlobalPred*/);
4983   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4984   auto LibCost = IntrinsicCost;
4985   if (!CI->isNoBuiltin() && VecFunc) {
4986     // Calculate the cost of the vector library call.
4987     // If the corresponding vector call is cheaper, return its cost.
4988     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4989                                     TTI::TCK_RecipThroughput);
4990   }
4991   return {IntrinsicCost, LibCost};
4992 }
4993 
4994 /// Compute the cost of creating a vector of type \p VecTy containing the
4995 /// extracted values from \p VL.
4996 static InstructionCost
4997 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4998                    TargetTransformInfo::ShuffleKind ShuffleKind,
4999                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5000   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5001 
5002   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5003       VecTy->getNumElements() < NumOfParts)
5004     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5005 
5006   bool AllConsecutive = true;
5007   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5008   unsigned Idx = -1;
5009   InstructionCost Cost = 0;
5010 
5011   // Process extracts in blocks of EltsPerVector to check if the source vector
5012   // operand can be re-used directly. If not, add the cost of creating a shuffle
5013   // to extract the values into a vector register.
5014   for (auto *V : VL) {
5015     ++Idx;
5016 
5017     // Need to exclude undefs from analysis.
5018     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5019       continue;
5020 
5021     // Reached the start of a new vector registers.
5022     if (Idx % EltsPerVector == 0) {
5023       AllConsecutive = true;
5024       continue;
5025     }
5026 
5027     // Check all extracts for a vector register on the target directly
5028     // extract values in order.
5029     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5030     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5031       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5032       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5033                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5034     }
5035 
5036     if (AllConsecutive)
5037       continue;
5038 
5039     // Skip all indices, except for the last index per vector block.
5040     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5041       continue;
5042 
5043     // If we have a series of extracts which are not consecutive and hence
5044     // cannot re-use the source vector register directly, compute the shuffle
5045     // cost to extract the a vector with EltsPerVector elements.
5046     Cost += TTI.getShuffleCost(
5047         TargetTransformInfo::SK_PermuteSingleSrc,
5048         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5049   }
5050   return Cost;
5051 }
5052 
5053 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5054 /// operations operands.
5055 static void
5056 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5057                       ArrayRef<int> ReusesIndices,
5058                       const function_ref<bool(Instruction *)> IsAltOp,
5059                       SmallVectorImpl<int> &Mask,
5060                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5061                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5062   unsigned Sz = VL.size();
5063   Mask.assign(Sz, UndefMaskElem);
5064   SmallVector<int> OrderMask;
5065   if (!ReorderIndices.empty())
5066     inversePermutation(ReorderIndices, OrderMask);
5067   for (unsigned I = 0; I < Sz; ++I) {
5068     unsigned Idx = I;
5069     if (!ReorderIndices.empty())
5070       Idx = OrderMask[I];
5071     auto *OpInst = cast<Instruction>(VL[Idx]);
5072     if (IsAltOp(OpInst)) {
5073       Mask[I] = Sz + Idx;
5074       if (AltScalars)
5075         AltScalars->push_back(OpInst);
5076     } else {
5077       Mask[I] = Idx;
5078       if (OpScalars)
5079         OpScalars->push_back(OpInst);
5080     }
5081   }
5082   if (!ReusesIndices.empty()) {
5083     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5084     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5085       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5086     });
5087     Mask.swap(NewMask);
5088   }
5089 }
5090 
5091 /// Checks if the specified instruction \p I is an alternate operation for the
5092 /// given \p MainOp and \p AltOp instructions.
5093 static bool isAlternateInstruction(const Instruction *I,
5094                                    const Instruction *MainOp,
5095                                    const Instruction *AltOp) {
5096   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5097     auto *AltCI0 = cast<CmpInst>(AltOp);
5098     auto *CI = cast<CmpInst>(I);
5099     CmpInst::Predicate P0 = CI0->getPredicate();
5100     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5101     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5102     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5103     CmpInst::Predicate CurrentPred = CI->getPredicate();
5104     if (P0 == AltP0Swapped)
5105       return I == AltCI0 ||
5106              (I != MainOp &&
5107               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5108                                    CI->getOperand(0), CI->getOperand(1)));
5109     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5110   }
5111   return I->getOpcode() == AltOp->getOpcode();
5112 }
5113 
5114 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5115                                       ArrayRef<Value *> VectorizedVals) {
5116   ArrayRef<Value*> VL = E->Scalars;
5117 
5118   Type *ScalarTy = VL[0]->getType();
5119   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5120     ScalarTy = SI->getValueOperand()->getType();
5121   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5122     ScalarTy = CI->getOperand(0)->getType();
5123   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5124     ScalarTy = IE->getOperand(1)->getType();
5125   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5126   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5127 
5128   // If we have computed a smaller type for the expression, update VecTy so
5129   // that the costs will be accurate.
5130   if (MinBWs.count(VL[0]))
5131     VecTy = FixedVectorType::get(
5132         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5133   unsigned EntryVF = E->getVectorFactor();
5134   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5135 
5136   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5137   // FIXME: it tries to fix a problem with MSVC buildbots.
5138   TargetTransformInfo &TTIRef = *TTI;
5139   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5140                                VectorizedVals, E](InstructionCost &Cost) {
5141     DenseMap<Value *, int> ExtractVectorsTys;
5142     SmallPtrSet<Value *, 4> CheckedExtracts;
5143     for (auto *V : VL) {
5144       if (isa<UndefValue>(V))
5145         continue;
5146       // If all users of instruction are going to be vectorized and this
5147       // instruction itself is not going to be vectorized, consider this
5148       // instruction as dead and remove its cost from the final cost of the
5149       // vectorized tree.
5150       // Also, avoid adjusting the cost for extractelements with multiple uses
5151       // in different graph entries.
5152       const TreeEntry *VE = getTreeEntry(V);
5153       if (!CheckedExtracts.insert(V).second ||
5154           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5155           (VE && VE != E))
5156         continue;
5157       auto *EE = cast<ExtractElementInst>(V);
5158       Optional<unsigned> EEIdx = getExtractIndex(EE);
5159       if (!EEIdx)
5160         continue;
5161       unsigned Idx = *EEIdx;
5162       if (TTIRef.getNumberOfParts(VecTy) !=
5163           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5164         auto It =
5165             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5166         It->getSecond() = std::min<int>(It->second, Idx);
5167       }
5168       // Take credit for instruction that will become dead.
5169       if (EE->hasOneUse()) {
5170         Instruction *Ext = EE->user_back();
5171         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5172             all_of(Ext->users(),
5173                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5174           // Use getExtractWithExtendCost() to calculate the cost of
5175           // extractelement/ext pair.
5176           Cost -=
5177               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5178                                               EE->getVectorOperandType(), Idx);
5179           // Add back the cost of s|zext which is subtracted separately.
5180           Cost += TTIRef.getCastInstrCost(
5181               Ext->getOpcode(), Ext->getType(), EE->getType(),
5182               TTI::getCastContextHint(Ext), CostKind, Ext);
5183           continue;
5184         }
5185       }
5186       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5187                                         EE->getVectorOperandType(), Idx);
5188     }
5189     // Add a cost for subvector extracts/inserts if required.
5190     for (const auto &Data : ExtractVectorsTys) {
5191       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5192       unsigned NumElts = VecTy->getNumElements();
5193       if (Data.second % NumElts == 0)
5194         continue;
5195       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5196         unsigned Idx = (Data.second / NumElts) * NumElts;
5197         unsigned EENumElts = EEVTy->getNumElements();
5198         if (Idx + NumElts <= EENumElts) {
5199           Cost +=
5200               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5201                                     EEVTy, None, Idx, VecTy);
5202         } else {
5203           // Need to round up the subvector type vectorization factor to avoid a
5204           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5205           // <= EENumElts.
5206           auto *SubVT =
5207               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5208           Cost +=
5209               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5210                                     EEVTy, None, Idx, SubVT);
5211         }
5212       } else {
5213         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5214                                       VecTy, None, 0, EEVTy);
5215       }
5216     }
5217   };
5218   if (E->State == TreeEntry::NeedToGather) {
5219     if (allConstant(VL))
5220       return 0;
5221     if (isa<InsertElementInst>(VL[0]))
5222       return InstructionCost::getInvalid();
5223     SmallVector<int> Mask;
5224     SmallVector<const TreeEntry *> Entries;
5225     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5226         isGatherShuffledEntry(E, Mask, Entries);
5227     if (Shuffle.hasValue()) {
5228       InstructionCost GatherCost = 0;
5229       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5230         // Perfect match in the graph, will reuse the previously vectorized
5231         // node. Cost is 0.
5232         LLVM_DEBUG(
5233             dbgs()
5234             << "SLP: perfect diamond match for gather bundle that starts with "
5235             << *VL.front() << ".\n");
5236         if (NeedToShuffleReuses)
5237           GatherCost =
5238               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5239                                   FinalVecTy, E->ReuseShuffleIndices);
5240       } else {
5241         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5242                           << " entries for bundle that starts with "
5243                           << *VL.front() << ".\n");
5244         // Detected that instead of gather we can emit a shuffle of single/two
5245         // previously vectorized nodes. Add the cost of the permutation rather
5246         // than gather.
5247         ::addMask(Mask, E->ReuseShuffleIndices);
5248         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5249       }
5250       return GatherCost;
5251     }
5252     if ((E->getOpcode() == Instruction::ExtractElement ||
5253          all_of(E->Scalars,
5254                 [](Value *V) {
5255                   return isa<ExtractElementInst, UndefValue>(V);
5256                 })) &&
5257         allSameType(VL)) {
5258       // Check that gather of extractelements can be represented as just a
5259       // shuffle of a single/two vectors the scalars are extracted from.
5260       SmallVector<int> Mask;
5261       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5262           isFixedVectorShuffle(VL, Mask);
5263       if (ShuffleKind.hasValue()) {
5264         // Found the bunch of extractelement instructions that must be gathered
5265         // into a vector and can be represented as a permutation elements in a
5266         // single input vector or of 2 input vectors.
5267         InstructionCost Cost =
5268             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5269         AdjustExtractsCost(Cost);
5270         if (NeedToShuffleReuses)
5271           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5272                                       FinalVecTy, E->ReuseShuffleIndices);
5273         return Cost;
5274       }
5275     }
5276     if (isSplat(VL)) {
5277       // Found the broadcasting of the single scalar, calculate the cost as the
5278       // broadcast.
5279       assert(VecTy == FinalVecTy &&
5280              "No reused scalars expected for broadcast.");
5281       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5282                                  /*Mask=*/None, /*Index=*/0,
5283                                  /*SubTp=*/nullptr, /*Args=*/VL);
5284     }
5285     InstructionCost ReuseShuffleCost = 0;
5286     if (NeedToShuffleReuses)
5287       ReuseShuffleCost = TTI->getShuffleCost(
5288           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5289     // Improve gather cost for gather of loads, if we can group some of the
5290     // loads into vector loads.
5291     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5292         !E->isAltShuffle()) {
5293       BoUpSLP::ValueSet VectorizedLoads;
5294       unsigned StartIdx = 0;
5295       unsigned VF = VL.size() / 2;
5296       unsigned VectorizedCnt = 0;
5297       unsigned ScatterVectorizeCnt = 0;
5298       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5299       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5300         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5301              Cnt += VF) {
5302           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5303           if (!VectorizedLoads.count(Slice.front()) &&
5304               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5305             SmallVector<Value *> PointerOps;
5306             OrdersType CurrentOrder;
5307             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5308                                               *SE, CurrentOrder, PointerOps);
5309             switch (LS) {
5310             case LoadsState::Vectorize:
5311             case LoadsState::ScatterVectorize:
5312               // Mark the vectorized loads so that we don't vectorize them
5313               // again.
5314               if (LS == LoadsState::Vectorize)
5315                 ++VectorizedCnt;
5316               else
5317                 ++ScatterVectorizeCnt;
5318               VectorizedLoads.insert(Slice.begin(), Slice.end());
5319               // If we vectorized initial block, no need to try to vectorize it
5320               // again.
5321               if (Cnt == StartIdx)
5322                 StartIdx += VF;
5323               break;
5324             case LoadsState::Gather:
5325               break;
5326             }
5327           }
5328         }
5329         // Check if the whole array was vectorized already - exit.
5330         if (StartIdx >= VL.size())
5331           break;
5332         // Found vectorizable parts - exit.
5333         if (!VectorizedLoads.empty())
5334           break;
5335       }
5336       if (!VectorizedLoads.empty()) {
5337         InstructionCost GatherCost = 0;
5338         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5339         bool NeedInsertSubvectorAnalysis =
5340             !NumParts || (VL.size() / VF) > NumParts;
5341         // Get the cost for gathered loads.
5342         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5343           if (VectorizedLoads.contains(VL[I]))
5344             continue;
5345           GatherCost += getGatherCost(VL.slice(I, VF));
5346         }
5347         // The cost for vectorized loads.
5348         InstructionCost ScalarsCost = 0;
5349         for (Value *V : VectorizedLoads) {
5350           auto *LI = cast<LoadInst>(V);
5351           ScalarsCost += TTI->getMemoryOpCost(
5352               Instruction::Load, LI->getType(), LI->getAlign(),
5353               LI->getPointerAddressSpace(), CostKind, LI);
5354         }
5355         auto *LI = cast<LoadInst>(E->getMainOp());
5356         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5357         Align Alignment = LI->getAlign();
5358         GatherCost +=
5359             VectorizedCnt *
5360             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5361                                  LI->getPointerAddressSpace(), CostKind, LI);
5362         GatherCost += ScatterVectorizeCnt *
5363                       TTI->getGatherScatterOpCost(
5364                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5365                           /*VariableMask=*/false, Alignment, CostKind, LI);
5366         if (NeedInsertSubvectorAnalysis) {
5367           // Add the cost for the subvectors insert.
5368           for (int I = VF, E = VL.size(); I < E; I += VF)
5369             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5370                                               None, I, LoadTy);
5371         }
5372         return ReuseShuffleCost + GatherCost - ScalarsCost;
5373       }
5374     }
5375     return ReuseShuffleCost + getGatherCost(VL);
5376   }
5377   InstructionCost CommonCost = 0;
5378   SmallVector<int> Mask;
5379   if (!E->ReorderIndices.empty()) {
5380     SmallVector<int> NewMask;
5381     if (E->getOpcode() == Instruction::Store) {
5382       // For stores the order is actually a mask.
5383       NewMask.resize(E->ReorderIndices.size());
5384       copy(E->ReorderIndices, NewMask.begin());
5385     } else {
5386       inversePermutation(E->ReorderIndices, NewMask);
5387     }
5388     ::addMask(Mask, NewMask);
5389   }
5390   if (NeedToShuffleReuses)
5391     ::addMask(Mask, E->ReuseShuffleIndices);
5392   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5393     CommonCost =
5394         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5395   assert((E->State == TreeEntry::Vectorize ||
5396           E->State == TreeEntry::ScatterVectorize) &&
5397          "Unhandled state");
5398   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5399   Instruction *VL0 = E->getMainOp();
5400   unsigned ShuffleOrOp =
5401       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5402   switch (ShuffleOrOp) {
5403     case Instruction::PHI:
5404       return 0;
5405 
5406     case Instruction::ExtractValue:
5407     case Instruction::ExtractElement: {
5408       // The common cost of removal ExtractElement/ExtractValue instructions +
5409       // the cost of shuffles, if required to resuffle the original vector.
5410       if (NeedToShuffleReuses) {
5411         unsigned Idx = 0;
5412         for (unsigned I : E->ReuseShuffleIndices) {
5413           if (ShuffleOrOp == Instruction::ExtractElement) {
5414             auto *EE = cast<ExtractElementInst>(VL[I]);
5415             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5416                                                   EE->getVectorOperandType(),
5417                                                   *getExtractIndex(EE));
5418           } else {
5419             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5420                                                   VecTy, Idx);
5421             ++Idx;
5422           }
5423         }
5424         Idx = EntryVF;
5425         for (Value *V : VL) {
5426           if (ShuffleOrOp == Instruction::ExtractElement) {
5427             auto *EE = cast<ExtractElementInst>(V);
5428             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5429                                                   EE->getVectorOperandType(),
5430                                                   *getExtractIndex(EE));
5431           } else {
5432             --Idx;
5433             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5434                                                   VecTy, Idx);
5435           }
5436         }
5437       }
5438       if (ShuffleOrOp == Instruction::ExtractValue) {
5439         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5440           auto *EI = cast<Instruction>(VL[I]);
5441           // Take credit for instruction that will become dead.
5442           if (EI->hasOneUse()) {
5443             Instruction *Ext = EI->user_back();
5444             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5445                 all_of(Ext->users(),
5446                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5447               // Use getExtractWithExtendCost() to calculate the cost of
5448               // extractelement/ext pair.
5449               CommonCost -= TTI->getExtractWithExtendCost(
5450                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5451               // Add back the cost of s|zext which is subtracted separately.
5452               CommonCost += TTI->getCastInstrCost(
5453                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5454                   TTI::getCastContextHint(Ext), CostKind, Ext);
5455               continue;
5456             }
5457           }
5458           CommonCost -=
5459               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5460         }
5461       } else {
5462         AdjustExtractsCost(CommonCost);
5463       }
5464       return CommonCost;
5465     }
5466     case Instruction::InsertElement: {
5467       assert(E->ReuseShuffleIndices.empty() &&
5468              "Unique insertelements only are expected.");
5469       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5470 
5471       unsigned const NumElts = SrcVecTy->getNumElements();
5472       unsigned const NumScalars = VL.size();
5473       APInt DemandedElts = APInt::getZero(NumElts);
5474       // TODO: Add support for Instruction::InsertValue.
5475       SmallVector<int> Mask;
5476       if (!E->ReorderIndices.empty()) {
5477         inversePermutation(E->ReorderIndices, Mask);
5478         Mask.append(NumElts - NumScalars, UndefMaskElem);
5479       } else {
5480         Mask.assign(NumElts, UndefMaskElem);
5481         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5482       }
5483       unsigned Offset = *getInsertIndex(VL0);
5484       bool IsIdentity = true;
5485       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5486       Mask.swap(PrevMask);
5487       for (unsigned I = 0; I < NumScalars; ++I) {
5488         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5489         DemandedElts.setBit(InsertIdx);
5490         IsIdentity &= InsertIdx - Offset == I;
5491         Mask[InsertIdx - Offset] = I;
5492       }
5493       assert(Offset < NumElts && "Failed to find vector index offset");
5494 
5495       InstructionCost Cost = 0;
5496       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5497                                             /*Insert*/ true, /*Extract*/ false);
5498 
5499       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5500         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5501         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5502         Cost += TTI->getShuffleCost(
5503             TargetTransformInfo::SK_PermuteSingleSrc,
5504             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5505       } else if (!IsIdentity) {
5506         auto *FirstInsert =
5507             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5508               return !is_contained(E->Scalars,
5509                                    cast<Instruction>(V)->getOperand(0));
5510             }));
5511         if (isUndefVector(FirstInsert->getOperand(0))) {
5512           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5513         } else {
5514           SmallVector<int> InsertMask(NumElts);
5515           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5516           for (unsigned I = 0; I < NumElts; I++) {
5517             if (Mask[I] != UndefMaskElem)
5518               InsertMask[Offset + I] = NumElts + I;
5519           }
5520           Cost +=
5521               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5522         }
5523       }
5524 
5525       return Cost;
5526     }
5527     case Instruction::ZExt:
5528     case Instruction::SExt:
5529     case Instruction::FPToUI:
5530     case Instruction::FPToSI:
5531     case Instruction::FPExt:
5532     case Instruction::PtrToInt:
5533     case Instruction::IntToPtr:
5534     case Instruction::SIToFP:
5535     case Instruction::UIToFP:
5536     case Instruction::Trunc:
5537     case Instruction::FPTrunc:
5538     case Instruction::BitCast: {
5539       Type *SrcTy = VL0->getOperand(0)->getType();
5540       InstructionCost ScalarEltCost =
5541           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5542                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5543       if (NeedToShuffleReuses) {
5544         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5545       }
5546 
5547       // Calculate the cost of this instruction.
5548       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5549 
5550       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5551       InstructionCost VecCost = 0;
5552       // Check if the values are candidates to demote.
5553       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5554         VecCost = CommonCost + TTI->getCastInstrCost(
5555                                    E->getOpcode(), VecTy, SrcVecTy,
5556                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5557       }
5558       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5559       return VecCost - ScalarCost;
5560     }
5561     case Instruction::FCmp:
5562     case Instruction::ICmp:
5563     case Instruction::Select: {
5564       // Calculate the cost of this instruction.
5565       InstructionCost ScalarEltCost =
5566           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5567                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5568       if (NeedToShuffleReuses) {
5569         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5570       }
5571       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5572       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5573 
5574       // Check if all entries in VL are either compares or selects with compares
5575       // as condition that have the same predicates.
5576       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5577       bool First = true;
5578       for (auto *V : VL) {
5579         CmpInst::Predicate CurrentPred;
5580         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5581         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5582              !match(V, MatchCmp)) ||
5583             (!First && VecPred != CurrentPred)) {
5584           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5585           break;
5586         }
5587         First = false;
5588         VecPred = CurrentPred;
5589       }
5590 
5591       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5592           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5593       // Check if it is possible and profitable to use min/max for selects in
5594       // VL.
5595       //
5596       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5597       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5598         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5599                                           {VecTy, VecTy});
5600         InstructionCost IntrinsicCost =
5601             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5602         // If the selects are the only uses of the compares, they will be dead
5603         // and we can adjust the cost by removing their cost.
5604         if (IntrinsicAndUse.second)
5605           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5606                                                    MaskTy, VecPred, CostKind);
5607         VecCost = std::min(VecCost, IntrinsicCost);
5608       }
5609       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5610       return CommonCost + VecCost - ScalarCost;
5611     }
5612     case Instruction::FNeg:
5613     case Instruction::Add:
5614     case Instruction::FAdd:
5615     case Instruction::Sub:
5616     case Instruction::FSub:
5617     case Instruction::Mul:
5618     case Instruction::FMul:
5619     case Instruction::UDiv:
5620     case Instruction::SDiv:
5621     case Instruction::FDiv:
5622     case Instruction::URem:
5623     case Instruction::SRem:
5624     case Instruction::FRem:
5625     case Instruction::Shl:
5626     case Instruction::LShr:
5627     case Instruction::AShr:
5628     case Instruction::And:
5629     case Instruction::Or:
5630     case Instruction::Xor: {
5631       // Certain instructions can be cheaper to vectorize if they have a
5632       // constant second vector operand.
5633       TargetTransformInfo::OperandValueKind Op1VK =
5634           TargetTransformInfo::OK_AnyValue;
5635       TargetTransformInfo::OperandValueKind Op2VK =
5636           TargetTransformInfo::OK_UniformConstantValue;
5637       TargetTransformInfo::OperandValueProperties Op1VP =
5638           TargetTransformInfo::OP_None;
5639       TargetTransformInfo::OperandValueProperties Op2VP =
5640           TargetTransformInfo::OP_PowerOf2;
5641 
5642       // If all operands are exactly the same ConstantInt then set the
5643       // operand kind to OK_UniformConstantValue.
5644       // If instead not all operands are constants, then set the operand kind
5645       // to OK_AnyValue. If all operands are constants but not the same,
5646       // then set the operand kind to OK_NonUniformConstantValue.
5647       ConstantInt *CInt0 = nullptr;
5648       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5649         const Instruction *I = cast<Instruction>(VL[i]);
5650         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5651         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5652         if (!CInt) {
5653           Op2VK = TargetTransformInfo::OK_AnyValue;
5654           Op2VP = TargetTransformInfo::OP_None;
5655           break;
5656         }
5657         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5658             !CInt->getValue().isPowerOf2())
5659           Op2VP = TargetTransformInfo::OP_None;
5660         if (i == 0) {
5661           CInt0 = CInt;
5662           continue;
5663         }
5664         if (CInt0 != CInt)
5665           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5666       }
5667 
5668       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5669       InstructionCost ScalarEltCost =
5670           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5671                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5672       if (NeedToShuffleReuses) {
5673         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5674       }
5675       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5676       InstructionCost VecCost =
5677           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5678                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5679       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5680       return CommonCost + VecCost - ScalarCost;
5681     }
5682     case Instruction::GetElementPtr: {
5683       TargetTransformInfo::OperandValueKind Op1VK =
5684           TargetTransformInfo::OK_AnyValue;
5685       TargetTransformInfo::OperandValueKind Op2VK =
5686           TargetTransformInfo::OK_UniformConstantValue;
5687 
5688       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5689           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5690       if (NeedToShuffleReuses) {
5691         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5692       }
5693       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5694       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5695           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5696       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5697       return CommonCost + VecCost - ScalarCost;
5698     }
5699     case Instruction::Load: {
5700       // Cost of wide load - cost of scalar loads.
5701       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5702       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5703           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5704       if (NeedToShuffleReuses) {
5705         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5706       }
5707       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5708       InstructionCost VecLdCost;
5709       if (E->State == TreeEntry::Vectorize) {
5710         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5711                                          CostKind, VL0);
5712       } else {
5713         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5714         Align CommonAlignment = Alignment;
5715         for (Value *V : VL)
5716           CommonAlignment =
5717               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5718         VecLdCost = TTI->getGatherScatterOpCost(
5719             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5720             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5721       }
5722       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5723       return CommonCost + VecLdCost - ScalarLdCost;
5724     }
5725     case Instruction::Store: {
5726       // We know that we can merge the stores. Calculate the cost.
5727       bool IsReorder = !E->ReorderIndices.empty();
5728       auto *SI =
5729           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5730       Align Alignment = SI->getAlign();
5731       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5732           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5733       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5734       InstructionCost VecStCost = TTI->getMemoryOpCost(
5735           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5736       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5737       return CommonCost + VecStCost - ScalarStCost;
5738     }
5739     case Instruction::Call: {
5740       CallInst *CI = cast<CallInst>(VL0);
5741       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5742 
5743       // Calculate the cost of the scalar and vector calls.
5744       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5745       InstructionCost ScalarEltCost =
5746           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5747       if (NeedToShuffleReuses) {
5748         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5749       }
5750       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5751 
5752       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5753       InstructionCost VecCallCost =
5754           std::min(VecCallCosts.first, VecCallCosts.second);
5755 
5756       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5757                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5758                         << " for " << *CI << "\n");
5759 
5760       return CommonCost + VecCallCost - ScalarCallCost;
5761     }
5762     case Instruction::ShuffleVector: {
5763       assert(E->isAltShuffle() &&
5764              ((Instruction::isBinaryOp(E->getOpcode()) &&
5765                Instruction::isBinaryOp(E->getAltOpcode())) ||
5766               (Instruction::isCast(E->getOpcode()) &&
5767                Instruction::isCast(E->getAltOpcode())) ||
5768               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5769              "Invalid Shuffle Vector Operand");
5770       InstructionCost ScalarCost = 0;
5771       if (NeedToShuffleReuses) {
5772         for (unsigned Idx : E->ReuseShuffleIndices) {
5773           Instruction *I = cast<Instruction>(VL[Idx]);
5774           CommonCost -= TTI->getInstructionCost(I, CostKind);
5775         }
5776         for (Value *V : VL) {
5777           Instruction *I = cast<Instruction>(V);
5778           CommonCost += TTI->getInstructionCost(I, CostKind);
5779         }
5780       }
5781       for (Value *V : VL) {
5782         Instruction *I = cast<Instruction>(V);
5783         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5784         ScalarCost += TTI->getInstructionCost(I, CostKind);
5785       }
5786       // VecCost is equal to sum of the cost of creating 2 vectors
5787       // and the cost of creating shuffle.
5788       InstructionCost VecCost = 0;
5789       // Try to find the previous shuffle node with the same operands and same
5790       // main/alternate ops.
5791       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5792         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5793           if (TE.get() == E)
5794             break;
5795           if (TE->isAltShuffle() &&
5796               ((TE->getOpcode() == E->getOpcode() &&
5797                 TE->getAltOpcode() == E->getAltOpcode()) ||
5798                (TE->getOpcode() == E->getAltOpcode() &&
5799                 TE->getAltOpcode() == E->getOpcode())) &&
5800               TE->hasEqualOperands(*E))
5801             return true;
5802         }
5803         return false;
5804       };
5805       if (TryFindNodeWithEqualOperands()) {
5806         LLVM_DEBUG({
5807           dbgs() << "SLP: diamond match for alternate node found.\n";
5808           E->dump();
5809         });
5810         // No need to add new vector costs here since we're going to reuse
5811         // same main/alternate vector ops, just do different shuffling.
5812       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5813         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5814         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5815                                                CostKind);
5816       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5817         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5818                                           Builder.getInt1Ty(),
5819                                           CI0->getPredicate(), CostKind, VL0);
5820         VecCost += TTI->getCmpSelInstrCost(
5821             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5822             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5823             E->getAltOp());
5824       } else {
5825         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5826         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5827         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5828         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5829         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5830                                         TTI::CastContextHint::None, CostKind);
5831         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5832                                          TTI::CastContextHint::None, CostKind);
5833       }
5834 
5835       SmallVector<int> Mask;
5836       buildShuffleEntryMask(
5837           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5838           [E](Instruction *I) {
5839             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5840             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5841           },
5842           Mask);
5843       CommonCost =
5844           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5845       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5846       return CommonCost + VecCost - ScalarCost;
5847     }
5848     default:
5849       llvm_unreachable("Unknown instruction");
5850   }
5851 }
5852 
5853 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5854   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5855                     << VectorizableTree.size() << " is fully vectorizable .\n");
5856 
5857   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5858     SmallVector<int> Mask;
5859     return TE->State == TreeEntry::NeedToGather &&
5860            !any_of(TE->Scalars,
5861                    [this](Value *V) { return EphValues.contains(V); }) &&
5862            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5863             TE->Scalars.size() < Limit ||
5864             ((TE->getOpcode() == Instruction::ExtractElement ||
5865               all_of(TE->Scalars,
5866                      [](Value *V) {
5867                        return isa<ExtractElementInst, UndefValue>(V);
5868                      })) &&
5869              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5870             (TE->State == TreeEntry::NeedToGather &&
5871              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5872   };
5873 
5874   // We only handle trees of heights 1 and 2.
5875   if (VectorizableTree.size() == 1 &&
5876       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5877        (ForReduction &&
5878         AreVectorizableGathers(VectorizableTree[0].get(),
5879                                VectorizableTree[0]->Scalars.size()) &&
5880         VectorizableTree[0]->getVectorFactor() > 2)))
5881     return true;
5882 
5883   if (VectorizableTree.size() != 2)
5884     return false;
5885 
5886   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5887   // with the second gather nodes if they have less scalar operands rather than
5888   // the initial tree element (may be profitable to shuffle the second gather)
5889   // or they are extractelements, which form shuffle.
5890   SmallVector<int> Mask;
5891   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5892       AreVectorizableGathers(VectorizableTree[1].get(),
5893                              VectorizableTree[0]->Scalars.size()))
5894     return true;
5895 
5896   // Gathering cost would be too much for tiny trees.
5897   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5898       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5899        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5900     return false;
5901 
5902   return true;
5903 }
5904 
5905 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5906                                        TargetTransformInfo *TTI,
5907                                        bool MustMatchOrInst) {
5908   // Look past the root to find a source value. Arbitrarily follow the
5909   // path through operand 0 of any 'or'. Also, peek through optional
5910   // shift-left-by-multiple-of-8-bits.
5911   Value *ZextLoad = Root;
5912   const APInt *ShAmtC;
5913   bool FoundOr = false;
5914   while (!isa<ConstantExpr>(ZextLoad) &&
5915          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5916           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5917            ShAmtC->urem(8) == 0))) {
5918     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5919     ZextLoad = BinOp->getOperand(0);
5920     if (BinOp->getOpcode() == Instruction::Or)
5921       FoundOr = true;
5922   }
5923   // Check if the input is an extended load of the required or/shift expression.
5924   Value *Load;
5925   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5926       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5927     return false;
5928 
5929   // Require that the total load bit width is a legal integer type.
5930   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5931   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5932   Type *SrcTy = Load->getType();
5933   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5934   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5935     return false;
5936 
5937   // Everything matched - assume that we can fold the whole sequence using
5938   // load combining.
5939   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5940              << *(cast<Instruction>(Root)) << "\n");
5941 
5942   return true;
5943 }
5944 
5945 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5946   if (RdxKind != RecurKind::Or)
5947     return false;
5948 
5949   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5950   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5951   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5952                                     /* MatchOr */ false);
5953 }
5954 
5955 bool BoUpSLP::isLoadCombineCandidate() const {
5956   // Peek through a final sequence of stores and check if all operations are
5957   // likely to be load-combined.
5958   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5959   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5960     Value *X;
5961     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5962         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5963       return false;
5964   }
5965   return true;
5966 }
5967 
5968 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5969   // No need to vectorize inserts of gathered values.
5970   if (VectorizableTree.size() == 2 &&
5971       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5972       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5973     return true;
5974 
5975   // We can vectorize the tree if its size is greater than or equal to the
5976   // minimum size specified by the MinTreeSize command line option.
5977   if (VectorizableTree.size() >= MinTreeSize)
5978     return false;
5979 
5980   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5981   // can vectorize it if we can prove it fully vectorizable.
5982   if (isFullyVectorizableTinyTree(ForReduction))
5983     return false;
5984 
5985   assert(VectorizableTree.empty()
5986              ? ExternalUses.empty()
5987              : true && "We shouldn't have any external users");
5988 
5989   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5990   // vectorizable.
5991   return true;
5992 }
5993 
5994 InstructionCost BoUpSLP::getSpillCost() const {
5995   // Walk from the bottom of the tree to the top, tracking which values are
5996   // live. When we see a call instruction that is not part of our tree,
5997   // query TTI to see if there is a cost to keeping values live over it
5998   // (for example, if spills and fills are required).
5999   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6000   InstructionCost Cost = 0;
6001 
6002   SmallPtrSet<Instruction*, 4> LiveValues;
6003   Instruction *PrevInst = nullptr;
6004 
6005   // The entries in VectorizableTree are not necessarily ordered by their
6006   // position in basic blocks. Collect them and order them by dominance so later
6007   // instructions are guaranteed to be visited first. For instructions in
6008   // different basic blocks, we only scan to the beginning of the block, so
6009   // their order does not matter, as long as all instructions in a basic block
6010   // are grouped together. Using dominance ensures a deterministic order.
6011   SmallVector<Instruction *, 16> OrderedScalars;
6012   for (const auto &TEPtr : VectorizableTree) {
6013     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6014     if (!Inst)
6015       continue;
6016     OrderedScalars.push_back(Inst);
6017   }
6018   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6019     auto *NodeA = DT->getNode(A->getParent());
6020     auto *NodeB = DT->getNode(B->getParent());
6021     assert(NodeA && "Should only process reachable instructions");
6022     assert(NodeB && "Should only process reachable instructions");
6023     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6024            "Different nodes should have different DFS numbers");
6025     if (NodeA != NodeB)
6026       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6027     return B->comesBefore(A);
6028   });
6029 
6030   for (Instruction *Inst : OrderedScalars) {
6031     if (!PrevInst) {
6032       PrevInst = Inst;
6033       continue;
6034     }
6035 
6036     // Update LiveValues.
6037     LiveValues.erase(PrevInst);
6038     for (auto &J : PrevInst->operands()) {
6039       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6040         LiveValues.insert(cast<Instruction>(&*J));
6041     }
6042 
6043     LLVM_DEBUG({
6044       dbgs() << "SLP: #LV: " << LiveValues.size();
6045       for (auto *X : LiveValues)
6046         dbgs() << " " << X->getName();
6047       dbgs() << ", Looking at ";
6048       Inst->dump();
6049     });
6050 
6051     // Now find the sequence of instructions between PrevInst and Inst.
6052     unsigned NumCalls = 0;
6053     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6054                                  PrevInstIt =
6055                                      PrevInst->getIterator().getReverse();
6056     while (InstIt != PrevInstIt) {
6057       if (PrevInstIt == PrevInst->getParent()->rend()) {
6058         PrevInstIt = Inst->getParent()->rbegin();
6059         continue;
6060       }
6061 
6062       // Debug information does not impact spill cost.
6063       if ((isa<CallInst>(&*PrevInstIt) &&
6064            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6065           &*PrevInstIt != PrevInst)
6066         NumCalls++;
6067 
6068       ++PrevInstIt;
6069     }
6070 
6071     if (NumCalls) {
6072       SmallVector<Type*, 4> V;
6073       for (auto *II : LiveValues) {
6074         auto *ScalarTy = II->getType();
6075         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6076           ScalarTy = VectorTy->getElementType();
6077         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6078       }
6079       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6080     }
6081 
6082     PrevInst = Inst;
6083   }
6084 
6085   return Cost;
6086 }
6087 
6088 /// Check if two insertelement instructions are from the same buildvector.
6089 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6090                                             InsertElementInst *V) {
6091   // Instructions must be from the same basic blocks.
6092   if (VU->getParent() != V->getParent())
6093     return false;
6094   // Checks if 2 insertelements are from the same buildvector.
6095   if (VU->getType() != V->getType())
6096     return false;
6097   // Multiple used inserts are separate nodes.
6098   if (!VU->hasOneUse() && !V->hasOneUse())
6099     return false;
6100   auto *IE1 = VU;
6101   auto *IE2 = V;
6102   // Go through the vector operand of insertelement instructions trying to find
6103   // either VU as the original vector for IE2 or V as the original vector for
6104   // IE1.
6105   do {
6106     if (IE2 == VU || IE1 == V)
6107       return true;
6108     if (IE1) {
6109       if (IE1 != VU && !IE1->hasOneUse())
6110         IE1 = nullptr;
6111       else
6112         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6113     }
6114     if (IE2) {
6115       if (IE2 != V && !IE2->hasOneUse())
6116         IE2 = nullptr;
6117       else
6118         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6119     }
6120   } while (IE1 || IE2);
6121   return false;
6122 }
6123 
6124 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6125   InstructionCost Cost = 0;
6126   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6127                     << VectorizableTree.size() << ".\n");
6128 
6129   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6130 
6131   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6132     TreeEntry &TE = *VectorizableTree[I];
6133 
6134     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6135     Cost += C;
6136     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6137                       << " for bundle that starts with " << *TE.Scalars[0]
6138                       << ".\n"
6139                       << "SLP: Current total cost = " << Cost << "\n");
6140   }
6141 
6142   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6143   InstructionCost ExtractCost = 0;
6144   SmallVector<unsigned> VF;
6145   SmallVector<SmallVector<int>> ShuffleMask;
6146   SmallVector<Value *> FirstUsers;
6147   SmallVector<APInt> DemandedElts;
6148   for (ExternalUser &EU : ExternalUses) {
6149     // We only add extract cost once for the same scalar.
6150     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6151         !ExtractCostCalculated.insert(EU.Scalar).second)
6152       continue;
6153 
6154     // Uses by ephemeral values are free (because the ephemeral value will be
6155     // removed prior to code generation, and so the extraction will be
6156     // removed as well).
6157     if (EphValues.count(EU.User))
6158       continue;
6159 
6160     // No extract cost for vector "scalar"
6161     if (isa<FixedVectorType>(EU.Scalar->getType()))
6162       continue;
6163 
6164     // Already counted the cost for external uses when tried to adjust the cost
6165     // for extractelements, no need to add it again.
6166     if (isa<ExtractElementInst>(EU.Scalar))
6167       continue;
6168 
6169     // If found user is an insertelement, do not calculate extract cost but try
6170     // to detect it as a final shuffled/identity match.
6171     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6172       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6173         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6174         if (InsertIdx) {
6175           auto *It = find_if(FirstUsers, [VU](Value *V) {
6176             return areTwoInsertFromSameBuildVector(VU,
6177                                                    cast<InsertElementInst>(V));
6178           });
6179           int VecId = -1;
6180           if (It == FirstUsers.end()) {
6181             VF.push_back(FTy->getNumElements());
6182             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6183             // Find the insertvector, vectorized in tree, if any.
6184             Value *Base = VU;
6185             while (isa<InsertElementInst>(Base)) {
6186               // Build the mask for the vectorized insertelement instructions.
6187               if (const TreeEntry *E = getTreeEntry(Base)) {
6188                 VU = cast<InsertElementInst>(Base);
6189                 do {
6190                   int Idx = E->findLaneForValue(Base);
6191                   ShuffleMask.back()[Idx] = Idx;
6192                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6193                 } while (E == getTreeEntry(Base));
6194                 break;
6195               }
6196               Base = cast<InsertElementInst>(Base)->getOperand(0);
6197             }
6198             FirstUsers.push_back(VU);
6199             DemandedElts.push_back(APInt::getZero(VF.back()));
6200             VecId = FirstUsers.size() - 1;
6201           } else {
6202             VecId = std::distance(FirstUsers.begin(), It);
6203           }
6204           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6205           DemandedElts[VecId].setBit(*InsertIdx);
6206           continue;
6207         }
6208       }
6209     }
6210 
6211     // If we plan to rewrite the tree in a smaller type, we will need to sign
6212     // extend the extracted value back to the original type. Here, we account
6213     // for the extract and the added cost of the sign extend if needed.
6214     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6215     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6216     if (MinBWs.count(ScalarRoot)) {
6217       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6218       auto Extend =
6219           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6220       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6221       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6222                                                    VecTy, EU.Lane);
6223     } else {
6224       ExtractCost +=
6225           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6226     }
6227   }
6228 
6229   InstructionCost SpillCost = getSpillCost();
6230   Cost += SpillCost + ExtractCost;
6231   if (FirstUsers.size() == 1) {
6232     int Limit = ShuffleMask.front().size() * 2;
6233     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6234         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6235       InstructionCost C = TTI->getShuffleCost(
6236           TTI::SK_PermuteSingleSrc,
6237           cast<FixedVectorType>(FirstUsers.front()->getType()),
6238           ShuffleMask.front());
6239       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6240                         << " for final shuffle of insertelement external users "
6241                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6242                         << "SLP: Current total cost = " << Cost << "\n");
6243       Cost += C;
6244     }
6245     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6246         cast<FixedVectorType>(FirstUsers.front()->getType()),
6247         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6248     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6249                       << " for insertelements gather.\n"
6250                       << "SLP: Current total cost = " << Cost << "\n");
6251     Cost -= InsertCost;
6252   } else if (FirstUsers.size() >= 2) {
6253     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6254     // Combined masks of the first 2 vectors.
6255     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6256     copy(ShuffleMask.front(), CombinedMask.begin());
6257     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6258     auto *VecTy = FixedVectorType::get(
6259         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6260         MaxVF);
6261     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6262       if (ShuffleMask[1][I] != UndefMaskElem) {
6263         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6264         CombinedDemandedElts.setBit(I);
6265       }
6266     }
6267     InstructionCost C =
6268         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6269     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6270                       << " for final shuffle of vector node and external "
6271                          "insertelement users "
6272                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6273                       << "SLP: Current total cost = " << Cost << "\n");
6274     Cost += C;
6275     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6276         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6277     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6278                       << " for insertelements gather.\n"
6279                       << "SLP: Current total cost = " << Cost << "\n");
6280     Cost -= InsertCost;
6281     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6282       // Other elements - permutation of 2 vectors (the initial one and the
6283       // next Ith incoming vector).
6284       unsigned VF = ShuffleMask[I].size();
6285       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6286         int Mask = ShuffleMask[I][Idx];
6287         if (Mask != UndefMaskElem)
6288           CombinedMask[Idx] = MaxVF + Mask;
6289         else if (CombinedMask[Idx] != UndefMaskElem)
6290           CombinedMask[Idx] = Idx;
6291       }
6292       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6293         if (CombinedMask[Idx] != UndefMaskElem)
6294           CombinedMask[Idx] = Idx;
6295       InstructionCost C =
6296           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6297       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6298                         << " for final shuffle of vector node and external "
6299                            "insertelement users "
6300                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6301                         << "SLP: Current total cost = " << Cost << "\n");
6302       Cost += C;
6303       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6304           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6305           /*Insert*/ true, /*Extract*/ false);
6306       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6307                         << " for insertelements gather.\n"
6308                         << "SLP: Current total cost = " << Cost << "\n");
6309       Cost -= InsertCost;
6310     }
6311   }
6312 
6313 #ifndef NDEBUG
6314   SmallString<256> Str;
6315   {
6316     raw_svector_ostream OS(Str);
6317     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6318        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6319        << "SLP: Total Cost = " << Cost << ".\n";
6320   }
6321   LLVM_DEBUG(dbgs() << Str);
6322   if (ViewSLPTree)
6323     ViewGraph(this, "SLP" + F->getName(), false, Str);
6324 #endif
6325 
6326   return Cost;
6327 }
6328 
6329 Optional<TargetTransformInfo::ShuffleKind>
6330 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6331                                SmallVectorImpl<const TreeEntry *> &Entries) {
6332   // TODO: currently checking only for Scalars in the tree entry, need to count
6333   // reused elements too for better cost estimation.
6334   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6335   Entries.clear();
6336   // Build a lists of values to tree entries.
6337   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6338   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6339     if (EntryPtr.get() == TE)
6340       break;
6341     if (EntryPtr->State != TreeEntry::NeedToGather)
6342       continue;
6343     for (Value *V : EntryPtr->Scalars)
6344       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6345   }
6346   // Find all tree entries used by the gathered values. If no common entries
6347   // found - not a shuffle.
6348   // Here we build a set of tree nodes for each gathered value and trying to
6349   // find the intersection between these sets. If we have at least one common
6350   // tree node for each gathered value - we have just a permutation of the
6351   // single vector. If we have 2 different sets, we're in situation where we
6352   // have a permutation of 2 input vectors.
6353   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6354   DenseMap<Value *, int> UsedValuesEntry;
6355   for (Value *V : TE->Scalars) {
6356     if (isa<UndefValue>(V))
6357       continue;
6358     // Build a list of tree entries where V is used.
6359     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6360     auto It = ValueToTEs.find(V);
6361     if (It != ValueToTEs.end())
6362       VToTEs = It->second;
6363     if (const TreeEntry *VTE = getTreeEntry(V))
6364       VToTEs.insert(VTE);
6365     if (VToTEs.empty())
6366       return None;
6367     if (UsedTEs.empty()) {
6368       // The first iteration, just insert the list of nodes to vector.
6369       UsedTEs.push_back(VToTEs);
6370     } else {
6371       // Need to check if there are any previously used tree nodes which use V.
6372       // If there are no such nodes, consider that we have another one input
6373       // vector.
6374       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6375       unsigned Idx = 0;
6376       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6377         // Do we have a non-empty intersection of previously listed tree entries
6378         // and tree entries using current V?
6379         set_intersect(VToTEs, Set);
6380         if (!VToTEs.empty()) {
6381           // Yes, write the new subset and continue analysis for the next
6382           // scalar.
6383           Set.swap(VToTEs);
6384           break;
6385         }
6386         VToTEs = SavedVToTEs;
6387         ++Idx;
6388       }
6389       // No non-empty intersection found - need to add a second set of possible
6390       // source vectors.
6391       if (Idx == UsedTEs.size()) {
6392         // If the number of input vectors is greater than 2 - not a permutation,
6393         // fallback to the regular gather.
6394         if (UsedTEs.size() == 2)
6395           return None;
6396         UsedTEs.push_back(SavedVToTEs);
6397         Idx = UsedTEs.size() - 1;
6398       }
6399       UsedValuesEntry.try_emplace(V, Idx);
6400     }
6401   }
6402 
6403   unsigned VF = 0;
6404   if (UsedTEs.size() == 1) {
6405     // Try to find the perfect match in another gather node at first.
6406     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6407       return EntryPtr->isSame(TE->Scalars);
6408     });
6409     if (It != UsedTEs.front().end()) {
6410       Entries.push_back(*It);
6411       std::iota(Mask.begin(), Mask.end(), 0);
6412       return TargetTransformInfo::SK_PermuteSingleSrc;
6413     }
6414     // No perfect match, just shuffle, so choose the first tree node.
6415     Entries.push_back(*UsedTEs.front().begin());
6416   } else {
6417     // Try to find nodes with the same vector factor.
6418     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6419     DenseMap<int, const TreeEntry *> VFToTE;
6420     for (const TreeEntry *TE : UsedTEs.front())
6421       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6422     for (const TreeEntry *TE : UsedTEs.back()) {
6423       auto It = VFToTE.find(TE->getVectorFactor());
6424       if (It != VFToTE.end()) {
6425         VF = It->first;
6426         Entries.push_back(It->second);
6427         Entries.push_back(TE);
6428         break;
6429       }
6430     }
6431     // No 2 source vectors with the same vector factor - give up and do regular
6432     // gather.
6433     if (Entries.empty())
6434       return None;
6435   }
6436 
6437   // Build a shuffle mask for better cost estimation and vector emission.
6438   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6439     Value *V = TE->Scalars[I];
6440     if (isa<UndefValue>(V))
6441       continue;
6442     unsigned Idx = UsedValuesEntry.lookup(V);
6443     const TreeEntry *VTE = Entries[Idx];
6444     int FoundLane = VTE->findLaneForValue(V);
6445     Mask[I] = Idx * VF + FoundLane;
6446     // Extra check required by isSingleSourceMaskImpl function (called by
6447     // ShuffleVectorInst::isSingleSourceMask).
6448     if (Mask[I] >= 2 * E)
6449       return None;
6450   }
6451   switch (Entries.size()) {
6452   case 1:
6453     return TargetTransformInfo::SK_PermuteSingleSrc;
6454   case 2:
6455     return TargetTransformInfo::SK_PermuteTwoSrc;
6456   default:
6457     break;
6458   }
6459   return None;
6460 }
6461 
6462 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6463                                        const APInt &ShuffledIndices,
6464                                        bool NeedToShuffle) const {
6465   InstructionCost Cost =
6466       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6467                                     /*Extract*/ false);
6468   if (NeedToShuffle)
6469     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6470   return Cost;
6471 }
6472 
6473 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6474   // Find the type of the operands in VL.
6475   Type *ScalarTy = VL[0]->getType();
6476   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6477     ScalarTy = SI->getValueOperand()->getType();
6478   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6479   bool DuplicateNonConst = false;
6480   // Find the cost of inserting/extracting values from the vector.
6481   // Check if the same elements are inserted several times and count them as
6482   // shuffle candidates.
6483   APInt ShuffledElements = APInt::getZero(VL.size());
6484   DenseSet<Value *> UniqueElements;
6485   // Iterate in reverse order to consider insert elements with the high cost.
6486   for (unsigned I = VL.size(); I > 0; --I) {
6487     unsigned Idx = I - 1;
6488     // No need to shuffle duplicates for constants.
6489     if (isConstant(VL[Idx])) {
6490       ShuffledElements.setBit(Idx);
6491       continue;
6492     }
6493     if (!UniqueElements.insert(VL[Idx]).second) {
6494       DuplicateNonConst = true;
6495       ShuffledElements.setBit(Idx);
6496     }
6497   }
6498   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6499 }
6500 
6501 // Perform operand reordering on the instructions in VL and return the reordered
6502 // operands in Left and Right.
6503 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6504                                              SmallVectorImpl<Value *> &Left,
6505                                              SmallVectorImpl<Value *> &Right,
6506                                              const DataLayout &DL,
6507                                              ScalarEvolution &SE,
6508                                              const BoUpSLP &R) {
6509   if (VL.empty())
6510     return;
6511   VLOperands Ops(VL, DL, SE, R);
6512   // Reorder the operands in place.
6513   Ops.reorder();
6514   Left = Ops.getVL(0);
6515   Right = Ops.getVL(1);
6516 }
6517 
6518 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6519   // Get the basic block this bundle is in. All instructions in the bundle
6520   // should be in this block.
6521   auto *Front = E->getMainOp();
6522   auto *BB = Front->getParent();
6523   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6524     auto *I = cast<Instruction>(V);
6525     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6526   }));
6527 
6528   auto &&FindLastInst = [E, Front]() {
6529     Instruction *LastInst = Front;
6530     for (Value *V : E->Scalars) {
6531       auto *I = dyn_cast<Instruction>(V);
6532       if (!I)
6533         continue;
6534       if (LastInst->comesBefore(I))
6535         LastInst = I;
6536     }
6537     return LastInst;
6538   };
6539 
6540   auto &&FindFirstInst = [E, Front]() {
6541     Instruction *FirstInst = Front;
6542     for (Value *V : E->Scalars) {
6543       auto *I = dyn_cast<Instruction>(V);
6544       if (!I)
6545         continue;
6546       if (I->comesBefore(FirstInst))
6547         FirstInst = I;
6548     }
6549     return FirstInst;
6550   };
6551 
6552   // Set the insert point to the beginning of the basic block if the entry
6553   // should not be scheduled.
6554   if (E->State != TreeEntry::NeedToGather &&
6555       doesNotNeedToSchedule(E->Scalars)) {
6556     BasicBlock::iterator InsertPt;
6557     if (all_of(E->Scalars, isUsedOutsideBlock))
6558       InsertPt = FindLastInst()->getIterator();
6559     else
6560       InsertPt = FindFirstInst()->getIterator();
6561     Builder.SetInsertPoint(BB, InsertPt);
6562     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6563     return;
6564   }
6565 
6566   // The last instruction in the bundle in program order.
6567   Instruction *LastInst = nullptr;
6568 
6569   // Find the last instruction. The common case should be that BB has been
6570   // scheduled, and the last instruction is VL.back(). So we start with
6571   // VL.back() and iterate over schedule data until we reach the end of the
6572   // bundle. The end of the bundle is marked by null ScheduleData.
6573   if (BlocksSchedules.count(BB)) {
6574     Value *V = E->isOneOf(E->Scalars.back());
6575     if (doesNotNeedToBeScheduled(V))
6576       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6577     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6578     if (Bundle && Bundle->isPartOfBundle())
6579       for (; Bundle; Bundle = Bundle->NextInBundle)
6580         if (Bundle->OpValue == Bundle->Inst)
6581           LastInst = Bundle->Inst;
6582   }
6583 
6584   // LastInst can still be null at this point if there's either not an entry
6585   // for BB in BlocksSchedules or there's no ScheduleData available for
6586   // VL.back(). This can be the case if buildTree_rec aborts for various
6587   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6588   // size is reached, etc.). ScheduleData is initialized in the scheduling
6589   // "dry-run".
6590   //
6591   // If this happens, we can still find the last instruction by brute force. We
6592   // iterate forwards from Front (inclusive) until we either see all
6593   // instructions in the bundle or reach the end of the block. If Front is the
6594   // last instruction in program order, LastInst will be set to Front, and we
6595   // will visit all the remaining instructions in the block.
6596   //
6597   // One of the reasons we exit early from buildTree_rec is to place an upper
6598   // bound on compile-time. Thus, taking an additional compile-time hit here is
6599   // not ideal. However, this should be exceedingly rare since it requires that
6600   // we both exit early from buildTree_rec and that the bundle be out-of-order
6601   // (causing us to iterate all the way to the end of the block).
6602   if (!LastInst)
6603     LastInst = FindLastInst();
6604   assert(LastInst && "Failed to find last instruction in bundle");
6605 
6606   // Set the insertion point after the last instruction in the bundle. Set the
6607   // debug location to Front.
6608   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6609   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6610 }
6611 
6612 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6613   // List of instructions/lanes from current block and/or the blocks which are
6614   // part of the current loop. These instructions will be inserted at the end to
6615   // make it possible to optimize loops and hoist invariant instructions out of
6616   // the loops body with better chances for success.
6617   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6618   SmallSet<int, 4> PostponedIndices;
6619   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6620   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6621     SmallPtrSet<BasicBlock *, 4> Visited;
6622     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6623       InsertBB = InsertBB->getSinglePredecessor();
6624     return InsertBB && InsertBB == InstBB;
6625   };
6626   for (int I = 0, E = VL.size(); I < E; ++I) {
6627     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6628       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6629            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6630           PostponedIndices.insert(I).second)
6631         PostponedInsts.emplace_back(Inst, I);
6632   }
6633 
6634   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6635     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6636     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6637     if (!InsElt)
6638       return Vec;
6639     GatherShuffleSeq.insert(InsElt);
6640     CSEBlocks.insert(InsElt->getParent());
6641     // Add to our 'need-to-extract' list.
6642     if (TreeEntry *Entry = getTreeEntry(V)) {
6643       // Find which lane we need to extract.
6644       unsigned FoundLane = Entry->findLaneForValue(V);
6645       ExternalUses.emplace_back(V, InsElt, FoundLane);
6646     }
6647     return Vec;
6648   };
6649   Value *Val0 =
6650       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6651   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6652   Value *Vec = PoisonValue::get(VecTy);
6653   SmallVector<int> NonConsts;
6654   // Insert constant values at first.
6655   for (int I = 0, E = VL.size(); I < E; ++I) {
6656     if (PostponedIndices.contains(I))
6657       continue;
6658     if (!isConstant(VL[I])) {
6659       NonConsts.push_back(I);
6660       continue;
6661     }
6662     Vec = CreateInsertElement(Vec, VL[I], I);
6663   }
6664   // Insert non-constant values.
6665   for (int I : NonConsts)
6666     Vec = CreateInsertElement(Vec, VL[I], I);
6667   // Append instructions, which are/may be part of the loop, in the end to make
6668   // it possible to hoist non-loop-based instructions.
6669   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6670     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6671 
6672   return Vec;
6673 }
6674 
6675 namespace {
6676 /// Merges shuffle masks and emits final shuffle instruction, if required.
6677 class ShuffleInstructionBuilder {
6678   IRBuilderBase &Builder;
6679   const unsigned VF = 0;
6680   bool IsFinalized = false;
6681   SmallVector<int, 4> Mask;
6682   /// Holds all of the instructions that we gathered.
6683   SetVector<Instruction *> &GatherShuffleSeq;
6684   /// A list of blocks that we are going to CSE.
6685   SetVector<BasicBlock *> &CSEBlocks;
6686 
6687 public:
6688   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6689                             SetVector<Instruction *> &GatherShuffleSeq,
6690                             SetVector<BasicBlock *> &CSEBlocks)
6691       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6692         CSEBlocks(CSEBlocks) {}
6693 
6694   /// Adds a mask, inverting it before applying.
6695   void addInversedMask(ArrayRef<unsigned> SubMask) {
6696     if (SubMask.empty())
6697       return;
6698     SmallVector<int, 4> NewMask;
6699     inversePermutation(SubMask, NewMask);
6700     addMask(NewMask);
6701   }
6702 
6703   /// Functions adds masks, merging them into  single one.
6704   void addMask(ArrayRef<unsigned> SubMask) {
6705     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6706     addMask(NewMask);
6707   }
6708 
6709   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6710 
6711   Value *finalize(Value *V) {
6712     IsFinalized = true;
6713     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6714     if (VF == ValueVF && Mask.empty())
6715       return V;
6716     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6717     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6718     addMask(NormalizedMask);
6719 
6720     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6721       return V;
6722     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6723     if (auto *I = dyn_cast<Instruction>(Vec)) {
6724       GatherShuffleSeq.insert(I);
6725       CSEBlocks.insert(I->getParent());
6726     }
6727     return Vec;
6728   }
6729 
6730   ~ShuffleInstructionBuilder() {
6731     assert((IsFinalized || Mask.empty()) &&
6732            "Shuffle construction must be finalized.");
6733   }
6734 };
6735 } // namespace
6736 
6737 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6738   const unsigned VF = VL.size();
6739   InstructionsState S = getSameOpcode(VL);
6740   if (S.getOpcode()) {
6741     if (TreeEntry *E = getTreeEntry(S.OpValue))
6742       if (E->isSame(VL)) {
6743         Value *V = vectorizeTree(E);
6744         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6745           if (!E->ReuseShuffleIndices.empty()) {
6746             // Reshuffle to get only unique values.
6747             // If some of the scalars are duplicated in the vectorization tree
6748             // entry, we do not vectorize them but instead generate a mask for
6749             // the reuses. But if there are several users of the same entry,
6750             // they may have different vectorization factors. This is especially
6751             // important for PHI nodes. In this case, we need to adapt the
6752             // resulting instruction for the user vectorization factor and have
6753             // to reshuffle it again to take only unique elements of the vector.
6754             // Without this code the function incorrectly returns reduced vector
6755             // instruction with the same elements, not with the unique ones.
6756 
6757             // block:
6758             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6759             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6760             // ... (use %2)
6761             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6762             // br %block
6763             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6764             SmallSet<int, 4> UsedIdxs;
6765             int Pos = 0;
6766             int Sz = VL.size();
6767             for (int Idx : E->ReuseShuffleIndices) {
6768               if (Idx != Sz && Idx != UndefMaskElem &&
6769                   UsedIdxs.insert(Idx).second)
6770                 UniqueIdxs[Idx] = Pos;
6771               ++Pos;
6772             }
6773             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6774                                             "less than original vector size.");
6775             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6776             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6777           } else {
6778             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6779                    "Expected vectorization factor less "
6780                    "than original vector size.");
6781             SmallVector<int> UniformMask(VF, 0);
6782             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6783             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6784           }
6785           if (auto *I = dyn_cast<Instruction>(V)) {
6786             GatherShuffleSeq.insert(I);
6787             CSEBlocks.insert(I->getParent());
6788           }
6789         }
6790         return V;
6791       }
6792   }
6793 
6794   // Can't vectorize this, so simply build a new vector with each lane
6795   // corresponding to the requested value.
6796   return createBuildVector(VL);
6797 }
6798 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6799   unsigned VF = VL.size();
6800   // Exploit possible reuse of values across lanes.
6801   SmallVector<int> ReuseShuffleIndicies;
6802   SmallVector<Value *> UniqueValues;
6803   if (VL.size() > 2) {
6804     DenseMap<Value *, unsigned> UniquePositions;
6805     unsigned NumValues =
6806         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6807                                     return !isa<UndefValue>(V);
6808                                   }).base());
6809     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6810     int UniqueVals = 0;
6811     for (Value *V : VL.drop_back(VL.size() - VF)) {
6812       if (isa<UndefValue>(V)) {
6813         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6814         continue;
6815       }
6816       if (isConstant(V)) {
6817         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6818         UniqueValues.emplace_back(V);
6819         continue;
6820       }
6821       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6822       ReuseShuffleIndicies.emplace_back(Res.first->second);
6823       if (Res.second) {
6824         UniqueValues.emplace_back(V);
6825         ++UniqueVals;
6826       }
6827     }
6828     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6829       // Emit pure splat vector.
6830       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6831                                   UndefMaskElem);
6832     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6833       ReuseShuffleIndicies.clear();
6834       UniqueValues.clear();
6835       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6836     }
6837     UniqueValues.append(VF - UniqueValues.size(),
6838                         PoisonValue::get(VL[0]->getType()));
6839     VL = UniqueValues;
6840   }
6841 
6842   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6843                                            CSEBlocks);
6844   Value *Vec = gather(VL);
6845   if (!ReuseShuffleIndicies.empty()) {
6846     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6847     Vec = ShuffleBuilder.finalize(Vec);
6848   }
6849   return Vec;
6850 }
6851 
6852 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6853   IRBuilder<>::InsertPointGuard Guard(Builder);
6854 
6855   if (E->VectorizedValue) {
6856     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6857     return E->VectorizedValue;
6858   }
6859 
6860   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6861   unsigned VF = E->getVectorFactor();
6862   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6863                                            CSEBlocks);
6864   if (E->State == TreeEntry::NeedToGather) {
6865     if (E->getMainOp())
6866       setInsertPointAfterBundle(E);
6867     Value *Vec;
6868     SmallVector<int> Mask;
6869     SmallVector<const TreeEntry *> Entries;
6870     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6871         isGatherShuffledEntry(E, Mask, Entries);
6872     if (Shuffle.hasValue()) {
6873       assert((Entries.size() == 1 || Entries.size() == 2) &&
6874              "Expected shuffle of 1 or 2 entries.");
6875       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6876                                         Entries.back()->VectorizedValue, Mask);
6877       if (auto *I = dyn_cast<Instruction>(Vec)) {
6878         GatherShuffleSeq.insert(I);
6879         CSEBlocks.insert(I->getParent());
6880       }
6881     } else {
6882       Vec = gather(E->Scalars);
6883     }
6884     if (NeedToShuffleReuses) {
6885       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6886       Vec = ShuffleBuilder.finalize(Vec);
6887     }
6888     E->VectorizedValue = Vec;
6889     return Vec;
6890   }
6891 
6892   assert((E->State == TreeEntry::Vectorize ||
6893           E->State == TreeEntry::ScatterVectorize) &&
6894          "Unhandled state");
6895   unsigned ShuffleOrOp =
6896       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6897   Instruction *VL0 = E->getMainOp();
6898   Type *ScalarTy = VL0->getType();
6899   if (auto *Store = dyn_cast<StoreInst>(VL0))
6900     ScalarTy = Store->getValueOperand()->getType();
6901   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6902     ScalarTy = IE->getOperand(1)->getType();
6903   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6904   switch (ShuffleOrOp) {
6905     case Instruction::PHI: {
6906       assert(
6907           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6908           "PHI reordering is free.");
6909       auto *PH = cast<PHINode>(VL0);
6910       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6911       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6912       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6913       Value *V = NewPhi;
6914 
6915       // Adjust insertion point once all PHI's have been generated.
6916       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6917       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6918 
6919       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6920       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6921       V = ShuffleBuilder.finalize(V);
6922 
6923       E->VectorizedValue = V;
6924 
6925       // PHINodes may have multiple entries from the same block. We want to
6926       // visit every block once.
6927       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6928 
6929       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6930         ValueList Operands;
6931         BasicBlock *IBB = PH->getIncomingBlock(i);
6932 
6933         if (!VisitedBBs.insert(IBB).second) {
6934           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6935           continue;
6936         }
6937 
6938         Builder.SetInsertPoint(IBB->getTerminator());
6939         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6940         Value *Vec = vectorizeTree(E->getOperand(i));
6941         NewPhi->addIncoming(Vec, IBB);
6942       }
6943 
6944       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6945              "Invalid number of incoming values");
6946       return V;
6947     }
6948 
6949     case Instruction::ExtractElement: {
6950       Value *V = E->getSingleOperand(0);
6951       Builder.SetInsertPoint(VL0);
6952       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6953       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6954       V = ShuffleBuilder.finalize(V);
6955       E->VectorizedValue = V;
6956       return V;
6957     }
6958     case Instruction::ExtractValue: {
6959       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6960       Builder.SetInsertPoint(LI);
6961       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6962       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6963       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6964       Value *NewV = propagateMetadata(V, E->Scalars);
6965       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6966       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6967       NewV = ShuffleBuilder.finalize(NewV);
6968       E->VectorizedValue = NewV;
6969       return NewV;
6970     }
6971     case Instruction::InsertElement: {
6972       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6973       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6974       Value *V = vectorizeTree(E->getOperand(1));
6975 
6976       // Create InsertVector shuffle if necessary
6977       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6978         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6979       }));
6980       const unsigned NumElts =
6981           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6982       const unsigned NumScalars = E->Scalars.size();
6983 
6984       unsigned Offset = *getInsertIndex(VL0);
6985       assert(Offset < NumElts && "Failed to find vector index offset");
6986 
6987       // Create shuffle to resize vector
6988       SmallVector<int> Mask;
6989       if (!E->ReorderIndices.empty()) {
6990         inversePermutation(E->ReorderIndices, Mask);
6991         Mask.append(NumElts - NumScalars, UndefMaskElem);
6992       } else {
6993         Mask.assign(NumElts, UndefMaskElem);
6994         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6995       }
6996       // Create InsertVector shuffle if necessary
6997       bool IsIdentity = true;
6998       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6999       Mask.swap(PrevMask);
7000       for (unsigned I = 0; I < NumScalars; ++I) {
7001         Value *Scalar = E->Scalars[PrevMask[I]];
7002         unsigned InsertIdx = *getInsertIndex(Scalar);
7003         IsIdentity &= InsertIdx - Offset == I;
7004         Mask[InsertIdx - Offset] = I;
7005       }
7006       if (!IsIdentity || NumElts != NumScalars) {
7007         V = Builder.CreateShuffleVector(V, Mask);
7008         if (auto *I = dyn_cast<Instruction>(V)) {
7009           GatherShuffleSeq.insert(I);
7010           CSEBlocks.insert(I->getParent());
7011         }
7012       }
7013 
7014       if ((!IsIdentity || Offset != 0 ||
7015            !isUndefVector(FirstInsert->getOperand(0))) &&
7016           NumElts != NumScalars) {
7017         SmallVector<int> InsertMask(NumElts);
7018         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7019         for (unsigned I = 0; I < NumElts; I++) {
7020           if (Mask[I] != UndefMaskElem)
7021             InsertMask[Offset + I] = NumElts + I;
7022         }
7023 
7024         V = Builder.CreateShuffleVector(
7025             FirstInsert->getOperand(0), V, InsertMask,
7026             cast<Instruction>(E->Scalars.back())->getName());
7027         if (auto *I = dyn_cast<Instruction>(V)) {
7028           GatherShuffleSeq.insert(I);
7029           CSEBlocks.insert(I->getParent());
7030         }
7031       }
7032 
7033       ++NumVectorInstructions;
7034       E->VectorizedValue = V;
7035       return V;
7036     }
7037     case Instruction::ZExt:
7038     case Instruction::SExt:
7039     case Instruction::FPToUI:
7040     case Instruction::FPToSI:
7041     case Instruction::FPExt:
7042     case Instruction::PtrToInt:
7043     case Instruction::IntToPtr:
7044     case Instruction::SIToFP:
7045     case Instruction::UIToFP:
7046     case Instruction::Trunc:
7047     case Instruction::FPTrunc:
7048     case Instruction::BitCast: {
7049       setInsertPointAfterBundle(E);
7050 
7051       Value *InVec = vectorizeTree(E->getOperand(0));
7052 
7053       if (E->VectorizedValue) {
7054         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7055         return E->VectorizedValue;
7056       }
7057 
7058       auto *CI = cast<CastInst>(VL0);
7059       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7060       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7061       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7062       V = ShuffleBuilder.finalize(V);
7063 
7064       E->VectorizedValue = V;
7065       ++NumVectorInstructions;
7066       return V;
7067     }
7068     case Instruction::FCmp:
7069     case Instruction::ICmp: {
7070       setInsertPointAfterBundle(E);
7071 
7072       Value *L = vectorizeTree(E->getOperand(0));
7073       Value *R = vectorizeTree(E->getOperand(1));
7074 
7075       if (E->VectorizedValue) {
7076         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7077         return E->VectorizedValue;
7078       }
7079 
7080       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7081       Value *V = Builder.CreateCmp(P0, L, R);
7082       propagateIRFlags(V, E->Scalars, VL0);
7083       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7084       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7085       V = ShuffleBuilder.finalize(V);
7086 
7087       E->VectorizedValue = V;
7088       ++NumVectorInstructions;
7089       return V;
7090     }
7091     case Instruction::Select: {
7092       setInsertPointAfterBundle(E);
7093 
7094       Value *Cond = vectorizeTree(E->getOperand(0));
7095       Value *True = vectorizeTree(E->getOperand(1));
7096       Value *False = vectorizeTree(E->getOperand(2));
7097 
7098       if (E->VectorizedValue) {
7099         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7100         return E->VectorizedValue;
7101       }
7102 
7103       Value *V = Builder.CreateSelect(Cond, True, False);
7104       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7105       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7106       V = ShuffleBuilder.finalize(V);
7107 
7108       E->VectorizedValue = V;
7109       ++NumVectorInstructions;
7110       return V;
7111     }
7112     case Instruction::FNeg: {
7113       setInsertPointAfterBundle(E);
7114 
7115       Value *Op = vectorizeTree(E->getOperand(0));
7116 
7117       if (E->VectorizedValue) {
7118         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7119         return E->VectorizedValue;
7120       }
7121 
7122       Value *V = Builder.CreateUnOp(
7123           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7124       propagateIRFlags(V, E->Scalars, VL0);
7125       if (auto *I = dyn_cast<Instruction>(V))
7126         V = propagateMetadata(I, E->Scalars);
7127 
7128       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7129       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7130       V = ShuffleBuilder.finalize(V);
7131 
7132       E->VectorizedValue = V;
7133       ++NumVectorInstructions;
7134 
7135       return V;
7136     }
7137     case Instruction::Add:
7138     case Instruction::FAdd:
7139     case Instruction::Sub:
7140     case Instruction::FSub:
7141     case Instruction::Mul:
7142     case Instruction::FMul:
7143     case Instruction::UDiv:
7144     case Instruction::SDiv:
7145     case Instruction::FDiv:
7146     case Instruction::URem:
7147     case Instruction::SRem:
7148     case Instruction::FRem:
7149     case Instruction::Shl:
7150     case Instruction::LShr:
7151     case Instruction::AShr:
7152     case Instruction::And:
7153     case Instruction::Or:
7154     case Instruction::Xor: {
7155       setInsertPointAfterBundle(E);
7156 
7157       Value *LHS = vectorizeTree(E->getOperand(0));
7158       Value *RHS = vectorizeTree(E->getOperand(1));
7159 
7160       if (E->VectorizedValue) {
7161         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7162         return E->VectorizedValue;
7163       }
7164 
7165       Value *V = Builder.CreateBinOp(
7166           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7167           RHS);
7168       propagateIRFlags(V, E->Scalars, VL0);
7169       if (auto *I = dyn_cast<Instruction>(V))
7170         V = propagateMetadata(I, E->Scalars);
7171 
7172       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7173       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7174       V = ShuffleBuilder.finalize(V);
7175 
7176       E->VectorizedValue = V;
7177       ++NumVectorInstructions;
7178 
7179       return V;
7180     }
7181     case Instruction::Load: {
7182       // Loads are inserted at the head of the tree because we don't want to
7183       // sink them all the way down past store instructions.
7184       setInsertPointAfterBundle(E);
7185 
7186       LoadInst *LI = cast<LoadInst>(VL0);
7187       Instruction *NewLI;
7188       unsigned AS = LI->getPointerAddressSpace();
7189       Value *PO = LI->getPointerOperand();
7190       if (E->State == TreeEntry::Vectorize) {
7191         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7192         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7193 
7194         // The pointer operand uses an in-tree scalar so we add the new BitCast
7195         // or LoadInst to ExternalUses list to make sure that an extract will
7196         // be generated in the future.
7197         if (TreeEntry *Entry = getTreeEntry(PO)) {
7198           // Find which lane we need to extract.
7199           unsigned FoundLane = Entry->findLaneForValue(PO);
7200           ExternalUses.emplace_back(
7201               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7202         }
7203       } else {
7204         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7205         Value *VecPtr = vectorizeTree(E->getOperand(0));
7206         // Use the minimum alignment of the gathered loads.
7207         Align CommonAlignment = LI->getAlign();
7208         for (Value *V : E->Scalars)
7209           CommonAlignment =
7210               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7211         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7212       }
7213       Value *V = propagateMetadata(NewLI, E->Scalars);
7214 
7215       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7216       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7217       V = ShuffleBuilder.finalize(V);
7218       E->VectorizedValue = V;
7219       ++NumVectorInstructions;
7220       return V;
7221     }
7222     case Instruction::Store: {
7223       auto *SI = cast<StoreInst>(VL0);
7224       unsigned AS = SI->getPointerAddressSpace();
7225 
7226       setInsertPointAfterBundle(E);
7227 
7228       Value *VecValue = vectorizeTree(E->getOperand(0));
7229       ShuffleBuilder.addMask(E->ReorderIndices);
7230       VecValue = ShuffleBuilder.finalize(VecValue);
7231 
7232       Value *ScalarPtr = SI->getPointerOperand();
7233       Value *VecPtr = Builder.CreateBitCast(
7234           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7235       StoreInst *ST =
7236           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7237 
7238       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7239       // StoreInst to ExternalUses to make sure that an extract will be
7240       // generated in the future.
7241       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7242         // Find which lane we need to extract.
7243         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7244         ExternalUses.push_back(ExternalUser(
7245             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7246             FoundLane));
7247       }
7248 
7249       Value *V = propagateMetadata(ST, E->Scalars);
7250 
7251       E->VectorizedValue = V;
7252       ++NumVectorInstructions;
7253       return V;
7254     }
7255     case Instruction::GetElementPtr: {
7256       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7257       setInsertPointAfterBundle(E);
7258 
7259       Value *Op0 = vectorizeTree(E->getOperand(0));
7260 
7261       SmallVector<Value *> OpVecs;
7262       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7263         Value *OpVec = vectorizeTree(E->getOperand(J));
7264         OpVecs.push_back(OpVec);
7265       }
7266 
7267       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7268       if (Instruction *I = dyn_cast<Instruction>(V))
7269         V = propagateMetadata(I, E->Scalars);
7270 
7271       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7272       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7273       V = ShuffleBuilder.finalize(V);
7274 
7275       E->VectorizedValue = V;
7276       ++NumVectorInstructions;
7277 
7278       return V;
7279     }
7280     case Instruction::Call: {
7281       CallInst *CI = cast<CallInst>(VL0);
7282       setInsertPointAfterBundle(E);
7283 
7284       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7285       if (Function *FI = CI->getCalledFunction())
7286         IID = FI->getIntrinsicID();
7287 
7288       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7289 
7290       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7291       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7292                           VecCallCosts.first <= VecCallCosts.second;
7293 
7294       Value *ScalarArg = nullptr;
7295       std::vector<Value *> OpVecs;
7296       SmallVector<Type *, 2> TysForDecl =
7297           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7298       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7299         ValueList OpVL;
7300         // Some intrinsics have scalar arguments. This argument should not be
7301         // vectorized.
7302         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7303           CallInst *CEI = cast<CallInst>(VL0);
7304           ScalarArg = CEI->getArgOperand(j);
7305           OpVecs.push_back(CEI->getArgOperand(j));
7306           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7307             TysForDecl.push_back(ScalarArg->getType());
7308           continue;
7309         }
7310 
7311         Value *OpVec = vectorizeTree(E->getOperand(j));
7312         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7313         OpVecs.push_back(OpVec);
7314       }
7315 
7316       Function *CF;
7317       if (!UseIntrinsic) {
7318         VFShape Shape =
7319             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7320                                   VecTy->getNumElements())),
7321                          false /*HasGlobalPred*/);
7322         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7323       } else {
7324         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7325       }
7326 
7327       SmallVector<OperandBundleDef, 1> OpBundles;
7328       CI->getOperandBundlesAsDefs(OpBundles);
7329       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7330 
7331       // The scalar argument uses an in-tree scalar so we add the new vectorized
7332       // call to ExternalUses list to make sure that an extract will be
7333       // generated in the future.
7334       if (ScalarArg) {
7335         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7336           // Find which lane we need to extract.
7337           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7338           ExternalUses.push_back(
7339               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7340         }
7341       }
7342 
7343       propagateIRFlags(V, E->Scalars, VL0);
7344       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7345       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7346       V = ShuffleBuilder.finalize(V);
7347 
7348       E->VectorizedValue = V;
7349       ++NumVectorInstructions;
7350       return V;
7351     }
7352     case Instruction::ShuffleVector: {
7353       assert(E->isAltShuffle() &&
7354              ((Instruction::isBinaryOp(E->getOpcode()) &&
7355                Instruction::isBinaryOp(E->getAltOpcode())) ||
7356               (Instruction::isCast(E->getOpcode()) &&
7357                Instruction::isCast(E->getAltOpcode())) ||
7358               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7359              "Invalid Shuffle Vector Operand");
7360 
7361       Value *LHS = nullptr, *RHS = nullptr;
7362       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7363         setInsertPointAfterBundle(E);
7364         LHS = vectorizeTree(E->getOperand(0));
7365         RHS = vectorizeTree(E->getOperand(1));
7366       } else {
7367         setInsertPointAfterBundle(E);
7368         LHS = vectorizeTree(E->getOperand(0));
7369       }
7370 
7371       if (E->VectorizedValue) {
7372         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7373         return E->VectorizedValue;
7374       }
7375 
7376       Value *V0, *V1;
7377       if (Instruction::isBinaryOp(E->getOpcode())) {
7378         V0 = Builder.CreateBinOp(
7379             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7380         V1 = Builder.CreateBinOp(
7381             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7382       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7383         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7384         auto *AltCI = cast<CmpInst>(E->getAltOp());
7385         CmpInst::Predicate AltPred = AltCI->getPredicate();
7386         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7387       } else {
7388         V0 = Builder.CreateCast(
7389             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7390         V1 = Builder.CreateCast(
7391             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7392       }
7393       // Add V0 and V1 to later analysis to try to find and remove matching
7394       // instruction, if any.
7395       for (Value *V : {V0, V1}) {
7396         if (auto *I = dyn_cast<Instruction>(V)) {
7397           GatherShuffleSeq.insert(I);
7398           CSEBlocks.insert(I->getParent());
7399         }
7400       }
7401 
7402       // Create shuffle to take alternate operations from the vector.
7403       // Also, gather up main and alt scalar ops to propagate IR flags to
7404       // each vector operation.
7405       ValueList OpScalars, AltScalars;
7406       SmallVector<int> Mask;
7407       buildShuffleEntryMask(
7408           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7409           [E](Instruction *I) {
7410             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7411             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7412           },
7413           Mask, &OpScalars, &AltScalars);
7414 
7415       propagateIRFlags(V0, OpScalars);
7416       propagateIRFlags(V1, AltScalars);
7417 
7418       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7419       if (auto *I = dyn_cast<Instruction>(V)) {
7420         V = propagateMetadata(I, E->Scalars);
7421         GatherShuffleSeq.insert(I);
7422         CSEBlocks.insert(I->getParent());
7423       }
7424       V = ShuffleBuilder.finalize(V);
7425 
7426       E->VectorizedValue = V;
7427       ++NumVectorInstructions;
7428 
7429       return V;
7430     }
7431     default:
7432     llvm_unreachable("unknown inst");
7433   }
7434   return nullptr;
7435 }
7436 
7437 Value *BoUpSLP::vectorizeTree() {
7438   ExtraValueToDebugLocsMap ExternallyUsedValues;
7439   return vectorizeTree(ExternallyUsedValues);
7440 }
7441 
7442 Value *
7443 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7444   // All blocks must be scheduled before any instructions are inserted.
7445   for (auto &BSIter : BlocksSchedules) {
7446     scheduleBlock(BSIter.second.get());
7447   }
7448 
7449   Builder.SetInsertPoint(&F->getEntryBlock().front());
7450   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7451 
7452   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7453   // vectorized root. InstCombine will then rewrite the entire expression. We
7454   // sign extend the extracted values below.
7455   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7456   if (MinBWs.count(ScalarRoot)) {
7457     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7458       // If current instr is a phi and not the last phi, insert it after the
7459       // last phi node.
7460       if (isa<PHINode>(I))
7461         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7462       else
7463         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7464     }
7465     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7466     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7467     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7468     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7469     VectorizableTree[0]->VectorizedValue = Trunc;
7470   }
7471 
7472   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7473                     << " values .\n");
7474 
7475   // Extract all of the elements with the external uses.
7476   for (const auto &ExternalUse : ExternalUses) {
7477     Value *Scalar = ExternalUse.Scalar;
7478     llvm::User *User = ExternalUse.User;
7479 
7480     // Skip users that we already RAUW. This happens when one instruction
7481     // has multiple uses of the same value.
7482     if (User && !is_contained(Scalar->users(), User))
7483       continue;
7484     TreeEntry *E = getTreeEntry(Scalar);
7485     assert(E && "Invalid scalar");
7486     assert(E->State != TreeEntry::NeedToGather &&
7487            "Extracting from a gather list");
7488 
7489     Value *Vec = E->VectorizedValue;
7490     assert(Vec && "Can't find vectorizable value");
7491 
7492     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7493     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7494       if (Scalar->getType() != Vec->getType()) {
7495         Value *Ex;
7496         // "Reuse" the existing extract to improve final codegen.
7497         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7498           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7499                                             ES->getOperand(1));
7500         } else {
7501           Ex = Builder.CreateExtractElement(Vec, Lane);
7502         }
7503         // If necessary, sign-extend or zero-extend ScalarRoot
7504         // to the larger type.
7505         if (!MinBWs.count(ScalarRoot))
7506           return Ex;
7507         if (MinBWs[ScalarRoot].second)
7508           return Builder.CreateSExt(Ex, Scalar->getType());
7509         return Builder.CreateZExt(Ex, Scalar->getType());
7510       }
7511       assert(isa<FixedVectorType>(Scalar->getType()) &&
7512              isa<InsertElementInst>(Scalar) &&
7513              "In-tree scalar of vector type is not insertelement?");
7514       return Vec;
7515     };
7516     // If User == nullptr, the Scalar is used as extra arg. Generate
7517     // ExtractElement instruction and update the record for this scalar in
7518     // ExternallyUsedValues.
7519     if (!User) {
7520       assert(ExternallyUsedValues.count(Scalar) &&
7521              "Scalar with nullptr as an external user must be registered in "
7522              "ExternallyUsedValues map");
7523       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7524         Builder.SetInsertPoint(VecI->getParent(),
7525                                std::next(VecI->getIterator()));
7526       } else {
7527         Builder.SetInsertPoint(&F->getEntryBlock().front());
7528       }
7529       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7530       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7531       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7532       auto It = ExternallyUsedValues.find(Scalar);
7533       assert(It != ExternallyUsedValues.end() &&
7534              "Externally used scalar is not found in ExternallyUsedValues");
7535       NewInstLocs.append(It->second);
7536       ExternallyUsedValues.erase(Scalar);
7537       // Required to update internally referenced instructions.
7538       Scalar->replaceAllUsesWith(NewInst);
7539       continue;
7540     }
7541 
7542     // Generate extracts for out-of-tree users.
7543     // Find the insertion point for the extractelement lane.
7544     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7545       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7546         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7547           if (PH->getIncomingValue(i) == Scalar) {
7548             Instruction *IncomingTerminator =
7549                 PH->getIncomingBlock(i)->getTerminator();
7550             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7551               Builder.SetInsertPoint(VecI->getParent(),
7552                                      std::next(VecI->getIterator()));
7553             } else {
7554               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7555             }
7556             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7557             CSEBlocks.insert(PH->getIncomingBlock(i));
7558             PH->setOperand(i, NewInst);
7559           }
7560         }
7561       } else {
7562         Builder.SetInsertPoint(cast<Instruction>(User));
7563         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7564         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7565         User->replaceUsesOfWith(Scalar, NewInst);
7566       }
7567     } else {
7568       Builder.SetInsertPoint(&F->getEntryBlock().front());
7569       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7570       CSEBlocks.insert(&F->getEntryBlock());
7571       User->replaceUsesOfWith(Scalar, NewInst);
7572     }
7573 
7574     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7575   }
7576 
7577   // For each vectorized value:
7578   for (auto &TEPtr : VectorizableTree) {
7579     TreeEntry *Entry = TEPtr.get();
7580 
7581     // No need to handle users of gathered values.
7582     if (Entry->State == TreeEntry::NeedToGather)
7583       continue;
7584 
7585     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7586 
7587     // For each lane:
7588     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7589       Value *Scalar = Entry->Scalars[Lane];
7590 
7591 #ifndef NDEBUG
7592       Type *Ty = Scalar->getType();
7593       if (!Ty->isVoidTy()) {
7594         for (User *U : Scalar->users()) {
7595           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7596 
7597           // It is legal to delete users in the ignorelist.
7598           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7599                   (isa_and_nonnull<Instruction>(U) &&
7600                    isDeleted(cast<Instruction>(U)))) &&
7601                  "Deleting out-of-tree value");
7602         }
7603       }
7604 #endif
7605       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7606       eraseInstruction(cast<Instruction>(Scalar));
7607     }
7608   }
7609 
7610   Builder.ClearInsertionPoint();
7611   InstrElementSize.clear();
7612 
7613   return VectorizableTree[0]->VectorizedValue;
7614 }
7615 
7616 void BoUpSLP::optimizeGatherSequence() {
7617   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7618                     << " gather sequences instructions.\n");
7619   // LICM InsertElementInst sequences.
7620   for (Instruction *I : GatherShuffleSeq) {
7621     if (isDeleted(I))
7622       continue;
7623 
7624     // Check if this block is inside a loop.
7625     Loop *L = LI->getLoopFor(I->getParent());
7626     if (!L)
7627       continue;
7628 
7629     // Check if it has a preheader.
7630     BasicBlock *PreHeader = L->getLoopPreheader();
7631     if (!PreHeader)
7632       continue;
7633 
7634     // If the vector or the element that we insert into it are
7635     // instructions that are defined in this basic block then we can't
7636     // hoist this instruction.
7637     if (any_of(I->operands(), [L](Value *V) {
7638           auto *OpI = dyn_cast<Instruction>(V);
7639           return OpI && L->contains(OpI);
7640         }))
7641       continue;
7642 
7643     // We can hoist this instruction. Move it to the pre-header.
7644     I->moveBefore(PreHeader->getTerminator());
7645   }
7646 
7647   // Make a list of all reachable blocks in our CSE queue.
7648   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7649   CSEWorkList.reserve(CSEBlocks.size());
7650   for (BasicBlock *BB : CSEBlocks)
7651     if (DomTreeNode *N = DT->getNode(BB)) {
7652       assert(DT->isReachableFromEntry(N));
7653       CSEWorkList.push_back(N);
7654     }
7655 
7656   // Sort blocks by domination. This ensures we visit a block after all blocks
7657   // dominating it are visited.
7658   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7659     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7660            "Different nodes should have different DFS numbers");
7661     return A->getDFSNumIn() < B->getDFSNumIn();
7662   });
7663 
7664   // Less defined shuffles can be replaced by the more defined copies.
7665   // Between two shuffles one is less defined if it has the same vector operands
7666   // and its mask indeces are the same as in the first one or undefs. E.g.
7667   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7668   // poison, <0, 0, 0, 0>.
7669   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7670                                            SmallVectorImpl<int> &NewMask) {
7671     if (I1->getType() != I2->getType())
7672       return false;
7673     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7674     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7675     if (!SI1 || !SI2)
7676       return I1->isIdenticalTo(I2);
7677     if (SI1->isIdenticalTo(SI2))
7678       return true;
7679     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7680       if (SI1->getOperand(I) != SI2->getOperand(I))
7681         return false;
7682     // Check if the second instruction is more defined than the first one.
7683     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7684     ArrayRef<int> SM1 = SI1->getShuffleMask();
7685     // Count trailing undefs in the mask to check the final number of used
7686     // registers.
7687     unsigned LastUndefsCnt = 0;
7688     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7689       if (SM1[I] == UndefMaskElem)
7690         ++LastUndefsCnt;
7691       else
7692         LastUndefsCnt = 0;
7693       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7694           NewMask[I] != SM1[I])
7695         return false;
7696       if (NewMask[I] == UndefMaskElem)
7697         NewMask[I] = SM1[I];
7698     }
7699     // Check if the last undefs actually change the final number of used vector
7700     // registers.
7701     return SM1.size() - LastUndefsCnt > 1 &&
7702            TTI->getNumberOfParts(SI1->getType()) ==
7703                TTI->getNumberOfParts(
7704                    FixedVectorType::get(SI1->getType()->getElementType(),
7705                                         SM1.size() - LastUndefsCnt));
7706   };
7707   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7708   // instructions. TODO: We can further optimize this scan if we split the
7709   // instructions into different buckets based on the insert lane.
7710   SmallVector<Instruction *, 16> Visited;
7711   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7712     assert(*I &&
7713            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7714            "Worklist not sorted properly!");
7715     BasicBlock *BB = (*I)->getBlock();
7716     // For all instructions in blocks containing gather sequences:
7717     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7718       if (isDeleted(&In))
7719         continue;
7720       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7721           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7722         continue;
7723 
7724       // Check if we can replace this instruction with any of the
7725       // visited instructions.
7726       bool Replaced = false;
7727       for (Instruction *&V : Visited) {
7728         SmallVector<int> NewMask;
7729         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7730             DT->dominates(V->getParent(), In.getParent())) {
7731           In.replaceAllUsesWith(V);
7732           eraseInstruction(&In);
7733           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7734             if (!NewMask.empty())
7735               SI->setShuffleMask(NewMask);
7736           Replaced = true;
7737           break;
7738         }
7739         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7740             GatherShuffleSeq.contains(V) &&
7741             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7742             DT->dominates(In.getParent(), V->getParent())) {
7743           In.moveAfter(V);
7744           V->replaceAllUsesWith(&In);
7745           eraseInstruction(V);
7746           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7747             if (!NewMask.empty())
7748               SI->setShuffleMask(NewMask);
7749           V = &In;
7750           Replaced = true;
7751           break;
7752         }
7753       }
7754       if (!Replaced) {
7755         assert(!is_contained(Visited, &In));
7756         Visited.push_back(&In);
7757       }
7758     }
7759   }
7760   CSEBlocks.clear();
7761   GatherShuffleSeq.clear();
7762 }
7763 
7764 BoUpSLP::ScheduleData *
7765 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7766   ScheduleData *Bundle = nullptr;
7767   ScheduleData *PrevInBundle = nullptr;
7768   for (Value *V : VL) {
7769     if (doesNotNeedToBeScheduled(V))
7770       continue;
7771     ScheduleData *BundleMember = getScheduleData(V);
7772     assert(BundleMember &&
7773            "no ScheduleData for bundle member "
7774            "(maybe not in same basic block)");
7775     assert(BundleMember->isSchedulingEntity() &&
7776            "bundle member already part of other bundle");
7777     if (PrevInBundle) {
7778       PrevInBundle->NextInBundle = BundleMember;
7779     } else {
7780       Bundle = BundleMember;
7781     }
7782 
7783     // Group the instructions to a bundle.
7784     BundleMember->FirstInBundle = Bundle;
7785     PrevInBundle = BundleMember;
7786   }
7787   assert(Bundle && "Failed to find schedule bundle");
7788   return Bundle;
7789 }
7790 
7791 // Groups the instructions to a bundle (which is then a single scheduling entity)
7792 // and schedules instructions until the bundle gets ready.
7793 Optional<BoUpSLP::ScheduleData *>
7794 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7795                                             const InstructionsState &S) {
7796   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7797   // instructions.
7798   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7799       doesNotNeedToSchedule(VL))
7800     return nullptr;
7801 
7802   // Initialize the instruction bundle.
7803   Instruction *OldScheduleEnd = ScheduleEnd;
7804   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7805 
7806   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7807                                                          ScheduleData *Bundle) {
7808     // The scheduling region got new instructions at the lower end (or it is a
7809     // new region for the first bundle). This makes it necessary to
7810     // recalculate all dependencies.
7811     // It is seldom that this needs to be done a second time after adding the
7812     // initial bundle to the region.
7813     if (ScheduleEnd != OldScheduleEnd) {
7814       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7815         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7816       ReSchedule = true;
7817     }
7818     if (Bundle) {
7819       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7820                         << " in block " << BB->getName() << "\n");
7821       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7822     }
7823 
7824     if (ReSchedule) {
7825       resetSchedule();
7826       initialFillReadyList(ReadyInsts);
7827     }
7828 
7829     // Now try to schedule the new bundle or (if no bundle) just calculate
7830     // dependencies. As soon as the bundle is "ready" it means that there are no
7831     // cyclic dependencies and we can schedule it. Note that's important that we
7832     // don't "schedule" the bundle yet (see cancelScheduling).
7833     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7834            !ReadyInsts.empty()) {
7835       ScheduleData *Picked = ReadyInsts.pop_back_val();
7836       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7837              "must be ready to schedule");
7838       schedule(Picked, ReadyInsts);
7839     }
7840   };
7841 
7842   // Make sure that the scheduling region contains all
7843   // instructions of the bundle.
7844   for (Value *V : VL) {
7845     if (doesNotNeedToBeScheduled(V))
7846       continue;
7847     if (!extendSchedulingRegion(V, S)) {
7848       // If the scheduling region got new instructions at the lower end (or it
7849       // is a new region for the first bundle). This makes it necessary to
7850       // recalculate all dependencies.
7851       // Otherwise the compiler may crash trying to incorrectly calculate
7852       // dependencies and emit instruction in the wrong order at the actual
7853       // scheduling.
7854       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7855       return None;
7856     }
7857   }
7858 
7859   bool ReSchedule = false;
7860   for (Value *V : VL) {
7861     if (doesNotNeedToBeScheduled(V))
7862       continue;
7863     ScheduleData *BundleMember = getScheduleData(V);
7864     assert(BundleMember &&
7865            "no ScheduleData for bundle member (maybe not in same basic block)");
7866 
7867     // Make sure we don't leave the pieces of the bundle in the ready list when
7868     // whole bundle might not be ready.
7869     ReadyInsts.remove(BundleMember);
7870 
7871     if (!BundleMember->IsScheduled)
7872       continue;
7873     // A bundle member was scheduled as single instruction before and now
7874     // needs to be scheduled as part of the bundle. We just get rid of the
7875     // existing schedule.
7876     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7877                       << " was already scheduled\n");
7878     ReSchedule = true;
7879   }
7880 
7881   auto *Bundle = buildBundle(VL);
7882   TryScheduleBundleImpl(ReSchedule, Bundle);
7883   if (!Bundle->isReady()) {
7884     cancelScheduling(VL, S.OpValue);
7885     return None;
7886   }
7887   return Bundle;
7888 }
7889 
7890 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7891                                                 Value *OpValue) {
7892   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7893       doesNotNeedToSchedule(VL))
7894     return;
7895 
7896   if (doesNotNeedToBeScheduled(OpValue))
7897     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7898   ScheduleData *Bundle = getScheduleData(OpValue);
7899   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7900   assert(!Bundle->IsScheduled &&
7901          "Can't cancel bundle which is already scheduled");
7902   assert(Bundle->isSchedulingEntity() &&
7903          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7904          "tried to unbundle something which is not a bundle");
7905 
7906   // Remove the bundle from the ready list.
7907   if (Bundle->isReady())
7908     ReadyInsts.remove(Bundle);
7909 
7910   // Un-bundle: make single instructions out of the bundle.
7911   ScheduleData *BundleMember = Bundle;
7912   while (BundleMember) {
7913     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7914     BundleMember->FirstInBundle = BundleMember;
7915     ScheduleData *Next = BundleMember->NextInBundle;
7916     BundleMember->NextInBundle = nullptr;
7917     BundleMember->TE = nullptr;
7918     if (BundleMember->unscheduledDepsInBundle() == 0) {
7919       ReadyInsts.insert(BundleMember);
7920     }
7921     BundleMember = Next;
7922   }
7923 }
7924 
7925 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7926   // Allocate a new ScheduleData for the instruction.
7927   if (ChunkPos >= ChunkSize) {
7928     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7929     ChunkPos = 0;
7930   }
7931   return &(ScheduleDataChunks.back()[ChunkPos++]);
7932 }
7933 
7934 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7935                                                       const InstructionsState &S) {
7936   if (getScheduleData(V, isOneOf(S, V)))
7937     return true;
7938   Instruction *I = dyn_cast<Instruction>(V);
7939   assert(I && "bundle member must be an instruction");
7940   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7941          !doesNotNeedToBeScheduled(I) &&
7942          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7943          "be scheduled");
7944   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7945     ScheduleData *ISD = getScheduleData(I);
7946     if (!ISD)
7947       return false;
7948     assert(isInSchedulingRegion(ISD) &&
7949            "ScheduleData not in scheduling region");
7950     ScheduleData *SD = allocateScheduleDataChunks();
7951     SD->Inst = I;
7952     SD->init(SchedulingRegionID, S.OpValue);
7953     ExtraScheduleDataMap[I][S.OpValue] = SD;
7954     return true;
7955   };
7956   if (CheckScheduleForI(I))
7957     return true;
7958   if (!ScheduleStart) {
7959     // It's the first instruction in the new region.
7960     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7961     ScheduleStart = I;
7962     ScheduleEnd = I->getNextNode();
7963     if (isOneOf(S, I) != I)
7964       CheckScheduleForI(I);
7965     assert(ScheduleEnd && "tried to vectorize a terminator?");
7966     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7967     return true;
7968   }
7969   // Search up and down at the same time, because we don't know if the new
7970   // instruction is above or below the existing scheduling region.
7971   BasicBlock::reverse_iterator UpIter =
7972       ++ScheduleStart->getIterator().getReverse();
7973   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7974   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7975   BasicBlock::iterator LowerEnd = BB->end();
7976   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7977          &*DownIter != I) {
7978     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7979       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7980       return false;
7981     }
7982 
7983     ++UpIter;
7984     ++DownIter;
7985   }
7986   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7987     assert(I->getParent() == ScheduleStart->getParent() &&
7988            "Instruction is in wrong basic block.");
7989     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7990     ScheduleStart = I;
7991     if (isOneOf(S, I) != I)
7992       CheckScheduleForI(I);
7993     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7994                       << "\n");
7995     return true;
7996   }
7997   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7998          "Expected to reach top of the basic block or instruction down the "
7999          "lower end.");
8000   assert(I->getParent() == ScheduleEnd->getParent() &&
8001          "Instruction is in wrong basic block.");
8002   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8003                    nullptr);
8004   ScheduleEnd = I->getNextNode();
8005   if (isOneOf(S, I) != I)
8006     CheckScheduleForI(I);
8007   assert(ScheduleEnd && "tried to vectorize a terminator?");
8008   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8009   return true;
8010 }
8011 
8012 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8013                                                 Instruction *ToI,
8014                                                 ScheduleData *PrevLoadStore,
8015                                                 ScheduleData *NextLoadStore) {
8016   ScheduleData *CurrentLoadStore = PrevLoadStore;
8017   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8018     // No need to allocate data for non-schedulable instructions.
8019     if (doesNotNeedToBeScheduled(I))
8020       continue;
8021     ScheduleData *SD = ScheduleDataMap.lookup(I);
8022     if (!SD) {
8023       SD = allocateScheduleDataChunks();
8024       ScheduleDataMap[I] = SD;
8025       SD->Inst = I;
8026     }
8027     assert(!isInSchedulingRegion(SD) &&
8028            "new ScheduleData already in scheduling region");
8029     SD->init(SchedulingRegionID, I);
8030 
8031     if (I->mayReadOrWriteMemory() &&
8032         (!isa<IntrinsicInst>(I) ||
8033          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8034           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8035               Intrinsic::pseudoprobe))) {
8036       // Update the linked list of memory accessing instructions.
8037       if (CurrentLoadStore) {
8038         CurrentLoadStore->NextLoadStore = SD;
8039       } else {
8040         FirstLoadStoreInRegion = SD;
8041       }
8042       CurrentLoadStore = SD;
8043     }
8044 
8045     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8046         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8047       RegionHasStackSave = true;
8048   }
8049   if (NextLoadStore) {
8050     if (CurrentLoadStore)
8051       CurrentLoadStore->NextLoadStore = NextLoadStore;
8052   } else {
8053     LastLoadStoreInRegion = CurrentLoadStore;
8054   }
8055 }
8056 
8057 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8058                                                      bool InsertInReadyList,
8059                                                      BoUpSLP *SLP) {
8060   assert(SD->isSchedulingEntity());
8061 
8062   SmallVector<ScheduleData *, 10> WorkList;
8063   WorkList.push_back(SD);
8064 
8065   while (!WorkList.empty()) {
8066     ScheduleData *SD = WorkList.pop_back_val();
8067     for (ScheduleData *BundleMember = SD; BundleMember;
8068          BundleMember = BundleMember->NextInBundle) {
8069       assert(isInSchedulingRegion(BundleMember));
8070       if (BundleMember->hasValidDependencies())
8071         continue;
8072 
8073       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8074                  << "\n");
8075       BundleMember->Dependencies = 0;
8076       BundleMember->resetUnscheduledDeps();
8077 
8078       // Handle def-use chain dependencies.
8079       if (BundleMember->OpValue != BundleMember->Inst) {
8080         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8081           BundleMember->Dependencies++;
8082           ScheduleData *DestBundle = UseSD->FirstInBundle;
8083           if (!DestBundle->IsScheduled)
8084             BundleMember->incrementUnscheduledDeps(1);
8085           if (!DestBundle->hasValidDependencies())
8086             WorkList.push_back(DestBundle);
8087         }
8088       } else {
8089         for (User *U : BundleMember->Inst->users()) {
8090           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8091             BundleMember->Dependencies++;
8092             ScheduleData *DestBundle = UseSD->FirstInBundle;
8093             if (!DestBundle->IsScheduled)
8094               BundleMember->incrementUnscheduledDeps(1);
8095             if (!DestBundle->hasValidDependencies())
8096               WorkList.push_back(DestBundle);
8097           }
8098         }
8099       }
8100 
8101       auto makeControlDependent = [&](Instruction *I) {
8102         auto *DepDest = getScheduleData(I);
8103         assert(DepDest && "must be in schedule window");
8104         DepDest->ControlDependencies.push_back(BundleMember);
8105         BundleMember->Dependencies++;
8106         ScheduleData *DestBundle = DepDest->FirstInBundle;
8107         if (!DestBundle->IsScheduled)
8108           BundleMember->incrementUnscheduledDeps(1);
8109         if (!DestBundle->hasValidDependencies())
8110           WorkList.push_back(DestBundle);
8111       };
8112 
8113       // Any instruction which isn't safe to speculate at the begining of the
8114       // block is control dependend on any early exit or non-willreturn call
8115       // which proceeds it.
8116       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8117         for (Instruction *I = BundleMember->Inst->getNextNode();
8118              I != ScheduleEnd; I = I->getNextNode()) {
8119           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8120             continue;
8121 
8122           // Add the dependency
8123           makeControlDependent(I);
8124 
8125           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8126             // Everything past here must be control dependent on I.
8127             break;
8128         }
8129       }
8130 
8131       if (RegionHasStackSave) {
8132         // If we have an inalloc alloca instruction, it needs to be scheduled
8133         // after any preceeding stacksave.  We also need to prevent any alloca
8134         // from reordering above a preceeding stackrestore.
8135         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8136             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8137           for (Instruction *I = BundleMember->Inst->getNextNode();
8138                I != ScheduleEnd; I = I->getNextNode()) {
8139             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8140                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8141               // Any allocas past here must be control dependent on I, and I
8142               // must be memory dependend on BundleMember->Inst.
8143               break;
8144 
8145             if (!isa<AllocaInst>(I))
8146               continue;
8147 
8148             // Add the dependency
8149             makeControlDependent(I);
8150           }
8151         }
8152 
8153         // In addition to the cases handle just above, we need to prevent
8154         // allocas from moving below a stacksave.  The stackrestore case
8155         // is currently thought to be conservatism.
8156         if (isa<AllocaInst>(BundleMember->Inst)) {
8157           for (Instruction *I = BundleMember->Inst->getNextNode();
8158                I != ScheduleEnd; I = I->getNextNode()) {
8159             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8160                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8161               continue;
8162 
8163             // Add the dependency
8164             makeControlDependent(I);
8165             break;
8166           }
8167         }
8168       }
8169 
8170       // Handle the memory dependencies (if any).
8171       ScheduleData *DepDest = BundleMember->NextLoadStore;
8172       if (!DepDest)
8173         continue;
8174       Instruction *SrcInst = BundleMember->Inst;
8175       assert(SrcInst->mayReadOrWriteMemory() &&
8176              "NextLoadStore list for non memory effecting bundle?");
8177       MemoryLocation SrcLoc = getLocation(SrcInst);
8178       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8179       unsigned numAliased = 0;
8180       unsigned DistToSrc = 1;
8181 
8182       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8183         assert(isInSchedulingRegion(DepDest));
8184 
8185         // We have two limits to reduce the complexity:
8186         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8187         //    SLP->isAliased (which is the expensive part in this loop).
8188         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8189         //    the whole loop (even if the loop is fast, it's quadratic).
8190         //    It's important for the loop break condition (see below) to
8191         //    check this limit even between two read-only instructions.
8192         if (DistToSrc >= MaxMemDepDistance ||
8193             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8194              (numAliased >= AliasedCheckLimit ||
8195               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8196 
8197           // We increment the counter only if the locations are aliased
8198           // (instead of counting all alias checks). This gives a better
8199           // balance between reduced runtime and accurate dependencies.
8200           numAliased++;
8201 
8202           DepDest->MemoryDependencies.push_back(BundleMember);
8203           BundleMember->Dependencies++;
8204           ScheduleData *DestBundle = DepDest->FirstInBundle;
8205           if (!DestBundle->IsScheduled) {
8206             BundleMember->incrementUnscheduledDeps(1);
8207           }
8208           if (!DestBundle->hasValidDependencies()) {
8209             WorkList.push_back(DestBundle);
8210           }
8211         }
8212 
8213         // Example, explaining the loop break condition: Let's assume our
8214         // starting instruction is i0 and MaxMemDepDistance = 3.
8215         //
8216         //                      +--------v--v--v
8217         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8218         //             +--------^--^--^
8219         //
8220         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8221         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8222         // Previously we already added dependencies from i3 to i6,i7,i8
8223         // (because of MaxMemDepDistance). As we added a dependency from
8224         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8225         // and we can abort this loop at i6.
8226         if (DistToSrc >= 2 * MaxMemDepDistance)
8227           break;
8228         DistToSrc++;
8229       }
8230     }
8231     if (InsertInReadyList && SD->isReady()) {
8232       ReadyInsts.insert(SD);
8233       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8234                         << "\n");
8235     }
8236   }
8237 }
8238 
8239 void BoUpSLP::BlockScheduling::resetSchedule() {
8240   assert(ScheduleStart &&
8241          "tried to reset schedule on block which has not been scheduled");
8242   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8243     doForAllOpcodes(I, [&](ScheduleData *SD) {
8244       assert(isInSchedulingRegion(SD) &&
8245              "ScheduleData not in scheduling region");
8246       SD->IsScheduled = false;
8247       SD->resetUnscheduledDeps();
8248     });
8249   }
8250   ReadyInsts.clear();
8251 }
8252 
8253 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8254   if (!BS->ScheduleStart)
8255     return;
8256 
8257   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8258 
8259   // A key point - if we got here, pre-scheduling was able to find a valid
8260   // scheduling of the sub-graph of the scheduling window which consists
8261   // of all vector bundles and their transitive users.  As such, we do not
8262   // need to reschedule anything *outside of* that subgraph.
8263 
8264   BS->resetSchedule();
8265 
8266   // For the real scheduling we use a more sophisticated ready-list: it is
8267   // sorted by the original instruction location. This lets the final schedule
8268   // be as  close as possible to the original instruction order.
8269   // WARNING: If changing this order causes a correctness issue, that means
8270   // there is some missing dependence edge in the schedule data graph.
8271   struct ScheduleDataCompare {
8272     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8273       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8274     }
8275   };
8276   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8277 
8278   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8279   // and fill the ready-list with initial instructions.
8280   int Idx = 0;
8281   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8282        I = I->getNextNode()) {
8283     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8284       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8285       (void)SDTE;
8286       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8287               SD->isPartOfBundle() ==
8288                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8289              "scheduler and vectorizer bundle mismatch");
8290       SD->FirstInBundle->SchedulingPriority = Idx++;
8291 
8292       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8293         BS->calculateDependencies(SD, false, this);
8294     });
8295   }
8296   BS->initialFillReadyList(ReadyInsts);
8297 
8298   Instruction *LastScheduledInst = BS->ScheduleEnd;
8299 
8300   // Do the "real" scheduling.
8301   while (!ReadyInsts.empty()) {
8302     ScheduleData *picked = *ReadyInsts.begin();
8303     ReadyInsts.erase(ReadyInsts.begin());
8304 
8305     // Move the scheduled instruction(s) to their dedicated places, if not
8306     // there yet.
8307     for (ScheduleData *BundleMember = picked; BundleMember;
8308          BundleMember = BundleMember->NextInBundle) {
8309       Instruction *pickedInst = BundleMember->Inst;
8310       if (pickedInst->getNextNode() != LastScheduledInst)
8311         pickedInst->moveBefore(LastScheduledInst);
8312       LastScheduledInst = pickedInst;
8313     }
8314 
8315     BS->schedule(picked, ReadyInsts);
8316   }
8317 
8318   // Check that we didn't break any of our invariants.
8319 #ifdef EXPENSIVE_CHECKS
8320   BS->verify();
8321 #endif
8322 
8323 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8324   // Check that all schedulable entities got scheduled
8325   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8326     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8327       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8328         assert(SD->IsScheduled && "must be scheduled at this point");
8329       }
8330     });
8331   }
8332 #endif
8333 
8334   // Avoid duplicate scheduling of the block.
8335   BS->ScheduleStart = nullptr;
8336 }
8337 
8338 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8339   // If V is a store, just return the width of the stored value (or value
8340   // truncated just before storing) without traversing the expression tree.
8341   // This is the common case.
8342   if (auto *Store = dyn_cast<StoreInst>(V)) {
8343     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8344       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8345     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8346   }
8347 
8348   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8349     return getVectorElementSize(IEI->getOperand(1));
8350 
8351   auto E = InstrElementSize.find(V);
8352   if (E != InstrElementSize.end())
8353     return E->second;
8354 
8355   // If V is not a store, we can traverse the expression tree to find loads
8356   // that feed it. The type of the loaded value may indicate a more suitable
8357   // width than V's type. We want to base the vector element size on the width
8358   // of memory operations where possible.
8359   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8360   SmallPtrSet<Instruction *, 16> Visited;
8361   if (auto *I = dyn_cast<Instruction>(V)) {
8362     Worklist.emplace_back(I, I->getParent());
8363     Visited.insert(I);
8364   }
8365 
8366   // Traverse the expression tree in bottom-up order looking for loads. If we
8367   // encounter an instruction we don't yet handle, we give up.
8368   auto Width = 0u;
8369   while (!Worklist.empty()) {
8370     Instruction *I;
8371     BasicBlock *Parent;
8372     std::tie(I, Parent) = Worklist.pop_back_val();
8373 
8374     // We should only be looking at scalar instructions here. If the current
8375     // instruction has a vector type, skip.
8376     auto *Ty = I->getType();
8377     if (isa<VectorType>(Ty))
8378       continue;
8379 
8380     // If the current instruction is a load, update MaxWidth to reflect the
8381     // width of the loaded value.
8382     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8383         isa<ExtractValueInst>(I))
8384       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8385 
8386     // Otherwise, we need to visit the operands of the instruction. We only
8387     // handle the interesting cases from buildTree here. If an operand is an
8388     // instruction we haven't yet visited and from the same basic block as the
8389     // user or the use is a PHI node, we add it to the worklist.
8390     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8391              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8392              isa<UnaryOperator>(I)) {
8393       for (Use &U : I->operands())
8394         if (auto *J = dyn_cast<Instruction>(U.get()))
8395           if (Visited.insert(J).second &&
8396               (isa<PHINode>(I) || J->getParent() == Parent))
8397             Worklist.emplace_back(J, J->getParent());
8398     } else {
8399       break;
8400     }
8401   }
8402 
8403   // If we didn't encounter a memory access in the expression tree, or if we
8404   // gave up for some reason, just return the width of V. Otherwise, return the
8405   // maximum width we found.
8406   if (!Width) {
8407     if (auto *CI = dyn_cast<CmpInst>(V))
8408       V = CI->getOperand(0);
8409     Width = DL->getTypeSizeInBits(V->getType());
8410   }
8411 
8412   for (Instruction *I : Visited)
8413     InstrElementSize[I] = Width;
8414 
8415   return Width;
8416 }
8417 
8418 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8419 // smaller type with a truncation. We collect the values that will be demoted
8420 // in ToDemote and additional roots that require investigating in Roots.
8421 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8422                                   SmallVectorImpl<Value *> &ToDemote,
8423                                   SmallVectorImpl<Value *> &Roots) {
8424   // We can always demote constants.
8425   if (isa<Constant>(V)) {
8426     ToDemote.push_back(V);
8427     return true;
8428   }
8429 
8430   // If the value is not an instruction in the expression with only one use, it
8431   // cannot be demoted.
8432   auto *I = dyn_cast<Instruction>(V);
8433   if (!I || !I->hasOneUse() || !Expr.count(I))
8434     return false;
8435 
8436   switch (I->getOpcode()) {
8437 
8438   // We can always demote truncations and extensions. Since truncations can
8439   // seed additional demotion, we save the truncated value.
8440   case Instruction::Trunc:
8441     Roots.push_back(I->getOperand(0));
8442     break;
8443   case Instruction::ZExt:
8444   case Instruction::SExt:
8445     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8446         isa<InsertElementInst>(I->getOperand(0)))
8447       return false;
8448     break;
8449 
8450   // We can demote certain binary operations if we can demote both of their
8451   // operands.
8452   case Instruction::Add:
8453   case Instruction::Sub:
8454   case Instruction::Mul:
8455   case Instruction::And:
8456   case Instruction::Or:
8457   case Instruction::Xor:
8458     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8459         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8460       return false;
8461     break;
8462 
8463   // We can demote selects if we can demote their true and false values.
8464   case Instruction::Select: {
8465     SelectInst *SI = cast<SelectInst>(I);
8466     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8467         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8468       return false;
8469     break;
8470   }
8471 
8472   // We can demote phis if we can demote all their incoming operands. Note that
8473   // we don't need to worry about cycles since we ensure single use above.
8474   case Instruction::PHI: {
8475     PHINode *PN = cast<PHINode>(I);
8476     for (Value *IncValue : PN->incoming_values())
8477       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8478         return false;
8479     break;
8480   }
8481 
8482   // Otherwise, conservatively give up.
8483   default:
8484     return false;
8485   }
8486 
8487   // Record the value that we can demote.
8488   ToDemote.push_back(V);
8489   return true;
8490 }
8491 
8492 void BoUpSLP::computeMinimumValueSizes() {
8493   // If there are no external uses, the expression tree must be rooted by a
8494   // store. We can't demote in-memory values, so there is nothing to do here.
8495   if (ExternalUses.empty())
8496     return;
8497 
8498   // We only attempt to truncate integer expressions.
8499   auto &TreeRoot = VectorizableTree[0]->Scalars;
8500   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8501   if (!TreeRootIT)
8502     return;
8503 
8504   // If the expression is not rooted by a store, these roots should have
8505   // external uses. We will rely on InstCombine to rewrite the expression in
8506   // the narrower type. However, InstCombine only rewrites single-use values.
8507   // This means that if a tree entry other than a root is used externally, it
8508   // must have multiple uses and InstCombine will not rewrite it. The code
8509   // below ensures that only the roots are used externally.
8510   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8511   for (auto &EU : ExternalUses)
8512     if (!Expr.erase(EU.Scalar))
8513       return;
8514   if (!Expr.empty())
8515     return;
8516 
8517   // Collect the scalar values of the vectorizable expression. We will use this
8518   // context to determine which values can be demoted. If we see a truncation,
8519   // we mark it as seeding another demotion.
8520   for (auto &EntryPtr : VectorizableTree)
8521     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8522 
8523   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8524   // have a single external user that is not in the vectorizable tree.
8525   for (auto *Root : TreeRoot)
8526     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8527       return;
8528 
8529   // Conservatively determine if we can actually truncate the roots of the
8530   // expression. Collect the values that can be demoted in ToDemote and
8531   // additional roots that require investigating in Roots.
8532   SmallVector<Value *, 32> ToDemote;
8533   SmallVector<Value *, 4> Roots;
8534   for (auto *Root : TreeRoot)
8535     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8536       return;
8537 
8538   // The maximum bit width required to represent all the values that can be
8539   // demoted without loss of precision. It would be safe to truncate the roots
8540   // of the expression to this width.
8541   auto MaxBitWidth = 8u;
8542 
8543   // We first check if all the bits of the roots are demanded. If they're not,
8544   // we can truncate the roots to this narrower type.
8545   for (auto *Root : TreeRoot) {
8546     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8547     MaxBitWidth = std::max<unsigned>(
8548         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8549   }
8550 
8551   // True if the roots can be zero-extended back to their original type, rather
8552   // than sign-extended. We know that if the leading bits are not demanded, we
8553   // can safely zero-extend. So we initialize IsKnownPositive to True.
8554   bool IsKnownPositive = true;
8555 
8556   // If all the bits of the roots are demanded, we can try a little harder to
8557   // compute a narrower type. This can happen, for example, if the roots are
8558   // getelementptr indices. InstCombine promotes these indices to the pointer
8559   // width. Thus, all their bits are technically demanded even though the
8560   // address computation might be vectorized in a smaller type.
8561   //
8562   // We start by looking at each entry that can be demoted. We compute the
8563   // maximum bit width required to store the scalar by using ValueTracking to
8564   // compute the number of high-order bits we can truncate.
8565   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8566       llvm::all_of(TreeRoot, [](Value *R) {
8567         assert(R->hasOneUse() && "Root should have only one use!");
8568         return isa<GetElementPtrInst>(R->user_back());
8569       })) {
8570     MaxBitWidth = 8u;
8571 
8572     // Determine if the sign bit of all the roots is known to be zero. If not,
8573     // IsKnownPositive is set to False.
8574     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8575       KnownBits Known = computeKnownBits(R, *DL);
8576       return Known.isNonNegative();
8577     });
8578 
8579     // Determine the maximum number of bits required to store the scalar
8580     // values.
8581     for (auto *Scalar : ToDemote) {
8582       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8583       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8584       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8585     }
8586 
8587     // If we can't prove that the sign bit is zero, we must add one to the
8588     // maximum bit width to account for the unknown sign bit. This preserves
8589     // the existing sign bit so we can safely sign-extend the root back to the
8590     // original type. Otherwise, if we know the sign bit is zero, we will
8591     // zero-extend the root instead.
8592     //
8593     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8594     //        one to the maximum bit width will yield a larger-than-necessary
8595     //        type. In general, we need to add an extra bit only if we can't
8596     //        prove that the upper bit of the original type is equal to the
8597     //        upper bit of the proposed smaller type. If these two bits are the
8598     //        same (either zero or one) we know that sign-extending from the
8599     //        smaller type will result in the same value. Here, since we can't
8600     //        yet prove this, we are just making the proposed smaller type
8601     //        larger to ensure correctness.
8602     if (!IsKnownPositive)
8603       ++MaxBitWidth;
8604   }
8605 
8606   // Round MaxBitWidth up to the next power-of-two.
8607   if (!isPowerOf2_64(MaxBitWidth))
8608     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8609 
8610   // If the maximum bit width we compute is less than the with of the roots'
8611   // type, we can proceed with the narrowing. Otherwise, do nothing.
8612   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8613     return;
8614 
8615   // If we can truncate the root, we must collect additional values that might
8616   // be demoted as a result. That is, those seeded by truncations we will
8617   // modify.
8618   while (!Roots.empty())
8619     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8620 
8621   // Finally, map the values we can demote to the maximum bit with we computed.
8622   for (auto *Scalar : ToDemote)
8623     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8624 }
8625 
8626 namespace {
8627 
8628 /// The SLPVectorizer Pass.
8629 struct SLPVectorizer : public FunctionPass {
8630   SLPVectorizerPass Impl;
8631 
8632   /// Pass identification, replacement for typeid
8633   static char ID;
8634 
8635   explicit SLPVectorizer() : FunctionPass(ID) {
8636     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8637   }
8638 
8639   bool doInitialization(Module &M) override { return false; }
8640 
8641   bool runOnFunction(Function &F) override {
8642     if (skipFunction(F))
8643       return false;
8644 
8645     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8646     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8647     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8648     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8649     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8650     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8651     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8652     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8653     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8654     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8655 
8656     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8657   }
8658 
8659   void getAnalysisUsage(AnalysisUsage &AU) const override {
8660     FunctionPass::getAnalysisUsage(AU);
8661     AU.addRequired<AssumptionCacheTracker>();
8662     AU.addRequired<ScalarEvolutionWrapperPass>();
8663     AU.addRequired<AAResultsWrapperPass>();
8664     AU.addRequired<TargetTransformInfoWrapperPass>();
8665     AU.addRequired<LoopInfoWrapperPass>();
8666     AU.addRequired<DominatorTreeWrapperPass>();
8667     AU.addRequired<DemandedBitsWrapperPass>();
8668     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8669     AU.addRequired<InjectTLIMappingsLegacy>();
8670     AU.addPreserved<LoopInfoWrapperPass>();
8671     AU.addPreserved<DominatorTreeWrapperPass>();
8672     AU.addPreserved<AAResultsWrapperPass>();
8673     AU.addPreserved<GlobalsAAWrapperPass>();
8674     AU.setPreservesCFG();
8675   }
8676 };
8677 
8678 } // end anonymous namespace
8679 
8680 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8681   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8682   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8683   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8684   auto *AA = &AM.getResult<AAManager>(F);
8685   auto *LI = &AM.getResult<LoopAnalysis>(F);
8686   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8687   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8688   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8689   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8690 
8691   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8692   if (!Changed)
8693     return PreservedAnalyses::all();
8694 
8695   PreservedAnalyses PA;
8696   PA.preserveSet<CFGAnalyses>();
8697   return PA;
8698 }
8699 
8700 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8701                                 TargetTransformInfo *TTI_,
8702                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8703                                 LoopInfo *LI_, DominatorTree *DT_,
8704                                 AssumptionCache *AC_, DemandedBits *DB_,
8705                                 OptimizationRemarkEmitter *ORE_) {
8706   if (!RunSLPVectorization)
8707     return false;
8708   SE = SE_;
8709   TTI = TTI_;
8710   TLI = TLI_;
8711   AA = AA_;
8712   LI = LI_;
8713   DT = DT_;
8714   AC = AC_;
8715   DB = DB_;
8716   DL = &F.getParent()->getDataLayout();
8717 
8718   Stores.clear();
8719   GEPs.clear();
8720   bool Changed = false;
8721 
8722   // If the target claims to have no vector registers don't attempt
8723   // vectorization.
8724   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8725     LLVM_DEBUG(
8726         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8727     return false;
8728   }
8729 
8730   // Don't vectorize when the attribute NoImplicitFloat is used.
8731   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8732     return false;
8733 
8734   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8735 
8736   // Use the bottom up slp vectorizer to construct chains that start with
8737   // store instructions.
8738   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8739 
8740   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8741   // delete instructions.
8742 
8743   // Update DFS numbers now so that we can use them for ordering.
8744   DT->updateDFSNumbers();
8745 
8746   // Scan the blocks in the function in post order.
8747   for (auto BB : post_order(&F.getEntryBlock())) {
8748     collectSeedInstructions(BB);
8749 
8750     // Vectorize trees that end at stores.
8751     if (!Stores.empty()) {
8752       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8753                         << " underlying objects.\n");
8754       Changed |= vectorizeStoreChains(R);
8755     }
8756 
8757     // Vectorize trees that end at reductions.
8758     Changed |= vectorizeChainsInBlock(BB, R);
8759 
8760     // Vectorize the index computations of getelementptr instructions. This
8761     // is primarily intended to catch gather-like idioms ending at
8762     // non-consecutive loads.
8763     if (!GEPs.empty()) {
8764       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8765                         << " underlying objects.\n");
8766       Changed |= vectorizeGEPIndices(BB, R);
8767     }
8768   }
8769 
8770   if (Changed) {
8771     R.optimizeGatherSequence();
8772     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8773   }
8774   return Changed;
8775 }
8776 
8777 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8778                                             unsigned Idx) {
8779   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8780                     << "\n");
8781   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8782   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8783   unsigned VF = Chain.size();
8784 
8785   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8786     return false;
8787 
8788   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8789                     << "\n");
8790 
8791   R.buildTree(Chain);
8792   if (R.isTreeTinyAndNotFullyVectorizable())
8793     return false;
8794   if (R.isLoadCombineCandidate())
8795     return false;
8796   R.reorderTopToBottom();
8797   R.reorderBottomToTop();
8798   R.buildExternalUses();
8799 
8800   R.computeMinimumValueSizes();
8801 
8802   InstructionCost Cost = R.getTreeCost();
8803 
8804   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8805   if (Cost < -SLPCostThreshold) {
8806     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8807 
8808     using namespace ore;
8809 
8810     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8811                                         cast<StoreInst>(Chain[0]))
8812                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8813                      << " and with tree size "
8814                      << NV("TreeSize", R.getTreeSize()));
8815 
8816     R.vectorizeTree();
8817     return true;
8818   }
8819 
8820   return false;
8821 }
8822 
8823 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8824                                         BoUpSLP &R) {
8825   // We may run into multiple chains that merge into a single chain. We mark the
8826   // stores that we vectorized so that we don't visit the same store twice.
8827   BoUpSLP::ValueSet VectorizedStores;
8828   bool Changed = false;
8829 
8830   int E = Stores.size();
8831   SmallBitVector Tails(E, false);
8832   int MaxIter = MaxStoreLookup.getValue();
8833   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8834       E, std::make_pair(E, INT_MAX));
8835   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8836   int IterCnt;
8837   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8838                                   &CheckedPairs,
8839                                   &ConsecutiveChain](int K, int Idx) {
8840     if (IterCnt >= MaxIter)
8841       return true;
8842     if (CheckedPairs[Idx].test(K))
8843       return ConsecutiveChain[K].second == 1 &&
8844              ConsecutiveChain[K].first == Idx;
8845     ++IterCnt;
8846     CheckedPairs[Idx].set(K);
8847     CheckedPairs[K].set(Idx);
8848     Optional<int> Diff = getPointersDiff(
8849         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8850         Stores[Idx]->getValueOperand()->getType(),
8851         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8852     if (!Diff || *Diff == 0)
8853       return false;
8854     int Val = *Diff;
8855     if (Val < 0) {
8856       if (ConsecutiveChain[Idx].second > -Val) {
8857         Tails.set(K);
8858         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8859       }
8860       return false;
8861     }
8862     if (ConsecutiveChain[K].second <= Val)
8863       return false;
8864 
8865     Tails.set(Idx);
8866     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8867     return Val == 1;
8868   };
8869   // Do a quadratic search on all of the given stores in reverse order and find
8870   // all of the pairs of stores that follow each other.
8871   for (int Idx = E - 1; Idx >= 0; --Idx) {
8872     // If a store has multiple consecutive store candidates, search according
8873     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8874     // This is because usually pairing with immediate succeeding or preceding
8875     // candidate create the best chance to find slp vectorization opportunity.
8876     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8877     IterCnt = 0;
8878     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8879       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8880           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8881         break;
8882   }
8883 
8884   // Tracks if we tried to vectorize stores starting from the given tail
8885   // already.
8886   SmallBitVector TriedTails(E, false);
8887   // For stores that start but don't end a link in the chain:
8888   for (int Cnt = E; Cnt > 0; --Cnt) {
8889     int I = Cnt - 1;
8890     if (ConsecutiveChain[I].first == E || Tails.test(I))
8891       continue;
8892     // We found a store instr that starts a chain. Now follow the chain and try
8893     // to vectorize it.
8894     BoUpSLP::ValueList Operands;
8895     // Collect the chain into a list.
8896     while (I != E && !VectorizedStores.count(Stores[I])) {
8897       Operands.push_back(Stores[I]);
8898       Tails.set(I);
8899       if (ConsecutiveChain[I].second != 1) {
8900         // Mark the new end in the chain and go back, if required. It might be
8901         // required if the original stores come in reversed order, for example.
8902         if (ConsecutiveChain[I].first != E &&
8903             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8904             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8905           TriedTails.set(I);
8906           Tails.reset(ConsecutiveChain[I].first);
8907           if (Cnt < ConsecutiveChain[I].first + 2)
8908             Cnt = ConsecutiveChain[I].first + 2;
8909         }
8910         break;
8911       }
8912       // Move to the next value in the chain.
8913       I = ConsecutiveChain[I].first;
8914     }
8915     assert(!Operands.empty() && "Expected non-empty list of stores.");
8916 
8917     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8918     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8919     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8920 
8921     unsigned MinVF = R.getMinVF(EltSize);
8922     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8923                               MaxElts);
8924 
8925     // FIXME: Is division-by-2 the correct step? Should we assert that the
8926     // register size is a power-of-2?
8927     unsigned StartIdx = 0;
8928     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8929       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8930         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8931         if (!VectorizedStores.count(Slice.front()) &&
8932             !VectorizedStores.count(Slice.back()) &&
8933             vectorizeStoreChain(Slice, R, Cnt)) {
8934           // Mark the vectorized stores so that we don't vectorize them again.
8935           VectorizedStores.insert(Slice.begin(), Slice.end());
8936           Changed = true;
8937           // If we vectorized initial block, no need to try to vectorize it
8938           // again.
8939           if (Cnt == StartIdx)
8940             StartIdx += Size;
8941           Cnt += Size;
8942           continue;
8943         }
8944         ++Cnt;
8945       }
8946       // Check if the whole array was vectorized already - exit.
8947       if (StartIdx >= Operands.size())
8948         break;
8949     }
8950   }
8951 
8952   return Changed;
8953 }
8954 
8955 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8956   // Initialize the collections. We will make a single pass over the block.
8957   Stores.clear();
8958   GEPs.clear();
8959 
8960   // Visit the store and getelementptr instructions in BB and organize them in
8961   // Stores and GEPs according to the underlying objects of their pointer
8962   // operands.
8963   for (Instruction &I : *BB) {
8964     // Ignore store instructions that are volatile or have a pointer operand
8965     // that doesn't point to a scalar type.
8966     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8967       if (!SI->isSimple())
8968         continue;
8969       if (!isValidElementType(SI->getValueOperand()->getType()))
8970         continue;
8971       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8972     }
8973 
8974     // Ignore getelementptr instructions that have more than one index, a
8975     // constant index, or a pointer operand that doesn't point to a scalar
8976     // type.
8977     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8978       auto Idx = GEP->idx_begin()->get();
8979       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8980         continue;
8981       if (!isValidElementType(Idx->getType()))
8982         continue;
8983       if (GEP->getType()->isVectorTy())
8984         continue;
8985       GEPs[GEP->getPointerOperand()].push_back(GEP);
8986     }
8987   }
8988 }
8989 
8990 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8991   if (!A || !B)
8992     return false;
8993   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8994     return false;
8995   Value *VL[] = {A, B};
8996   return tryToVectorizeList(VL, R);
8997 }
8998 
8999 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9000                                            bool LimitForRegisterSize) {
9001   if (VL.size() < 2)
9002     return false;
9003 
9004   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9005                     << VL.size() << ".\n");
9006 
9007   // Check that all of the parts are instructions of the same type,
9008   // we permit an alternate opcode via InstructionsState.
9009   InstructionsState S = getSameOpcode(VL);
9010   if (!S.getOpcode())
9011     return false;
9012 
9013   Instruction *I0 = cast<Instruction>(S.OpValue);
9014   // Make sure invalid types (including vector type) are rejected before
9015   // determining vectorization factor for scalar instructions.
9016   for (Value *V : VL) {
9017     Type *Ty = V->getType();
9018     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9019       // NOTE: the following will give user internal llvm type name, which may
9020       // not be useful.
9021       R.getORE()->emit([&]() {
9022         std::string type_str;
9023         llvm::raw_string_ostream rso(type_str);
9024         Ty->print(rso);
9025         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9026                << "Cannot SLP vectorize list: type "
9027                << rso.str() + " is unsupported by vectorizer";
9028       });
9029       return false;
9030     }
9031   }
9032 
9033   unsigned Sz = R.getVectorElementSize(I0);
9034   unsigned MinVF = R.getMinVF(Sz);
9035   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9036   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9037   if (MaxVF < 2) {
9038     R.getORE()->emit([&]() {
9039       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9040              << "Cannot SLP vectorize list: vectorization factor "
9041              << "less than 2 is not supported";
9042     });
9043     return false;
9044   }
9045 
9046   bool Changed = false;
9047   bool CandidateFound = false;
9048   InstructionCost MinCost = SLPCostThreshold.getValue();
9049   Type *ScalarTy = VL[0]->getType();
9050   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9051     ScalarTy = IE->getOperand(1)->getType();
9052 
9053   unsigned NextInst = 0, MaxInst = VL.size();
9054   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9055     // No actual vectorization should happen, if number of parts is the same as
9056     // provided vectorization factor (i.e. the scalar type is used for vector
9057     // code during codegen).
9058     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9059     if (TTI->getNumberOfParts(VecTy) == VF)
9060       continue;
9061     for (unsigned I = NextInst; I < MaxInst; ++I) {
9062       unsigned OpsWidth = 0;
9063 
9064       if (I + VF > MaxInst)
9065         OpsWidth = MaxInst - I;
9066       else
9067         OpsWidth = VF;
9068 
9069       if (!isPowerOf2_32(OpsWidth))
9070         continue;
9071 
9072       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9073           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9074         break;
9075 
9076       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9077       // Check that a previous iteration of this loop did not delete the Value.
9078       if (llvm::any_of(Ops, [&R](Value *V) {
9079             auto *I = dyn_cast<Instruction>(V);
9080             return I && R.isDeleted(I);
9081           }))
9082         continue;
9083 
9084       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9085                         << "\n");
9086 
9087       R.buildTree(Ops);
9088       if (R.isTreeTinyAndNotFullyVectorizable())
9089         continue;
9090       R.reorderTopToBottom();
9091       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9092       R.buildExternalUses();
9093 
9094       R.computeMinimumValueSizes();
9095       InstructionCost Cost = R.getTreeCost();
9096       CandidateFound = true;
9097       MinCost = std::min(MinCost, Cost);
9098 
9099       if (Cost < -SLPCostThreshold) {
9100         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9101         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9102                                                     cast<Instruction>(Ops[0]))
9103                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9104                                  << " and with tree size "
9105                                  << ore::NV("TreeSize", R.getTreeSize()));
9106 
9107         R.vectorizeTree();
9108         // Move to the next bundle.
9109         I += VF - 1;
9110         NextInst = I + 1;
9111         Changed = true;
9112       }
9113     }
9114   }
9115 
9116   if (!Changed && CandidateFound) {
9117     R.getORE()->emit([&]() {
9118       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9119              << "List vectorization was possible but not beneficial with cost "
9120              << ore::NV("Cost", MinCost) << " >= "
9121              << ore::NV("Treshold", -SLPCostThreshold);
9122     });
9123   } else if (!Changed) {
9124     R.getORE()->emit([&]() {
9125       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9126              << "Cannot SLP vectorize list: vectorization was impossible"
9127              << " with available vectorization factors";
9128     });
9129   }
9130   return Changed;
9131 }
9132 
9133 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9134   if (!I)
9135     return false;
9136 
9137   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9138     return false;
9139 
9140   Value *P = I->getParent();
9141 
9142   // Vectorize in current basic block only.
9143   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9144   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9145   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9146     return false;
9147 
9148   // Try to vectorize V.
9149   if (tryToVectorizePair(Op0, Op1, R))
9150     return true;
9151 
9152   auto *A = dyn_cast<BinaryOperator>(Op0);
9153   auto *B = dyn_cast<BinaryOperator>(Op1);
9154   // Try to skip B.
9155   if (B && B->hasOneUse()) {
9156     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9157     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9158     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9159       return true;
9160     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9161       return true;
9162   }
9163 
9164   // Try to skip A.
9165   if (A && A->hasOneUse()) {
9166     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9167     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9168     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9169       return true;
9170     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9171       return true;
9172   }
9173   return false;
9174 }
9175 
9176 namespace {
9177 
9178 /// Model horizontal reductions.
9179 ///
9180 /// A horizontal reduction is a tree of reduction instructions that has values
9181 /// that can be put into a vector as its leaves. For example:
9182 ///
9183 /// mul mul mul mul
9184 ///  \  /    \  /
9185 ///   +       +
9186 ///    \     /
9187 ///       +
9188 /// This tree has "mul" as its leaf values and "+" as its reduction
9189 /// instructions. A reduction can feed into a store or a binary operation
9190 /// feeding a phi.
9191 ///    ...
9192 ///    \  /
9193 ///     +
9194 ///     |
9195 ///  phi +=
9196 ///
9197 ///  Or:
9198 ///    ...
9199 ///    \  /
9200 ///     +
9201 ///     |
9202 ///   *p =
9203 ///
9204 class HorizontalReduction {
9205   using ReductionOpsType = SmallVector<Value *, 16>;
9206   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9207   ReductionOpsListType ReductionOps;
9208   SmallVector<Value *, 32> ReducedVals;
9209   // Use map vector to make stable output.
9210   MapVector<Instruction *, Value *> ExtraArgs;
9211   WeakTrackingVH ReductionRoot;
9212   /// The type of reduction operation.
9213   RecurKind RdxKind;
9214 
9215   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9216 
9217   static bool isCmpSelMinMax(Instruction *I) {
9218     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9219            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9220   }
9221 
9222   // And/or are potentially poison-safe logical patterns like:
9223   // select x, y, false
9224   // select x, true, y
9225   static bool isBoolLogicOp(Instruction *I) {
9226     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9227            match(I, m_LogicalOr(m_Value(), m_Value()));
9228   }
9229 
9230   /// Checks if instruction is associative and can be vectorized.
9231   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9232     if (Kind == RecurKind::None)
9233       return false;
9234 
9235     // Integer ops that map to select instructions or intrinsics are fine.
9236     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9237         isBoolLogicOp(I))
9238       return true;
9239 
9240     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9241       // FP min/max are associative except for NaN and -0.0. We do not
9242       // have to rule out -0.0 here because the intrinsic semantics do not
9243       // specify a fixed result for it.
9244       return I->getFastMathFlags().noNaNs();
9245     }
9246 
9247     return I->isAssociative();
9248   }
9249 
9250   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9251     // Poison-safe 'or' takes the form: select X, true, Y
9252     // To make that work with the normal operand processing, we skip the
9253     // true value operand.
9254     // TODO: Change the code and data structures to handle this without a hack.
9255     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9256       return I->getOperand(2);
9257     return I->getOperand(Index);
9258   }
9259 
9260   /// Checks if the ParentStackElem.first should be marked as a reduction
9261   /// operation with an extra argument or as extra argument itself.
9262   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9263                     Value *ExtraArg) {
9264     if (ExtraArgs.count(ParentStackElem.first)) {
9265       ExtraArgs[ParentStackElem.first] = nullptr;
9266       // We ran into something like:
9267       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9268       // The whole ParentStackElem.first should be considered as an extra value
9269       // in this case.
9270       // Do not perform analysis of remaining operands of ParentStackElem.first
9271       // instruction, this whole instruction is an extra argument.
9272       ParentStackElem.second = INVALID_OPERAND_INDEX;
9273     } else {
9274       // We ran into something like:
9275       // ParentStackElem.first += ... + ExtraArg + ...
9276       ExtraArgs[ParentStackElem.first] = ExtraArg;
9277     }
9278   }
9279 
9280   /// Creates reduction operation with the current opcode.
9281   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9282                          Value *RHS, const Twine &Name, bool UseSelect) {
9283     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9284     switch (Kind) {
9285     case RecurKind::Or:
9286       if (UseSelect &&
9287           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9288         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9289       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9290                                  Name);
9291     case RecurKind::And:
9292       if (UseSelect &&
9293           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9294         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9295       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9296                                  Name);
9297     case RecurKind::Add:
9298     case RecurKind::Mul:
9299     case RecurKind::Xor:
9300     case RecurKind::FAdd:
9301     case RecurKind::FMul:
9302       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9303                                  Name);
9304     case RecurKind::FMax:
9305       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9306     case RecurKind::FMin:
9307       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9308     case RecurKind::SMax:
9309       if (UseSelect) {
9310         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9311         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9312       }
9313       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9314     case RecurKind::SMin:
9315       if (UseSelect) {
9316         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9317         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9318       }
9319       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9320     case RecurKind::UMax:
9321       if (UseSelect) {
9322         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9323         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9324       }
9325       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9326     case RecurKind::UMin:
9327       if (UseSelect) {
9328         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9329         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9330       }
9331       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9332     default:
9333       llvm_unreachable("Unknown reduction operation.");
9334     }
9335   }
9336 
9337   /// Creates reduction operation with the current opcode with the IR flags
9338   /// from \p ReductionOps.
9339   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9340                          Value *RHS, const Twine &Name,
9341                          const ReductionOpsListType &ReductionOps) {
9342     bool UseSelect = ReductionOps.size() == 2 ||
9343                      // Logical or/and.
9344                      (ReductionOps.size() == 1 &&
9345                       isa<SelectInst>(ReductionOps.front().front()));
9346     assert((!UseSelect || ReductionOps.size() != 2 ||
9347             isa<SelectInst>(ReductionOps[1][0])) &&
9348            "Expected cmp + select pairs for reduction");
9349     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9350     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9351       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9352         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9353         propagateIRFlags(Op, ReductionOps[1]);
9354         return Op;
9355       }
9356     }
9357     propagateIRFlags(Op, ReductionOps[0]);
9358     return Op;
9359   }
9360 
9361   /// Creates reduction operation with the current opcode with the IR flags
9362   /// from \p I.
9363   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9364                          Value *RHS, const Twine &Name, Instruction *I) {
9365     auto *SelI = dyn_cast<SelectInst>(I);
9366     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9367     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9368       if (auto *Sel = dyn_cast<SelectInst>(Op))
9369         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9370     }
9371     propagateIRFlags(Op, I);
9372     return Op;
9373   }
9374 
9375   static RecurKind getRdxKind(Instruction *I) {
9376     assert(I && "Expected instruction for reduction matching");
9377     if (match(I, m_Add(m_Value(), m_Value())))
9378       return RecurKind::Add;
9379     if (match(I, m_Mul(m_Value(), m_Value())))
9380       return RecurKind::Mul;
9381     if (match(I, m_And(m_Value(), m_Value())) ||
9382         match(I, m_LogicalAnd(m_Value(), m_Value())))
9383       return RecurKind::And;
9384     if (match(I, m_Or(m_Value(), m_Value())) ||
9385         match(I, m_LogicalOr(m_Value(), m_Value())))
9386       return RecurKind::Or;
9387     if (match(I, m_Xor(m_Value(), m_Value())))
9388       return RecurKind::Xor;
9389     if (match(I, m_FAdd(m_Value(), m_Value())))
9390       return RecurKind::FAdd;
9391     if (match(I, m_FMul(m_Value(), m_Value())))
9392       return RecurKind::FMul;
9393 
9394     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9395       return RecurKind::FMax;
9396     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9397       return RecurKind::FMin;
9398 
9399     // This matches either cmp+select or intrinsics. SLP is expected to handle
9400     // either form.
9401     // TODO: If we are canonicalizing to intrinsics, we can remove several
9402     //       special-case paths that deal with selects.
9403     if (match(I, m_SMax(m_Value(), m_Value())))
9404       return RecurKind::SMax;
9405     if (match(I, m_SMin(m_Value(), m_Value())))
9406       return RecurKind::SMin;
9407     if (match(I, m_UMax(m_Value(), m_Value())))
9408       return RecurKind::UMax;
9409     if (match(I, m_UMin(m_Value(), m_Value())))
9410       return RecurKind::UMin;
9411 
9412     if (auto *Select = dyn_cast<SelectInst>(I)) {
9413       // Try harder: look for min/max pattern based on instructions producing
9414       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9415       // During the intermediate stages of SLP, it's very common to have
9416       // pattern like this (since optimizeGatherSequence is run only once
9417       // at the end):
9418       // %1 = extractelement <2 x i32> %a, i32 0
9419       // %2 = extractelement <2 x i32> %a, i32 1
9420       // %cond = icmp sgt i32 %1, %2
9421       // %3 = extractelement <2 x i32> %a, i32 0
9422       // %4 = extractelement <2 x i32> %a, i32 1
9423       // %select = select i1 %cond, i32 %3, i32 %4
9424       CmpInst::Predicate Pred;
9425       Instruction *L1;
9426       Instruction *L2;
9427 
9428       Value *LHS = Select->getTrueValue();
9429       Value *RHS = Select->getFalseValue();
9430       Value *Cond = Select->getCondition();
9431 
9432       // TODO: Support inverse predicates.
9433       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9434         if (!isa<ExtractElementInst>(RHS) ||
9435             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9436           return RecurKind::None;
9437       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9438         if (!isa<ExtractElementInst>(LHS) ||
9439             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9440           return RecurKind::None;
9441       } else {
9442         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9443           return RecurKind::None;
9444         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9445             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9446             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9447           return RecurKind::None;
9448       }
9449 
9450       switch (Pred) {
9451       default:
9452         return RecurKind::None;
9453       case CmpInst::ICMP_SGT:
9454       case CmpInst::ICMP_SGE:
9455         return RecurKind::SMax;
9456       case CmpInst::ICMP_SLT:
9457       case CmpInst::ICMP_SLE:
9458         return RecurKind::SMin;
9459       case CmpInst::ICMP_UGT:
9460       case CmpInst::ICMP_UGE:
9461         return RecurKind::UMax;
9462       case CmpInst::ICMP_ULT:
9463       case CmpInst::ICMP_ULE:
9464         return RecurKind::UMin;
9465       }
9466     }
9467     return RecurKind::None;
9468   }
9469 
9470   /// Get the index of the first operand.
9471   static unsigned getFirstOperandIndex(Instruction *I) {
9472     return isCmpSelMinMax(I) ? 1 : 0;
9473   }
9474 
9475   /// Total number of operands in the reduction operation.
9476   static unsigned getNumberOfOperands(Instruction *I) {
9477     return isCmpSelMinMax(I) ? 3 : 2;
9478   }
9479 
9480   /// Checks if the instruction is in basic block \p BB.
9481   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9482   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9483     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9484       auto *Sel = cast<SelectInst>(I);
9485       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9486       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9487     }
9488     return I->getParent() == BB;
9489   }
9490 
9491   /// Expected number of uses for reduction operations/reduced values.
9492   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9493     if (IsCmpSelMinMax) {
9494       // SelectInst must be used twice while the condition op must have single
9495       // use only.
9496       if (auto *Sel = dyn_cast<SelectInst>(I))
9497         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9498       return I->hasNUses(2);
9499     }
9500 
9501     // Arithmetic reduction operation must be used once only.
9502     return I->hasOneUse();
9503   }
9504 
9505   /// Initializes the list of reduction operations.
9506   void initReductionOps(Instruction *I) {
9507     if (isCmpSelMinMax(I))
9508       ReductionOps.assign(2, ReductionOpsType());
9509     else
9510       ReductionOps.assign(1, ReductionOpsType());
9511   }
9512 
9513   /// Add all reduction operations for the reduction instruction \p I.
9514   void addReductionOps(Instruction *I) {
9515     if (isCmpSelMinMax(I)) {
9516       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9517       ReductionOps[1].emplace_back(I);
9518     } else {
9519       ReductionOps[0].emplace_back(I);
9520     }
9521   }
9522 
9523   static Value *getLHS(RecurKind Kind, Instruction *I) {
9524     if (Kind == RecurKind::None)
9525       return nullptr;
9526     return I->getOperand(getFirstOperandIndex(I));
9527   }
9528   static Value *getRHS(RecurKind Kind, Instruction *I) {
9529     if (Kind == RecurKind::None)
9530       return nullptr;
9531     return I->getOperand(getFirstOperandIndex(I) + 1);
9532   }
9533 
9534 public:
9535   HorizontalReduction() = default;
9536 
9537   /// Try to find a reduction tree.
9538   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9539     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9540            "Phi needs to use the binary operator");
9541     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9542             isa<IntrinsicInst>(Inst)) &&
9543            "Expected binop, select, or intrinsic for reduction matching");
9544     RdxKind = getRdxKind(Inst);
9545 
9546     // We could have a initial reductions that is not an add.
9547     //  r *= v1 + v2 + v3 + v4
9548     // In such a case start looking for a tree rooted in the first '+'.
9549     if (Phi) {
9550       if (getLHS(RdxKind, Inst) == Phi) {
9551         Phi = nullptr;
9552         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9553         if (!Inst)
9554           return false;
9555         RdxKind = getRdxKind(Inst);
9556       } else if (getRHS(RdxKind, Inst) == Phi) {
9557         Phi = nullptr;
9558         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9559         if (!Inst)
9560           return false;
9561         RdxKind = getRdxKind(Inst);
9562       }
9563     }
9564 
9565     if (!isVectorizable(RdxKind, Inst))
9566       return false;
9567 
9568     // Analyze "regular" integer/FP types for reductions - no target-specific
9569     // types or pointers.
9570     Type *Ty = Inst->getType();
9571     if (!isValidElementType(Ty) || Ty->isPointerTy())
9572       return false;
9573 
9574     // Though the ultimate reduction may have multiple uses, its condition must
9575     // have only single use.
9576     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9577       if (!Sel->getCondition()->hasOneUse())
9578         return false;
9579 
9580     ReductionRoot = Inst;
9581 
9582     // The opcode for leaf values that we perform a reduction on.
9583     // For example: load(x) + load(y) + load(z) + fptoui(w)
9584     // The leaf opcode for 'w' does not match, so we don't include it as a
9585     // potential candidate for the reduction.
9586     unsigned LeafOpcode = 0;
9587 
9588     // Post-order traverse the reduction tree starting at Inst. We only handle
9589     // true trees containing binary operators or selects.
9590     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9591     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9592     initReductionOps(Inst);
9593     while (!Stack.empty()) {
9594       Instruction *TreeN = Stack.back().first;
9595       unsigned EdgeToVisit = Stack.back().second++;
9596       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9597       bool IsReducedValue = TreeRdxKind != RdxKind;
9598 
9599       // Postorder visit.
9600       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9601         if (IsReducedValue)
9602           ReducedVals.push_back(TreeN);
9603         else {
9604           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9605           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9606             // Check if TreeN is an extra argument of its parent operation.
9607             if (Stack.size() <= 1) {
9608               // TreeN can't be an extra argument as it is a root reduction
9609               // operation.
9610               return false;
9611             }
9612             // Yes, TreeN is an extra argument, do not add it to a list of
9613             // reduction operations.
9614             // Stack[Stack.size() - 2] always points to the parent operation.
9615             markExtraArg(Stack[Stack.size() - 2], TreeN);
9616             ExtraArgs.erase(TreeN);
9617           } else
9618             addReductionOps(TreeN);
9619         }
9620         // Retract.
9621         Stack.pop_back();
9622         continue;
9623       }
9624 
9625       // Visit operands.
9626       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9627       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9628       if (!EdgeInst) {
9629         // Edge value is not a reduction instruction or a leaf instruction.
9630         // (It may be a constant, function argument, or something else.)
9631         markExtraArg(Stack.back(), EdgeVal);
9632         continue;
9633       }
9634       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9635       // Continue analysis if the next operand is a reduction operation or
9636       // (possibly) a leaf value. If the leaf value opcode is not set,
9637       // the first met operation != reduction operation is considered as the
9638       // leaf opcode.
9639       // Only handle trees in the current basic block.
9640       // Each tree node needs to have minimal number of users except for the
9641       // ultimate reduction.
9642       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9643       if (EdgeInst != Phi && EdgeInst != Inst &&
9644           hasSameParent(EdgeInst, Inst->getParent()) &&
9645           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9646           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9647         if (IsRdxInst) {
9648           // We need to be able to reassociate the reduction operations.
9649           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9650             // I is an extra argument for TreeN (its parent operation).
9651             markExtraArg(Stack.back(), EdgeInst);
9652             continue;
9653           }
9654         } else if (!LeafOpcode) {
9655           LeafOpcode = EdgeInst->getOpcode();
9656         }
9657         Stack.push_back(
9658             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9659         continue;
9660       }
9661       // I is an extra argument for TreeN (its parent operation).
9662       markExtraArg(Stack.back(), EdgeInst);
9663     }
9664     return true;
9665   }
9666 
9667   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9668   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9669     // If there are a sufficient number of reduction values, reduce
9670     // to a nearby power-of-2. We can safely generate oversized
9671     // vectors and rely on the backend to split them to legal sizes.
9672     unsigned NumReducedVals = ReducedVals.size();
9673     if (NumReducedVals < 4)
9674       return nullptr;
9675 
9676     // Intersect the fast-math-flags from all reduction operations.
9677     FastMathFlags RdxFMF;
9678     RdxFMF.set();
9679     for (ReductionOpsType &RdxOp : ReductionOps) {
9680       for (Value *RdxVal : RdxOp) {
9681         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9682           RdxFMF &= FPMO->getFastMathFlags();
9683       }
9684     }
9685 
9686     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9687     Builder.setFastMathFlags(RdxFMF);
9688 
9689     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9690     // The same extra argument may be used several times, so log each attempt
9691     // to use it.
9692     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9693       assert(Pair.first && "DebugLoc must be set.");
9694       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9695     }
9696 
9697     // The compare instruction of a min/max is the insertion point for new
9698     // instructions and may be replaced with a new compare instruction.
9699     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9700       assert(isa<SelectInst>(RdxRootInst) &&
9701              "Expected min/max reduction to have select root instruction");
9702       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9703       assert(isa<Instruction>(ScalarCond) &&
9704              "Expected min/max reduction to have compare condition");
9705       return cast<Instruction>(ScalarCond);
9706     };
9707 
9708     // The reduction root is used as the insertion point for new instructions,
9709     // so set it as externally used to prevent it from being deleted.
9710     ExternallyUsedValues[ReductionRoot];
9711     SmallVector<Value *, 16> IgnoreList;
9712     for (ReductionOpsType &RdxOp : ReductionOps)
9713       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9714 
9715     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9716     if (NumReducedVals > ReduxWidth) {
9717       // In the loop below, we are building a tree based on a window of
9718       // 'ReduxWidth' values.
9719       // If the operands of those values have common traits (compare predicate,
9720       // constant operand, etc), then we want to group those together to
9721       // minimize the cost of the reduction.
9722 
9723       // TODO: This should be extended to count common operands for
9724       //       compares and binops.
9725 
9726       // Step 1: Count the number of times each compare predicate occurs.
9727       SmallDenseMap<unsigned, unsigned> PredCountMap;
9728       for (Value *RdxVal : ReducedVals) {
9729         CmpInst::Predicate Pred;
9730         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9731           ++PredCountMap[Pred];
9732       }
9733       // Step 2: Sort the values so the most common predicates come first.
9734       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9735         CmpInst::Predicate PredA, PredB;
9736         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9737             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9738           return PredCountMap[PredA] > PredCountMap[PredB];
9739         }
9740         return false;
9741       });
9742     }
9743 
9744     Value *VectorizedTree = nullptr;
9745     unsigned i = 0;
9746     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9747       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9748       V.buildTree(VL, IgnoreList);
9749       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9750         break;
9751       if (V.isLoadCombineReductionCandidate(RdxKind))
9752         break;
9753       V.reorderTopToBottom();
9754       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9755       V.buildExternalUses(ExternallyUsedValues);
9756 
9757       // For a poison-safe boolean logic reduction, do not replace select
9758       // instructions with logic ops. All reduced values will be frozen (see
9759       // below) to prevent leaking poison.
9760       if (isa<SelectInst>(ReductionRoot) &&
9761           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9762           NumReducedVals != ReduxWidth)
9763         break;
9764 
9765       V.computeMinimumValueSizes();
9766 
9767       // Estimate cost.
9768       InstructionCost TreeCost =
9769           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9770       InstructionCost ReductionCost =
9771           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9772       InstructionCost Cost = TreeCost + ReductionCost;
9773       if (!Cost.isValid()) {
9774         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9775         return nullptr;
9776       }
9777       if (Cost >= -SLPCostThreshold) {
9778         V.getORE()->emit([&]() {
9779           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9780                                           cast<Instruction>(VL[0]))
9781                  << "Vectorizing horizontal reduction is possible"
9782                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9783                  << " and threshold "
9784                  << ore::NV("Threshold", -SLPCostThreshold);
9785         });
9786         break;
9787       }
9788 
9789       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9790                         << Cost << ". (HorRdx)\n");
9791       V.getORE()->emit([&]() {
9792         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9793                                   cast<Instruction>(VL[0]))
9794                << "Vectorized horizontal reduction with cost "
9795                << ore::NV("Cost", Cost) << " and with tree size "
9796                << ore::NV("TreeSize", V.getTreeSize());
9797       });
9798 
9799       // Vectorize a tree.
9800       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9801       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9802 
9803       // Emit a reduction. If the root is a select (min/max idiom), the insert
9804       // point is the compare condition of that select.
9805       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9806       if (isCmpSelMinMax(RdxRootInst))
9807         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9808       else
9809         Builder.SetInsertPoint(RdxRootInst);
9810 
9811       // To prevent poison from leaking across what used to be sequential, safe,
9812       // scalar boolean logic operations, the reduction operand must be frozen.
9813       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9814         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9815 
9816       Value *ReducedSubTree =
9817           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9818 
9819       if (!VectorizedTree) {
9820         // Initialize the final value in the reduction.
9821         VectorizedTree = ReducedSubTree;
9822       } else {
9823         // Update the final value in the reduction.
9824         Builder.SetCurrentDebugLocation(Loc);
9825         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9826                                   ReducedSubTree, "op.rdx", ReductionOps);
9827       }
9828       i += ReduxWidth;
9829       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9830     }
9831 
9832     if (VectorizedTree) {
9833       // Finish the reduction.
9834       for (; i < NumReducedVals; ++i) {
9835         auto *I = cast<Instruction>(ReducedVals[i]);
9836         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9837         VectorizedTree =
9838             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9839       }
9840       for (auto &Pair : ExternallyUsedValues) {
9841         // Add each externally used value to the final reduction.
9842         for (auto *I : Pair.second) {
9843           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9844           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9845                                     Pair.first, "op.extra", I);
9846         }
9847       }
9848 
9849       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9850 
9851       // The original scalar reduction is expected to have no remaining
9852       // uses outside the reduction tree itself.  Assert that we got this
9853       // correct, replace internal uses with undef, and mark for eventual
9854       // deletion.
9855 #ifndef NDEBUG
9856       SmallSet<Value *, 4> IgnoreSet;
9857       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
9858 #endif
9859       for (auto *Ignore : IgnoreList) {
9860 #ifndef NDEBUG
9861         for (auto *U : Ignore->users()) {
9862           assert(IgnoreSet.count(U));
9863         }
9864 #endif
9865         if (!Ignore->use_empty()) {
9866           Value *Undef = UndefValue::get(Ignore->getType());
9867           Ignore->replaceAllUsesWith(Undef);
9868         }
9869         V.eraseInstruction(cast<Instruction>(Ignore));
9870       }
9871     }
9872     return VectorizedTree;
9873   }
9874 
9875   unsigned numReductionValues() const { return ReducedVals.size(); }
9876 
9877 private:
9878   /// Calculate the cost of a reduction.
9879   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9880                                    Value *FirstReducedVal, unsigned ReduxWidth,
9881                                    FastMathFlags FMF) {
9882     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9883     Type *ScalarTy = FirstReducedVal->getType();
9884     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9885     InstructionCost VectorCost, ScalarCost;
9886     switch (RdxKind) {
9887     case RecurKind::Add:
9888     case RecurKind::Mul:
9889     case RecurKind::Or:
9890     case RecurKind::And:
9891     case RecurKind::Xor:
9892     case RecurKind::FAdd:
9893     case RecurKind::FMul: {
9894       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9895       VectorCost =
9896           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9897       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9898       break;
9899     }
9900     case RecurKind::FMax:
9901     case RecurKind::FMin: {
9902       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9903       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9904       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9905                                                /*IsUnsigned=*/false, CostKind);
9906       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9907       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9908                                            SclCondTy, RdxPred, CostKind) +
9909                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9910                                            SclCondTy, RdxPred, CostKind);
9911       break;
9912     }
9913     case RecurKind::SMax:
9914     case RecurKind::SMin:
9915     case RecurKind::UMax:
9916     case RecurKind::UMin: {
9917       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9918       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9919       bool IsUnsigned =
9920           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9921       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9922                                                CostKind);
9923       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9924       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9925                                            SclCondTy, RdxPred, CostKind) +
9926                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9927                                            SclCondTy, RdxPred, CostKind);
9928       break;
9929     }
9930     default:
9931       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9932     }
9933 
9934     // Scalar cost is repeated for N-1 elements.
9935     ScalarCost *= (ReduxWidth - 1);
9936     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9937                       << " for reduction that starts with " << *FirstReducedVal
9938                       << " (It is a splitting reduction)\n");
9939     return VectorCost - ScalarCost;
9940   }
9941 
9942   /// Emit a horizontal reduction of the vectorized value.
9943   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9944                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9945     assert(VectorizedValue && "Need to have a vectorized tree node");
9946     assert(isPowerOf2_32(ReduxWidth) &&
9947            "We only handle power-of-two reductions for now");
9948     assert(RdxKind != RecurKind::FMulAdd &&
9949            "A call to the llvm.fmuladd intrinsic is not handled yet");
9950 
9951     ++NumVectorInstructions;
9952     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9953   }
9954 };
9955 
9956 } // end anonymous namespace
9957 
9958 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9959   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9960     return cast<FixedVectorType>(IE->getType())->getNumElements();
9961 
9962   unsigned AggregateSize = 1;
9963   auto *IV = cast<InsertValueInst>(InsertInst);
9964   Type *CurrentType = IV->getType();
9965   do {
9966     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9967       for (auto *Elt : ST->elements())
9968         if (Elt != ST->getElementType(0)) // check homogeneity
9969           return None;
9970       AggregateSize *= ST->getNumElements();
9971       CurrentType = ST->getElementType(0);
9972     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9973       AggregateSize *= AT->getNumElements();
9974       CurrentType = AT->getElementType();
9975     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9976       AggregateSize *= VT->getNumElements();
9977       return AggregateSize;
9978     } else if (CurrentType->isSingleValueType()) {
9979       return AggregateSize;
9980     } else {
9981       return None;
9982     }
9983   } while (true);
9984 }
9985 
9986 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9987                                    TargetTransformInfo *TTI,
9988                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9989                                    SmallVectorImpl<Value *> &InsertElts,
9990                                    unsigned OperandOffset) {
9991   do {
9992     Value *InsertedOperand = LastInsertInst->getOperand(1);
9993     Optional<unsigned> OperandIndex =
9994         getInsertIndex(LastInsertInst, OperandOffset);
9995     if (!OperandIndex)
9996       return;
9997     if (isa<InsertElementInst>(InsertedOperand) ||
9998         isa<InsertValueInst>(InsertedOperand)) {
9999       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10000                              BuildVectorOpds, InsertElts, *OperandIndex);
10001 
10002     } else {
10003       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10004       InsertElts[*OperandIndex] = LastInsertInst;
10005     }
10006     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10007   } while (LastInsertInst != nullptr &&
10008            (isa<InsertValueInst>(LastInsertInst) ||
10009             isa<InsertElementInst>(LastInsertInst)) &&
10010            LastInsertInst->hasOneUse());
10011 }
10012 
10013 /// Recognize construction of vectors like
10014 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10015 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10016 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10017 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10018 ///  starting from the last insertelement or insertvalue instruction.
10019 ///
10020 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10021 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10022 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10023 ///
10024 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10025 ///
10026 /// \return true if it matches.
10027 static bool findBuildAggregate(Instruction *LastInsertInst,
10028                                TargetTransformInfo *TTI,
10029                                SmallVectorImpl<Value *> &BuildVectorOpds,
10030                                SmallVectorImpl<Value *> &InsertElts) {
10031 
10032   assert((isa<InsertElementInst>(LastInsertInst) ||
10033           isa<InsertValueInst>(LastInsertInst)) &&
10034          "Expected insertelement or insertvalue instruction!");
10035 
10036   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10037          "Expected empty result vectors!");
10038 
10039   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10040   if (!AggregateSize)
10041     return false;
10042   BuildVectorOpds.resize(*AggregateSize);
10043   InsertElts.resize(*AggregateSize);
10044 
10045   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10046   llvm::erase_value(BuildVectorOpds, nullptr);
10047   llvm::erase_value(InsertElts, nullptr);
10048   if (BuildVectorOpds.size() >= 2)
10049     return true;
10050 
10051   return false;
10052 }
10053 
10054 /// Try and get a reduction value from a phi node.
10055 ///
10056 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10057 /// if they come from either \p ParentBB or a containing loop latch.
10058 ///
10059 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10060 /// if not possible.
10061 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10062                                 BasicBlock *ParentBB, LoopInfo *LI) {
10063   // There are situations where the reduction value is not dominated by the
10064   // reduction phi. Vectorizing such cases has been reported to cause
10065   // miscompiles. See PR25787.
10066   auto DominatedReduxValue = [&](Value *R) {
10067     return isa<Instruction>(R) &&
10068            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10069   };
10070 
10071   Value *Rdx = nullptr;
10072 
10073   // Return the incoming value if it comes from the same BB as the phi node.
10074   if (P->getIncomingBlock(0) == ParentBB) {
10075     Rdx = P->getIncomingValue(0);
10076   } else if (P->getIncomingBlock(1) == ParentBB) {
10077     Rdx = P->getIncomingValue(1);
10078   }
10079 
10080   if (Rdx && DominatedReduxValue(Rdx))
10081     return Rdx;
10082 
10083   // Otherwise, check whether we have a loop latch to look at.
10084   Loop *BBL = LI->getLoopFor(ParentBB);
10085   if (!BBL)
10086     return nullptr;
10087   BasicBlock *BBLatch = BBL->getLoopLatch();
10088   if (!BBLatch)
10089     return nullptr;
10090 
10091   // There is a loop latch, return the incoming value if it comes from
10092   // that. This reduction pattern occasionally turns up.
10093   if (P->getIncomingBlock(0) == BBLatch) {
10094     Rdx = P->getIncomingValue(0);
10095   } else if (P->getIncomingBlock(1) == BBLatch) {
10096     Rdx = P->getIncomingValue(1);
10097   }
10098 
10099   if (Rdx && DominatedReduxValue(Rdx))
10100     return Rdx;
10101 
10102   return nullptr;
10103 }
10104 
10105 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10106   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10107     return true;
10108   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10109     return true;
10110   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10111     return true;
10112   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10113     return true;
10114   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10115     return true;
10116   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10117     return true;
10118   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10119     return true;
10120   return false;
10121 }
10122 
10123 /// Attempt to reduce a horizontal reduction.
10124 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10125 /// with reduction operators \a Root (or one of its operands) in a basic block
10126 /// \a BB, then check if it can be done. If horizontal reduction is not found
10127 /// and root instruction is a binary operation, vectorization of the operands is
10128 /// attempted.
10129 /// \returns true if a horizontal reduction was matched and reduced or operands
10130 /// of one of the binary instruction were vectorized.
10131 /// \returns false if a horizontal reduction was not matched (or not possible)
10132 /// or no vectorization of any binary operation feeding \a Root instruction was
10133 /// performed.
10134 static bool tryToVectorizeHorReductionOrInstOperands(
10135     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10136     TargetTransformInfo *TTI,
10137     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10138   if (!ShouldVectorizeHor)
10139     return false;
10140 
10141   if (!Root)
10142     return false;
10143 
10144   if (Root->getParent() != BB || isa<PHINode>(Root))
10145     return false;
10146   // Start analysis starting from Root instruction. If horizontal reduction is
10147   // found, try to vectorize it. If it is not a horizontal reduction or
10148   // vectorization is not possible or not effective, and currently analyzed
10149   // instruction is a binary operation, try to vectorize the operands, using
10150   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10151   // the same procedure considering each operand as a possible root of the
10152   // horizontal reduction.
10153   // Interrupt the process if the Root instruction itself was vectorized or all
10154   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10155   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10156   // CmpInsts so we can skip extra attempts in
10157   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10158   std::queue<std::pair<Instruction *, unsigned>> Stack;
10159   Stack.emplace(Root, 0);
10160   SmallPtrSet<Value *, 8> VisitedInstrs;
10161   SmallVector<WeakTrackingVH> PostponedInsts;
10162   bool Res = false;
10163   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10164                                      Value *&B1) -> Value * {
10165     bool IsBinop = matchRdxBop(Inst, B0, B1);
10166     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10167     if (IsBinop || IsSelect) {
10168       HorizontalReduction HorRdx;
10169       if (HorRdx.matchAssociativeReduction(P, Inst))
10170         return HorRdx.tryToReduce(R, TTI);
10171     }
10172     return nullptr;
10173   };
10174   while (!Stack.empty()) {
10175     Instruction *Inst;
10176     unsigned Level;
10177     std::tie(Inst, Level) = Stack.front();
10178     Stack.pop();
10179     // Do not try to analyze instruction that has already been vectorized.
10180     // This may happen when we vectorize instruction operands on a previous
10181     // iteration while stack was populated before that happened.
10182     if (R.isDeleted(Inst))
10183       continue;
10184     Value *B0 = nullptr, *B1 = nullptr;
10185     if (Value *V = TryToReduce(Inst, B0, B1)) {
10186       Res = true;
10187       // Set P to nullptr to avoid re-analysis of phi node in
10188       // matchAssociativeReduction function unless this is the root node.
10189       P = nullptr;
10190       if (auto *I = dyn_cast<Instruction>(V)) {
10191         // Try to find another reduction.
10192         Stack.emplace(I, Level);
10193         continue;
10194       }
10195     } else {
10196       bool IsBinop = B0 && B1;
10197       if (P && IsBinop) {
10198         Inst = dyn_cast<Instruction>(B0);
10199         if (Inst == P)
10200           Inst = dyn_cast<Instruction>(B1);
10201         if (!Inst) {
10202           // Set P to nullptr to avoid re-analysis of phi node in
10203           // matchAssociativeReduction function unless this is the root node.
10204           P = nullptr;
10205           continue;
10206         }
10207       }
10208       // Set P to nullptr to avoid re-analysis of phi node in
10209       // matchAssociativeReduction function unless this is the root node.
10210       P = nullptr;
10211       // Do not try to vectorize CmpInst operands, this is done separately.
10212       // Final attempt for binop args vectorization should happen after the loop
10213       // to try to find reductions.
10214       if (!isa<CmpInst>(Inst))
10215         PostponedInsts.push_back(Inst);
10216     }
10217 
10218     // Try to vectorize operands.
10219     // Continue analysis for the instruction from the same basic block only to
10220     // save compile time.
10221     if (++Level < RecursionMaxDepth)
10222       for (auto *Op : Inst->operand_values())
10223         if (VisitedInstrs.insert(Op).second)
10224           if (auto *I = dyn_cast<Instruction>(Op))
10225             // Do not try to vectorize CmpInst operands,  this is done
10226             // separately.
10227             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10228                 I->getParent() == BB)
10229               Stack.emplace(I, Level);
10230   }
10231   // Try to vectorized binops where reductions were not found.
10232   for (Value *V : PostponedInsts)
10233     if (auto *Inst = dyn_cast<Instruction>(V))
10234       if (!R.isDeleted(Inst))
10235         Res |= Vectorize(Inst, R);
10236   return Res;
10237 }
10238 
10239 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10240                                                  BasicBlock *BB, BoUpSLP &R,
10241                                                  TargetTransformInfo *TTI) {
10242   auto *I = dyn_cast_or_null<Instruction>(V);
10243   if (!I)
10244     return false;
10245 
10246   if (!isa<BinaryOperator>(I))
10247     P = nullptr;
10248   // Try to match and vectorize a horizontal reduction.
10249   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10250     return tryToVectorize(I, R);
10251   };
10252   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10253                                                   ExtraVectorization);
10254 }
10255 
10256 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10257                                                  BasicBlock *BB, BoUpSLP &R) {
10258   const DataLayout &DL = BB->getModule()->getDataLayout();
10259   if (!R.canMapToVector(IVI->getType(), DL))
10260     return false;
10261 
10262   SmallVector<Value *, 16> BuildVectorOpds;
10263   SmallVector<Value *, 16> BuildVectorInsts;
10264   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10265     return false;
10266 
10267   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10268   // Aggregate value is unlikely to be processed in vector register.
10269   return tryToVectorizeList(BuildVectorOpds, R);
10270 }
10271 
10272 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10273                                                    BasicBlock *BB, BoUpSLP &R) {
10274   SmallVector<Value *, 16> BuildVectorInsts;
10275   SmallVector<Value *, 16> BuildVectorOpds;
10276   SmallVector<int> Mask;
10277   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10278       (llvm::all_of(
10279            BuildVectorOpds,
10280            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10281        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10282     return false;
10283 
10284   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10285   return tryToVectorizeList(BuildVectorInsts, R);
10286 }
10287 
10288 template <typename T>
10289 static bool
10290 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10291                        function_ref<unsigned(T *)> Limit,
10292                        function_ref<bool(T *, T *)> Comparator,
10293                        function_ref<bool(T *, T *)> AreCompatible,
10294                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10295                        bool LimitForRegisterSize) {
10296   bool Changed = false;
10297   // Sort by type, parent, operands.
10298   stable_sort(Incoming, Comparator);
10299 
10300   // Try to vectorize elements base on their type.
10301   SmallVector<T *> Candidates;
10302   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10303     // Look for the next elements with the same type, parent and operand
10304     // kinds.
10305     auto *SameTypeIt = IncIt;
10306     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10307       ++SameTypeIt;
10308 
10309     // Try to vectorize them.
10310     unsigned NumElts = (SameTypeIt - IncIt);
10311     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10312                       << NumElts << ")\n");
10313     // The vectorization is a 3-state attempt:
10314     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10315     // size of maximal register at first.
10316     // 2. Try to vectorize remaining instructions with the same type, if
10317     // possible. This may result in the better vectorization results rather than
10318     // if we try just to vectorize instructions with the same/alternate opcodes.
10319     // 3. Final attempt to try to vectorize all instructions with the
10320     // same/alternate ops only, this may result in some extra final
10321     // vectorization.
10322     if (NumElts > 1 &&
10323         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10324       // Success start over because instructions might have been changed.
10325       Changed = true;
10326     } else if (NumElts < Limit(*IncIt) &&
10327                (Candidates.empty() ||
10328                 Candidates.front()->getType() == (*IncIt)->getType())) {
10329       Candidates.append(IncIt, std::next(IncIt, NumElts));
10330     }
10331     // Final attempt to vectorize instructions with the same types.
10332     if (Candidates.size() > 1 &&
10333         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10334       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10335         // Success start over because instructions might have been changed.
10336         Changed = true;
10337       } else if (LimitForRegisterSize) {
10338         // Try to vectorize using small vectors.
10339         for (auto *It = Candidates.begin(), *End = Candidates.end();
10340              It != End;) {
10341           auto *SameTypeIt = It;
10342           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10343             ++SameTypeIt;
10344           unsigned NumElts = (SameTypeIt - It);
10345           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10346                                             /*LimitForRegisterSize=*/false))
10347             Changed = true;
10348           It = SameTypeIt;
10349         }
10350       }
10351       Candidates.clear();
10352     }
10353 
10354     // Start over at the next instruction of a different type (or the end).
10355     IncIt = SameTypeIt;
10356   }
10357   return Changed;
10358 }
10359 
10360 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10361 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10362 /// operands. If IsCompatibility is false, function implements strict weak
10363 /// ordering relation between two cmp instructions, returning true if the first
10364 /// instruction is "less" than the second, i.e. its predicate is less than the
10365 /// predicate of the second or the operands IDs are less than the operands IDs
10366 /// of the second cmp instruction.
10367 template <bool IsCompatibility>
10368 static bool compareCmp(Value *V, Value *V2,
10369                        function_ref<bool(Instruction *)> IsDeleted) {
10370   auto *CI1 = cast<CmpInst>(V);
10371   auto *CI2 = cast<CmpInst>(V2);
10372   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10373     return false;
10374   if (CI1->getOperand(0)->getType()->getTypeID() <
10375       CI2->getOperand(0)->getType()->getTypeID())
10376     return !IsCompatibility;
10377   if (CI1->getOperand(0)->getType()->getTypeID() >
10378       CI2->getOperand(0)->getType()->getTypeID())
10379     return false;
10380   CmpInst::Predicate Pred1 = CI1->getPredicate();
10381   CmpInst::Predicate Pred2 = CI2->getPredicate();
10382   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10383   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10384   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10385   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10386   if (BasePred1 < BasePred2)
10387     return !IsCompatibility;
10388   if (BasePred1 > BasePred2)
10389     return false;
10390   // Compare operands.
10391   bool LEPreds = Pred1 <= Pred2;
10392   bool GEPreds = Pred1 >= Pred2;
10393   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10394     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10395     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10396     if (Op1->getValueID() < Op2->getValueID())
10397       return !IsCompatibility;
10398     if (Op1->getValueID() > Op2->getValueID())
10399       return false;
10400     if (auto *I1 = dyn_cast<Instruction>(Op1))
10401       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10402         if (I1->getParent() != I2->getParent())
10403           return false;
10404         InstructionsState S = getSameOpcode({I1, I2});
10405         if (S.getOpcode())
10406           continue;
10407         return false;
10408       }
10409   }
10410   return IsCompatibility;
10411 }
10412 
10413 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10414     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10415     bool AtTerminator) {
10416   bool OpsChanged = false;
10417   SmallVector<Instruction *, 4> PostponedCmps;
10418   for (auto *I : reverse(Instructions)) {
10419     if (R.isDeleted(I))
10420       continue;
10421     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10422       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10423     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10424       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10425     else if (isa<CmpInst>(I))
10426       PostponedCmps.push_back(I);
10427   }
10428   if (AtTerminator) {
10429     // Try to find reductions first.
10430     for (Instruction *I : PostponedCmps) {
10431       if (R.isDeleted(I))
10432         continue;
10433       for (Value *Op : I->operands())
10434         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10435     }
10436     // Try to vectorize operands as vector bundles.
10437     for (Instruction *I : PostponedCmps) {
10438       if (R.isDeleted(I))
10439         continue;
10440       OpsChanged |= tryToVectorize(I, R);
10441     }
10442     // Try to vectorize list of compares.
10443     // Sort by type, compare predicate, etc.
10444     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10445       return compareCmp<false>(V, V2,
10446                                [&R](Instruction *I) { return R.isDeleted(I); });
10447     };
10448 
10449     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10450       if (V1 == V2)
10451         return true;
10452       return compareCmp<true>(V1, V2,
10453                               [&R](Instruction *I) { return R.isDeleted(I); });
10454     };
10455     auto Limit = [&R](Value *V) {
10456       unsigned EltSize = R.getVectorElementSize(V);
10457       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10458     };
10459 
10460     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10461     OpsChanged |= tryToVectorizeSequence<Value>(
10462         Vals, Limit, CompareSorter, AreCompatibleCompares,
10463         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10464           // Exclude possible reductions from other blocks.
10465           bool ArePossiblyReducedInOtherBlock =
10466               any_of(Candidates, [](Value *V) {
10467                 return any_of(V->users(), [V](User *U) {
10468                   return isa<SelectInst>(U) &&
10469                          cast<SelectInst>(U)->getParent() !=
10470                              cast<Instruction>(V)->getParent();
10471                 });
10472               });
10473           if (ArePossiblyReducedInOtherBlock)
10474             return false;
10475           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10476         },
10477         /*LimitForRegisterSize=*/true);
10478     Instructions.clear();
10479   } else {
10480     // Insert in reverse order since the PostponedCmps vector was filled in
10481     // reverse order.
10482     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10483   }
10484   return OpsChanged;
10485 }
10486 
10487 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10488   bool Changed = false;
10489   SmallVector<Value *, 4> Incoming;
10490   SmallPtrSet<Value *, 16> VisitedInstrs;
10491   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10492   // node. Allows better to identify the chains that can be vectorized in the
10493   // better way.
10494   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10495   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10496     assert(isValidElementType(V1->getType()) &&
10497            isValidElementType(V2->getType()) &&
10498            "Expected vectorizable types only.");
10499     // It is fine to compare type IDs here, since we expect only vectorizable
10500     // types, like ints, floats and pointers, we don't care about other type.
10501     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10502       return true;
10503     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10504       return false;
10505     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10506     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10507     if (Opcodes1.size() < Opcodes2.size())
10508       return true;
10509     if (Opcodes1.size() > Opcodes2.size())
10510       return false;
10511     Optional<bool> ConstOrder;
10512     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10513       // Undefs are compatible with any other value.
10514       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10515         if (!ConstOrder)
10516           ConstOrder =
10517               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10518         continue;
10519       }
10520       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10521         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10522           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10523           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10524           if (!NodeI1)
10525             return NodeI2 != nullptr;
10526           if (!NodeI2)
10527             return false;
10528           assert((NodeI1 == NodeI2) ==
10529                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10530                  "Different nodes should have different DFS numbers");
10531           if (NodeI1 != NodeI2)
10532             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10533           InstructionsState S = getSameOpcode({I1, I2});
10534           if (S.getOpcode())
10535             continue;
10536           return I1->getOpcode() < I2->getOpcode();
10537         }
10538       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10539         if (!ConstOrder)
10540           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10541         continue;
10542       }
10543       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10544         return true;
10545       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10546         return false;
10547     }
10548     return ConstOrder && *ConstOrder;
10549   };
10550   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10551     if (V1 == V2)
10552       return true;
10553     if (V1->getType() != V2->getType())
10554       return false;
10555     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10556     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10557     if (Opcodes1.size() != Opcodes2.size())
10558       return false;
10559     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10560       // Undefs are compatible with any other value.
10561       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10562         continue;
10563       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10564         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10565           if (I1->getParent() != I2->getParent())
10566             return false;
10567           InstructionsState S = getSameOpcode({I1, I2});
10568           if (S.getOpcode())
10569             continue;
10570           return false;
10571         }
10572       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10573         continue;
10574       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10575         return false;
10576     }
10577     return true;
10578   };
10579   auto Limit = [&R](Value *V) {
10580     unsigned EltSize = R.getVectorElementSize(V);
10581     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10582   };
10583 
10584   bool HaveVectorizedPhiNodes = false;
10585   do {
10586     // Collect the incoming values from the PHIs.
10587     Incoming.clear();
10588     for (Instruction &I : *BB) {
10589       PHINode *P = dyn_cast<PHINode>(&I);
10590       if (!P)
10591         break;
10592 
10593       // No need to analyze deleted, vectorized and non-vectorizable
10594       // instructions.
10595       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10596           isValidElementType(P->getType()))
10597         Incoming.push_back(P);
10598     }
10599 
10600     // Find the corresponding non-phi nodes for better matching when trying to
10601     // build the tree.
10602     for (Value *V : Incoming) {
10603       SmallVectorImpl<Value *> &Opcodes =
10604           PHIToOpcodes.try_emplace(V).first->getSecond();
10605       if (!Opcodes.empty())
10606         continue;
10607       SmallVector<Value *, 4> Nodes(1, V);
10608       SmallPtrSet<Value *, 4> Visited;
10609       while (!Nodes.empty()) {
10610         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10611         if (!Visited.insert(PHI).second)
10612           continue;
10613         for (Value *V : PHI->incoming_values()) {
10614           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10615             Nodes.push_back(PHI1);
10616             continue;
10617           }
10618           Opcodes.emplace_back(V);
10619         }
10620       }
10621     }
10622 
10623     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10624         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10625         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10626           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10627         },
10628         /*LimitForRegisterSize=*/true);
10629     Changed |= HaveVectorizedPhiNodes;
10630     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10631   } while (HaveVectorizedPhiNodes);
10632 
10633   VisitedInstrs.clear();
10634 
10635   SmallVector<Instruction *, 8> PostProcessInstructions;
10636   SmallDenseSet<Instruction *, 4> KeyNodes;
10637   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10638     // Skip instructions with scalable type. The num of elements is unknown at
10639     // compile-time for scalable type.
10640     if (isa<ScalableVectorType>(it->getType()))
10641       continue;
10642 
10643     // Skip instructions marked for the deletion.
10644     if (R.isDeleted(&*it))
10645       continue;
10646     // We may go through BB multiple times so skip the one we have checked.
10647     if (!VisitedInstrs.insert(&*it).second) {
10648       if (it->use_empty() && KeyNodes.contains(&*it) &&
10649           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10650                                       it->isTerminator())) {
10651         // We would like to start over since some instructions are deleted
10652         // and the iterator may become invalid value.
10653         Changed = true;
10654         it = BB->begin();
10655         e = BB->end();
10656       }
10657       continue;
10658     }
10659 
10660     if (isa<DbgInfoIntrinsic>(it))
10661       continue;
10662 
10663     // Try to vectorize reductions that use PHINodes.
10664     if (PHINode *P = dyn_cast<PHINode>(it)) {
10665       // Check that the PHI is a reduction PHI.
10666       if (P->getNumIncomingValues() == 2) {
10667         // Try to match and vectorize a horizontal reduction.
10668         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10669                                      TTI)) {
10670           Changed = true;
10671           it = BB->begin();
10672           e = BB->end();
10673           continue;
10674         }
10675       }
10676       // Try to vectorize the incoming values of the PHI, to catch reductions
10677       // that feed into PHIs.
10678       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10679         // Skip if the incoming block is the current BB for now. Also, bypass
10680         // unreachable IR for efficiency and to avoid crashing.
10681         // TODO: Collect the skipped incoming values and try to vectorize them
10682         // after processing BB.
10683         if (BB == P->getIncomingBlock(I) ||
10684             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10685           continue;
10686 
10687         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10688                                             P->getIncomingBlock(I), R, TTI);
10689       }
10690       continue;
10691     }
10692 
10693     // Ran into an instruction without users, like terminator, or function call
10694     // with ignored return value, store. Ignore unused instructions (basing on
10695     // instruction type, except for CallInst and InvokeInst).
10696     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10697                             isa<InvokeInst>(it))) {
10698       KeyNodes.insert(&*it);
10699       bool OpsChanged = false;
10700       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10701         for (auto *V : it->operand_values()) {
10702           // Try to match and vectorize a horizontal reduction.
10703           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10704         }
10705       }
10706       // Start vectorization of post-process list of instructions from the
10707       // top-tree instructions to try to vectorize as many instructions as
10708       // possible.
10709       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10710                                                 it->isTerminator());
10711       if (OpsChanged) {
10712         // We would like to start over since some instructions are deleted
10713         // and the iterator may become invalid value.
10714         Changed = true;
10715         it = BB->begin();
10716         e = BB->end();
10717         continue;
10718       }
10719     }
10720 
10721     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10722         isa<InsertValueInst>(it))
10723       PostProcessInstructions.push_back(&*it);
10724   }
10725 
10726   return Changed;
10727 }
10728 
10729 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10730   auto Changed = false;
10731   for (auto &Entry : GEPs) {
10732     // If the getelementptr list has fewer than two elements, there's nothing
10733     // to do.
10734     if (Entry.second.size() < 2)
10735       continue;
10736 
10737     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10738                       << Entry.second.size() << ".\n");
10739 
10740     // Process the GEP list in chunks suitable for the target's supported
10741     // vector size. If a vector register can't hold 1 element, we are done. We
10742     // are trying to vectorize the index computations, so the maximum number of
10743     // elements is based on the size of the index expression, rather than the
10744     // size of the GEP itself (the target's pointer size).
10745     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10746     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10747     if (MaxVecRegSize < EltSize)
10748       continue;
10749 
10750     unsigned MaxElts = MaxVecRegSize / EltSize;
10751     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10752       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10753       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10754 
10755       // Initialize a set a candidate getelementptrs. Note that we use a
10756       // SetVector here to preserve program order. If the index computations
10757       // are vectorizable and begin with loads, we want to minimize the chance
10758       // of having to reorder them later.
10759       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10760 
10761       // Some of the candidates may have already been vectorized after we
10762       // initially collected them. If so, they are marked as deleted, so remove
10763       // them from the set of candidates.
10764       Candidates.remove_if(
10765           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10766 
10767       // Remove from the set of candidates all pairs of getelementptrs with
10768       // constant differences. Such getelementptrs are likely not good
10769       // candidates for vectorization in a bottom-up phase since one can be
10770       // computed from the other. We also ensure all candidate getelementptr
10771       // indices are unique.
10772       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10773         auto *GEPI = GEPList[I];
10774         if (!Candidates.count(GEPI))
10775           continue;
10776         auto *SCEVI = SE->getSCEV(GEPList[I]);
10777         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10778           auto *GEPJ = GEPList[J];
10779           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10780           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10781             Candidates.remove(GEPI);
10782             Candidates.remove(GEPJ);
10783           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10784             Candidates.remove(GEPJ);
10785           }
10786         }
10787       }
10788 
10789       // We break out of the above computation as soon as we know there are
10790       // fewer than two candidates remaining.
10791       if (Candidates.size() < 2)
10792         continue;
10793 
10794       // Add the single, non-constant index of each candidate to the bundle. We
10795       // ensured the indices met these constraints when we originally collected
10796       // the getelementptrs.
10797       SmallVector<Value *, 16> Bundle(Candidates.size());
10798       auto BundleIndex = 0u;
10799       for (auto *V : Candidates) {
10800         auto *GEP = cast<GetElementPtrInst>(V);
10801         auto *GEPIdx = GEP->idx_begin()->get();
10802         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10803         Bundle[BundleIndex++] = GEPIdx;
10804       }
10805 
10806       // Try and vectorize the indices. We are currently only interested in
10807       // gather-like cases of the form:
10808       //
10809       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10810       //
10811       // where the loads of "a", the loads of "b", and the subtractions can be
10812       // performed in parallel. It's likely that detecting this pattern in a
10813       // bottom-up phase will be simpler and less costly than building a
10814       // full-blown top-down phase beginning at the consecutive loads.
10815       Changed |= tryToVectorizeList(Bundle, R);
10816     }
10817   }
10818   return Changed;
10819 }
10820 
10821 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10822   bool Changed = false;
10823   // Sort by type, base pointers and values operand. Value operands must be
10824   // compatible (have the same opcode, same parent), otherwise it is
10825   // definitely not profitable to try to vectorize them.
10826   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10827     if (V->getPointerOperandType()->getTypeID() <
10828         V2->getPointerOperandType()->getTypeID())
10829       return true;
10830     if (V->getPointerOperandType()->getTypeID() >
10831         V2->getPointerOperandType()->getTypeID())
10832       return false;
10833     // UndefValues are compatible with all other values.
10834     if (isa<UndefValue>(V->getValueOperand()) ||
10835         isa<UndefValue>(V2->getValueOperand()))
10836       return false;
10837     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10838       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10839         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10840             DT->getNode(I1->getParent());
10841         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10842             DT->getNode(I2->getParent());
10843         assert(NodeI1 && "Should only process reachable instructions");
10844         assert(NodeI1 && "Should only process reachable instructions");
10845         assert((NodeI1 == NodeI2) ==
10846                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10847                "Different nodes should have different DFS numbers");
10848         if (NodeI1 != NodeI2)
10849           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10850         InstructionsState S = getSameOpcode({I1, I2});
10851         if (S.getOpcode())
10852           return false;
10853         return I1->getOpcode() < I2->getOpcode();
10854       }
10855     if (isa<Constant>(V->getValueOperand()) &&
10856         isa<Constant>(V2->getValueOperand()))
10857       return false;
10858     return V->getValueOperand()->getValueID() <
10859            V2->getValueOperand()->getValueID();
10860   };
10861 
10862   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10863     if (V1 == V2)
10864       return true;
10865     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10866       return false;
10867     // Undefs are compatible with any other value.
10868     if (isa<UndefValue>(V1->getValueOperand()) ||
10869         isa<UndefValue>(V2->getValueOperand()))
10870       return true;
10871     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10872       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10873         if (I1->getParent() != I2->getParent())
10874           return false;
10875         InstructionsState S = getSameOpcode({I1, I2});
10876         return S.getOpcode() > 0;
10877       }
10878     if (isa<Constant>(V1->getValueOperand()) &&
10879         isa<Constant>(V2->getValueOperand()))
10880       return true;
10881     return V1->getValueOperand()->getValueID() ==
10882            V2->getValueOperand()->getValueID();
10883   };
10884   auto Limit = [&R, this](StoreInst *SI) {
10885     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10886     return R.getMinVF(EltSize);
10887   };
10888 
10889   // Attempt to sort and vectorize each of the store-groups.
10890   for (auto &Pair : Stores) {
10891     if (Pair.second.size() < 2)
10892       continue;
10893 
10894     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10895                       << Pair.second.size() << ".\n");
10896 
10897     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10898       continue;
10899 
10900     Changed |= tryToVectorizeSequence<StoreInst>(
10901         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10902         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10903           return vectorizeStores(Candidates, R);
10904         },
10905         /*LimitForRegisterSize=*/false);
10906   }
10907   return Changed;
10908 }
10909 
10910 char SLPVectorizer::ID = 0;
10911 
10912 static const char lv_name[] = "SLP Vectorizer";
10913 
10914 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10915 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10916 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10917 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10918 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10919 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10920 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10921 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10922 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10923 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10924 
10925 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10926