1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/Operator.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #ifdef EXPENSIVE_CHECKS
75 #include "llvm/IR/Verifier.h"
76 #endif
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 /// 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     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1169     /// MainAltOps.
1170     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1171                                ScalarEvolution &SE, int NumLanes,
1172                                ArrayRef<Value *> MainAltOps,
1173                                const TargetTransformInfo *TTI) {
1174       if (V1 == V2) {
1175         if (isa<LoadInst>(V1)) {
1176           // A broadcast of a load can be cheaper on some targets.
1177           // TODO: For now accept a broadcast load with no other internal uses.
1178           if (TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1179               (int)V1->getNumUses() == NumLanes)
1180             return VLOperands::ScoreSplatLoads;
1181         }
1182         return VLOperands::ScoreSplat;
1183       }
1184 
1185       auto *LI1 = dyn_cast<LoadInst>(V1);
1186       auto *LI2 = dyn_cast<LoadInst>(V2);
1187       if (LI1 && LI2) {
1188         if (LI1->getParent() != LI2->getParent())
1189           return VLOperands::ScoreFail;
1190 
1191         Optional<int> Dist = getPointersDiff(
1192             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1193             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1194         if (!Dist || *Dist == 0)
1195           return VLOperands::ScoreFail;
1196         // The distance is too large - still may be profitable to use masked
1197         // loads/gathers.
1198         if (std::abs(*Dist) > NumLanes / 2)
1199           return VLOperands::ScoreAltOpcodes;
1200         // This still will detect consecutive loads, but we might have "holes"
1201         // in some cases. It is ok for non-power-2 vectorization and may produce
1202         // better results. It should not affect current vectorization.
1203         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1204                            : VLOperands::ScoreReversedLoads;
1205       }
1206 
1207       auto *C1 = dyn_cast<Constant>(V1);
1208       auto *C2 = dyn_cast<Constant>(V2);
1209       if (C1 && C2)
1210         return VLOperands::ScoreConstants;
1211 
1212       // Extracts from consecutive indexes of the same vector better score as
1213       // the extracts could be optimized away.
1214       Value *EV1;
1215       ConstantInt *Ex1Idx;
1216       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1217         // Undefs are always profitable for extractelements.
1218         if (isa<UndefValue>(V2))
1219           return VLOperands::ScoreConsecutiveExtracts;
1220         Value *EV2 = nullptr;
1221         ConstantInt *Ex2Idx = nullptr;
1222         if (match(V2,
1223                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1224                                                          m_Undef())))) {
1225           // Undefs are always profitable for extractelements.
1226           if (!Ex2Idx)
1227             return VLOperands::ScoreConsecutiveExtracts;
1228           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1229             return VLOperands::ScoreConsecutiveExtracts;
1230           if (EV2 == EV1) {
1231             int Idx1 = Ex1Idx->getZExtValue();
1232             int Idx2 = Ex2Idx->getZExtValue();
1233             int Dist = Idx2 - Idx1;
1234             // The distance is too large - still may be profitable to use
1235             // shuffles.
1236             if (std::abs(Dist) == 0)
1237               return VLOperands::ScoreSplat;
1238             if (std::abs(Dist) > NumLanes / 2)
1239               return VLOperands::ScoreSameOpcode;
1240             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1241                               : VLOperands::ScoreReversedExtracts;
1242           }
1243           return VLOperands::ScoreAltOpcodes;
1244         }
1245         return VLOperands::ScoreFail;
1246       }
1247 
1248       auto *I1 = dyn_cast<Instruction>(V1);
1249       auto *I2 = dyn_cast<Instruction>(V2);
1250       if (I1 && I2) {
1251         if (I1->getParent() != I2->getParent())
1252           return VLOperands::ScoreFail;
1253         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1254         Ops.push_back(I1);
1255         Ops.push_back(I2);
1256         InstructionsState S = getSameOpcode(Ops);
1257         // Note: Only consider instructions with <= 2 operands to avoid
1258         // complexity explosion.
1259         if (S.getOpcode() &&
1260             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1261              !S.isAltShuffle()) &&
1262             all_of(Ops, [&S](Value *V) {
1263               return cast<Instruction>(V)->getNumOperands() ==
1264                      S.MainOp->getNumOperands();
1265             }))
1266           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1267                                   : VLOperands::ScoreSameOpcode;
1268       }
1269 
1270       if (isa<UndefValue>(V2))
1271         return VLOperands::ScoreUndef;
1272 
1273       return VLOperands::ScoreFail;
1274     }
1275 
1276     /// \param Lane lane of the operands under analysis.
1277     /// \param OpIdx operand index in \p Lane lane we're looking the best
1278     /// candidate for.
1279     /// \param Idx operand index of the current candidate value.
1280     /// \returns The additional score due to possible broadcasting of the
1281     /// elements in the lane. It is more profitable to have power-of-2 unique
1282     /// elements in the lane, it will be vectorized with higher probability
1283     /// after removing duplicates. Currently the SLP vectorizer supports only
1284     /// vectorization of the power-of-2 number of unique scalars.
1285     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1286       Value *IdxLaneV = getData(Idx, Lane).V;
1287       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1288         return 0;
1289       SmallPtrSet<Value *, 4> Uniques;
1290       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1291         if (Ln == Lane)
1292           continue;
1293         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1294         if (!isa<Instruction>(OpIdxLnV))
1295           return 0;
1296         Uniques.insert(OpIdxLnV);
1297       }
1298       int UniquesCount = Uniques.size();
1299       int UniquesCntWithIdxLaneV =
1300           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1301       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1302       int UniquesCntWithOpIdxLaneV =
1303           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1304       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1305         return 0;
1306       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1307               UniquesCntWithOpIdxLaneV) -
1308              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1309     }
1310 
1311     /// \param Lane lane of the operands under analysis.
1312     /// \param OpIdx operand index in \p Lane lane we're looking the best
1313     /// candidate for.
1314     /// \param Idx operand index of the current candidate value.
1315     /// \returns The additional score for the scalar which users are all
1316     /// vectorized.
1317     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1318       Value *IdxLaneV = getData(Idx, Lane).V;
1319       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1320       // Do not care about number of uses for vector-like instructions
1321       // (extractelement/extractvalue with constant indices), they are extracts
1322       // themselves and already externally used. Vectorization of such
1323       // instructions does not add extra extractelement instruction, just may
1324       // remove it.
1325       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1326           isVectorLikeInstWithConstOps(OpIdxLaneV))
1327         return VLOperands::ScoreAllUserVectorized;
1328       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1329       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1330         return 0;
1331       return R.areAllUsersVectorized(IdxLaneI, None)
1332                  ? VLOperands::ScoreAllUserVectorized
1333                  : 0;
1334     }
1335 
1336     /// Go through the operands of \p LHS and \p RHS recursively until \p
1337     /// MaxLevel, and return the cummulative score. For example:
1338     /// \verbatim
1339     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1340     ///     \ /         \ /         \ /        \ /
1341     ///      +           +           +          +
1342     ///     G1          G2          G3         G4
1343     /// \endverbatim
1344     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1345     /// each level recursively, accumulating the score. It starts from matching
1346     /// the additions at level 0, then moves on to the loads (level 1). The
1347     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1348     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1349     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1350     /// Please note that the order of the operands does not matter, as we
1351     /// evaluate the score of all profitable combinations of operands. In
1352     /// other words the score of G1 and G4 is the same as G1 and G2. This
1353     /// heuristic is based on ideas described in:
1354     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1355     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1356     ///   Luís F. W. Góes
1357     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1358                            ArrayRef<Value *> MainAltOps) {
1359 
1360       // Get the shallow score of V1 and V2.
1361       int ShallowScoreAtThisLevel =
1362           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps, R.TTI);
1363 
1364       // If reached MaxLevel,
1365       //  or if V1 and V2 are not instructions,
1366       //  or if they are SPLAT,
1367       //  or if they are not consecutive,
1368       //  or if profitable to vectorize loads or extractelements, early return
1369       //  the current cost.
1370       auto *I1 = dyn_cast<Instruction>(LHS);
1371       auto *I2 = dyn_cast<Instruction>(RHS);
1372       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1373           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1374           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1375             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1376             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1377            ShallowScoreAtThisLevel))
1378         return ShallowScoreAtThisLevel;
1379       assert(I1 && I2 && "Should have early exited.");
1380 
1381       // Contains the I2 operand indexes that got matched with I1 operands.
1382       SmallSet<unsigned, 4> Op2Used;
1383 
1384       // Recursion towards the operands of I1 and I2. We are trying all possible
1385       // operand pairs, and keeping track of the best score.
1386       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1387            OpIdx1 != NumOperands1; ++OpIdx1) {
1388         // Try to pair op1I with the best operand of I2.
1389         int MaxTmpScore = 0;
1390         unsigned MaxOpIdx2 = 0;
1391         bool FoundBest = false;
1392         // If I2 is commutative try all combinations.
1393         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1394         unsigned ToIdx = isCommutative(I2)
1395                              ? I2->getNumOperands()
1396                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1397         assert(FromIdx <= ToIdx && "Bad index");
1398         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1399           // Skip operands already paired with OpIdx1.
1400           if (Op2Used.count(OpIdx2))
1401             continue;
1402           // Recursively calculate the cost at each level
1403           int TmpScore =
1404               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1405                                  CurrLevel + 1, MaxLevel, None);
1406           // Look for the best score.
1407           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1408             MaxTmpScore = TmpScore;
1409             MaxOpIdx2 = OpIdx2;
1410             FoundBest = true;
1411           }
1412         }
1413         if (FoundBest) {
1414           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1415           Op2Used.insert(MaxOpIdx2);
1416           ShallowScoreAtThisLevel += MaxTmpScore;
1417         }
1418       }
1419       return ShallowScoreAtThisLevel;
1420     }
1421 
1422     /// Score scaling factor for fully compatible instructions but with
1423     /// different number of external uses. Allows better selection of the
1424     /// instructions with less external uses.
1425     static const int ScoreScaleFactor = 10;
1426 
1427     /// \Returns the look-ahead score, which tells us how much the sub-trees
1428     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1429     /// score. This helps break ties in an informed way when we cannot decide on
1430     /// the order of the operands by just considering the immediate
1431     /// predecessors.
1432     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1433                           int Lane, unsigned OpIdx, unsigned Idx,
1434                           bool &IsUsed) {
1435       int Score =
1436           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1437       if (Score) {
1438         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1439         if (Score <= -SplatScore) {
1440           // Set the minimum score for splat-like sequence to avoid setting
1441           // failed state.
1442           Score = 1;
1443         } else {
1444           Score += SplatScore;
1445           // Scale score to see the difference between different operands
1446           // and similar operands but all vectorized/not all vectorized
1447           // uses. It does not affect actual selection of the best
1448           // compatible operand in general, just allows to select the
1449           // operand with all vectorized uses.
1450           Score *= ScoreScaleFactor;
1451           Score += getExternalUseScore(Lane, OpIdx, Idx);
1452           IsUsed = true;
1453         }
1454       }
1455       return Score;
1456     }
1457 
1458     /// Best defined scores per lanes between the passes. Used to choose the
1459     /// best operand (with the highest score) between the passes.
1460     /// The key - {Operand Index, Lane}.
1461     /// The value - the best score between the passes for the lane and the
1462     /// operand.
1463     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1464         BestScoresPerLanes;
1465 
1466     // Search all operands in Ops[*][Lane] for the one that matches best
1467     // Ops[OpIdx][LastLane] and return its opreand index.
1468     // If no good match can be found, return None.
1469     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1470                                       ArrayRef<ReorderingMode> ReorderingModes,
1471                                       ArrayRef<Value *> MainAltOps) {
1472       unsigned NumOperands = getNumOperands();
1473 
1474       // The operand of the previous lane at OpIdx.
1475       Value *OpLastLane = getData(OpIdx, LastLane).V;
1476 
1477       // Our strategy mode for OpIdx.
1478       ReorderingMode RMode = ReorderingModes[OpIdx];
1479       if (RMode == ReorderingMode::Failed)
1480         return None;
1481 
1482       // The linearized opcode of the operand at OpIdx, Lane.
1483       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1484 
1485       // The best operand index and its score.
1486       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1487       // are using the score to differentiate between the two.
1488       struct BestOpData {
1489         Optional<unsigned> Idx = None;
1490         unsigned Score = 0;
1491       } BestOp;
1492       BestOp.Score =
1493           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1494               .first->second;
1495 
1496       // Track if the operand must be marked as used. If the operand is set to
1497       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1498       // want to reestimate the operands again on the following iterations).
1499       bool IsUsed =
1500           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1501       // Iterate through all unused operands and look for the best.
1502       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1503         // Get the operand at Idx and Lane.
1504         OperandData &OpData = getData(Idx, Lane);
1505         Value *Op = OpData.V;
1506         bool OpAPO = OpData.APO;
1507 
1508         // Skip already selected operands.
1509         if (OpData.IsUsed)
1510           continue;
1511 
1512         // Skip if we are trying to move the operand to a position with a
1513         // different opcode in the linearized tree form. This would break the
1514         // semantics.
1515         if (OpAPO != OpIdxAPO)
1516           continue;
1517 
1518         // Look for an operand that matches the current mode.
1519         switch (RMode) {
1520         case ReorderingMode::Load:
1521         case ReorderingMode::Constant:
1522         case ReorderingMode::Opcode: {
1523           bool LeftToRight = Lane > LastLane;
1524           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1525           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1526           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1527                                         OpIdx, Idx, IsUsed);
1528           if (Score > static_cast<int>(BestOp.Score)) {
1529             BestOp.Idx = Idx;
1530             BestOp.Score = Score;
1531             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1532           }
1533           break;
1534         }
1535         case ReorderingMode::Splat:
1536           if (Op == OpLastLane)
1537             BestOp.Idx = Idx;
1538           break;
1539         case ReorderingMode::Failed:
1540           llvm_unreachable("Not expected Failed reordering mode.");
1541         }
1542       }
1543 
1544       if (BestOp.Idx) {
1545         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1546         return BestOp.Idx;
1547       }
1548       // If we could not find a good match return None.
1549       return None;
1550     }
1551 
1552     /// Helper for reorderOperandVecs.
1553     /// \returns the lane that we should start reordering from. This is the one
1554     /// which has the least number of operands that can freely move about or
1555     /// less profitable because it already has the most optimal set of operands.
1556     unsigned getBestLaneToStartReordering() const {
1557       unsigned Min = UINT_MAX;
1558       unsigned SameOpNumber = 0;
1559       // std::pair<unsigned, unsigned> is used to implement a simple voting
1560       // algorithm and choose the lane with the least number of operands that
1561       // can freely move about or less profitable because it already has the
1562       // most optimal set of operands. The first unsigned is a counter for
1563       // voting, the second unsigned is the counter of lanes with instructions
1564       // with same/alternate opcodes and same parent basic block.
1565       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1566       // Try to be closer to the original results, if we have multiple lanes
1567       // with same cost. If 2 lanes have the same cost, use the one with the
1568       // lowest index.
1569       for (int I = getNumLanes(); I > 0; --I) {
1570         unsigned Lane = I - 1;
1571         OperandsOrderData NumFreeOpsHash =
1572             getMaxNumOperandsThatCanBeReordered(Lane);
1573         // Compare the number of operands that can move and choose the one with
1574         // the least number.
1575         if (NumFreeOpsHash.NumOfAPOs < Min) {
1576           Min = NumFreeOpsHash.NumOfAPOs;
1577           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1578           HashMap.clear();
1579           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1580         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1581                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1582           // Select the most optimal lane in terms of number of operands that
1583           // should be moved around.
1584           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1585           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1586         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1587                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1588           auto It = HashMap.find(NumFreeOpsHash.Hash);
1589           if (It == HashMap.end())
1590             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1591           else
1592             ++It->second.first;
1593         }
1594       }
1595       // Select the lane with the minimum counter.
1596       unsigned BestLane = 0;
1597       unsigned CntMin = UINT_MAX;
1598       for (const auto &Data : reverse(HashMap)) {
1599         if (Data.second.first < CntMin) {
1600           CntMin = Data.second.first;
1601           BestLane = Data.second.second;
1602         }
1603       }
1604       return BestLane;
1605     }
1606 
1607     /// Data structure that helps to reorder operands.
1608     struct OperandsOrderData {
1609       /// The best number of operands with the same APOs, which can be
1610       /// reordered.
1611       unsigned NumOfAPOs = UINT_MAX;
1612       /// Number of operands with the same/alternate instruction opcode and
1613       /// parent.
1614       unsigned NumOpsWithSameOpcodeParent = 0;
1615       /// Hash for the actual operands ordering.
1616       /// Used to count operands, actually their position id and opcode
1617       /// value. It is used in the voting mechanism to find the lane with the
1618       /// least number of operands that can freely move about or less profitable
1619       /// because it already has the most optimal set of operands. Can be
1620       /// replaced with SmallVector<unsigned> instead but hash code is faster
1621       /// and requires less memory.
1622       unsigned Hash = 0;
1623     };
1624     /// \returns the maximum number of operands that are allowed to be reordered
1625     /// for \p Lane and the number of compatible instructions(with the same
1626     /// parent/opcode). This is used as a heuristic for selecting the first lane
1627     /// to start operand reordering.
1628     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1629       unsigned CntTrue = 0;
1630       unsigned NumOperands = getNumOperands();
1631       // Operands with the same APO can be reordered. We therefore need to count
1632       // how many of them we have for each APO, like this: Cnt[APO] = x.
1633       // Since we only have two APOs, namely true and false, we can avoid using
1634       // a map. Instead we can simply count the number of operands that
1635       // correspond to one of them (in this case the 'true' APO), and calculate
1636       // the other by subtracting it from the total number of operands.
1637       // Operands with the same instruction opcode and parent are more
1638       // profitable since we don't need to move them in many cases, with a high
1639       // probability such lane already can be vectorized effectively.
1640       bool AllUndefs = true;
1641       unsigned NumOpsWithSameOpcodeParent = 0;
1642       Instruction *OpcodeI = nullptr;
1643       BasicBlock *Parent = nullptr;
1644       unsigned Hash = 0;
1645       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1646         const OperandData &OpData = getData(OpIdx, Lane);
1647         if (OpData.APO)
1648           ++CntTrue;
1649         // Use Boyer-Moore majority voting for finding the majority opcode and
1650         // the number of times it occurs.
1651         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1652           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1653               I->getParent() != Parent) {
1654             if (NumOpsWithSameOpcodeParent == 0) {
1655               NumOpsWithSameOpcodeParent = 1;
1656               OpcodeI = I;
1657               Parent = I->getParent();
1658             } else {
1659               --NumOpsWithSameOpcodeParent;
1660             }
1661           } else {
1662             ++NumOpsWithSameOpcodeParent;
1663           }
1664         }
1665         Hash = hash_combine(
1666             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1667         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1668       }
1669       if (AllUndefs)
1670         return {};
1671       OperandsOrderData Data;
1672       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1673       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1674       Data.Hash = Hash;
1675       return Data;
1676     }
1677 
1678     /// Go through the instructions in VL and append their operands.
1679     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1680       assert(!VL.empty() && "Bad VL");
1681       assert((empty() || VL.size() == getNumLanes()) &&
1682              "Expected same number of lanes");
1683       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1684       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1685       OpsVec.resize(NumOperands);
1686       unsigned NumLanes = VL.size();
1687       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1688         OpsVec[OpIdx].resize(NumLanes);
1689         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1690           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1691           // Our tree has just 3 nodes: the root and two operands.
1692           // It is therefore trivial to get the APO. We only need to check the
1693           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1694           // RHS operand. The LHS operand of both add and sub is never attached
1695           // to an inversese operation in the linearized form, therefore its APO
1696           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1697 
1698           // Since operand reordering is performed on groups of commutative
1699           // operations or alternating sequences (e.g., +, -), we can safely
1700           // tell the inverse operations by checking commutativity.
1701           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1702           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1703           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1704                                  APO, false};
1705         }
1706       }
1707     }
1708 
1709     /// \returns the number of operands.
1710     unsigned getNumOperands() const { return OpsVec.size(); }
1711 
1712     /// \returns the number of lanes.
1713     unsigned getNumLanes() const { return OpsVec[0].size(); }
1714 
1715     /// \returns the operand value at \p OpIdx and \p Lane.
1716     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1717       return getData(OpIdx, Lane).V;
1718     }
1719 
1720     /// \returns true if the data structure is empty.
1721     bool empty() const { return OpsVec.empty(); }
1722 
1723     /// Clears the data.
1724     void clear() { OpsVec.clear(); }
1725 
1726     /// \Returns true if there are enough operands identical to \p Op to fill
1727     /// the whole vector.
1728     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1729     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1730       bool OpAPO = getData(OpIdx, Lane).APO;
1731       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1732         if (Ln == Lane)
1733           continue;
1734         // This is set to true if we found a candidate for broadcast at Lane.
1735         bool FoundCandidate = false;
1736         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1737           OperandData &Data = getData(OpI, Ln);
1738           if (Data.APO != OpAPO || Data.IsUsed)
1739             continue;
1740           if (Data.V == Op) {
1741             FoundCandidate = true;
1742             Data.IsUsed = true;
1743             break;
1744           }
1745         }
1746         if (!FoundCandidate)
1747           return false;
1748       }
1749       return true;
1750     }
1751 
1752   public:
1753     /// Initialize with all the operands of the instruction vector \p RootVL.
1754     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1755                ScalarEvolution &SE, const BoUpSLP &R)
1756         : DL(DL), SE(SE), R(R) {
1757       // Append all the operands of RootVL.
1758       appendOperandsOfVL(RootVL);
1759     }
1760 
1761     /// \Returns a value vector with the operands across all lanes for the
1762     /// opearnd at \p OpIdx.
1763     ValueList getVL(unsigned OpIdx) const {
1764       ValueList OpVL(OpsVec[OpIdx].size());
1765       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1766              "Expected same num of lanes across all operands");
1767       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1768         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1769       return OpVL;
1770     }
1771 
1772     // Performs operand reordering for 2 or more operands.
1773     // The original operands are in OrigOps[OpIdx][Lane].
1774     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1775     void reorder() {
1776       unsigned NumOperands = getNumOperands();
1777       unsigned NumLanes = getNumLanes();
1778       // Each operand has its own mode. We are using this mode to help us select
1779       // the instructions for each lane, so that they match best with the ones
1780       // we have selected so far.
1781       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1782 
1783       // This is a greedy single-pass algorithm. We are going over each lane
1784       // once and deciding on the best order right away with no back-tracking.
1785       // However, in order to increase its effectiveness, we start with the lane
1786       // that has operands that can move the least. For example, given the
1787       // following lanes:
1788       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1789       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1790       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1791       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1792       // we will start at Lane 1, since the operands of the subtraction cannot
1793       // be reordered. Then we will visit the rest of the lanes in a circular
1794       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1795 
1796       // Find the first lane that we will start our search from.
1797       unsigned FirstLane = getBestLaneToStartReordering();
1798 
1799       // Initialize the modes.
1800       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1801         Value *OpLane0 = getValue(OpIdx, FirstLane);
1802         // Keep track if we have instructions with all the same opcode on one
1803         // side.
1804         if (isa<LoadInst>(OpLane0))
1805           ReorderingModes[OpIdx] = ReorderingMode::Load;
1806         else if (isa<Instruction>(OpLane0)) {
1807           // Check if OpLane0 should be broadcast.
1808           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1809             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1810           else
1811             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1812         }
1813         else if (isa<Constant>(OpLane0))
1814           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1815         else if (isa<Argument>(OpLane0))
1816           // Our best hope is a Splat. It may save some cost in some cases.
1817           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1818         else
1819           // NOTE: This should be unreachable.
1820           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1821       }
1822 
1823       // Check that we don't have same operands. No need to reorder if operands
1824       // are just perfect diamond or shuffled diamond match. Do not do it only
1825       // for possible broadcasts or non-power of 2 number of scalars (just for
1826       // now).
1827       auto &&SkipReordering = [this]() {
1828         SmallPtrSet<Value *, 4> UniqueValues;
1829         ArrayRef<OperandData> Op0 = OpsVec.front();
1830         for (const OperandData &Data : Op0)
1831           UniqueValues.insert(Data.V);
1832         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1833           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1834                 return !UniqueValues.contains(Data.V);
1835               }))
1836             return false;
1837         }
1838         // TODO: Check if we can remove a check for non-power-2 number of
1839         // scalars after full support of non-power-2 vectorization.
1840         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1841       };
1842 
1843       // If the initial strategy fails for any of the operand indexes, then we
1844       // perform reordering again in a second pass. This helps avoid assigning
1845       // high priority to the failed strategy, and should improve reordering for
1846       // the non-failed operand indexes.
1847       for (int Pass = 0; Pass != 2; ++Pass) {
1848         // Check if no need to reorder operands since they're are perfect or
1849         // shuffled diamond match.
1850         // Need to to do it to avoid extra external use cost counting for
1851         // shuffled matches, which may cause regressions.
1852         if (SkipReordering())
1853           break;
1854         // Skip the second pass if the first pass did not fail.
1855         bool StrategyFailed = false;
1856         // Mark all operand data as free to use.
1857         clearUsed();
1858         // We keep the original operand order for the FirstLane, so reorder the
1859         // rest of the lanes. We are visiting the nodes in a circular fashion,
1860         // using FirstLane as the center point and increasing the radius
1861         // distance.
1862         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1863         for (unsigned I = 0; I < NumOperands; ++I)
1864           MainAltOps[I].push_back(getData(I, FirstLane).V);
1865 
1866         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1867           // Visit the lane on the right and then the lane on the left.
1868           for (int Direction : {+1, -1}) {
1869             int Lane = FirstLane + Direction * Distance;
1870             if (Lane < 0 || Lane >= (int)NumLanes)
1871               continue;
1872             int LastLane = Lane - Direction;
1873             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1874                    "Out of bounds");
1875             // Look for a good match for each operand.
1876             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1877               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1878               Optional<unsigned> BestIdx = getBestOperand(
1879                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1880               // By not selecting a value, we allow the operands that follow to
1881               // select a better matching value. We will get a non-null value in
1882               // the next run of getBestOperand().
1883               if (BestIdx) {
1884                 // Swap the current operand with the one returned by
1885                 // getBestOperand().
1886                 swap(OpIdx, BestIdx.getValue(), Lane);
1887               } else {
1888                 // We failed to find a best operand, set mode to 'Failed'.
1889                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1890                 // Enable the second pass.
1891                 StrategyFailed = true;
1892               }
1893               // Try to get the alternate opcode and follow it during analysis.
1894               if (MainAltOps[OpIdx].size() != 2) {
1895                 OperandData &AltOp = getData(OpIdx, Lane);
1896                 InstructionsState OpS =
1897                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1898                 if (OpS.getOpcode() && OpS.isAltShuffle())
1899                   MainAltOps[OpIdx].push_back(AltOp.V);
1900               }
1901             }
1902           }
1903         }
1904         // Skip second pass if the strategy did not fail.
1905         if (!StrategyFailed)
1906           break;
1907       }
1908     }
1909 
1910 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1911     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1912       switch (RMode) {
1913       case ReorderingMode::Load:
1914         return "Load";
1915       case ReorderingMode::Opcode:
1916         return "Opcode";
1917       case ReorderingMode::Constant:
1918         return "Constant";
1919       case ReorderingMode::Splat:
1920         return "Splat";
1921       case ReorderingMode::Failed:
1922         return "Failed";
1923       }
1924       llvm_unreachable("Unimplemented Reordering Type");
1925     }
1926 
1927     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1928                                                    raw_ostream &OS) {
1929       return OS << getModeStr(RMode);
1930     }
1931 
1932     /// Debug print.
1933     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1934       printMode(RMode, dbgs());
1935     }
1936 
1937     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1938       return printMode(RMode, OS);
1939     }
1940 
1941     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1942       const unsigned Indent = 2;
1943       unsigned Cnt = 0;
1944       for (const OperandDataVec &OpDataVec : OpsVec) {
1945         OS << "Operand " << Cnt++ << "\n";
1946         for (const OperandData &OpData : OpDataVec) {
1947           OS.indent(Indent) << "{";
1948           if (Value *V = OpData.V)
1949             OS << *V;
1950           else
1951             OS << "null";
1952           OS << ", APO:" << OpData.APO << "}\n";
1953         }
1954         OS << "\n";
1955       }
1956       return OS;
1957     }
1958 
1959     /// Debug print.
1960     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1961 #endif
1962   };
1963 
1964   /// Checks if the instruction is marked for deletion.
1965   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1966 
1967   /// Marks values operands for later deletion by replacing them with Undefs.
1968   void eraseInstructions(ArrayRef<Value *> AV);
1969 
1970   ~BoUpSLP();
1971 
1972 private:
1973   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1974   /// reordering (i.e. the operands can be reordered because they have only one
1975   /// user and reordarable).
1976   /// \param NonVectorized List of all gather nodes that require reordering
1977   /// (e.g., gather of extractlements or partially vectorizable loads).
1978   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1979   /// reordering, subset of \p NonVectorized.
1980   bool
1981   canReorderOperands(TreeEntry *UserTE,
1982                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1983                      ArrayRef<TreeEntry *> ReorderableGathers,
1984                      SmallVectorImpl<TreeEntry *> &GatherOps);
1985 
1986   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1987   /// if any. If it is not vectorized (gather node), returns nullptr.
1988   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1989     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1990     TreeEntry *TE = nullptr;
1991     const auto *It = find_if(VL, [this, &TE](Value *V) {
1992       TE = getTreeEntry(V);
1993       return TE;
1994     });
1995     if (It != VL.end() && TE->isSame(VL))
1996       return TE;
1997     return nullptr;
1998   }
1999 
2000   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2001   /// if any. If it is not vectorized (gather node), returns nullptr.
2002   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2003                                         unsigned OpIdx) const {
2004     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2005         const_cast<TreeEntry *>(UserTE), OpIdx);
2006   }
2007 
2008   /// Checks if all users of \p I are the part of the vectorization tree.
2009   bool areAllUsersVectorized(Instruction *I,
2010                              ArrayRef<Value *> VectorizedVals) const;
2011 
2012   /// \returns the cost of the vectorizable entry.
2013   InstructionCost getEntryCost(const TreeEntry *E,
2014                                ArrayRef<Value *> VectorizedVals);
2015 
2016   /// This is the recursive part of buildTree.
2017   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2018                      const EdgeInfo &EI);
2019 
2020   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2021   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2022   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2023   /// returns false, setting \p CurrentOrder to either an empty vector or a
2024   /// non-identity permutation that allows to reuse extract instructions.
2025   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2026                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2027 
2028   /// Vectorize a single entry in the tree.
2029   Value *vectorizeTree(TreeEntry *E);
2030 
2031   /// Vectorize a single entry in the tree, starting in \p VL.
2032   Value *vectorizeTree(ArrayRef<Value *> VL);
2033 
2034   /// Create a new vector from a list of scalar values.  Produces a sequence
2035   /// which exploits values reused across lanes, and arranges the inserts
2036   /// for ease of later optimization.
2037   Value *createBuildVector(ArrayRef<Value *> VL);
2038 
2039   /// \returns the scalarization cost for this type. Scalarization in this
2040   /// context means the creation of vectors from a group of scalars. If \p
2041   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2042   /// vector elements.
2043   InstructionCost getGatherCost(FixedVectorType *Ty,
2044                                 const APInt &ShuffledIndices,
2045                                 bool NeedToShuffle) const;
2046 
2047   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2048   /// tree entries.
2049   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2050   /// previous tree entries. \p Mask is filled with the shuffle mask.
2051   Optional<TargetTransformInfo::ShuffleKind>
2052   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2053                         SmallVectorImpl<const TreeEntry *> &Entries);
2054 
2055   /// \returns the scalarization cost for this list of values. Assuming that
2056   /// this subtree gets vectorized, we may need to extract the values from the
2057   /// roots. This method calculates the cost of extracting the values.
2058   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2059 
2060   /// Set the Builder insert point to one after the last instruction in
2061   /// the bundle
2062   void setInsertPointAfterBundle(const TreeEntry *E);
2063 
2064   /// \returns a vector from a collection of scalars in \p VL.
2065   Value *gather(ArrayRef<Value *> VL);
2066 
2067   /// \returns whether the VectorizableTree is fully vectorizable and will
2068   /// be beneficial even the tree height is tiny.
2069   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2070 
2071   /// Reorder commutative or alt operands to get better probability of
2072   /// generating vectorized code.
2073   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2074                                              SmallVectorImpl<Value *> &Left,
2075                                              SmallVectorImpl<Value *> &Right,
2076                                              const DataLayout &DL,
2077                                              ScalarEvolution &SE,
2078                                              const BoUpSLP &R);
2079   struct TreeEntry {
2080     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2081     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2082 
2083     /// \returns true if the scalars in VL are equal to this entry.
2084     bool isSame(ArrayRef<Value *> VL) const {
2085       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2086         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2087           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2088         return VL.size() == Mask.size() &&
2089                std::equal(VL.begin(), VL.end(), Mask.begin(),
2090                           [Scalars](Value *V, int Idx) {
2091                             return (isa<UndefValue>(V) &&
2092                                     Idx == UndefMaskElem) ||
2093                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2094                           });
2095       };
2096       if (!ReorderIndices.empty()) {
2097         // TODO: implement matching if the nodes are just reordered, still can
2098         // treat the vector as the same if the list of scalars matches VL
2099         // directly, without reordering.
2100         SmallVector<int> Mask;
2101         inversePermutation(ReorderIndices, Mask);
2102         if (VL.size() == Scalars.size())
2103           return IsSame(Scalars, Mask);
2104         if (VL.size() == ReuseShuffleIndices.size()) {
2105           ::addMask(Mask, ReuseShuffleIndices);
2106           return IsSame(Scalars, Mask);
2107         }
2108         return false;
2109       }
2110       return IsSame(Scalars, ReuseShuffleIndices);
2111     }
2112 
2113     /// \returns true if current entry has same operands as \p TE.
2114     bool hasEqualOperands(const TreeEntry &TE) const {
2115       if (TE.getNumOperands() != getNumOperands())
2116         return false;
2117       SmallBitVector Used(getNumOperands());
2118       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2119         unsigned PrevCount = Used.count();
2120         for (unsigned K = 0; K < E; ++K) {
2121           if (Used.test(K))
2122             continue;
2123           if (getOperand(K) == TE.getOperand(I)) {
2124             Used.set(K);
2125             break;
2126           }
2127         }
2128         // Check if we actually found the matching operand.
2129         if (PrevCount == Used.count())
2130           return false;
2131       }
2132       return true;
2133     }
2134 
2135     /// \return Final vectorization factor for the node. Defined by the total
2136     /// number of vectorized scalars, including those, used several times in the
2137     /// entry and counted in the \a ReuseShuffleIndices, if any.
2138     unsigned getVectorFactor() const {
2139       if (!ReuseShuffleIndices.empty())
2140         return ReuseShuffleIndices.size();
2141       return Scalars.size();
2142     };
2143 
2144     /// A vector of scalars.
2145     ValueList Scalars;
2146 
2147     /// The Scalars are vectorized into this value. It is initialized to Null.
2148     Value *VectorizedValue = nullptr;
2149 
2150     /// Do we need to gather this sequence or vectorize it
2151     /// (either with vector instruction or with scatter/gather
2152     /// intrinsics for store/load)?
2153     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2154     EntryState State;
2155 
2156     /// Does this sequence require some shuffling?
2157     SmallVector<int, 4> ReuseShuffleIndices;
2158 
2159     /// Does this entry require reordering?
2160     SmallVector<unsigned, 4> ReorderIndices;
2161 
2162     /// Points back to the VectorizableTree.
2163     ///
2164     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2165     /// to be a pointer and needs to be able to initialize the child iterator.
2166     /// Thus we need a reference back to the container to translate the indices
2167     /// to entries.
2168     VecTreeTy &Container;
2169 
2170     /// The TreeEntry index containing the user of this entry.  We can actually
2171     /// have multiple users so the data structure is not truly a tree.
2172     SmallVector<EdgeInfo, 1> UserTreeIndices;
2173 
2174     /// The index of this treeEntry in VectorizableTree.
2175     int Idx = -1;
2176 
2177   private:
2178     /// The operands of each instruction in each lane Operands[op_index][lane].
2179     /// Note: This helps avoid the replication of the code that performs the
2180     /// reordering of operands during buildTree_rec() and vectorizeTree().
2181     SmallVector<ValueList, 2> Operands;
2182 
2183     /// The main/alternate instruction.
2184     Instruction *MainOp = nullptr;
2185     Instruction *AltOp = nullptr;
2186 
2187   public:
2188     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2189     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2190       if (Operands.size() < OpIdx + 1)
2191         Operands.resize(OpIdx + 1);
2192       assert(Operands[OpIdx].empty() && "Already resized?");
2193       assert(OpVL.size() <= Scalars.size() &&
2194              "Number of operands is greater than the number of scalars.");
2195       Operands[OpIdx].resize(OpVL.size());
2196       copy(OpVL, Operands[OpIdx].begin());
2197     }
2198 
2199     /// Set the operands of this bundle in their original order.
2200     void setOperandsInOrder() {
2201       assert(Operands.empty() && "Already initialized?");
2202       auto *I0 = cast<Instruction>(Scalars[0]);
2203       Operands.resize(I0->getNumOperands());
2204       unsigned NumLanes = Scalars.size();
2205       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2206            OpIdx != NumOperands; ++OpIdx) {
2207         Operands[OpIdx].resize(NumLanes);
2208         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2209           auto *I = cast<Instruction>(Scalars[Lane]);
2210           assert(I->getNumOperands() == NumOperands &&
2211                  "Expected same number of operands");
2212           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2213         }
2214       }
2215     }
2216 
2217     /// Reorders operands of the node to the given mask \p Mask.
2218     void reorderOperands(ArrayRef<int> Mask) {
2219       for (ValueList &Operand : Operands)
2220         reorderScalars(Operand, Mask);
2221     }
2222 
2223     /// \returns the \p OpIdx operand of this TreeEntry.
2224     ValueList &getOperand(unsigned OpIdx) {
2225       assert(OpIdx < Operands.size() && "Off bounds");
2226       return Operands[OpIdx];
2227     }
2228 
2229     /// \returns the \p OpIdx operand of this TreeEntry.
2230     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2231       assert(OpIdx < Operands.size() && "Off bounds");
2232       return Operands[OpIdx];
2233     }
2234 
2235     /// \returns the number of operands.
2236     unsigned getNumOperands() const { return Operands.size(); }
2237 
2238     /// \return the single \p OpIdx operand.
2239     Value *getSingleOperand(unsigned OpIdx) const {
2240       assert(OpIdx < Operands.size() && "Off bounds");
2241       assert(!Operands[OpIdx].empty() && "No operand available");
2242       return Operands[OpIdx][0];
2243     }
2244 
2245     /// Some of the instructions in the list have alternate opcodes.
2246     bool isAltShuffle() const { return MainOp != AltOp; }
2247 
2248     bool isOpcodeOrAlt(Instruction *I) const {
2249       unsigned CheckedOpcode = I->getOpcode();
2250       return (getOpcode() == CheckedOpcode ||
2251               getAltOpcode() == CheckedOpcode);
2252     }
2253 
2254     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2255     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2256     /// \p OpValue.
2257     Value *isOneOf(Value *Op) const {
2258       auto *I = dyn_cast<Instruction>(Op);
2259       if (I && isOpcodeOrAlt(I))
2260         return Op;
2261       return MainOp;
2262     }
2263 
2264     void setOperations(const InstructionsState &S) {
2265       MainOp = S.MainOp;
2266       AltOp = S.AltOp;
2267     }
2268 
2269     Instruction *getMainOp() const {
2270       return MainOp;
2271     }
2272 
2273     Instruction *getAltOp() const {
2274       return AltOp;
2275     }
2276 
2277     /// The main/alternate opcodes for the list of instructions.
2278     unsigned getOpcode() const {
2279       return MainOp ? MainOp->getOpcode() : 0;
2280     }
2281 
2282     unsigned getAltOpcode() const {
2283       return AltOp ? AltOp->getOpcode() : 0;
2284     }
2285 
2286     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2287     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2288     int findLaneForValue(Value *V) const {
2289       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2290       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2291       if (!ReorderIndices.empty())
2292         FoundLane = ReorderIndices[FoundLane];
2293       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2294       if (!ReuseShuffleIndices.empty()) {
2295         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2296                                   find(ReuseShuffleIndices, FoundLane));
2297       }
2298       return FoundLane;
2299     }
2300 
2301 #ifndef NDEBUG
2302     /// Debug printer.
2303     LLVM_DUMP_METHOD void dump() const {
2304       dbgs() << Idx << ".\n";
2305       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2306         dbgs() << "Operand " << OpI << ":\n";
2307         for (const Value *V : Operands[OpI])
2308           dbgs().indent(2) << *V << "\n";
2309       }
2310       dbgs() << "Scalars: \n";
2311       for (Value *V : Scalars)
2312         dbgs().indent(2) << *V << "\n";
2313       dbgs() << "State: ";
2314       switch (State) {
2315       case Vectorize:
2316         dbgs() << "Vectorize\n";
2317         break;
2318       case ScatterVectorize:
2319         dbgs() << "ScatterVectorize\n";
2320         break;
2321       case NeedToGather:
2322         dbgs() << "NeedToGather\n";
2323         break;
2324       }
2325       dbgs() << "MainOp: ";
2326       if (MainOp)
2327         dbgs() << *MainOp << "\n";
2328       else
2329         dbgs() << "NULL\n";
2330       dbgs() << "AltOp: ";
2331       if (AltOp)
2332         dbgs() << *AltOp << "\n";
2333       else
2334         dbgs() << "NULL\n";
2335       dbgs() << "VectorizedValue: ";
2336       if (VectorizedValue)
2337         dbgs() << *VectorizedValue << "\n";
2338       else
2339         dbgs() << "NULL\n";
2340       dbgs() << "ReuseShuffleIndices: ";
2341       if (ReuseShuffleIndices.empty())
2342         dbgs() << "Empty";
2343       else
2344         for (int ReuseIdx : ReuseShuffleIndices)
2345           dbgs() << ReuseIdx << ", ";
2346       dbgs() << "\n";
2347       dbgs() << "ReorderIndices: ";
2348       for (unsigned ReorderIdx : ReorderIndices)
2349         dbgs() << ReorderIdx << ", ";
2350       dbgs() << "\n";
2351       dbgs() << "UserTreeIndices: ";
2352       for (const auto &EInfo : UserTreeIndices)
2353         dbgs() << EInfo << ", ";
2354       dbgs() << "\n";
2355     }
2356 #endif
2357   };
2358 
2359 #ifndef NDEBUG
2360   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2361                      InstructionCost VecCost,
2362                      InstructionCost ScalarCost) const {
2363     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2364     dbgs() << "SLP: Costs:\n";
2365     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2366     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2367     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2368     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2369                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2370   }
2371 #endif
2372 
2373   /// Create a new VectorizableTree entry.
2374   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2375                           const InstructionsState &S,
2376                           const EdgeInfo &UserTreeIdx,
2377                           ArrayRef<int> ReuseShuffleIndices = None,
2378                           ArrayRef<unsigned> ReorderIndices = None) {
2379     TreeEntry::EntryState EntryState =
2380         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2381     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2382                         ReuseShuffleIndices, ReorderIndices);
2383   }
2384 
2385   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2386                           TreeEntry::EntryState EntryState,
2387                           Optional<ScheduleData *> Bundle,
2388                           const InstructionsState &S,
2389                           const EdgeInfo &UserTreeIdx,
2390                           ArrayRef<int> ReuseShuffleIndices = None,
2391                           ArrayRef<unsigned> ReorderIndices = None) {
2392     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2393             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2394            "Need to vectorize gather entry?");
2395     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2396     TreeEntry *Last = VectorizableTree.back().get();
2397     Last->Idx = VectorizableTree.size() - 1;
2398     Last->State = EntryState;
2399     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2400                                      ReuseShuffleIndices.end());
2401     if (ReorderIndices.empty()) {
2402       Last->Scalars.assign(VL.begin(), VL.end());
2403       Last->setOperations(S);
2404     } else {
2405       // Reorder scalars and build final mask.
2406       Last->Scalars.assign(VL.size(), nullptr);
2407       transform(ReorderIndices, Last->Scalars.begin(),
2408                 [VL](unsigned Idx) -> Value * {
2409                   if (Idx >= VL.size())
2410                     return UndefValue::get(VL.front()->getType());
2411                   return VL[Idx];
2412                 });
2413       InstructionsState S = getSameOpcode(Last->Scalars);
2414       Last->setOperations(S);
2415       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2416     }
2417     if (Last->State != TreeEntry::NeedToGather) {
2418       for (Value *V : VL) {
2419         assert(!getTreeEntry(V) && "Scalar already in tree!");
2420         ScalarToTreeEntry[V] = Last;
2421       }
2422       // Update the scheduler bundle to point to this TreeEntry.
2423       ScheduleData *BundleMember = Bundle.getValue();
2424       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2425               isVectorLikeInstWithConstOps(S.MainOp) ||
2426               doesNotNeedToSchedule(VL)) &&
2427              "Bundle and VL out of sync");
2428       if (BundleMember) {
2429         for (Value *V : VL) {
2430           if (doesNotNeedToBeScheduled(V))
2431             continue;
2432           assert(BundleMember && "Unexpected end of bundle.");
2433           BundleMember->TE = Last;
2434           BundleMember = BundleMember->NextInBundle;
2435         }
2436       }
2437       assert(!BundleMember && "Bundle and VL out of sync");
2438     } else {
2439       MustGather.insert(VL.begin(), VL.end());
2440     }
2441 
2442     if (UserTreeIdx.UserTE)
2443       Last->UserTreeIndices.push_back(UserTreeIdx);
2444 
2445     return Last;
2446   }
2447 
2448   /// -- Vectorization State --
2449   /// Holds all of the tree entries.
2450   TreeEntry::VecTreeTy VectorizableTree;
2451 
2452 #ifndef NDEBUG
2453   /// Debug printer.
2454   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2455     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2456       VectorizableTree[Id]->dump();
2457       dbgs() << "\n";
2458     }
2459   }
2460 #endif
2461 
2462   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2463 
2464   const TreeEntry *getTreeEntry(Value *V) const {
2465     return ScalarToTreeEntry.lookup(V);
2466   }
2467 
2468   /// Maps a specific scalar to its tree entry.
2469   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2470 
2471   /// Maps a value to the proposed vectorizable size.
2472   SmallDenseMap<Value *, unsigned> InstrElementSize;
2473 
2474   /// A list of scalars that we found that we need to keep as scalars.
2475   ValueSet MustGather;
2476 
2477   /// This POD struct describes one external user in the vectorized tree.
2478   struct ExternalUser {
2479     ExternalUser(Value *S, llvm::User *U, int L)
2480         : Scalar(S), User(U), Lane(L) {}
2481 
2482     // Which scalar in our function.
2483     Value *Scalar;
2484 
2485     // Which user that uses the scalar.
2486     llvm::User *User;
2487 
2488     // Which lane does the scalar belong to.
2489     int Lane;
2490   };
2491   using UserList = SmallVector<ExternalUser, 16>;
2492 
2493   /// Checks if two instructions may access the same memory.
2494   ///
2495   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2496   /// is invariant in the calling loop.
2497   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2498                  Instruction *Inst2) {
2499     // First check if the result is already in the cache.
2500     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2501     Optional<bool> &result = AliasCache[key];
2502     if (result.hasValue()) {
2503       return result.getValue();
2504     }
2505     bool aliased = true;
2506     if (Loc1.Ptr && isSimple(Inst1))
2507       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2508     // Store the result in the cache.
2509     result = aliased;
2510     return aliased;
2511   }
2512 
2513   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2514 
2515   /// Cache for alias results.
2516   /// TODO: consider moving this to the AliasAnalysis itself.
2517   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2518 
2519   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2520   // globally through SLP because we don't perform any action which
2521   // invalidates capture results.
2522   BatchAAResults BatchAA;
2523 
2524   /// Removes an instruction from its block and eventually deletes it.
2525   /// It's like Instruction::eraseFromParent() except that the actual deletion
2526   /// is delayed until BoUpSLP is destructed.
2527   /// This is required to ensure that there are no incorrect collisions in the
2528   /// AliasCache, which can happen if a new instruction is allocated at the
2529   /// same address as a previously deleted instruction.
2530   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2531     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2532     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2533   }
2534 
2535   /// Temporary store for deleted instructions. Instructions will be deleted
2536   /// eventually when the BoUpSLP is destructed.
2537   DenseMap<Instruction *, bool> DeletedInstructions;
2538 
2539   /// A list of values that need to extracted out of the tree.
2540   /// This list holds pairs of (Internal Scalar : External User). External User
2541   /// can be nullptr, it means that this Internal Scalar will be used later,
2542   /// after vectorization.
2543   UserList ExternalUses;
2544 
2545   /// Values used only by @llvm.assume calls.
2546   SmallPtrSet<const Value *, 32> EphValues;
2547 
2548   /// Holds all of the instructions that we gathered.
2549   SetVector<Instruction *> GatherShuffleSeq;
2550 
2551   /// A list of blocks that we are going to CSE.
2552   SetVector<BasicBlock *> CSEBlocks;
2553 
2554   /// Contains all scheduling relevant data for an instruction.
2555   /// A ScheduleData either represents a single instruction or a member of an
2556   /// instruction bundle (= a group of instructions which is combined into a
2557   /// vector instruction).
2558   struct ScheduleData {
2559     // The initial value for the dependency counters. It means that the
2560     // dependencies are not calculated yet.
2561     enum { InvalidDeps = -1 };
2562 
2563     ScheduleData() = default;
2564 
2565     void init(int BlockSchedulingRegionID, Value *OpVal) {
2566       FirstInBundle = this;
2567       NextInBundle = nullptr;
2568       NextLoadStore = nullptr;
2569       IsScheduled = false;
2570       SchedulingRegionID = BlockSchedulingRegionID;
2571       clearDependencies();
2572       OpValue = OpVal;
2573       TE = nullptr;
2574     }
2575 
2576     /// Verify basic self consistency properties
2577     void verify() {
2578       if (hasValidDependencies()) {
2579         assert(UnscheduledDeps <= Dependencies && "invariant");
2580       } else {
2581         assert(UnscheduledDeps == Dependencies && "invariant");
2582       }
2583 
2584       if (IsScheduled) {
2585         assert(isSchedulingEntity() &&
2586                 "unexpected scheduled state");
2587         for (const ScheduleData *BundleMember = this; BundleMember;
2588              BundleMember = BundleMember->NextInBundle) {
2589           assert(BundleMember->hasValidDependencies() &&
2590                  BundleMember->UnscheduledDeps == 0 &&
2591                  "unexpected scheduled state");
2592           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2593                  "only bundle is marked scheduled");
2594         }
2595       }
2596 
2597       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2598              "all bundle members must be in same basic block");
2599     }
2600 
2601     /// Returns true if the dependency information has been calculated.
2602     /// Note that depenendency validity can vary between instructions within
2603     /// a single bundle.
2604     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2605 
2606     /// Returns true for single instructions and for bundle representatives
2607     /// (= the head of a bundle).
2608     bool isSchedulingEntity() const { return FirstInBundle == this; }
2609 
2610     /// Returns true if it represents an instruction bundle and not only a
2611     /// single instruction.
2612     bool isPartOfBundle() const {
2613       return NextInBundle != nullptr || FirstInBundle != this || TE;
2614     }
2615 
2616     /// Returns true if it is ready for scheduling, i.e. it has no more
2617     /// unscheduled depending instructions/bundles.
2618     bool isReady() const {
2619       assert(isSchedulingEntity() &&
2620              "can't consider non-scheduling entity for ready list");
2621       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2622     }
2623 
2624     /// Modifies the number of unscheduled dependencies for this instruction,
2625     /// and returns the number of remaining dependencies for the containing
2626     /// bundle.
2627     int incrementUnscheduledDeps(int Incr) {
2628       assert(hasValidDependencies() &&
2629              "increment of unscheduled deps would be meaningless");
2630       UnscheduledDeps += Incr;
2631       return FirstInBundle->unscheduledDepsInBundle();
2632     }
2633 
2634     /// Sets the number of unscheduled dependencies to the number of
2635     /// dependencies.
2636     void resetUnscheduledDeps() {
2637       UnscheduledDeps = Dependencies;
2638     }
2639 
2640     /// Clears all dependency information.
2641     void clearDependencies() {
2642       Dependencies = InvalidDeps;
2643       resetUnscheduledDeps();
2644       MemoryDependencies.clear();
2645       ControlDependencies.clear();
2646     }
2647 
2648     int unscheduledDepsInBundle() const {
2649       assert(isSchedulingEntity() && "only meaningful on the bundle");
2650       int Sum = 0;
2651       for (const ScheduleData *BundleMember = this; BundleMember;
2652            BundleMember = BundleMember->NextInBundle) {
2653         if (BundleMember->UnscheduledDeps == InvalidDeps)
2654           return InvalidDeps;
2655         Sum += BundleMember->UnscheduledDeps;
2656       }
2657       return Sum;
2658     }
2659 
2660     void dump(raw_ostream &os) const {
2661       if (!isSchedulingEntity()) {
2662         os << "/ " << *Inst;
2663       } else if (NextInBundle) {
2664         os << '[' << *Inst;
2665         ScheduleData *SD = NextInBundle;
2666         while (SD) {
2667           os << ';' << *SD->Inst;
2668           SD = SD->NextInBundle;
2669         }
2670         os << ']';
2671       } else {
2672         os << *Inst;
2673       }
2674     }
2675 
2676     Instruction *Inst = nullptr;
2677 
2678     /// Opcode of the current instruction in the schedule data.
2679     Value *OpValue = nullptr;
2680 
2681     /// The TreeEntry that this instruction corresponds to.
2682     TreeEntry *TE = nullptr;
2683 
2684     /// Points to the head in an instruction bundle (and always to this for
2685     /// single instructions).
2686     ScheduleData *FirstInBundle = nullptr;
2687 
2688     /// Single linked list of all instructions in a bundle. Null if it is a
2689     /// single instruction.
2690     ScheduleData *NextInBundle = nullptr;
2691 
2692     /// Single linked list of all memory instructions (e.g. load, store, call)
2693     /// in the block - until the end of the scheduling region.
2694     ScheduleData *NextLoadStore = nullptr;
2695 
2696     /// The dependent memory instructions.
2697     /// This list is derived on demand in calculateDependencies().
2698     SmallVector<ScheduleData *, 4> MemoryDependencies;
2699 
2700     /// List of instructions which this instruction could be control dependent
2701     /// on.  Allowing such nodes to be scheduled below this one could introduce
2702     /// a runtime fault which didn't exist in the original program.
2703     /// ex: this is a load or udiv following a readonly call which inf loops
2704     SmallVector<ScheduleData *, 4> ControlDependencies;
2705 
2706     /// This ScheduleData is in the current scheduling region if this matches
2707     /// the current SchedulingRegionID of BlockScheduling.
2708     int SchedulingRegionID = 0;
2709 
2710     /// Used for getting a "good" final ordering of instructions.
2711     int SchedulingPriority = 0;
2712 
2713     /// The number of dependencies. Constitutes of the number of users of the
2714     /// instruction plus the number of dependent memory instructions (if any).
2715     /// This value is calculated on demand.
2716     /// If InvalidDeps, the number of dependencies is not calculated yet.
2717     int Dependencies = InvalidDeps;
2718 
2719     /// The number of dependencies minus the number of dependencies of scheduled
2720     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2721     /// for scheduling.
2722     /// Note that this is negative as long as Dependencies is not calculated.
2723     int UnscheduledDeps = InvalidDeps;
2724 
2725     /// True if this instruction is scheduled (or considered as scheduled in the
2726     /// dry-run).
2727     bool IsScheduled = false;
2728   };
2729 
2730 #ifndef NDEBUG
2731   friend inline raw_ostream &operator<<(raw_ostream &os,
2732                                         const BoUpSLP::ScheduleData &SD) {
2733     SD.dump(os);
2734     return os;
2735   }
2736 #endif
2737 
2738   friend struct GraphTraits<BoUpSLP *>;
2739   friend struct DOTGraphTraits<BoUpSLP *>;
2740 
2741   /// Contains all scheduling data for a basic block.
2742   /// It does not schedules instructions, which are not memory read/write
2743   /// instructions and their operands are either constants, or arguments, or
2744   /// phis, or instructions from others blocks, or their users are phis or from
2745   /// the other blocks. The resulting vector instructions can be placed at the
2746   /// beginning of the basic block without scheduling (if operands does not need
2747   /// to be scheduled) or at the end of the block (if users are outside of the
2748   /// block). It allows to save some compile time and memory used by the
2749   /// compiler.
2750   /// ScheduleData is assigned for each instruction in between the boundaries of
2751   /// the tree entry, even for those, which are not part of the graph. It is
2752   /// required to correctly follow the dependencies between the instructions and
2753   /// their correct scheduling. The ScheduleData is not allocated for the
2754   /// instructions, which do not require scheduling, like phis, nodes with
2755   /// extractelements/insertelements only or nodes with instructions, with
2756   /// uses/operands outside of the block.
2757   struct BlockScheduling {
2758     BlockScheduling(BasicBlock *BB)
2759         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2760 
2761     void clear() {
2762       ReadyInsts.clear();
2763       ScheduleStart = nullptr;
2764       ScheduleEnd = nullptr;
2765       FirstLoadStoreInRegion = nullptr;
2766       LastLoadStoreInRegion = nullptr;
2767 
2768       // Reduce the maximum schedule region size by the size of the
2769       // previous scheduling run.
2770       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2771       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2772         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2773       ScheduleRegionSize = 0;
2774 
2775       // Make a new scheduling region, i.e. all existing ScheduleData is not
2776       // in the new region yet.
2777       ++SchedulingRegionID;
2778     }
2779 
2780     ScheduleData *getScheduleData(Instruction *I) {
2781       if (BB != I->getParent())
2782         // Avoid lookup if can't possibly be in map.
2783         return nullptr;
2784       ScheduleData *SD = ScheduleDataMap.lookup(I);
2785       if (SD && isInSchedulingRegion(SD))
2786         return SD;
2787       return nullptr;
2788     }
2789 
2790     ScheduleData *getScheduleData(Value *V) {
2791       if (auto *I = dyn_cast<Instruction>(V))
2792         return getScheduleData(I);
2793       return nullptr;
2794     }
2795 
2796     ScheduleData *getScheduleData(Value *V, Value *Key) {
2797       if (V == Key)
2798         return getScheduleData(V);
2799       auto I = ExtraScheduleDataMap.find(V);
2800       if (I != ExtraScheduleDataMap.end()) {
2801         ScheduleData *SD = I->second.lookup(Key);
2802         if (SD && isInSchedulingRegion(SD))
2803           return SD;
2804       }
2805       return nullptr;
2806     }
2807 
2808     bool isInSchedulingRegion(ScheduleData *SD) const {
2809       return SD->SchedulingRegionID == SchedulingRegionID;
2810     }
2811 
2812     /// Marks an instruction as scheduled and puts all dependent ready
2813     /// instructions into the ready-list.
2814     template <typename ReadyListType>
2815     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2816       SD->IsScheduled = true;
2817       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2818 
2819       for (ScheduleData *BundleMember = SD; BundleMember;
2820            BundleMember = BundleMember->NextInBundle) {
2821         if (BundleMember->Inst != BundleMember->OpValue)
2822           continue;
2823 
2824         // Handle the def-use chain dependencies.
2825 
2826         // Decrement the unscheduled counter and insert to ready list if ready.
2827         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2828           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2829             if (OpDef && OpDef->hasValidDependencies() &&
2830                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2831               // There are no more unscheduled dependencies after
2832               // decrementing, so we can put the dependent instruction
2833               // into the ready list.
2834               ScheduleData *DepBundle = OpDef->FirstInBundle;
2835               assert(!DepBundle->IsScheduled &&
2836                      "already scheduled bundle gets ready");
2837               ReadyList.insert(DepBundle);
2838               LLVM_DEBUG(dbgs()
2839                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2840             }
2841           });
2842         };
2843 
2844         // If BundleMember is a vector bundle, its operands may have been
2845         // reordered during buildTree(). We therefore need to get its operands
2846         // through the TreeEntry.
2847         if (TreeEntry *TE = BundleMember->TE) {
2848           // Need to search for the lane since the tree entry can be reordered.
2849           int Lane = std::distance(TE->Scalars.begin(),
2850                                    find(TE->Scalars, BundleMember->Inst));
2851           assert(Lane >= 0 && "Lane not set");
2852 
2853           // Since vectorization tree is being built recursively this assertion
2854           // ensures that the tree entry has all operands set before reaching
2855           // this code. Couple of exceptions known at the moment are extracts
2856           // where their second (immediate) operand is not added. Since
2857           // immediates do not affect scheduler behavior this is considered
2858           // okay.
2859           auto *In = BundleMember->Inst;
2860           assert(In &&
2861                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2862                   In->getNumOperands() == TE->getNumOperands()) &&
2863                  "Missed TreeEntry operands?");
2864           (void)In; // fake use to avoid build failure when assertions disabled
2865 
2866           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2867                OpIdx != NumOperands; ++OpIdx)
2868             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2869               DecrUnsched(I);
2870         } else {
2871           // If BundleMember is a stand-alone instruction, no operand reordering
2872           // has taken place, so we directly access its operands.
2873           for (Use &U : BundleMember->Inst->operands())
2874             if (auto *I = dyn_cast<Instruction>(U.get()))
2875               DecrUnsched(I);
2876         }
2877         // Handle the memory dependencies.
2878         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2879           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2880             // There are no more unscheduled dependencies after decrementing,
2881             // so we can put the dependent instruction into the ready list.
2882             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2883             assert(!DepBundle->IsScheduled &&
2884                    "already scheduled bundle gets ready");
2885             ReadyList.insert(DepBundle);
2886             LLVM_DEBUG(dbgs()
2887                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2888           }
2889         }
2890         // Handle the control dependencies.
2891         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2892           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2893             // There are no more unscheduled dependencies after decrementing,
2894             // so we can put the dependent instruction into the ready list.
2895             ScheduleData *DepBundle = DepSD->FirstInBundle;
2896             assert(!DepBundle->IsScheduled &&
2897                    "already scheduled bundle gets ready");
2898             ReadyList.insert(DepBundle);
2899             LLVM_DEBUG(dbgs()
2900                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2901           }
2902         }
2903 
2904       }
2905     }
2906 
2907     /// Verify basic self consistency properties of the data structure.
2908     void verify() {
2909       if (!ScheduleStart)
2910         return;
2911 
2912       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2913              ScheduleStart->comesBefore(ScheduleEnd) &&
2914              "Not a valid scheduling region?");
2915 
2916       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2917         auto *SD = getScheduleData(I);
2918         if (!SD)
2919           continue;
2920         assert(isInSchedulingRegion(SD) &&
2921                "primary schedule data not in window?");
2922         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2923                "entire bundle in window!");
2924         (void)SD;
2925         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2926       }
2927 
2928       for (auto *SD : ReadyInsts) {
2929         assert(SD->isSchedulingEntity() && SD->isReady() &&
2930                "item in ready list not ready?");
2931         (void)SD;
2932       }
2933     }
2934 
2935     void doForAllOpcodes(Value *V,
2936                          function_ref<void(ScheduleData *SD)> Action) {
2937       if (ScheduleData *SD = getScheduleData(V))
2938         Action(SD);
2939       auto I = ExtraScheduleDataMap.find(V);
2940       if (I != ExtraScheduleDataMap.end())
2941         for (auto &P : I->second)
2942           if (isInSchedulingRegion(P.second))
2943             Action(P.second);
2944     }
2945 
2946     /// Put all instructions into the ReadyList which are ready for scheduling.
2947     template <typename ReadyListType>
2948     void initialFillReadyList(ReadyListType &ReadyList) {
2949       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2950         doForAllOpcodes(I, [&](ScheduleData *SD) {
2951           if (SD->isSchedulingEntity() && SD->isReady()) {
2952             ReadyList.insert(SD);
2953             LLVM_DEBUG(dbgs()
2954                        << "SLP:    initially in ready list: " << *SD << "\n");
2955           }
2956         });
2957       }
2958     }
2959 
2960     /// Build a bundle from the ScheduleData nodes corresponding to the
2961     /// scalar instruction for each lane.
2962     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2963 
2964     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2965     /// cyclic dependencies. This is only a dry-run, no instructions are
2966     /// actually moved at this stage.
2967     /// \returns the scheduling bundle. The returned Optional value is non-None
2968     /// if \p VL is allowed to be scheduled.
2969     Optional<ScheduleData *>
2970     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2971                       const InstructionsState &S);
2972 
2973     /// Un-bundles a group of instructions.
2974     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2975 
2976     /// Allocates schedule data chunk.
2977     ScheduleData *allocateScheduleDataChunks();
2978 
2979     /// Extends the scheduling region so that V is inside the region.
2980     /// \returns true if the region size is within the limit.
2981     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2982 
2983     /// Initialize the ScheduleData structures for new instructions in the
2984     /// scheduling region.
2985     void initScheduleData(Instruction *FromI, Instruction *ToI,
2986                           ScheduleData *PrevLoadStore,
2987                           ScheduleData *NextLoadStore);
2988 
2989     /// Updates the dependency information of a bundle and of all instructions/
2990     /// bundles which depend on the original bundle.
2991     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2992                                BoUpSLP *SLP);
2993 
2994     /// Sets all instruction in the scheduling region to un-scheduled.
2995     void resetSchedule();
2996 
2997     BasicBlock *BB;
2998 
2999     /// Simple memory allocation for ScheduleData.
3000     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3001 
3002     /// The size of a ScheduleData array in ScheduleDataChunks.
3003     int ChunkSize;
3004 
3005     /// The allocator position in the current chunk, which is the last entry
3006     /// of ScheduleDataChunks.
3007     int ChunkPos;
3008 
3009     /// Attaches ScheduleData to Instruction.
3010     /// Note that the mapping survives during all vectorization iterations, i.e.
3011     /// ScheduleData structures are recycled.
3012     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3013 
3014     /// Attaches ScheduleData to Instruction with the leading key.
3015     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3016         ExtraScheduleDataMap;
3017 
3018     /// The ready-list for scheduling (only used for the dry-run).
3019     SetVector<ScheduleData *> ReadyInsts;
3020 
3021     /// The first instruction of the scheduling region.
3022     Instruction *ScheduleStart = nullptr;
3023 
3024     /// The first instruction _after_ the scheduling region.
3025     Instruction *ScheduleEnd = nullptr;
3026 
3027     /// The first memory accessing instruction in the scheduling region
3028     /// (can be null).
3029     ScheduleData *FirstLoadStoreInRegion = nullptr;
3030 
3031     /// The last memory accessing instruction in the scheduling region
3032     /// (can be null).
3033     ScheduleData *LastLoadStoreInRegion = nullptr;
3034 
3035     /// The current size of the scheduling region.
3036     int ScheduleRegionSize = 0;
3037 
3038     /// The maximum size allowed for the scheduling region.
3039     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3040 
3041     /// The ID of the scheduling region. For a new vectorization iteration this
3042     /// is incremented which "removes" all ScheduleData from the region.
3043     /// Make sure that the initial SchedulingRegionID is greater than the
3044     /// initial SchedulingRegionID in ScheduleData (which is 0).
3045     int SchedulingRegionID = 1;
3046   };
3047 
3048   /// Attaches the BlockScheduling structures to basic blocks.
3049   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3050 
3051   /// Performs the "real" scheduling. Done before vectorization is actually
3052   /// performed in a basic block.
3053   void scheduleBlock(BlockScheduling *BS);
3054 
3055   /// List of users to ignore during scheduling and that don't need extracting.
3056   ArrayRef<Value *> UserIgnoreList;
3057 
3058   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3059   /// sorted SmallVectors of unsigned.
3060   struct OrdersTypeDenseMapInfo {
3061     static OrdersType getEmptyKey() {
3062       OrdersType V;
3063       V.push_back(~1U);
3064       return V;
3065     }
3066 
3067     static OrdersType getTombstoneKey() {
3068       OrdersType V;
3069       V.push_back(~2U);
3070       return V;
3071     }
3072 
3073     static unsigned getHashValue(const OrdersType &V) {
3074       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3075     }
3076 
3077     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3078       return LHS == RHS;
3079     }
3080   };
3081 
3082   // Analysis and block reference.
3083   Function *F;
3084   ScalarEvolution *SE;
3085   TargetTransformInfo *TTI;
3086   TargetLibraryInfo *TLI;
3087   LoopInfo *LI;
3088   DominatorTree *DT;
3089   AssumptionCache *AC;
3090   DemandedBits *DB;
3091   const DataLayout *DL;
3092   OptimizationRemarkEmitter *ORE;
3093 
3094   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3095   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3096 
3097   /// Instruction builder to construct the vectorized tree.
3098   IRBuilder<> Builder;
3099 
3100   /// A map of scalar integer values to the smallest bit width with which they
3101   /// can legally be represented. The values map to (width, signed) pairs,
3102   /// where "width" indicates the minimum bit width and "signed" is True if the
3103   /// value must be signed-extended, rather than zero-extended, back to its
3104   /// original width.
3105   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3106 };
3107 
3108 } // end namespace slpvectorizer
3109 
3110 template <> struct GraphTraits<BoUpSLP *> {
3111   using TreeEntry = BoUpSLP::TreeEntry;
3112 
3113   /// NodeRef has to be a pointer per the GraphWriter.
3114   using NodeRef = TreeEntry *;
3115 
3116   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3117 
3118   /// Add the VectorizableTree to the index iterator to be able to return
3119   /// TreeEntry pointers.
3120   struct ChildIteratorType
3121       : public iterator_adaptor_base<
3122             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3123     ContainerTy &VectorizableTree;
3124 
3125     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3126                       ContainerTy &VT)
3127         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3128 
3129     NodeRef operator*() { return I->UserTE; }
3130   };
3131 
3132   static NodeRef getEntryNode(BoUpSLP &R) {
3133     return R.VectorizableTree[0].get();
3134   }
3135 
3136   static ChildIteratorType child_begin(NodeRef N) {
3137     return {N->UserTreeIndices.begin(), N->Container};
3138   }
3139 
3140   static ChildIteratorType child_end(NodeRef N) {
3141     return {N->UserTreeIndices.end(), N->Container};
3142   }
3143 
3144   /// For the node iterator we just need to turn the TreeEntry iterator into a
3145   /// TreeEntry* iterator so that it dereferences to NodeRef.
3146   class nodes_iterator {
3147     using ItTy = ContainerTy::iterator;
3148     ItTy It;
3149 
3150   public:
3151     nodes_iterator(const ItTy &It2) : It(It2) {}
3152     NodeRef operator*() { return It->get(); }
3153     nodes_iterator operator++() {
3154       ++It;
3155       return *this;
3156     }
3157     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3158   };
3159 
3160   static nodes_iterator nodes_begin(BoUpSLP *R) {
3161     return nodes_iterator(R->VectorizableTree.begin());
3162   }
3163 
3164   static nodes_iterator nodes_end(BoUpSLP *R) {
3165     return nodes_iterator(R->VectorizableTree.end());
3166   }
3167 
3168   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3169 };
3170 
3171 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3172   using TreeEntry = BoUpSLP::TreeEntry;
3173 
3174   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3175 
3176   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3177     std::string Str;
3178     raw_string_ostream OS(Str);
3179     if (isSplat(Entry->Scalars))
3180       OS << "<splat> ";
3181     for (auto V : Entry->Scalars) {
3182       OS << *V;
3183       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3184             return EU.Scalar == V;
3185           }))
3186         OS << " <extract>";
3187       OS << "\n";
3188     }
3189     return Str;
3190   }
3191 
3192   static std::string getNodeAttributes(const TreeEntry *Entry,
3193                                        const BoUpSLP *) {
3194     if (Entry->State == TreeEntry::NeedToGather)
3195       return "color=red";
3196     return "";
3197   }
3198 };
3199 
3200 } // end namespace llvm
3201 
3202 BoUpSLP::~BoUpSLP() {
3203   for (const auto &Pair : DeletedInstructions) {
3204     // Replace operands of ignored instructions with Undefs in case if they were
3205     // marked for deletion.
3206     if (Pair.getSecond()) {
3207       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3208       Pair.getFirst()->replaceAllUsesWith(Undef);
3209     }
3210     Pair.getFirst()->dropAllReferences();
3211   }
3212   for (const auto &Pair : DeletedInstructions) {
3213     assert(Pair.getFirst()->use_empty() &&
3214            "trying to erase instruction with users.");
3215     Pair.getFirst()->eraseFromParent();
3216   }
3217 #ifdef EXPENSIVE_CHECKS
3218   // If we could guarantee that this call is not extremely slow, we could
3219   // remove the ifdef limitation (see PR47712).
3220   assert(!verifyFunction(*F, &dbgs()));
3221 #endif
3222 }
3223 
3224 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3225   for (auto *V : AV) {
3226     if (auto *I = dyn_cast<Instruction>(V))
3227       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3228   };
3229 }
3230 
3231 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3232 /// contains original mask for the scalars reused in the node. Procedure
3233 /// transform this mask in accordance with the given \p Mask.
3234 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3235   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3236          "Expected non-empty mask.");
3237   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3238   Prev.swap(Reuses);
3239   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3240     if (Mask[I] != UndefMaskElem)
3241       Reuses[Mask[I]] = Prev[I];
3242 }
3243 
3244 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3245 /// the original order of the scalars. Procedure transforms the provided order
3246 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3247 /// identity order, \p Order is cleared.
3248 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3249   assert(!Mask.empty() && "Expected non-empty mask.");
3250   SmallVector<int> MaskOrder;
3251   if (Order.empty()) {
3252     MaskOrder.resize(Mask.size());
3253     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3254   } else {
3255     inversePermutation(Order, MaskOrder);
3256   }
3257   reorderReuses(MaskOrder, Mask);
3258   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3259     Order.clear();
3260     return;
3261   }
3262   Order.assign(Mask.size(), Mask.size());
3263   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3264     if (MaskOrder[I] != UndefMaskElem)
3265       Order[MaskOrder[I]] = I;
3266   fixupOrderingIndices(Order);
3267 }
3268 
3269 Optional<BoUpSLP::OrdersType>
3270 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3271   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3272   unsigned NumScalars = TE.Scalars.size();
3273   OrdersType CurrentOrder(NumScalars, NumScalars);
3274   SmallVector<int> Positions;
3275   SmallBitVector UsedPositions(NumScalars);
3276   const TreeEntry *STE = nullptr;
3277   // Try to find all gathered scalars that are gets vectorized in other
3278   // vectorize node. Here we can have only one single tree vector node to
3279   // correctly identify order of the gathered scalars.
3280   for (unsigned I = 0; I < NumScalars; ++I) {
3281     Value *V = TE.Scalars[I];
3282     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3283       continue;
3284     if (const auto *LocalSTE = getTreeEntry(V)) {
3285       if (!STE)
3286         STE = LocalSTE;
3287       else if (STE != LocalSTE)
3288         // Take the order only from the single vector node.
3289         return None;
3290       unsigned Lane =
3291           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3292       if (Lane >= NumScalars)
3293         return None;
3294       if (CurrentOrder[Lane] != NumScalars) {
3295         if (Lane != I)
3296           continue;
3297         UsedPositions.reset(CurrentOrder[Lane]);
3298       }
3299       // The partial identity (where only some elements of the gather node are
3300       // in the identity order) is good.
3301       CurrentOrder[Lane] = I;
3302       UsedPositions.set(I);
3303     }
3304   }
3305   // Need to keep the order if we have a vector entry and at least 2 scalars or
3306   // the vectorized entry has just 2 scalars.
3307   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3308     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3309       for (unsigned I = 0; I < NumScalars; ++I)
3310         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3311           return false;
3312       return true;
3313     };
3314     if (IsIdentityOrder(CurrentOrder)) {
3315       CurrentOrder.clear();
3316       return CurrentOrder;
3317     }
3318     auto *It = CurrentOrder.begin();
3319     for (unsigned I = 0; I < NumScalars;) {
3320       if (UsedPositions.test(I)) {
3321         ++I;
3322         continue;
3323       }
3324       if (*It == NumScalars) {
3325         *It = I;
3326         ++I;
3327       }
3328       ++It;
3329     }
3330     return CurrentOrder;
3331   }
3332   return None;
3333 }
3334 
3335 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3336                                                          bool TopToBottom) {
3337   // No need to reorder if need to shuffle reuses, still need to shuffle the
3338   // node.
3339   if (!TE.ReuseShuffleIndices.empty())
3340     return None;
3341   if (TE.State == TreeEntry::Vectorize &&
3342       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3343        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3344       !TE.isAltShuffle())
3345     return TE.ReorderIndices;
3346   if (TE.State == TreeEntry::NeedToGather) {
3347     // TODO: add analysis of other gather nodes with extractelement
3348     // instructions and other values/instructions, not only undefs.
3349     if (((TE.getOpcode() == Instruction::ExtractElement &&
3350           !TE.isAltShuffle()) ||
3351          (all_of(TE.Scalars,
3352                  [](Value *V) {
3353                    return isa<UndefValue, ExtractElementInst>(V);
3354                  }) &&
3355           any_of(TE.Scalars,
3356                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3357         all_of(TE.Scalars,
3358                [](Value *V) {
3359                  auto *EE = dyn_cast<ExtractElementInst>(V);
3360                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3361                }) &&
3362         allSameType(TE.Scalars)) {
3363       // Check that gather of extractelements can be represented as
3364       // just a shuffle of a single vector.
3365       OrdersType CurrentOrder;
3366       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3367       if (Reuse || !CurrentOrder.empty()) {
3368         if (!CurrentOrder.empty())
3369           fixupOrderingIndices(CurrentOrder);
3370         return CurrentOrder;
3371       }
3372     }
3373     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3374       return CurrentOrder;
3375   }
3376   return None;
3377 }
3378 
3379 void BoUpSLP::reorderTopToBottom() {
3380   // Maps VF to the graph nodes.
3381   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3382   // ExtractElement gather nodes which can be vectorized and need to handle
3383   // their ordering.
3384   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3385   // Find all reorderable nodes with the given VF.
3386   // Currently the are vectorized stores,loads,extracts + some gathering of
3387   // extracts.
3388   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3389                                  const std::unique_ptr<TreeEntry> &TE) {
3390     if (Optional<OrdersType> CurrentOrder =
3391             getReorderingData(*TE, /*TopToBottom=*/true)) {
3392       // Do not include ordering for nodes used in the alt opcode vectorization,
3393       // better to reorder them during bottom-to-top stage. If follow the order
3394       // here, it causes reordering of the whole graph though actually it is
3395       // profitable just to reorder the subgraph that starts from the alternate
3396       // opcode vectorization node. Such nodes already end-up with the shuffle
3397       // instruction and it is just enough to change this shuffle rather than
3398       // rotate the scalars for the whole graph.
3399       unsigned Cnt = 0;
3400       const TreeEntry *UserTE = TE.get();
3401       while (UserTE && Cnt < RecursionMaxDepth) {
3402         if (UserTE->UserTreeIndices.size() != 1)
3403           break;
3404         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3405               return EI.UserTE->State == TreeEntry::Vectorize &&
3406                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3407             }))
3408           return;
3409         if (UserTE->UserTreeIndices.empty())
3410           UserTE = nullptr;
3411         else
3412           UserTE = UserTE->UserTreeIndices.back().UserTE;
3413         ++Cnt;
3414       }
3415       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3416       if (TE->State != TreeEntry::Vectorize)
3417         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3418     }
3419   });
3420 
3421   // Reorder the graph nodes according to their vectorization factor.
3422   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3423        VF /= 2) {
3424     auto It = VFToOrderedEntries.find(VF);
3425     if (It == VFToOrderedEntries.end())
3426       continue;
3427     // Try to find the most profitable order. We just are looking for the most
3428     // used order and reorder scalar elements in the nodes according to this
3429     // mostly used order.
3430     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3431     // All operands are reordered and used only in this node - propagate the
3432     // most used order to the user node.
3433     MapVector<OrdersType, unsigned,
3434               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3435         OrdersUses;
3436     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3437     for (const TreeEntry *OpTE : OrderedEntries) {
3438       // No need to reorder this nodes, still need to extend and to use shuffle,
3439       // just need to merge reordering shuffle and the reuse shuffle.
3440       if (!OpTE->ReuseShuffleIndices.empty())
3441         continue;
3442       // Count number of orders uses.
3443       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3444         if (OpTE->State == TreeEntry::NeedToGather)
3445           return GathersToOrders.find(OpTE)->second;
3446         return OpTE->ReorderIndices;
3447       }();
3448       // Stores actually store the mask, not the order, need to invert.
3449       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3450           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3451         SmallVector<int> Mask;
3452         inversePermutation(Order, Mask);
3453         unsigned E = Order.size();
3454         OrdersType CurrentOrder(E, E);
3455         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3456           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3457         });
3458         fixupOrderingIndices(CurrentOrder);
3459         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3460       } else {
3461         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3462       }
3463     }
3464     // Set order of the user node.
3465     if (OrdersUses.empty())
3466       continue;
3467     // Choose the most used order.
3468     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3469     unsigned Cnt = OrdersUses.front().second;
3470     for (const auto &Pair : drop_begin(OrdersUses)) {
3471       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3472         BestOrder = Pair.first;
3473         Cnt = Pair.second;
3474       }
3475     }
3476     // Set order of the user node.
3477     if (BestOrder.empty())
3478       continue;
3479     SmallVector<int> Mask;
3480     inversePermutation(BestOrder, Mask);
3481     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3482     unsigned E = BestOrder.size();
3483     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3484       return I < E ? static_cast<int>(I) : UndefMaskElem;
3485     });
3486     // Do an actual reordering, if profitable.
3487     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3488       // Just do the reordering for the nodes with the given VF.
3489       if (TE->Scalars.size() != VF) {
3490         if (TE->ReuseShuffleIndices.size() == VF) {
3491           // Need to reorder the reuses masks of the operands with smaller VF to
3492           // be able to find the match between the graph nodes and scalar
3493           // operands of the given node during vectorization/cost estimation.
3494           assert(all_of(TE->UserTreeIndices,
3495                         [VF, &TE](const EdgeInfo &EI) {
3496                           return EI.UserTE->Scalars.size() == VF ||
3497                                  EI.UserTE->Scalars.size() ==
3498                                      TE->Scalars.size();
3499                         }) &&
3500                  "All users must be of VF size.");
3501           // Update ordering of the operands with the smaller VF than the given
3502           // one.
3503           reorderReuses(TE->ReuseShuffleIndices, Mask);
3504         }
3505         continue;
3506       }
3507       if (TE->State == TreeEntry::Vectorize &&
3508           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3509               InsertElementInst>(TE->getMainOp()) &&
3510           !TE->isAltShuffle()) {
3511         // Build correct orders for extract{element,value}, loads and
3512         // stores.
3513         reorderOrder(TE->ReorderIndices, Mask);
3514         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3515           TE->reorderOperands(Mask);
3516       } else {
3517         // Reorder the node and its operands.
3518         TE->reorderOperands(Mask);
3519         assert(TE->ReorderIndices.empty() &&
3520                "Expected empty reorder sequence.");
3521         reorderScalars(TE->Scalars, Mask);
3522       }
3523       if (!TE->ReuseShuffleIndices.empty()) {
3524         // Apply reversed order to keep the original ordering of the reused
3525         // elements to avoid extra reorder indices shuffling.
3526         OrdersType CurrentOrder;
3527         reorderOrder(CurrentOrder, MaskOrder);
3528         SmallVector<int> NewReuses;
3529         inversePermutation(CurrentOrder, NewReuses);
3530         addMask(NewReuses, TE->ReuseShuffleIndices);
3531         TE->ReuseShuffleIndices.swap(NewReuses);
3532       }
3533     }
3534   }
3535 }
3536 
3537 bool BoUpSLP::canReorderOperands(
3538     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3539     ArrayRef<TreeEntry *> ReorderableGathers,
3540     SmallVectorImpl<TreeEntry *> &GatherOps) {
3541   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3542     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3543           return OpData.first == I &&
3544                  OpData.second->State == TreeEntry::Vectorize;
3545         }))
3546       continue;
3547     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3548       // Do not reorder if operand node is used by many user nodes.
3549       if (any_of(TE->UserTreeIndices,
3550                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3551         return false;
3552       // Add the node to the list of the ordered nodes with the identity
3553       // order.
3554       Edges.emplace_back(I, TE);
3555       continue;
3556     }
3557     ArrayRef<Value *> VL = UserTE->getOperand(I);
3558     TreeEntry *Gather = nullptr;
3559     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3560           assert(TE->State != TreeEntry::Vectorize &&
3561                  "Only non-vectorized nodes are expected.");
3562           if (TE->isSame(VL)) {
3563             Gather = TE;
3564             return true;
3565           }
3566           return false;
3567         }) > 1)
3568       return false;
3569     if (Gather)
3570       GatherOps.push_back(Gather);
3571   }
3572   return true;
3573 }
3574 
3575 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3576   SetVector<TreeEntry *> OrderedEntries;
3577   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3578   // Find all reorderable leaf nodes with the given VF.
3579   // Currently the are vectorized loads,extracts without alternate operands +
3580   // some gathering of extracts.
3581   SmallVector<TreeEntry *> NonVectorized;
3582   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3583                               &NonVectorized](
3584                                  const std::unique_ptr<TreeEntry> &TE) {
3585     if (TE->State != TreeEntry::Vectorize)
3586       NonVectorized.push_back(TE.get());
3587     if (Optional<OrdersType> CurrentOrder =
3588             getReorderingData(*TE, /*TopToBottom=*/false)) {
3589       OrderedEntries.insert(TE.get());
3590       if (TE->State != TreeEntry::Vectorize)
3591         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3592     }
3593   });
3594 
3595   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3596   // I.e., if the node has operands, that are reordered, try to make at least
3597   // one operand order in the natural order and reorder others + reorder the
3598   // user node itself.
3599   SmallPtrSet<const TreeEntry *, 4> Visited;
3600   while (!OrderedEntries.empty()) {
3601     // 1. Filter out only reordered nodes.
3602     // 2. If the entry has multiple uses - skip it and jump to the next node.
3603     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3604     SmallVector<TreeEntry *> Filtered;
3605     for (TreeEntry *TE : OrderedEntries) {
3606       if (!(TE->State == TreeEntry::Vectorize ||
3607             (TE->State == TreeEntry::NeedToGather &&
3608              GathersToOrders.count(TE))) ||
3609           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3610           !all_of(drop_begin(TE->UserTreeIndices),
3611                   [TE](const EdgeInfo &EI) {
3612                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3613                   }) ||
3614           !Visited.insert(TE).second) {
3615         Filtered.push_back(TE);
3616         continue;
3617       }
3618       // Build a map between user nodes and their operands order to speedup
3619       // search. The graph currently does not provide this dependency directly.
3620       for (EdgeInfo &EI : TE->UserTreeIndices) {
3621         TreeEntry *UserTE = EI.UserTE;
3622         auto It = Users.find(UserTE);
3623         if (It == Users.end())
3624           It = Users.insert({UserTE, {}}).first;
3625         It->second.emplace_back(EI.EdgeIdx, TE);
3626       }
3627     }
3628     // Erase filtered entries.
3629     for_each(Filtered,
3630              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3631     for (auto &Data : Users) {
3632       // Check that operands are used only in the User node.
3633       SmallVector<TreeEntry *> GatherOps;
3634       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3635                               GatherOps)) {
3636         for_each(Data.second,
3637                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3638                    OrderedEntries.remove(Op.second);
3639                  });
3640         continue;
3641       }
3642       // All operands are reordered and used only in this node - propagate the
3643       // most used order to the user node.
3644       MapVector<OrdersType, unsigned,
3645                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3646           OrdersUses;
3647       // Do the analysis for each tree entry only once, otherwise the order of
3648       // the same node my be considered several times, though might be not
3649       // profitable.
3650       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3651       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3652       for (const auto &Op : Data.second) {
3653         TreeEntry *OpTE = Op.second;
3654         if (!VisitedOps.insert(OpTE).second)
3655           continue;
3656         if (!OpTE->ReuseShuffleIndices.empty() ||
3657             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3658           continue;
3659         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3660           if (OpTE->State == TreeEntry::NeedToGather)
3661             return GathersToOrders.find(OpTE)->second;
3662           return OpTE->ReorderIndices;
3663         }();
3664         unsigned NumOps = count_if(
3665             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3666               return P.second == OpTE;
3667             });
3668         // Stores actually store the mask, not the order, need to invert.
3669         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3670             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3671           SmallVector<int> Mask;
3672           inversePermutation(Order, Mask);
3673           unsigned E = Order.size();
3674           OrdersType CurrentOrder(E, E);
3675           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3676             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3677           });
3678           fixupOrderingIndices(CurrentOrder);
3679           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3680               NumOps;
3681         } else {
3682           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3683         }
3684         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3685         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3686                                             const TreeEntry *TE) {
3687           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3688               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3689               (IgnoreReorder && TE->Idx == 0))
3690             return true;
3691           if (TE->State == TreeEntry::NeedToGather) {
3692             auto It = GathersToOrders.find(TE);
3693             if (It != GathersToOrders.end())
3694               return !It->second.empty();
3695             return true;
3696           }
3697           return false;
3698         };
3699         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3700           TreeEntry *UserTE = EI.UserTE;
3701           if (!VisitedUsers.insert(UserTE).second)
3702             continue;
3703           // May reorder user node if it requires reordering, has reused
3704           // scalars, is an alternate op vectorize node or its op nodes require
3705           // reordering.
3706           if (AllowsReordering(UserTE))
3707             continue;
3708           // Check if users allow reordering.
3709           // Currently look up just 1 level of operands to avoid increase of
3710           // the compile time.
3711           // Profitable to reorder if definitely more operands allow
3712           // reordering rather than those with natural order.
3713           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3714           if (static_cast<unsigned>(count_if(
3715                   Ops, [UserTE, &AllowsReordering](
3716                            const std::pair<unsigned, TreeEntry *> &Op) {
3717                     return AllowsReordering(Op.second) &&
3718                            all_of(Op.second->UserTreeIndices,
3719                                   [UserTE](const EdgeInfo &EI) {
3720                                     return EI.UserTE == UserTE;
3721                                   });
3722                   })) <= Ops.size() / 2)
3723             ++Res.first->second;
3724         }
3725       }
3726       // If no orders - skip current nodes and jump to the next one, if any.
3727       if (OrdersUses.empty()) {
3728         for_each(Data.second,
3729                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3730                    OrderedEntries.remove(Op.second);
3731                  });
3732         continue;
3733       }
3734       // Choose the best order.
3735       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3736       unsigned Cnt = OrdersUses.front().second;
3737       for (const auto &Pair : drop_begin(OrdersUses)) {
3738         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3739           BestOrder = Pair.first;
3740           Cnt = Pair.second;
3741         }
3742       }
3743       // Set order of the user node (reordering of operands and user nodes).
3744       if (BestOrder.empty()) {
3745         for_each(Data.second,
3746                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3747                    OrderedEntries.remove(Op.second);
3748                  });
3749         continue;
3750       }
3751       // Erase operands from OrderedEntries list and adjust their orders.
3752       VisitedOps.clear();
3753       SmallVector<int> Mask;
3754       inversePermutation(BestOrder, Mask);
3755       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3756       unsigned E = BestOrder.size();
3757       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3758         return I < E ? static_cast<int>(I) : UndefMaskElem;
3759       });
3760       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3761         TreeEntry *TE = Op.second;
3762         OrderedEntries.remove(TE);
3763         if (!VisitedOps.insert(TE).second)
3764           continue;
3765         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3766           // Just reorder reuses indices.
3767           reorderReuses(TE->ReuseShuffleIndices, Mask);
3768           continue;
3769         }
3770         // Gathers are processed separately.
3771         if (TE->State != TreeEntry::Vectorize)
3772           continue;
3773         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3774                 TE->ReorderIndices.empty()) &&
3775                "Non-matching sizes of user/operand entries.");
3776         reorderOrder(TE->ReorderIndices, Mask);
3777       }
3778       // For gathers just need to reorder its scalars.
3779       for (TreeEntry *Gather : GatherOps) {
3780         assert(Gather->ReorderIndices.empty() &&
3781                "Unexpected reordering of gathers.");
3782         if (!Gather->ReuseShuffleIndices.empty()) {
3783           // Just reorder reuses indices.
3784           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3785           continue;
3786         }
3787         reorderScalars(Gather->Scalars, Mask);
3788         OrderedEntries.remove(Gather);
3789       }
3790       // Reorder operands of the user node and set the ordering for the user
3791       // node itself.
3792       if (Data.first->State != TreeEntry::Vectorize ||
3793           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3794               Data.first->getMainOp()) ||
3795           Data.first->isAltShuffle())
3796         Data.first->reorderOperands(Mask);
3797       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3798           Data.first->isAltShuffle()) {
3799         reorderScalars(Data.first->Scalars, Mask);
3800         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3801         if (Data.first->ReuseShuffleIndices.empty() &&
3802             !Data.first->ReorderIndices.empty() &&
3803             !Data.first->isAltShuffle()) {
3804           // Insert user node to the list to try to sink reordering deeper in
3805           // the graph.
3806           OrderedEntries.insert(Data.first);
3807         }
3808       } else {
3809         reorderOrder(Data.first->ReorderIndices, Mask);
3810       }
3811     }
3812   }
3813   // If the reordering is unnecessary, just remove the reorder.
3814   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3815       VectorizableTree.front()->ReuseShuffleIndices.empty())
3816     VectorizableTree.front()->ReorderIndices.clear();
3817 }
3818 
3819 void BoUpSLP::buildExternalUses(
3820     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3821   // Collect the values that we need to extract from the tree.
3822   for (auto &TEPtr : VectorizableTree) {
3823     TreeEntry *Entry = TEPtr.get();
3824 
3825     // No need to handle users of gathered values.
3826     if (Entry->State == TreeEntry::NeedToGather)
3827       continue;
3828 
3829     // For each lane:
3830     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3831       Value *Scalar = Entry->Scalars[Lane];
3832       int FoundLane = Entry->findLaneForValue(Scalar);
3833 
3834       // Check if the scalar is externally used as an extra arg.
3835       auto ExtI = ExternallyUsedValues.find(Scalar);
3836       if (ExtI != ExternallyUsedValues.end()) {
3837         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3838                           << Lane << " from " << *Scalar << ".\n");
3839         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3840       }
3841       for (User *U : Scalar->users()) {
3842         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3843 
3844         Instruction *UserInst = dyn_cast<Instruction>(U);
3845         if (!UserInst)
3846           continue;
3847 
3848         if (isDeleted(UserInst))
3849           continue;
3850 
3851         // Skip in-tree scalars that become vectors
3852         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3853           Value *UseScalar = UseEntry->Scalars[0];
3854           // Some in-tree scalars will remain as scalar in vectorized
3855           // instructions. If that is the case, the one in Lane 0 will
3856           // be used.
3857           if (UseScalar != U ||
3858               UseEntry->State == TreeEntry::ScatterVectorize ||
3859               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3860             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3861                               << ".\n");
3862             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3863             continue;
3864           }
3865         }
3866 
3867         // Ignore users in the user ignore list.
3868         if (is_contained(UserIgnoreList, UserInst))
3869           continue;
3870 
3871         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3872                           << Lane << " from " << *Scalar << ".\n");
3873         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3874       }
3875     }
3876   }
3877 }
3878 
3879 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3880                         ArrayRef<Value *> UserIgnoreLst) {
3881   deleteTree();
3882   UserIgnoreList = UserIgnoreLst;
3883   if (!allSameType(Roots))
3884     return;
3885   buildTree_rec(Roots, 0, EdgeInfo());
3886 }
3887 
3888 namespace {
3889 /// Tracks the state we can represent the loads in the given sequence.
3890 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3891 } // anonymous namespace
3892 
3893 /// Checks if the given array of loads can be represented as a vectorized,
3894 /// scatter or just simple gather.
3895 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3896                                     const TargetTransformInfo &TTI,
3897                                     const DataLayout &DL, ScalarEvolution &SE,
3898                                     SmallVectorImpl<unsigned> &Order,
3899                                     SmallVectorImpl<Value *> &PointerOps) {
3900   // Check that a vectorized load would load the same memory as a scalar
3901   // load. For example, we don't want to vectorize loads that are smaller
3902   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3903   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3904   // from such a struct, we read/write packed bits disagreeing with the
3905   // unvectorized version.
3906   Type *ScalarTy = VL0->getType();
3907 
3908   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3909     return LoadsState::Gather;
3910 
3911   // Make sure all loads in the bundle are simple - we can't vectorize
3912   // atomic or volatile loads.
3913   PointerOps.clear();
3914   PointerOps.resize(VL.size());
3915   auto *POIter = PointerOps.begin();
3916   for (Value *V : VL) {
3917     auto *L = cast<LoadInst>(V);
3918     if (!L->isSimple())
3919       return LoadsState::Gather;
3920     *POIter = L->getPointerOperand();
3921     ++POIter;
3922   }
3923 
3924   Order.clear();
3925   // Check the order of pointer operands.
3926   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3927     Value *Ptr0;
3928     Value *PtrN;
3929     if (Order.empty()) {
3930       Ptr0 = PointerOps.front();
3931       PtrN = PointerOps.back();
3932     } else {
3933       Ptr0 = PointerOps[Order.front()];
3934       PtrN = PointerOps[Order.back()];
3935     }
3936     Optional<int> Diff =
3937         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3938     // Check that the sorted loads are consecutive.
3939     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3940       return LoadsState::Vectorize;
3941     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3942     for (Value *V : VL)
3943       CommonAlignment =
3944           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3945     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3946                                 CommonAlignment))
3947       return LoadsState::ScatterVectorize;
3948   }
3949 
3950   return LoadsState::Gather;
3951 }
3952 
3953 /// \return true if the specified list of values has only one instruction that
3954 /// requires scheduling, false otherwise.
3955 #ifndef NDEBUG
3956 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3957   Value *NeedsScheduling = nullptr;
3958   for (Value *V : VL) {
3959     if (doesNotNeedToBeScheduled(V))
3960       continue;
3961     if (!NeedsScheduling) {
3962       NeedsScheduling = V;
3963       continue;
3964     }
3965     return false;
3966   }
3967   return NeedsScheduling;
3968 }
3969 #endif
3970 
3971 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3972                             const EdgeInfo &UserTreeIdx) {
3973   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3974 
3975   SmallVector<int> ReuseShuffleIndicies;
3976   SmallVector<Value *> UniqueValues;
3977   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3978                                 &UserTreeIdx,
3979                                 this](const InstructionsState &S) {
3980     // Check that every instruction appears once in this bundle.
3981     DenseMap<Value *, unsigned> UniquePositions;
3982     for (Value *V : VL) {
3983       if (isConstant(V)) {
3984         ReuseShuffleIndicies.emplace_back(
3985             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3986         UniqueValues.emplace_back(V);
3987         continue;
3988       }
3989       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3990       ReuseShuffleIndicies.emplace_back(Res.first->second);
3991       if (Res.second)
3992         UniqueValues.emplace_back(V);
3993     }
3994     size_t NumUniqueScalarValues = UniqueValues.size();
3995     if (NumUniqueScalarValues == VL.size()) {
3996       ReuseShuffleIndicies.clear();
3997     } else {
3998       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3999       if (NumUniqueScalarValues <= 1 ||
4000           (UniquePositions.size() == 1 && all_of(UniqueValues,
4001                                                  [](Value *V) {
4002                                                    return isa<UndefValue>(V) ||
4003                                                           !isConstant(V);
4004                                                  })) ||
4005           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4006         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4007         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4008         return false;
4009       }
4010       VL = UniqueValues;
4011     }
4012     return true;
4013   };
4014 
4015   InstructionsState S = getSameOpcode(VL);
4016   if (Depth == RecursionMaxDepth) {
4017     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4018     if (TryToFindDuplicates(S))
4019       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4020                    ReuseShuffleIndicies);
4021     return;
4022   }
4023 
4024   // Don't handle scalable vectors
4025   if (S.getOpcode() == Instruction::ExtractElement &&
4026       isa<ScalableVectorType>(
4027           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4028     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4029     if (TryToFindDuplicates(S))
4030       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4031                    ReuseShuffleIndicies);
4032     return;
4033   }
4034 
4035   // Don't handle vectors.
4036   if (S.OpValue->getType()->isVectorTy() &&
4037       !isa<InsertElementInst>(S.OpValue)) {
4038     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4039     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4040     return;
4041   }
4042 
4043   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4044     if (SI->getValueOperand()->getType()->isVectorTy()) {
4045       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4046       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4047       return;
4048     }
4049 
4050   // If all of the operands are identical or constant we have a simple solution.
4051   // If we deal with insert/extract instructions, they all must have constant
4052   // indices, otherwise we should gather them, not try to vectorize.
4053   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4054       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4055        !all_of(VL, isVectorLikeInstWithConstOps))) {
4056     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4057     if (TryToFindDuplicates(S))
4058       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4059                    ReuseShuffleIndicies);
4060     return;
4061   }
4062 
4063   // We now know that this is a vector of instructions of the same type from
4064   // the same block.
4065 
4066   // Don't vectorize ephemeral values.
4067   for (Value *V : VL) {
4068     if (EphValues.count(V)) {
4069       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4070                         << ") is ephemeral.\n");
4071       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4072       return;
4073     }
4074   }
4075 
4076   // Check if this is a duplicate of another entry.
4077   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4078     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4079     if (!E->isSame(VL)) {
4080       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4081       if (TryToFindDuplicates(S))
4082         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4083                      ReuseShuffleIndicies);
4084       return;
4085     }
4086     // Record the reuse of the tree node.  FIXME, currently this is only used to
4087     // properly draw the graph rather than for the actual vectorization.
4088     E->UserTreeIndices.push_back(UserTreeIdx);
4089     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4090                       << ".\n");
4091     return;
4092   }
4093 
4094   // Check that none of the instructions in the bundle are already in the tree.
4095   for (Value *V : VL) {
4096     auto *I = dyn_cast<Instruction>(V);
4097     if (!I)
4098       continue;
4099     if (getTreeEntry(I)) {
4100       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4101                         << ") is already in tree.\n");
4102       if (TryToFindDuplicates(S))
4103         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4104                      ReuseShuffleIndicies);
4105       return;
4106     }
4107   }
4108 
4109   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4110   for (Value *V : VL) {
4111     if (is_contained(UserIgnoreList, V)) {
4112       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4113       if (TryToFindDuplicates(S))
4114         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4115                      ReuseShuffleIndicies);
4116       return;
4117     }
4118   }
4119 
4120   // Check that all of the users of the scalars that we want to vectorize are
4121   // schedulable.
4122   auto *VL0 = cast<Instruction>(S.OpValue);
4123   BasicBlock *BB = VL0->getParent();
4124 
4125   if (!DT->isReachableFromEntry(BB)) {
4126     // Don't go into unreachable blocks. They may contain instructions with
4127     // dependency cycles which confuse the final scheduling.
4128     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4129     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4130     return;
4131   }
4132 
4133   // Check that every instruction appears once in this bundle.
4134   if (!TryToFindDuplicates(S))
4135     return;
4136 
4137   auto &BSRef = BlocksSchedules[BB];
4138   if (!BSRef)
4139     BSRef = std::make_unique<BlockScheduling>(BB);
4140 
4141   BlockScheduling &BS = *BSRef;
4142 
4143   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4144 #ifdef EXPENSIVE_CHECKS
4145   // Make sure we didn't break any internal invariants
4146   BS.verify();
4147 #endif
4148   if (!Bundle) {
4149     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4150     assert((!BS.getScheduleData(VL0) ||
4151             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4152            "tryScheduleBundle should cancelScheduling on failure");
4153     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4154                  ReuseShuffleIndicies);
4155     return;
4156   }
4157   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4158 
4159   unsigned ShuffleOrOp = S.isAltShuffle() ?
4160                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4161   switch (ShuffleOrOp) {
4162     case Instruction::PHI: {
4163       auto *PH = cast<PHINode>(VL0);
4164 
4165       // Check for terminator values (e.g. invoke).
4166       for (Value *V : VL)
4167         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4168           Instruction *Term = dyn_cast<Instruction>(Incoming);
4169           if (Term && Term->isTerminator()) {
4170             LLVM_DEBUG(dbgs()
4171                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4172             BS.cancelScheduling(VL, VL0);
4173             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4174                          ReuseShuffleIndicies);
4175             return;
4176           }
4177         }
4178 
4179       TreeEntry *TE =
4180           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4181       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4182 
4183       // Keeps the reordered operands to avoid code duplication.
4184       SmallVector<ValueList, 2> OperandsVec;
4185       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4186         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4187           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4188           TE->setOperand(I, Operands);
4189           OperandsVec.push_back(Operands);
4190           continue;
4191         }
4192         ValueList Operands;
4193         // Prepare the operand vector.
4194         for (Value *V : VL)
4195           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4196               PH->getIncomingBlock(I)));
4197         TE->setOperand(I, Operands);
4198         OperandsVec.push_back(Operands);
4199       }
4200       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4201         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4202       return;
4203     }
4204     case Instruction::ExtractValue:
4205     case Instruction::ExtractElement: {
4206       OrdersType CurrentOrder;
4207       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4208       if (Reuse) {
4209         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4210         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4211                      ReuseShuffleIndicies);
4212         // This is a special case, as it does not gather, but at the same time
4213         // we are not extending buildTree_rec() towards the operands.
4214         ValueList Op0;
4215         Op0.assign(VL.size(), VL0->getOperand(0));
4216         VectorizableTree.back()->setOperand(0, Op0);
4217         return;
4218       }
4219       if (!CurrentOrder.empty()) {
4220         LLVM_DEBUG({
4221           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4222                     "with order";
4223           for (unsigned Idx : CurrentOrder)
4224             dbgs() << " " << Idx;
4225           dbgs() << "\n";
4226         });
4227         fixupOrderingIndices(CurrentOrder);
4228         // Insert new order with initial value 0, if it does not exist,
4229         // otherwise return the iterator to the existing one.
4230         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4231                      ReuseShuffleIndicies, CurrentOrder);
4232         // This is a special case, as it does not gather, but at the same time
4233         // we are not extending buildTree_rec() towards the operands.
4234         ValueList Op0;
4235         Op0.assign(VL.size(), VL0->getOperand(0));
4236         VectorizableTree.back()->setOperand(0, Op0);
4237         return;
4238       }
4239       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4240       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4241                    ReuseShuffleIndicies);
4242       BS.cancelScheduling(VL, VL0);
4243       return;
4244     }
4245     case Instruction::InsertElement: {
4246       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4247 
4248       // Check that we have a buildvector and not a shuffle of 2 or more
4249       // different vectors.
4250       ValueSet SourceVectors;
4251       for (Value *V : VL) {
4252         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4253         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4254       }
4255 
4256       if (count_if(VL, [&SourceVectors](Value *V) {
4257             return !SourceVectors.contains(V);
4258           }) >= 2) {
4259         // Found 2nd source vector - cancel.
4260         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4261                              "different source vectors.\n");
4262         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4263         BS.cancelScheduling(VL, VL0);
4264         return;
4265       }
4266 
4267       auto OrdCompare = [](const std::pair<int, int> &P1,
4268                            const std::pair<int, int> &P2) {
4269         return P1.first > P2.first;
4270       };
4271       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4272                     decltype(OrdCompare)>
4273           Indices(OrdCompare);
4274       for (int I = 0, E = VL.size(); I < E; ++I) {
4275         unsigned Idx = *getInsertIndex(VL[I]);
4276         Indices.emplace(Idx, I);
4277       }
4278       OrdersType CurrentOrder(VL.size(), VL.size());
4279       bool IsIdentity = true;
4280       for (int I = 0, E = VL.size(); I < E; ++I) {
4281         CurrentOrder[Indices.top().second] = I;
4282         IsIdentity &= Indices.top().second == I;
4283         Indices.pop();
4284       }
4285       if (IsIdentity)
4286         CurrentOrder.clear();
4287       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4288                                    None, CurrentOrder);
4289       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4290 
4291       constexpr int NumOps = 2;
4292       ValueList VectorOperands[NumOps];
4293       for (int I = 0; I < NumOps; ++I) {
4294         for (Value *V : VL)
4295           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4296 
4297         TE->setOperand(I, VectorOperands[I]);
4298       }
4299       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4300       return;
4301     }
4302     case Instruction::Load: {
4303       // Check that a vectorized load would load the same memory as a scalar
4304       // load. For example, we don't want to vectorize loads that are smaller
4305       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4306       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4307       // from such a struct, we read/write packed bits disagreeing with the
4308       // unvectorized version.
4309       SmallVector<Value *> PointerOps;
4310       OrdersType CurrentOrder;
4311       TreeEntry *TE = nullptr;
4312       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4313                                 PointerOps)) {
4314       case LoadsState::Vectorize:
4315         if (CurrentOrder.empty()) {
4316           // Original loads are consecutive and does not require reordering.
4317           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4318                             ReuseShuffleIndicies);
4319           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4320         } else {
4321           fixupOrderingIndices(CurrentOrder);
4322           // Need to reorder.
4323           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4324                             ReuseShuffleIndicies, CurrentOrder);
4325           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4326         }
4327         TE->setOperandsInOrder();
4328         break;
4329       case LoadsState::ScatterVectorize:
4330         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4331         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4332                           UserTreeIdx, ReuseShuffleIndicies);
4333         TE->setOperandsInOrder();
4334         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4335         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4336         break;
4337       case LoadsState::Gather:
4338         BS.cancelScheduling(VL, VL0);
4339         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4340                      ReuseShuffleIndicies);
4341 #ifndef NDEBUG
4342         Type *ScalarTy = VL0->getType();
4343         if (DL->getTypeSizeInBits(ScalarTy) !=
4344             DL->getTypeAllocSizeInBits(ScalarTy))
4345           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4346         else if (any_of(VL, [](Value *V) {
4347                    return !cast<LoadInst>(V)->isSimple();
4348                  }))
4349           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4350         else
4351           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4352 #endif // NDEBUG
4353         break;
4354       }
4355       return;
4356     }
4357     case Instruction::ZExt:
4358     case Instruction::SExt:
4359     case Instruction::FPToUI:
4360     case Instruction::FPToSI:
4361     case Instruction::FPExt:
4362     case Instruction::PtrToInt:
4363     case Instruction::IntToPtr:
4364     case Instruction::SIToFP:
4365     case Instruction::UIToFP:
4366     case Instruction::Trunc:
4367     case Instruction::FPTrunc:
4368     case Instruction::BitCast: {
4369       Type *SrcTy = VL0->getOperand(0)->getType();
4370       for (Value *V : VL) {
4371         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4372         if (Ty != SrcTy || !isValidElementType(Ty)) {
4373           BS.cancelScheduling(VL, VL0);
4374           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4375                        ReuseShuffleIndicies);
4376           LLVM_DEBUG(dbgs()
4377                      << "SLP: Gathering casts with different src types.\n");
4378           return;
4379         }
4380       }
4381       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4382                                    ReuseShuffleIndicies);
4383       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4384 
4385       TE->setOperandsInOrder();
4386       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4387         ValueList Operands;
4388         // Prepare the operand vector.
4389         for (Value *V : VL)
4390           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4391 
4392         buildTree_rec(Operands, Depth + 1, {TE, i});
4393       }
4394       return;
4395     }
4396     case Instruction::ICmp:
4397     case Instruction::FCmp: {
4398       // Check that all of the compares have the same predicate.
4399       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4400       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4401       Type *ComparedTy = VL0->getOperand(0)->getType();
4402       for (Value *V : VL) {
4403         CmpInst *Cmp = cast<CmpInst>(V);
4404         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4405             Cmp->getOperand(0)->getType() != ComparedTy) {
4406           BS.cancelScheduling(VL, VL0);
4407           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4408                        ReuseShuffleIndicies);
4409           LLVM_DEBUG(dbgs()
4410                      << "SLP: Gathering cmp with different predicate.\n");
4411           return;
4412         }
4413       }
4414 
4415       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4416                                    ReuseShuffleIndicies);
4417       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4418 
4419       ValueList Left, Right;
4420       if (cast<CmpInst>(VL0)->isCommutative()) {
4421         // Commutative predicate - collect + sort operands of the instructions
4422         // so that each side is more likely to have the same opcode.
4423         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4424         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4425       } else {
4426         // Collect operands - commute if it uses the swapped predicate.
4427         for (Value *V : VL) {
4428           auto *Cmp = cast<CmpInst>(V);
4429           Value *LHS = Cmp->getOperand(0);
4430           Value *RHS = Cmp->getOperand(1);
4431           if (Cmp->getPredicate() != P0)
4432             std::swap(LHS, RHS);
4433           Left.push_back(LHS);
4434           Right.push_back(RHS);
4435         }
4436       }
4437       TE->setOperand(0, Left);
4438       TE->setOperand(1, Right);
4439       buildTree_rec(Left, Depth + 1, {TE, 0});
4440       buildTree_rec(Right, Depth + 1, {TE, 1});
4441       return;
4442     }
4443     case Instruction::Select:
4444     case Instruction::FNeg:
4445     case Instruction::Add:
4446     case Instruction::FAdd:
4447     case Instruction::Sub:
4448     case Instruction::FSub:
4449     case Instruction::Mul:
4450     case Instruction::FMul:
4451     case Instruction::UDiv:
4452     case Instruction::SDiv:
4453     case Instruction::FDiv:
4454     case Instruction::URem:
4455     case Instruction::SRem:
4456     case Instruction::FRem:
4457     case Instruction::Shl:
4458     case Instruction::LShr:
4459     case Instruction::AShr:
4460     case Instruction::And:
4461     case Instruction::Or:
4462     case Instruction::Xor: {
4463       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4464                                    ReuseShuffleIndicies);
4465       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4466 
4467       // Sort operands of the instructions so that each side is more likely to
4468       // have the same opcode.
4469       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4470         ValueList Left, Right;
4471         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4472         TE->setOperand(0, Left);
4473         TE->setOperand(1, Right);
4474         buildTree_rec(Left, Depth + 1, {TE, 0});
4475         buildTree_rec(Right, Depth + 1, {TE, 1});
4476         return;
4477       }
4478 
4479       TE->setOperandsInOrder();
4480       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4481         ValueList Operands;
4482         // Prepare the operand vector.
4483         for (Value *V : VL)
4484           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4485 
4486         buildTree_rec(Operands, Depth + 1, {TE, i});
4487       }
4488       return;
4489     }
4490     case Instruction::GetElementPtr: {
4491       // We don't combine GEPs with complicated (nested) indexing.
4492       for (Value *V : VL) {
4493         if (cast<Instruction>(V)->getNumOperands() != 2) {
4494           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4495           BS.cancelScheduling(VL, VL0);
4496           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4497                        ReuseShuffleIndicies);
4498           return;
4499         }
4500       }
4501 
4502       // We can't combine several GEPs into one vector if they operate on
4503       // different types.
4504       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4505       for (Value *V : VL) {
4506         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4507         if (Ty0 != CurTy) {
4508           LLVM_DEBUG(dbgs()
4509                      << "SLP: not-vectorizable GEP (different types).\n");
4510           BS.cancelScheduling(VL, VL0);
4511           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4512                        ReuseShuffleIndicies);
4513           return;
4514         }
4515       }
4516 
4517       // We don't combine GEPs with non-constant indexes.
4518       Type *Ty1 = VL0->getOperand(1)->getType();
4519       for (Value *V : VL) {
4520         auto Op = cast<Instruction>(V)->getOperand(1);
4521         if (!isa<ConstantInt>(Op) ||
4522             (Op->getType() != Ty1 &&
4523              Op->getType()->getScalarSizeInBits() >
4524                  DL->getIndexSizeInBits(
4525                      V->getType()->getPointerAddressSpace()))) {
4526           LLVM_DEBUG(dbgs()
4527                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4528           BS.cancelScheduling(VL, VL0);
4529           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4530                        ReuseShuffleIndicies);
4531           return;
4532         }
4533       }
4534 
4535       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4536                                    ReuseShuffleIndicies);
4537       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4538       SmallVector<ValueList, 2> Operands(2);
4539       // Prepare the operand vector for pointer operands.
4540       for (Value *V : VL)
4541         Operands.front().push_back(
4542             cast<GetElementPtrInst>(V)->getPointerOperand());
4543       TE->setOperand(0, Operands.front());
4544       // Need to cast all indices to the same type before vectorization to
4545       // avoid crash.
4546       // Required to be able to find correct matches between different gather
4547       // nodes and reuse the vectorized values rather than trying to gather them
4548       // again.
4549       int IndexIdx = 1;
4550       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4551       Type *Ty = all_of(VL,
4552                         [VL0Ty, IndexIdx](Value *V) {
4553                           return VL0Ty == cast<GetElementPtrInst>(V)
4554                                               ->getOperand(IndexIdx)
4555                                               ->getType();
4556                         })
4557                      ? VL0Ty
4558                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4559                                             ->getPointerOperandType()
4560                                             ->getScalarType());
4561       // Prepare the operand vector.
4562       for (Value *V : VL) {
4563         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4564         auto *CI = cast<ConstantInt>(Op);
4565         Operands.back().push_back(ConstantExpr::getIntegerCast(
4566             CI, Ty, CI->getValue().isSignBitSet()));
4567       }
4568       TE->setOperand(IndexIdx, Operands.back());
4569 
4570       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4571         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4572       return;
4573     }
4574     case Instruction::Store: {
4575       // Check if the stores are consecutive or if we need to swizzle them.
4576       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4577       // Avoid types that are padded when being allocated as scalars, while
4578       // being packed together in a vector (such as i1).
4579       if (DL->getTypeSizeInBits(ScalarTy) !=
4580           DL->getTypeAllocSizeInBits(ScalarTy)) {
4581         BS.cancelScheduling(VL, VL0);
4582         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4583                      ReuseShuffleIndicies);
4584         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4585         return;
4586       }
4587       // Make sure all stores in the bundle are simple - we can't vectorize
4588       // atomic or volatile stores.
4589       SmallVector<Value *, 4> PointerOps(VL.size());
4590       ValueList Operands(VL.size());
4591       auto POIter = PointerOps.begin();
4592       auto OIter = Operands.begin();
4593       for (Value *V : VL) {
4594         auto *SI = cast<StoreInst>(V);
4595         if (!SI->isSimple()) {
4596           BS.cancelScheduling(VL, VL0);
4597           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4598                        ReuseShuffleIndicies);
4599           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4600           return;
4601         }
4602         *POIter = SI->getPointerOperand();
4603         *OIter = SI->getValueOperand();
4604         ++POIter;
4605         ++OIter;
4606       }
4607 
4608       OrdersType CurrentOrder;
4609       // Check the order of pointer operands.
4610       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4611         Value *Ptr0;
4612         Value *PtrN;
4613         if (CurrentOrder.empty()) {
4614           Ptr0 = PointerOps.front();
4615           PtrN = PointerOps.back();
4616         } else {
4617           Ptr0 = PointerOps[CurrentOrder.front()];
4618           PtrN = PointerOps[CurrentOrder.back()];
4619         }
4620         Optional<int> Dist =
4621             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4622         // Check that the sorted pointer operands are consecutive.
4623         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4624           if (CurrentOrder.empty()) {
4625             // Original stores are consecutive and does not require reordering.
4626             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4627                                          UserTreeIdx, ReuseShuffleIndicies);
4628             TE->setOperandsInOrder();
4629             buildTree_rec(Operands, Depth + 1, {TE, 0});
4630             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4631           } else {
4632             fixupOrderingIndices(CurrentOrder);
4633             TreeEntry *TE =
4634                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4635                              ReuseShuffleIndicies, CurrentOrder);
4636             TE->setOperandsInOrder();
4637             buildTree_rec(Operands, Depth + 1, {TE, 0});
4638             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4639           }
4640           return;
4641         }
4642       }
4643 
4644       BS.cancelScheduling(VL, VL0);
4645       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4646                    ReuseShuffleIndicies);
4647       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4648       return;
4649     }
4650     case Instruction::Call: {
4651       // Check if the calls are all to the same vectorizable intrinsic or
4652       // library function.
4653       CallInst *CI = cast<CallInst>(VL0);
4654       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4655 
4656       VFShape Shape = VFShape::get(
4657           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4658           false /*HasGlobalPred*/);
4659       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4660 
4661       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4662         BS.cancelScheduling(VL, VL0);
4663         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4664                      ReuseShuffleIndicies);
4665         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4666         return;
4667       }
4668       Function *F = CI->getCalledFunction();
4669       unsigned NumArgs = CI->arg_size();
4670       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4671       for (unsigned j = 0; j != NumArgs; ++j)
4672         if (hasVectorInstrinsicScalarOpd(ID, j))
4673           ScalarArgs[j] = CI->getArgOperand(j);
4674       for (Value *V : VL) {
4675         CallInst *CI2 = dyn_cast<CallInst>(V);
4676         if (!CI2 || CI2->getCalledFunction() != F ||
4677             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4678             (VecFunc &&
4679              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4680             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4681           BS.cancelScheduling(VL, VL0);
4682           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4683                        ReuseShuffleIndicies);
4684           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4685                             << "\n");
4686           return;
4687         }
4688         // Some intrinsics have scalar arguments and should be same in order for
4689         // them to be vectorized.
4690         for (unsigned j = 0; j != NumArgs; ++j) {
4691           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4692             Value *A1J = CI2->getArgOperand(j);
4693             if (ScalarArgs[j] != A1J) {
4694               BS.cancelScheduling(VL, VL0);
4695               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4696                            ReuseShuffleIndicies);
4697               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4698                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4699                                 << "\n");
4700               return;
4701             }
4702           }
4703         }
4704         // Verify that the bundle operands are identical between the two calls.
4705         if (CI->hasOperandBundles() &&
4706             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4707                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4708                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4709           BS.cancelScheduling(VL, VL0);
4710           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4711                        ReuseShuffleIndicies);
4712           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4713                             << *CI << "!=" << *V << '\n');
4714           return;
4715         }
4716       }
4717 
4718       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4719                                    ReuseShuffleIndicies);
4720       TE->setOperandsInOrder();
4721       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4722         // For scalar operands no need to to create an entry since no need to
4723         // vectorize it.
4724         if (hasVectorInstrinsicScalarOpd(ID, i))
4725           continue;
4726         ValueList Operands;
4727         // Prepare the operand vector.
4728         for (Value *V : VL) {
4729           auto *CI2 = cast<CallInst>(V);
4730           Operands.push_back(CI2->getArgOperand(i));
4731         }
4732         buildTree_rec(Operands, Depth + 1, {TE, i});
4733       }
4734       return;
4735     }
4736     case Instruction::ShuffleVector: {
4737       // If this is not an alternate sequence of opcode like add-sub
4738       // then do not vectorize this instruction.
4739       if (!S.isAltShuffle()) {
4740         BS.cancelScheduling(VL, VL0);
4741         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4742                      ReuseShuffleIndicies);
4743         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4744         return;
4745       }
4746       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4747                                    ReuseShuffleIndicies);
4748       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4749 
4750       // Reorder operands if reordering would enable vectorization.
4751       auto *CI = dyn_cast<CmpInst>(VL0);
4752       if (isa<BinaryOperator>(VL0) || CI) {
4753         ValueList Left, Right;
4754         if (!CI || all_of(VL, [](Value *V) {
4755               return cast<CmpInst>(V)->isCommutative();
4756             })) {
4757           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4758         } else {
4759           CmpInst::Predicate P0 = CI->getPredicate();
4760           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4761           assert(P0 != AltP0 &&
4762                  "Expected different main/alternate predicates.");
4763           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4764           Value *BaseOp0 = VL0->getOperand(0);
4765           Value *BaseOp1 = VL0->getOperand(1);
4766           // Collect operands - commute if it uses the swapped predicate or
4767           // alternate operation.
4768           for (Value *V : VL) {
4769             auto *Cmp = cast<CmpInst>(V);
4770             Value *LHS = Cmp->getOperand(0);
4771             Value *RHS = Cmp->getOperand(1);
4772             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4773             if (P0 == AltP0Swapped) {
4774               if (CI != Cmp && S.AltOp != Cmp &&
4775                   ((P0 == CurrentPred &&
4776                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4777                    (AltP0 == CurrentPred &&
4778                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4779                 std::swap(LHS, RHS);
4780             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4781               std::swap(LHS, RHS);
4782             }
4783             Left.push_back(LHS);
4784             Right.push_back(RHS);
4785           }
4786         }
4787         TE->setOperand(0, Left);
4788         TE->setOperand(1, Right);
4789         buildTree_rec(Left, Depth + 1, {TE, 0});
4790         buildTree_rec(Right, Depth + 1, {TE, 1});
4791         return;
4792       }
4793 
4794       TE->setOperandsInOrder();
4795       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4796         ValueList Operands;
4797         // Prepare the operand vector.
4798         for (Value *V : VL)
4799           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4800 
4801         buildTree_rec(Operands, Depth + 1, {TE, i});
4802       }
4803       return;
4804     }
4805     default:
4806       BS.cancelScheduling(VL, VL0);
4807       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4808                    ReuseShuffleIndicies);
4809       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4810       return;
4811   }
4812 }
4813 
4814 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4815   unsigned N = 1;
4816   Type *EltTy = T;
4817 
4818   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4819          isa<VectorType>(EltTy)) {
4820     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4821       // Check that struct is homogeneous.
4822       for (const auto *Ty : ST->elements())
4823         if (Ty != *ST->element_begin())
4824           return 0;
4825       N *= ST->getNumElements();
4826       EltTy = *ST->element_begin();
4827     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4828       N *= AT->getNumElements();
4829       EltTy = AT->getElementType();
4830     } else {
4831       auto *VT = cast<FixedVectorType>(EltTy);
4832       N *= VT->getNumElements();
4833       EltTy = VT->getElementType();
4834     }
4835   }
4836 
4837   if (!isValidElementType(EltTy))
4838     return 0;
4839   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4840   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4841     return 0;
4842   return N;
4843 }
4844 
4845 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4846                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4847   const auto *It = find_if(VL, [](Value *V) {
4848     return isa<ExtractElementInst, ExtractValueInst>(V);
4849   });
4850   assert(It != VL.end() && "Expected at least one extract instruction.");
4851   auto *E0 = cast<Instruction>(*It);
4852   assert(all_of(VL,
4853                 [](Value *V) {
4854                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4855                       V);
4856                 }) &&
4857          "Invalid opcode");
4858   // Check if all of the extracts come from the same vector and from the
4859   // correct offset.
4860   Value *Vec = E0->getOperand(0);
4861 
4862   CurrentOrder.clear();
4863 
4864   // We have to extract from a vector/aggregate with the same number of elements.
4865   unsigned NElts;
4866   if (E0->getOpcode() == Instruction::ExtractValue) {
4867     const DataLayout &DL = E0->getModule()->getDataLayout();
4868     NElts = canMapToVector(Vec->getType(), DL);
4869     if (!NElts)
4870       return false;
4871     // Check if load can be rewritten as load of vector.
4872     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4873     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4874       return false;
4875   } else {
4876     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4877   }
4878 
4879   if (NElts != VL.size())
4880     return false;
4881 
4882   // Check that all of the indices extract from the correct offset.
4883   bool ShouldKeepOrder = true;
4884   unsigned E = VL.size();
4885   // Assign to all items the initial value E + 1 so we can check if the extract
4886   // instruction index was used already.
4887   // Also, later we can check that all the indices are used and we have a
4888   // consecutive access in the extract instructions, by checking that no
4889   // element of CurrentOrder still has value E + 1.
4890   CurrentOrder.assign(E, E);
4891   unsigned I = 0;
4892   for (; I < E; ++I) {
4893     auto *Inst = dyn_cast<Instruction>(VL[I]);
4894     if (!Inst)
4895       continue;
4896     if (Inst->getOperand(0) != Vec)
4897       break;
4898     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4899       if (isa<UndefValue>(EE->getIndexOperand()))
4900         continue;
4901     Optional<unsigned> Idx = getExtractIndex(Inst);
4902     if (!Idx)
4903       break;
4904     const unsigned ExtIdx = *Idx;
4905     if (ExtIdx != I) {
4906       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4907         break;
4908       ShouldKeepOrder = false;
4909       CurrentOrder[ExtIdx] = I;
4910     } else {
4911       if (CurrentOrder[I] != E)
4912         break;
4913       CurrentOrder[I] = I;
4914     }
4915   }
4916   if (I < E) {
4917     CurrentOrder.clear();
4918     return false;
4919   }
4920   if (ShouldKeepOrder)
4921     CurrentOrder.clear();
4922 
4923   return ShouldKeepOrder;
4924 }
4925 
4926 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4927                                     ArrayRef<Value *> VectorizedVals) const {
4928   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4929          all_of(I->users(), [this](User *U) {
4930            return ScalarToTreeEntry.count(U) > 0 ||
4931                   isVectorLikeInstWithConstOps(U) ||
4932                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4933          });
4934 }
4935 
4936 static std::pair<InstructionCost, InstructionCost>
4937 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4938                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4939   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4940 
4941   // Calculate the cost of the scalar and vector calls.
4942   SmallVector<Type *, 4> VecTys;
4943   for (Use &Arg : CI->args())
4944     VecTys.push_back(
4945         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4946   FastMathFlags FMF;
4947   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4948     FMF = FPCI->getFastMathFlags();
4949   SmallVector<const Value *> Arguments(CI->args());
4950   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4951                                     dyn_cast<IntrinsicInst>(CI));
4952   auto IntrinsicCost =
4953     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4954 
4955   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4956                                      VecTy->getNumElements())),
4957                             false /*HasGlobalPred*/);
4958   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4959   auto LibCost = IntrinsicCost;
4960   if (!CI->isNoBuiltin() && VecFunc) {
4961     // Calculate the cost of the vector library call.
4962     // If the corresponding vector call is cheaper, return its cost.
4963     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4964                                     TTI::TCK_RecipThroughput);
4965   }
4966   return {IntrinsicCost, LibCost};
4967 }
4968 
4969 /// Compute the cost of creating a vector of type \p VecTy containing the
4970 /// extracted values from \p VL.
4971 static InstructionCost
4972 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4973                    TargetTransformInfo::ShuffleKind ShuffleKind,
4974                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4975   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4976 
4977   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4978       VecTy->getNumElements() < NumOfParts)
4979     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4980 
4981   bool AllConsecutive = true;
4982   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4983   unsigned Idx = -1;
4984   InstructionCost Cost = 0;
4985 
4986   // Process extracts in blocks of EltsPerVector to check if the source vector
4987   // operand can be re-used directly. If not, add the cost of creating a shuffle
4988   // to extract the values into a vector register.
4989   for (auto *V : VL) {
4990     ++Idx;
4991 
4992     // Need to exclude undefs from analysis.
4993     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4994       continue;
4995 
4996     // Reached the start of a new vector registers.
4997     if (Idx % EltsPerVector == 0) {
4998       AllConsecutive = true;
4999       continue;
5000     }
5001 
5002     // Check all extracts for a vector register on the target directly
5003     // extract values in order.
5004     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5005     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5006       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5007       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5008                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5009     }
5010 
5011     if (AllConsecutive)
5012       continue;
5013 
5014     // Skip all indices, except for the last index per vector block.
5015     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5016       continue;
5017 
5018     // If we have a series of extracts which are not consecutive and hence
5019     // cannot re-use the source vector register directly, compute the shuffle
5020     // cost to extract the a vector with EltsPerVector elements.
5021     Cost += TTI.getShuffleCost(
5022         TargetTransformInfo::SK_PermuteSingleSrc,
5023         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5024   }
5025   return Cost;
5026 }
5027 
5028 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5029 /// operations operands.
5030 static void
5031 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5032                       ArrayRef<int> ReusesIndices,
5033                       const function_ref<bool(Instruction *)> IsAltOp,
5034                       SmallVectorImpl<int> &Mask,
5035                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5036                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5037   unsigned Sz = VL.size();
5038   Mask.assign(Sz, UndefMaskElem);
5039   SmallVector<int> OrderMask;
5040   if (!ReorderIndices.empty())
5041     inversePermutation(ReorderIndices, OrderMask);
5042   for (unsigned I = 0; I < Sz; ++I) {
5043     unsigned Idx = I;
5044     if (!ReorderIndices.empty())
5045       Idx = OrderMask[I];
5046     auto *OpInst = cast<Instruction>(VL[Idx]);
5047     if (IsAltOp(OpInst)) {
5048       Mask[I] = Sz + Idx;
5049       if (AltScalars)
5050         AltScalars->push_back(OpInst);
5051     } else {
5052       Mask[I] = Idx;
5053       if (OpScalars)
5054         OpScalars->push_back(OpInst);
5055     }
5056   }
5057   if (!ReusesIndices.empty()) {
5058     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5059     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5060       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5061     });
5062     Mask.swap(NewMask);
5063   }
5064 }
5065 
5066 /// Checks if the specified instruction \p I is an alternate operation for the
5067 /// given \p MainOp and \p AltOp instructions.
5068 static bool isAlternateInstruction(const Instruction *I,
5069                                    const Instruction *MainOp,
5070                                    const Instruction *AltOp) {
5071   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5072     auto *AltCI0 = cast<CmpInst>(AltOp);
5073     auto *CI = cast<CmpInst>(I);
5074     CmpInst::Predicate P0 = CI0->getPredicate();
5075     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5076     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5077     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5078     CmpInst::Predicate CurrentPred = CI->getPredicate();
5079     if (P0 == AltP0Swapped)
5080       return I == AltCI0 ||
5081              (I != MainOp &&
5082               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5083                                    CI->getOperand(0), CI->getOperand(1)));
5084     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5085   }
5086   return I->getOpcode() == AltOp->getOpcode();
5087 }
5088 
5089 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5090                                       ArrayRef<Value *> VectorizedVals) {
5091   ArrayRef<Value*> VL = E->Scalars;
5092 
5093   Type *ScalarTy = VL[0]->getType();
5094   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5095     ScalarTy = SI->getValueOperand()->getType();
5096   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5097     ScalarTy = CI->getOperand(0)->getType();
5098   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5099     ScalarTy = IE->getOperand(1)->getType();
5100   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5101   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5102 
5103   // If we have computed a smaller type for the expression, update VecTy so
5104   // that the costs will be accurate.
5105   if (MinBWs.count(VL[0]))
5106     VecTy = FixedVectorType::get(
5107         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5108   unsigned EntryVF = E->getVectorFactor();
5109   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5110 
5111   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5112   // FIXME: it tries to fix a problem with MSVC buildbots.
5113   TargetTransformInfo &TTIRef = *TTI;
5114   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5115                                VectorizedVals, E](InstructionCost &Cost) {
5116     DenseMap<Value *, int> ExtractVectorsTys;
5117     SmallPtrSet<Value *, 4> CheckedExtracts;
5118     for (auto *V : VL) {
5119       if (isa<UndefValue>(V))
5120         continue;
5121       // If all users of instruction are going to be vectorized and this
5122       // instruction itself is not going to be vectorized, consider this
5123       // instruction as dead and remove its cost from the final cost of the
5124       // vectorized tree.
5125       // Also, avoid adjusting the cost for extractelements with multiple uses
5126       // in different graph entries.
5127       const TreeEntry *VE = getTreeEntry(V);
5128       if (!CheckedExtracts.insert(V).second ||
5129           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5130           (VE && VE != E))
5131         continue;
5132       auto *EE = cast<ExtractElementInst>(V);
5133       Optional<unsigned> EEIdx = getExtractIndex(EE);
5134       if (!EEIdx)
5135         continue;
5136       unsigned Idx = *EEIdx;
5137       if (TTIRef.getNumberOfParts(VecTy) !=
5138           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5139         auto It =
5140             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5141         It->getSecond() = std::min<int>(It->second, Idx);
5142       }
5143       // Take credit for instruction that will become dead.
5144       if (EE->hasOneUse()) {
5145         Instruction *Ext = EE->user_back();
5146         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5147             all_of(Ext->users(),
5148                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5149           // Use getExtractWithExtendCost() to calculate the cost of
5150           // extractelement/ext pair.
5151           Cost -=
5152               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5153                                               EE->getVectorOperandType(), Idx);
5154           // Add back the cost of s|zext which is subtracted separately.
5155           Cost += TTIRef.getCastInstrCost(
5156               Ext->getOpcode(), Ext->getType(), EE->getType(),
5157               TTI::getCastContextHint(Ext), CostKind, Ext);
5158           continue;
5159         }
5160       }
5161       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5162                                         EE->getVectorOperandType(), Idx);
5163     }
5164     // Add a cost for subvector extracts/inserts if required.
5165     for (const auto &Data : ExtractVectorsTys) {
5166       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5167       unsigned NumElts = VecTy->getNumElements();
5168       if (Data.second % NumElts == 0)
5169         continue;
5170       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5171         unsigned Idx = (Data.second / NumElts) * NumElts;
5172         unsigned EENumElts = EEVTy->getNumElements();
5173         if (Idx + NumElts <= EENumElts) {
5174           Cost +=
5175               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5176                                     EEVTy, None, Idx, VecTy);
5177         } else {
5178           // Need to round up the subvector type vectorization factor to avoid a
5179           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5180           // <= EENumElts.
5181           auto *SubVT =
5182               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5183           Cost +=
5184               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5185                                     EEVTy, None, Idx, SubVT);
5186         }
5187       } else {
5188         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5189                                       VecTy, None, 0, EEVTy);
5190       }
5191     }
5192   };
5193   if (E->State == TreeEntry::NeedToGather) {
5194     if (allConstant(VL))
5195       return 0;
5196     if (isa<InsertElementInst>(VL[0]))
5197       return InstructionCost::getInvalid();
5198     SmallVector<int> Mask;
5199     SmallVector<const TreeEntry *> Entries;
5200     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5201         isGatherShuffledEntry(E, Mask, Entries);
5202     if (Shuffle.hasValue()) {
5203       InstructionCost GatherCost = 0;
5204       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5205         // Perfect match in the graph, will reuse the previously vectorized
5206         // node. Cost is 0.
5207         LLVM_DEBUG(
5208             dbgs()
5209             << "SLP: perfect diamond match for gather bundle that starts with "
5210             << *VL.front() << ".\n");
5211         if (NeedToShuffleReuses)
5212           GatherCost =
5213               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5214                                   FinalVecTy, E->ReuseShuffleIndices);
5215       } else {
5216         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5217                           << " entries for bundle that starts with "
5218                           << *VL.front() << ".\n");
5219         // Detected that instead of gather we can emit a shuffle of single/two
5220         // previously vectorized nodes. Add the cost of the permutation rather
5221         // than gather.
5222         ::addMask(Mask, E->ReuseShuffleIndices);
5223         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5224       }
5225       return GatherCost;
5226     }
5227     if ((E->getOpcode() == Instruction::ExtractElement ||
5228          all_of(E->Scalars,
5229                 [](Value *V) {
5230                   return isa<ExtractElementInst, UndefValue>(V);
5231                 })) &&
5232         allSameType(VL)) {
5233       // Check that gather of extractelements can be represented as just a
5234       // shuffle of a single/two vectors the scalars are extracted from.
5235       SmallVector<int> Mask;
5236       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5237           isFixedVectorShuffle(VL, Mask);
5238       if (ShuffleKind.hasValue()) {
5239         // Found the bunch of extractelement instructions that must be gathered
5240         // into a vector and can be represented as a permutation elements in a
5241         // single input vector or of 2 input vectors.
5242         InstructionCost Cost =
5243             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5244         AdjustExtractsCost(Cost);
5245         if (NeedToShuffleReuses)
5246           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5247                                       FinalVecTy, E->ReuseShuffleIndices);
5248         return Cost;
5249       }
5250     }
5251     if (isSplat(VL)) {
5252       // Found the broadcasting of the single scalar, calculate the cost as the
5253       // broadcast.
5254       assert(VecTy == FinalVecTy &&
5255              "No reused scalars expected for broadcast.");
5256       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5257                                  /*Mask=*/None, /*Index=*/0,
5258                                  /*SubTp=*/nullptr, /*Args=*/VL);
5259     }
5260     InstructionCost ReuseShuffleCost = 0;
5261     if (NeedToShuffleReuses)
5262       ReuseShuffleCost = TTI->getShuffleCost(
5263           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5264     // Improve gather cost for gather of loads, if we can group some of the
5265     // loads into vector loads.
5266     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5267         !E->isAltShuffle()) {
5268       BoUpSLP::ValueSet VectorizedLoads;
5269       unsigned StartIdx = 0;
5270       unsigned VF = VL.size() / 2;
5271       unsigned VectorizedCnt = 0;
5272       unsigned ScatterVectorizeCnt = 0;
5273       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5274       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5275         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5276              Cnt += VF) {
5277           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5278           if (!VectorizedLoads.count(Slice.front()) &&
5279               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5280             SmallVector<Value *> PointerOps;
5281             OrdersType CurrentOrder;
5282             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5283                                               *SE, CurrentOrder, PointerOps);
5284             switch (LS) {
5285             case LoadsState::Vectorize:
5286             case LoadsState::ScatterVectorize:
5287               // Mark the vectorized loads so that we don't vectorize them
5288               // again.
5289               if (LS == LoadsState::Vectorize)
5290                 ++VectorizedCnt;
5291               else
5292                 ++ScatterVectorizeCnt;
5293               VectorizedLoads.insert(Slice.begin(), Slice.end());
5294               // If we vectorized initial block, no need to try to vectorize it
5295               // again.
5296               if (Cnt == StartIdx)
5297                 StartIdx += VF;
5298               break;
5299             case LoadsState::Gather:
5300               break;
5301             }
5302           }
5303         }
5304         // Check if the whole array was vectorized already - exit.
5305         if (StartIdx >= VL.size())
5306           break;
5307         // Found vectorizable parts - exit.
5308         if (!VectorizedLoads.empty())
5309           break;
5310       }
5311       if (!VectorizedLoads.empty()) {
5312         InstructionCost GatherCost = 0;
5313         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5314         bool NeedInsertSubvectorAnalysis =
5315             !NumParts || (VL.size() / VF) > NumParts;
5316         // Get the cost for gathered loads.
5317         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5318           if (VectorizedLoads.contains(VL[I]))
5319             continue;
5320           GatherCost += getGatherCost(VL.slice(I, VF));
5321         }
5322         // The cost for vectorized loads.
5323         InstructionCost ScalarsCost = 0;
5324         for (Value *V : VectorizedLoads) {
5325           auto *LI = cast<LoadInst>(V);
5326           ScalarsCost += TTI->getMemoryOpCost(
5327               Instruction::Load, LI->getType(), LI->getAlign(),
5328               LI->getPointerAddressSpace(), CostKind, LI);
5329         }
5330         auto *LI = cast<LoadInst>(E->getMainOp());
5331         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5332         Align Alignment = LI->getAlign();
5333         GatherCost +=
5334             VectorizedCnt *
5335             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5336                                  LI->getPointerAddressSpace(), CostKind, LI);
5337         GatherCost += ScatterVectorizeCnt *
5338                       TTI->getGatherScatterOpCost(
5339                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5340                           /*VariableMask=*/false, Alignment, CostKind, LI);
5341         if (NeedInsertSubvectorAnalysis) {
5342           // Add the cost for the subvectors insert.
5343           for (int I = VF, E = VL.size(); I < E; I += VF)
5344             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5345                                               None, I, LoadTy);
5346         }
5347         return ReuseShuffleCost + GatherCost - ScalarsCost;
5348       }
5349     }
5350     return ReuseShuffleCost + getGatherCost(VL);
5351   }
5352   InstructionCost CommonCost = 0;
5353   SmallVector<int> Mask;
5354   if (!E->ReorderIndices.empty()) {
5355     SmallVector<int> NewMask;
5356     if (E->getOpcode() == Instruction::Store) {
5357       // For stores the order is actually a mask.
5358       NewMask.resize(E->ReorderIndices.size());
5359       copy(E->ReorderIndices, NewMask.begin());
5360     } else {
5361       inversePermutation(E->ReorderIndices, NewMask);
5362     }
5363     ::addMask(Mask, NewMask);
5364   }
5365   if (NeedToShuffleReuses)
5366     ::addMask(Mask, E->ReuseShuffleIndices);
5367   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5368     CommonCost =
5369         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5370   assert((E->State == TreeEntry::Vectorize ||
5371           E->State == TreeEntry::ScatterVectorize) &&
5372          "Unhandled state");
5373   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5374   Instruction *VL0 = E->getMainOp();
5375   unsigned ShuffleOrOp =
5376       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5377   switch (ShuffleOrOp) {
5378     case Instruction::PHI:
5379       return 0;
5380 
5381     case Instruction::ExtractValue:
5382     case Instruction::ExtractElement: {
5383       // The common cost of removal ExtractElement/ExtractValue instructions +
5384       // the cost of shuffles, if required to resuffle the original vector.
5385       if (NeedToShuffleReuses) {
5386         unsigned Idx = 0;
5387         for (unsigned I : E->ReuseShuffleIndices) {
5388           if (ShuffleOrOp == Instruction::ExtractElement) {
5389             auto *EE = cast<ExtractElementInst>(VL[I]);
5390             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5391                                                   EE->getVectorOperandType(),
5392                                                   *getExtractIndex(EE));
5393           } else {
5394             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5395                                                   VecTy, Idx);
5396             ++Idx;
5397           }
5398         }
5399         Idx = EntryVF;
5400         for (Value *V : VL) {
5401           if (ShuffleOrOp == Instruction::ExtractElement) {
5402             auto *EE = cast<ExtractElementInst>(V);
5403             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5404                                                   EE->getVectorOperandType(),
5405                                                   *getExtractIndex(EE));
5406           } else {
5407             --Idx;
5408             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5409                                                   VecTy, Idx);
5410           }
5411         }
5412       }
5413       if (ShuffleOrOp == Instruction::ExtractValue) {
5414         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5415           auto *EI = cast<Instruction>(VL[I]);
5416           // Take credit for instruction that will become dead.
5417           if (EI->hasOneUse()) {
5418             Instruction *Ext = EI->user_back();
5419             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5420                 all_of(Ext->users(),
5421                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5422               // Use getExtractWithExtendCost() to calculate the cost of
5423               // extractelement/ext pair.
5424               CommonCost -= TTI->getExtractWithExtendCost(
5425                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5426               // Add back the cost of s|zext which is subtracted separately.
5427               CommonCost += TTI->getCastInstrCost(
5428                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5429                   TTI::getCastContextHint(Ext), CostKind, Ext);
5430               continue;
5431             }
5432           }
5433           CommonCost -=
5434               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5435         }
5436       } else {
5437         AdjustExtractsCost(CommonCost);
5438       }
5439       return CommonCost;
5440     }
5441     case Instruction::InsertElement: {
5442       assert(E->ReuseShuffleIndices.empty() &&
5443              "Unique insertelements only are expected.");
5444       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5445 
5446       unsigned const NumElts = SrcVecTy->getNumElements();
5447       unsigned const NumScalars = VL.size();
5448       APInt DemandedElts = APInt::getZero(NumElts);
5449       // TODO: Add support for Instruction::InsertValue.
5450       SmallVector<int> Mask;
5451       if (!E->ReorderIndices.empty()) {
5452         inversePermutation(E->ReorderIndices, Mask);
5453         Mask.append(NumElts - NumScalars, UndefMaskElem);
5454       } else {
5455         Mask.assign(NumElts, UndefMaskElem);
5456         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5457       }
5458       unsigned Offset = *getInsertIndex(VL0);
5459       bool IsIdentity = true;
5460       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5461       Mask.swap(PrevMask);
5462       for (unsigned I = 0; I < NumScalars; ++I) {
5463         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5464         DemandedElts.setBit(InsertIdx);
5465         IsIdentity &= InsertIdx - Offset == I;
5466         Mask[InsertIdx - Offset] = I;
5467       }
5468       assert(Offset < NumElts && "Failed to find vector index offset");
5469 
5470       InstructionCost Cost = 0;
5471       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5472                                             /*Insert*/ true, /*Extract*/ false);
5473 
5474       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5475         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5476         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5477         Cost += TTI->getShuffleCost(
5478             TargetTransformInfo::SK_PermuteSingleSrc,
5479             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5480       } else if (!IsIdentity) {
5481         auto *FirstInsert =
5482             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5483               return !is_contained(E->Scalars,
5484                                    cast<Instruction>(V)->getOperand(0));
5485             }));
5486         if (isUndefVector(FirstInsert->getOperand(0))) {
5487           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5488         } else {
5489           SmallVector<int> InsertMask(NumElts);
5490           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5491           for (unsigned I = 0; I < NumElts; I++) {
5492             if (Mask[I] != UndefMaskElem)
5493               InsertMask[Offset + I] = NumElts + I;
5494           }
5495           Cost +=
5496               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5497         }
5498       }
5499 
5500       return Cost;
5501     }
5502     case Instruction::ZExt:
5503     case Instruction::SExt:
5504     case Instruction::FPToUI:
5505     case Instruction::FPToSI:
5506     case Instruction::FPExt:
5507     case Instruction::PtrToInt:
5508     case Instruction::IntToPtr:
5509     case Instruction::SIToFP:
5510     case Instruction::UIToFP:
5511     case Instruction::Trunc:
5512     case Instruction::FPTrunc:
5513     case Instruction::BitCast: {
5514       Type *SrcTy = VL0->getOperand(0)->getType();
5515       InstructionCost ScalarEltCost =
5516           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5517                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5518       if (NeedToShuffleReuses) {
5519         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5520       }
5521 
5522       // Calculate the cost of this instruction.
5523       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5524 
5525       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5526       InstructionCost VecCost = 0;
5527       // Check if the values are candidates to demote.
5528       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5529         VecCost = CommonCost + TTI->getCastInstrCost(
5530                                    E->getOpcode(), VecTy, SrcVecTy,
5531                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5532       }
5533       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5534       return VecCost - ScalarCost;
5535     }
5536     case Instruction::FCmp:
5537     case Instruction::ICmp:
5538     case Instruction::Select: {
5539       // Calculate the cost of this instruction.
5540       InstructionCost ScalarEltCost =
5541           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5542                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5543       if (NeedToShuffleReuses) {
5544         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5545       }
5546       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5547       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5548 
5549       // Check if all entries in VL are either compares or selects with compares
5550       // as condition that have the same predicates.
5551       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5552       bool First = true;
5553       for (auto *V : VL) {
5554         CmpInst::Predicate CurrentPred;
5555         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5556         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5557              !match(V, MatchCmp)) ||
5558             (!First && VecPred != CurrentPred)) {
5559           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5560           break;
5561         }
5562         First = false;
5563         VecPred = CurrentPred;
5564       }
5565 
5566       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5567           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5568       // Check if it is possible and profitable to use min/max for selects in
5569       // VL.
5570       //
5571       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5572       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5573         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5574                                           {VecTy, VecTy});
5575         InstructionCost IntrinsicCost =
5576             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5577         // If the selects are the only uses of the compares, they will be dead
5578         // and we can adjust the cost by removing their cost.
5579         if (IntrinsicAndUse.second)
5580           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5581                                                    MaskTy, VecPred, CostKind);
5582         VecCost = std::min(VecCost, IntrinsicCost);
5583       }
5584       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5585       return CommonCost + VecCost - ScalarCost;
5586     }
5587     case Instruction::FNeg:
5588     case Instruction::Add:
5589     case Instruction::FAdd:
5590     case Instruction::Sub:
5591     case Instruction::FSub:
5592     case Instruction::Mul:
5593     case Instruction::FMul:
5594     case Instruction::UDiv:
5595     case Instruction::SDiv:
5596     case Instruction::FDiv:
5597     case Instruction::URem:
5598     case Instruction::SRem:
5599     case Instruction::FRem:
5600     case Instruction::Shl:
5601     case Instruction::LShr:
5602     case Instruction::AShr:
5603     case Instruction::And:
5604     case Instruction::Or:
5605     case Instruction::Xor: {
5606       // Certain instructions can be cheaper to vectorize if they have a
5607       // constant second vector operand.
5608       TargetTransformInfo::OperandValueKind Op1VK =
5609           TargetTransformInfo::OK_AnyValue;
5610       TargetTransformInfo::OperandValueKind Op2VK =
5611           TargetTransformInfo::OK_UniformConstantValue;
5612       TargetTransformInfo::OperandValueProperties Op1VP =
5613           TargetTransformInfo::OP_None;
5614       TargetTransformInfo::OperandValueProperties Op2VP =
5615           TargetTransformInfo::OP_PowerOf2;
5616 
5617       // If all operands are exactly the same ConstantInt then set the
5618       // operand kind to OK_UniformConstantValue.
5619       // If instead not all operands are constants, then set the operand kind
5620       // to OK_AnyValue. If all operands are constants but not the same,
5621       // then set the operand kind to OK_NonUniformConstantValue.
5622       ConstantInt *CInt0 = nullptr;
5623       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5624         const Instruction *I = cast<Instruction>(VL[i]);
5625         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5626         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5627         if (!CInt) {
5628           Op2VK = TargetTransformInfo::OK_AnyValue;
5629           Op2VP = TargetTransformInfo::OP_None;
5630           break;
5631         }
5632         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5633             !CInt->getValue().isPowerOf2())
5634           Op2VP = TargetTransformInfo::OP_None;
5635         if (i == 0) {
5636           CInt0 = CInt;
5637           continue;
5638         }
5639         if (CInt0 != CInt)
5640           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5641       }
5642 
5643       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5644       InstructionCost ScalarEltCost =
5645           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5646                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5647       if (NeedToShuffleReuses) {
5648         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5649       }
5650       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5651       InstructionCost VecCost =
5652           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5653                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5654       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5655       return CommonCost + VecCost - ScalarCost;
5656     }
5657     case Instruction::GetElementPtr: {
5658       TargetTransformInfo::OperandValueKind Op1VK =
5659           TargetTransformInfo::OK_AnyValue;
5660       TargetTransformInfo::OperandValueKind Op2VK =
5661           TargetTransformInfo::OK_UniformConstantValue;
5662 
5663       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5664           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5665       if (NeedToShuffleReuses) {
5666         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5667       }
5668       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5669       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5670           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5671       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5672       return CommonCost + VecCost - ScalarCost;
5673     }
5674     case Instruction::Load: {
5675       // Cost of wide load - cost of scalar loads.
5676       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5677       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5678           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5679       if (NeedToShuffleReuses) {
5680         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5681       }
5682       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5683       InstructionCost VecLdCost;
5684       if (E->State == TreeEntry::Vectorize) {
5685         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5686                                          CostKind, VL0);
5687       } else {
5688         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5689         Align CommonAlignment = Alignment;
5690         for (Value *V : VL)
5691           CommonAlignment =
5692               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5693         VecLdCost = TTI->getGatherScatterOpCost(
5694             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5695             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5696       }
5697       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5698       return CommonCost + VecLdCost - ScalarLdCost;
5699     }
5700     case Instruction::Store: {
5701       // We know that we can merge the stores. Calculate the cost.
5702       bool IsReorder = !E->ReorderIndices.empty();
5703       auto *SI =
5704           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5705       Align Alignment = SI->getAlign();
5706       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5707           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5708       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5709       InstructionCost VecStCost = TTI->getMemoryOpCost(
5710           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5711       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5712       return CommonCost + VecStCost - ScalarStCost;
5713     }
5714     case Instruction::Call: {
5715       CallInst *CI = cast<CallInst>(VL0);
5716       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5717 
5718       // Calculate the cost of the scalar and vector calls.
5719       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5720       InstructionCost ScalarEltCost =
5721           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5722       if (NeedToShuffleReuses) {
5723         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5724       }
5725       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5726 
5727       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5728       InstructionCost VecCallCost =
5729           std::min(VecCallCosts.first, VecCallCosts.second);
5730 
5731       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5732                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5733                         << " for " << *CI << "\n");
5734 
5735       return CommonCost + VecCallCost - ScalarCallCost;
5736     }
5737     case Instruction::ShuffleVector: {
5738       assert(E->isAltShuffle() &&
5739              ((Instruction::isBinaryOp(E->getOpcode()) &&
5740                Instruction::isBinaryOp(E->getAltOpcode())) ||
5741               (Instruction::isCast(E->getOpcode()) &&
5742                Instruction::isCast(E->getAltOpcode())) ||
5743               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5744              "Invalid Shuffle Vector Operand");
5745       InstructionCost ScalarCost = 0;
5746       if (NeedToShuffleReuses) {
5747         for (unsigned Idx : E->ReuseShuffleIndices) {
5748           Instruction *I = cast<Instruction>(VL[Idx]);
5749           CommonCost -= TTI->getInstructionCost(I, CostKind);
5750         }
5751         for (Value *V : VL) {
5752           Instruction *I = cast<Instruction>(V);
5753           CommonCost += TTI->getInstructionCost(I, CostKind);
5754         }
5755       }
5756       for (Value *V : VL) {
5757         Instruction *I = cast<Instruction>(V);
5758         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5759         ScalarCost += TTI->getInstructionCost(I, CostKind);
5760       }
5761       // VecCost is equal to sum of the cost of creating 2 vectors
5762       // and the cost of creating shuffle.
5763       InstructionCost VecCost = 0;
5764       // Try to find the previous shuffle node with the same operands and same
5765       // main/alternate ops.
5766       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5767         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5768           if (TE.get() == E)
5769             break;
5770           if (TE->isAltShuffle() &&
5771               ((TE->getOpcode() == E->getOpcode() &&
5772                 TE->getAltOpcode() == E->getAltOpcode()) ||
5773                (TE->getOpcode() == E->getAltOpcode() &&
5774                 TE->getAltOpcode() == E->getOpcode())) &&
5775               TE->hasEqualOperands(*E))
5776             return true;
5777         }
5778         return false;
5779       };
5780       if (TryFindNodeWithEqualOperands()) {
5781         LLVM_DEBUG({
5782           dbgs() << "SLP: diamond match for alternate node found.\n";
5783           E->dump();
5784         });
5785         // No need to add new vector costs here since we're going to reuse
5786         // same main/alternate vector ops, just do different shuffling.
5787       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5788         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5789         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5790                                                CostKind);
5791       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5792         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5793                                           Builder.getInt1Ty(),
5794                                           CI0->getPredicate(), CostKind, VL0);
5795         VecCost += TTI->getCmpSelInstrCost(
5796             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5797             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5798             E->getAltOp());
5799       } else {
5800         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5801         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5802         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5803         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5804         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5805                                         TTI::CastContextHint::None, CostKind);
5806         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5807                                          TTI::CastContextHint::None, CostKind);
5808       }
5809 
5810       SmallVector<int> Mask;
5811       buildShuffleEntryMask(
5812           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5813           [E](Instruction *I) {
5814             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5815             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5816           },
5817           Mask);
5818       CommonCost =
5819           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5820       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5821       return CommonCost + VecCost - ScalarCost;
5822     }
5823     default:
5824       llvm_unreachable("Unknown instruction");
5825   }
5826 }
5827 
5828 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5829   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5830                     << VectorizableTree.size() << " is fully vectorizable .\n");
5831 
5832   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5833     SmallVector<int> Mask;
5834     return TE->State == TreeEntry::NeedToGather &&
5835            !any_of(TE->Scalars,
5836                    [this](Value *V) { return EphValues.contains(V); }) &&
5837            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5838             TE->Scalars.size() < Limit ||
5839             ((TE->getOpcode() == Instruction::ExtractElement ||
5840               all_of(TE->Scalars,
5841                      [](Value *V) {
5842                        return isa<ExtractElementInst, UndefValue>(V);
5843                      })) &&
5844              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5845             (TE->State == TreeEntry::NeedToGather &&
5846              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5847   };
5848 
5849   // We only handle trees of heights 1 and 2.
5850   if (VectorizableTree.size() == 1 &&
5851       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5852        (ForReduction &&
5853         AreVectorizableGathers(VectorizableTree[0].get(),
5854                                VectorizableTree[0]->Scalars.size()) &&
5855         VectorizableTree[0]->getVectorFactor() > 2)))
5856     return true;
5857 
5858   if (VectorizableTree.size() != 2)
5859     return false;
5860 
5861   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5862   // with the second gather nodes if they have less scalar operands rather than
5863   // the initial tree element (may be profitable to shuffle the second gather)
5864   // or they are extractelements, which form shuffle.
5865   SmallVector<int> Mask;
5866   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5867       AreVectorizableGathers(VectorizableTree[1].get(),
5868                              VectorizableTree[0]->Scalars.size()))
5869     return true;
5870 
5871   // Gathering cost would be too much for tiny trees.
5872   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5873       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5874        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5875     return false;
5876 
5877   return true;
5878 }
5879 
5880 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5881                                        TargetTransformInfo *TTI,
5882                                        bool MustMatchOrInst) {
5883   // Look past the root to find a source value. Arbitrarily follow the
5884   // path through operand 0 of any 'or'. Also, peek through optional
5885   // shift-left-by-multiple-of-8-bits.
5886   Value *ZextLoad = Root;
5887   const APInt *ShAmtC;
5888   bool FoundOr = false;
5889   while (!isa<ConstantExpr>(ZextLoad) &&
5890          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5891           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5892            ShAmtC->urem(8) == 0))) {
5893     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5894     ZextLoad = BinOp->getOperand(0);
5895     if (BinOp->getOpcode() == Instruction::Or)
5896       FoundOr = true;
5897   }
5898   // Check if the input is an extended load of the required or/shift expression.
5899   Value *Load;
5900   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5901       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5902     return false;
5903 
5904   // Require that the total load bit width is a legal integer type.
5905   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5906   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5907   Type *SrcTy = Load->getType();
5908   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5909   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5910     return false;
5911 
5912   // Everything matched - assume that we can fold the whole sequence using
5913   // load combining.
5914   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5915              << *(cast<Instruction>(Root)) << "\n");
5916 
5917   return true;
5918 }
5919 
5920 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5921   if (RdxKind != RecurKind::Or)
5922     return false;
5923 
5924   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5925   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5926   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5927                                     /* MatchOr */ false);
5928 }
5929 
5930 bool BoUpSLP::isLoadCombineCandidate() const {
5931   // Peek through a final sequence of stores and check if all operations are
5932   // likely to be load-combined.
5933   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5934   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5935     Value *X;
5936     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5937         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5938       return false;
5939   }
5940   return true;
5941 }
5942 
5943 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5944   // No need to vectorize inserts of gathered values.
5945   if (VectorizableTree.size() == 2 &&
5946       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5947       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5948     return true;
5949 
5950   // We can vectorize the tree if its size is greater than or equal to the
5951   // minimum size specified by the MinTreeSize command line option.
5952   if (VectorizableTree.size() >= MinTreeSize)
5953     return false;
5954 
5955   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5956   // can vectorize it if we can prove it fully vectorizable.
5957   if (isFullyVectorizableTinyTree(ForReduction))
5958     return false;
5959 
5960   assert(VectorizableTree.empty()
5961              ? ExternalUses.empty()
5962              : true && "We shouldn't have any external users");
5963 
5964   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5965   // vectorizable.
5966   return true;
5967 }
5968 
5969 InstructionCost BoUpSLP::getSpillCost() const {
5970   // Walk from the bottom of the tree to the top, tracking which values are
5971   // live. When we see a call instruction that is not part of our tree,
5972   // query TTI to see if there is a cost to keeping values live over it
5973   // (for example, if spills and fills are required).
5974   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5975   InstructionCost Cost = 0;
5976 
5977   SmallPtrSet<Instruction*, 4> LiveValues;
5978   Instruction *PrevInst = nullptr;
5979 
5980   // The entries in VectorizableTree are not necessarily ordered by their
5981   // position in basic blocks. Collect them and order them by dominance so later
5982   // instructions are guaranteed to be visited first. For instructions in
5983   // different basic blocks, we only scan to the beginning of the block, so
5984   // their order does not matter, as long as all instructions in a basic block
5985   // are grouped together. Using dominance ensures a deterministic order.
5986   SmallVector<Instruction *, 16> OrderedScalars;
5987   for (const auto &TEPtr : VectorizableTree) {
5988     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5989     if (!Inst)
5990       continue;
5991     OrderedScalars.push_back(Inst);
5992   }
5993   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5994     auto *NodeA = DT->getNode(A->getParent());
5995     auto *NodeB = DT->getNode(B->getParent());
5996     assert(NodeA && "Should only process reachable instructions");
5997     assert(NodeB && "Should only process reachable instructions");
5998     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5999            "Different nodes should have different DFS numbers");
6000     if (NodeA != NodeB)
6001       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6002     return B->comesBefore(A);
6003   });
6004 
6005   for (Instruction *Inst : OrderedScalars) {
6006     if (!PrevInst) {
6007       PrevInst = Inst;
6008       continue;
6009     }
6010 
6011     // Update LiveValues.
6012     LiveValues.erase(PrevInst);
6013     for (auto &J : PrevInst->operands()) {
6014       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6015         LiveValues.insert(cast<Instruction>(&*J));
6016     }
6017 
6018     LLVM_DEBUG({
6019       dbgs() << "SLP: #LV: " << LiveValues.size();
6020       for (auto *X : LiveValues)
6021         dbgs() << " " << X->getName();
6022       dbgs() << ", Looking at ";
6023       Inst->dump();
6024     });
6025 
6026     // Now find the sequence of instructions between PrevInst and Inst.
6027     unsigned NumCalls = 0;
6028     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6029                                  PrevInstIt =
6030                                      PrevInst->getIterator().getReverse();
6031     while (InstIt != PrevInstIt) {
6032       if (PrevInstIt == PrevInst->getParent()->rend()) {
6033         PrevInstIt = Inst->getParent()->rbegin();
6034         continue;
6035       }
6036 
6037       // Debug information does not impact spill cost.
6038       if ((isa<CallInst>(&*PrevInstIt) &&
6039            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6040           &*PrevInstIt != PrevInst)
6041         NumCalls++;
6042 
6043       ++PrevInstIt;
6044     }
6045 
6046     if (NumCalls) {
6047       SmallVector<Type*, 4> V;
6048       for (auto *II : LiveValues) {
6049         auto *ScalarTy = II->getType();
6050         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6051           ScalarTy = VectorTy->getElementType();
6052         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6053       }
6054       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6055     }
6056 
6057     PrevInst = Inst;
6058   }
6059 
6060   return Cost;
6061 }
6062 
6063 /// Check if two insertelement instructions are from the same buildvector.
6064 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6065                                             InsertElementInst *V) {
6066   // Instructions must be from the same basic blocks.
6067   if (VU->getParent() != V->getParent())
6068     return false;
6069   // Checks if 2 insertelements are from the same buildvector.
6070   if (VU->getType() != V->getType())
6071     return false;
6072   // Multiple used inserts are separate nodes.
6073   if (!VU->hasOneUse() && !V->hasOneUse())
6074     return false;
6075   auto *IE1 = VU;
6076   auto *IE2 = V;
6077   // Go through the vector operand of insertelement instructions trying to find
6078   // either VU as the original vector for IE2 or V as the original vector for
6079   // IE1.
6080   do {
6081     if (IE2 == VU || IE1 == V)
6082       return true;
6083     if (IE1) {
6084       if (IE1 != VU && !IE1->hasOneUse())
6085         IE1 = nullptr;
6086       else
6087         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6088     }
6089     if (IE2) {
6090       if (IE2 != V && !IE2->hasOneUse())
6091         IE2 = nullptr;
6092       else
6093         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6094     }
6095   } while (IE1 || IE2);
6096   return false;
6097 }
6098 
6099 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6100   InstructionCost Cost = 0;
6101   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6102                     << VectorizableTree.size() << ".\n");
6103 
6104   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6105 
6106   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6107     TreeEntry &TE = *VectorizableTree[I];
6108 
6109     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6110     Cost += C;
6111     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6112                       << " for bundle that starts with " << *TE.Scalars[0]
6113                       << ".\n"
6114                       << "SLP: Current total cost = " << Cost << "\n");
6115   }
6116 
6117   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6118   InstructionCost ExtractCost = 0;
6119   SmallVector<unsigned> VF;
6120   SmallVector<SmallVector<int>> ShuffleMask;
6121   SmallVector<Value *> FirstUsers;
6122   SmallVector<APInt> DemandedElts;
6123   for (ExternalUser &EU : ExternalUses) {
6124     // We only add extract cost once for the same scalar.
6125     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6126         !ExtractCostCalculated.insert(EU.Scalar).second)
6127       continue;
6128 
6129     // Uses by ephemeral values are free (because the ephemeral value will be
6130     // removed prior to code generation, and so the extraction will be
6131     // removed as well).
6132     if (EphValues.count(EU.User))
6133       continue;
6134 
6135     // No extract cost for vector "scalar"
6136     if (isa<FixedVectorType>(EU.Scalar->getType()))
6137       continue;
6138 
6139     // Already counted the cost for external uses when tried to adjust the cost
6140     // for extractelements, no need to add it again.
6141     if (isa<ExtractElementInst>(EU.Scalar))
6142       continue;
6143 
6144     // If found user is an insertelement, do not calculate extract cost but try
6145     // to detect it as a final shuffled/identity match.
6146     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6147       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6148         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6149         if (InsertIdx) {
6150           auto *It = find_if(FirstUsers, [VU](Value *V) {
6151             return areTwoInsertFromSameBuildVector(VU,
6152                                                    cast<InsertElementInst>(V));
6153           });
6154           int VecId = -1;
6155           if (It == FirstUsers.end()) {
6156             VF.push_back(FTy->getNumElements());
6157             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6158             // Find the insertvector, vectorized in tree, if any.
6159             Value *Base = VU;
6160             while (isa<InsertElementInst>(Base)) {
6161               // Build the mask for the vectorized insertelement instructions.
6162               if (const TreeEntry *E = getTreeEntry(Base)) {
6163                 VU = cast<InsertElementInst>(Base);
6164                 do {
6165                   int Idx = E->findLaneForValue(Base);
6166                   ShuffleMask.back()[Idx] = Idx;
6167                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6168                 } while (E == getTreeEntry(Base));
6169                 break;
6170               }
6171               Base = cast<InsertElementInst>(Base)->getOperand(0);
6172             }
6173             FirstUsers.push_back(VU);
6174             DemandedElts.push_back(APInt::getZero(VF.back()));
6175             VecId = FirstUsers.size() - 1;
6176           } else {
6177             VecId = std::distance(FirstUsers.begin(), It);
6178           }
6179           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6180           DemandedElts[VecId].setBit(*InsertIdx);
6181           continue;
6182         }
6183       }
6184     }
6185 
6186     // If we plan to rewrite the tree in a smaller type, we will need to sign
6187     // extend the extracted value back to the original type. Here, we account
6188     // for the extract and the added cost of the sign extend if needed.
6189     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6190     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6191     if (MinBWs.count(ScalarRoot)) {
6192       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6193       auto Extend =
6194           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6195       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6196       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6197                                                    VecTy, EU.Lane);
6198     } else {
6199       ExtractCost +=
6200           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6201     }
6202   }
6203 
6204   InstructionCost SpillCost = getSpillCost();
6205   Cost += SpillCost + ExtractCost;
6206   if (FirstUsers.size() == 1) {
6207     int Limit = ShuffleMask.front().size() * 2;
6208     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6209         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6210       InstructionCost C = TTI->getShuffleCost(
6211           TTI::SK_PermuteSingleSrc,
6212           cast<FixedVectorType>(FirstUsers.front()->getType()),
6213           ShuffleMask.front());
6214       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6215                         << " for final shuffle of insertelement external users "
6216                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6217                         << "SLP: Current total cost = " << Cost << "\n");
6218       Cost += C;
6219     }
6220     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6221         cast<FixedVectorType>(FirstUsers.front()->getType()),
6222         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6223     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6224                       << " for insertelements gather.\n"
6225                       << "SLP: Current total cost = " << Cost << "\n");
6226     Cost -= InsertCost;
6227   } else if (FirstUsers.size() >= 2) {
6228     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6229     // Combined masks of the first 2 vectors.
6230     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6231     copy(ShuffleMask.front(), CombinedMask.begin());
6232     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6233     auto *VecTy = FixedVectorType::get(
6234         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6235         MaxVF);
6236     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6237       if (ShuffleMask[1][I] != UndefMaskElem) {
6238         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6239         CombinedDemandedElts.setBit(I);
6240       }
6241     }
6242     InstructionCost C =
6243         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6244     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6245                       << " for final shuffle of vector node and external "
6246                          "insertelement users "
6247                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6248                       << "SLP: Current total cost = " << Cost << "\n");
6249     Cost += C;
6250     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6251         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6252     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6253                       << " for insertelements gather.\n"
6254                       << "SLP: Current total cost = " << Cost << "\n");
6255     Cost -= InsertCost;
6256     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6257       // Other elements - permutation of 2 vectors (the initial one and the
6258       // next Ith incoming vector).
6259       unsigned VF = ShuffleMask[I].size();
6260       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6261         int Mask = ShuffleMask[I][Idx];
6262         if (Mask != UndefMaskElem)
6263           CombinedMask[Idx] = MaxVF + Mask;
6264         else if (CombinedMask[Idx] != UndefMaskElem)
6265           CombinedMask[Idx] = Idx;
6266       }
6267       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6268         if (CombinedMask[Idx] != UndefMaskElem)
6269           CombinedMask[Idx] = Idx;
6270       InstructionCost C =
6271           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6272       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6273                         << " for final shuffle of vector node and external "
6274                            "insertelement users "
6275                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6276                         << "SLP: Current total cost = " << Cost << "\n");
6277       Cost += C;
6278       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6279           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6280           /*Insert*/ true, /*Extract*/ false);
6281       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6282                         << " for insertelements gather.\n"
6283                         << "SLP: Current total cost = " << Cost << "\n");
6284       Cost -= InsertCost;
6285     }
6286   }
6287 
6288 #ifndef NDEBUG
6289   SmallString<256> Str;
6290   {
6291     raw_svector_ostream OS(Str);
6292     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6293        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6294        << "SLP: Total Cost = " << Cost << ".\n";
6295   }
6296   LLVM_DEBUG(dbgs() << Str);
6297   if (ViewSLPTree)
6298     ViewGraph(this, "SLP" + F->getName(), false, Str);
6299 #endif
6300 
6301   return Cost;
6302 }
6303 
6304 Optional<TargetTransformInfo::ShuffleKind>
6305 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6306                                SmallVectorImpl<const TreeEntry *> &Entries) {
6307   // TODO: currently checking only for Scalars in the tree entry, need to count
6308   // reused elements too for better cost estimation.
6309   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6310   Entries.clear();
6311   // Build a lists of values to tree entries.
6312   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6313   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6314     if (EntryPtr.get() == TE)
6315       break;
6316     if (EntryPtr->State != TreeEntry::NeedToGather)
6317       continue;
6318     for (Value *V : EntryPtr->Scalars)
6319       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6320   }
6321   // Find all tree entries used by the gathered values. If no common entries
6322   // found - not a shuffle.
6323   // Here we build a set of tree nodes for each gathered value and trying to
6324   // find the intersection between these sets. If we have at least one common
6325   // tree node for each gathered value - we have just a permutation of the
6326   // single vector. If we have 2 different sets, we're in situation where we
6327   // have a permutation of 2 input vectors.
6328   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6329   DenseMap<Value *, int> UsedValuesEntry;
6330   for (Value *V : TE->Scalars) {
6331     if (isa<UndefValue>(V))
6332       continue;
6333     // Build a list of tree entries where V is used.
6334     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6335     auto It = ValueToTEs.find(V);
6336     if (It != ValueToTEs.end())
6337       VToTEs = It->second;
6338     if (const TreeEntry *VTE = getTreeEntry(V))
6339       VToTEs.insert(VTE);
6340     if (VToTEs.empty())
6341       return None;
6342     if (UsedTEs.empty()) {
6343       // The first iteration, just insert the list of nodes to vector.
6344       UsedTEs.push_back(VToTEs);
6345     } else {
6346       // Need to check if there are any previously used tree nodes which use V.
6347       // If there are no such nodes, consider that we have another one input
6348       // vector.
6349       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6350       unsigned Idx = 0;
6351       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6352         // Do we have a non-empty intersection of previously listed tree entries
6353         // and tree entries using current V?
6354         set_intersect(VToTEs, Set);
6355         if (!VToTEs.empty()) {
6356           // Yes, write the new subset and continue analysis for the next
6357           // scalar.
6358           Set.swap(VToTEs);
6359           break;
6360         }
6361         VToTEs = SavedVToTEs;
6362         ++Idx;
6363       }
6364       // No non-empty intersection found - need to add a second set of possible
6365       // source vectors.
6366       if (Idx == UsedTEs.size()) {
6367         // If the number of input vectors is greater than 2 - not a permutation,
6368         // fallback to the regular gather.
6369         if (UsedTEs.size() == 2)
6370           return None;
6371         UsedTEs.push_back(SavedVToTEs);
6372         Idx = UsedTEs.size() - 1;
6373       }
6374       UsedValuesEntry.try_emplace(V, Idx);
6375     }
6376   }
6377 
6378   unsigned VF = 0;
6379   if (UsedTEs.size() == 1) {
6380     // Try to find the perfect match in another gather node at first.
6381     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6382       return EntryPtr->isSame(TE->Scalars);
6383     });
6384     if (It != UsedTEs.front().end()) {
6385       Entries.push_back(*It);
6386       std::iota(Mask.begin(), Mask.end(), 0);
6387       return TargetTransformInfo::SK_PermuteSingleSrc;
6388     }
6389     // No perfect match, just shuffle, so choose the first tree node.
6390     Entries.push_back(*UsedTEs.front().begin());
6391   } else {
6392     // Try to find nodes with the same vector factor.
6393     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6394     DenseMap<int, const TreeEntry *> VFToTE;
6395     for (const TreeEntry *TE : UsedTEs.front())
6396       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6397     for (const TreeEntry *TE : UsedTEs.back()) {
6398       auto It = VFToTE.find(TE->getVectorFactor());
6399       if (It != VFToTE.end()) {
6400         VF = It->first;
6401         Entries.push_back(It->second);
6402         Entries.push_back(TE);
6403         break;
6404       }
6405     }
6406     // No 2 source vectors with the same vector factor - give up and do regular
6407     // gather.
6408     if (Entries.empty())
6409       return None;
6410   }
6411 
6412   // Build a shuffle mask for better cost estimation and vector emission.
6413   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6414     Value *V = TE->Scalars[I];
6415     if (isa<UndefValue>(V))
6416       continue;
6417     unsigned Idx = UsedValuesEntry.lookup(V);
6418     const TreeEntry *VTE = Entries[Idx];
6419     int FoundLane = VTE->findLaneForValue(V);
6420     Mask[I] = Idx * VF + FoundLane;
6421     // Extra check required by isSingleSourceMaskImpl function (called by
6422     // ShuffleVectorInst::isSingleSourceMask).
6423     if (Mask[I] >= 2 * E)
6424       return None;
6425   }
6426   switch (Entries.size()) {
6427   case 1:
6428     return TargetTransformInfo::SK_PermuteSingleSrc;
6429   case 2:
6430     return TargetTransformInfo::SK_PermuteTwoSrc;
6431   default:
6432     break;
6433   }
6434   return None;
6435 }
6436 
6437 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6438                                        const APInt &ShuffledIndices,
6439                                        bool NeedToShuffle) const {
6440   InstructionCost Cost =
6441       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6442                                     /*Extract*/ false);
6443   if (NeedToShuffle)
6444     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6445   return Cost;
6446 }
6447 
6448 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6449   // Find the type of the operands in VL.
6450   Type *ScalarTy = VL[0]->getType();
6451   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6452     ScalarTy = SI->getValueOperand()->getType();
6453   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6454   bool DuplicateNonConst = false;
6455   // Find the cost of inserting/extracting values from the vector.
6456   // Check if the same elements are inserted several times and count them as
6457   // shuffle candidates.
6458   APInt ShuffledElements = APInt::getZero(VL.size());
6459   DenseSet<Value *> UniqueElements;
6460   // Iterate in reverse order to consider insert elements with the high cost.
6461   for (unsigned I = VL.size(); I > 0; --I) {
6462     unsigned Idx = I - 1;
6463     // No need to shuffle duplicates for constants.
6464     if (isConstant(VL[Idx])) {
6465       ShuffledElements.setBit(Idx);
6466       continue;
6467     }
6468     if (!UniqueElements.insert(VL[Idx]).second) {
6469       DuplicateNonConst = true;
6470       ShuffledElements.setBit(Idx);
6471     }
6472   }
6473   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6474 }
6475 
6476 // Perform operand reordering on the instructions in VL and return the reordered
6477 // operands in Left and Right.
6478 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6479                                              SmallVectorImpl<Value *> &Left,
6480                                              SmallVectorImpl<Value *> &Right,
6481                                              const DataLayout &DL,
6482                                              ScalarEvolution &SE,
6483                                              const BoUpSLP &R) {
6484   if (VL.empty())
6485     return;
6486   VLOperands Ops(VL, DL, SE, R);
6487   // Reorder the operands in place.
6488   Ops.reorder();
6489   Left = Ops.getVL(0);
6490   Right = Ops.getVL(1);
6491 }
6492 
6493 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6494   // Get the basic block this bundle is in. All instructions in the bundle
6495   // should be in this block.
6496   auto *Front = E->getMainOp();
6497   auto *BB = Front->getParent();
6498   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6499     auto *I = cast<Instruction>(V);
6500     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6501   }));
6502 
6503   auto &&FindLastInst = [E, Front]() {
6504     Instruction *LastInst = Front;
6505     for (Value *V : E->Scalars) {
6506       auto *I = dyn_cast<Instruction>(V);
6507       if (!I)
6508         continue;
6509       if (LastInst->comesBefore(I))
6510         LastInst = I;
6511     }
6512     return LastInst;
6513   };
6514 
6515   auto &&FindFirstInst = [E, Front]() {
6516     Instruction *FirstInst = Front;
6517     for (Value *V : E->Scalars) {
6518       auto *I = dyn_cast<Instruction>(V);
6519       if (!I)
6520         continue;
6521       if (I->comesBefore(FirstInst))
6522         FirstInst = I;
6523     }
6524     return FirstInst;
6525   };
6526 
6527   // Set the insert point to the beginning of the basic block if the entry
6528   // should not be scheduled.
6529   if (E->State != TreeEntry::NeedToGather &&
6530       doesNotNeedToSchedule(E->Scalars)) {
6531     BasicBlock::iterator InsertPt;
6532     if (all_of(E->Scalars, isUsedOutsideBlock))
6533       InsertPt = FindLastInst()->getIterator();
6534     else
6535       InsertPt = FindFirstInst()->getIterator();
6536     Builder.SetInsertPoint(BB, InsertPt);
6537     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6538     return;
6539   }
6540 
6541   // The last instruction in the bundle in program order.
6542   Instruction *LastInst = nullptr;
6543 
6544   // Find the last instruction. The common case should be that BB has been
6545   // scheduled, and the last instruction is VL.back(). So we start with
6546   // VL.back() and iterate over schedule data until we reach the end of the
6547   // bundle. The end of the bundle is marked by null ScheduleData.
6548   if (BlocksSchedules.count(BB)) {
6549     Value *V = E->isOneOf(E->Scalars.back());
6550     if (doesNotNeedToBeScheduled(V))
6551       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6552     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6553     if (Bundle && Bundle->isPartOfBundle())
6554       for (; Bundle; Bundle = Bundle->NextInBundle)
6555         if (Bundle->OpValue == Bundle->Inst)
6556           LastInst = Bundle->Inst;
6557   }
6558 
6559   // LastInst can still be null at this point if there's either not an entry
6560   // for BB in BlocksSchedules or there's no ScheduleData available for
6561   // VL.back(). This can be the case if buildTree_rec aborts for various
6562   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6563   // size is reached, etc.). ScheduleData is initialized in the scheduling
6564   // "dry-run".
6565   //
6566   // If this happens, we can still find the last instruction by brute force. We
6567   // iterate forwards from Front (inclusive) until we either see all
6568   // instructions in the bundle or reach the end of the block. If Front is the
6569   // last instruction in program order, LastInst will be set to Front, and we
6570   // will visit all the remaining instructions in the block.
6571   //
6572   // One of the reasons we exit early from buildTree_rec is to place an upper
6573   // bound on compile-time. Thus, taking an additional compile-time hit here is
6574   // not ideal. However, this should be exceedingly rare since it requires that
6575   // we both exit early from buildTree_rec and that the bundle be out-of-order
6576   // (causing us to iterate all the way to the end of the block).
6577   if (!LastInst)
6578     LastInst = FindLastInst();
6579   assert(LastInst && "Failed to find last instruction in bundle");
6580 
6581   // Set the insertion point after the last instruction in the bundle. Set the
6582   // debug location to Front.
6583   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6584   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6585 }
6586 
6587 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6588   // List of instructions/lanes from current block and/or the blocks which are
6589   // part of the current loop. These instructions will be inserted at the end to
6590   // make it possible to optimize loops and hoist invariant instructions out of
6591   // the loops body with better chances for success.
6592   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6593   SmallSet<int, 4> PostponedIndices;
6594   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6595   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6596     SmallPtrSet<BasicBlock *, 4> Visited;
6597     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6598       InsertBB = InsertBB->getSinglePredecessor();
6599     return InsertBB && InsertBB == InstBB;
6600   };
6601   for (int I = 0, E = VL.size(); I < E; ++I) {
6602     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6603       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6604            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6605           PostponedIndices.insert(I).second)
6606         PostponedInsts.emplace_back(Inst, I);
6607   }
6608 
6609   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6610     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6611     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6612     if (!InsElt)
6613       return Vec;
6614     GatherShuffleSeq.insert(InsElt);
6615     CSEBlocks.insert(InsElt->getParent());
6616     // Add to our 'need-to-extract' list.
6617     if (TreeEntry *Entry = getTreeEntry(V)) {
6618       // Find which lane we need to extract.
6619       unsigned FoundLane = Entry->findLaneForValue(V);
6620       ExternalUses.emplace_back(V, InsElt, FoundLane);
6621     }
6622     return Vec;
6623   };
6624   Value *Val0 =
6625       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6626   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6627   Value *Vec = PoisonValue::get(VecTy);
6628   SmallVector<int> NonConsts;
6629   // Insert constant values at first.
6630   for (int I = 0, E = VL.size(); I < E; ++I) {
6631     if (PostponedIndices.contains(I))
6632       continue;
6633     if (!isConstant(VL[I])) {
6634       NonConsts.push_back(I);
6635       continue;
6636     }
6637     Vec = CreateInsertElement(Vec, VL[I], I);
6638   }
6639   // Insert non-constant values.
6640   for (int I : NonConsts)
6641     Vec = CreateInsertElement(Vec, VL[I], I);
6642   // Append instructions, which are/may be part of the loop, in the end to make
6643   // it possible to hoist non-loop-based instructions.
6644   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6645     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6646 
6647   return Vec;
6648 }
6649 
6650 namespace {
6651 /// Merges shuffle masks and emits final shuffle instruction, if required.
6652 class ShuffleInstructionBuilder {
6653   IRBuilderBase &Builder;
6654   const unsigned VF = 0;
6655   bool IsFinalized = false;
6656   SmallVector<int, 4> Mask;
6657   /// Holds all of the instructions that we gathered.
6658   SetVector<Instruction *> &GatherShuffleSeq;
6659   /// A list of blocks that we are going to CSE.
6660   SetVector<BasicBlock *> &CSEBlocks;
6661 
6662 public:
6663   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6664                             SetVector<Instruction *> &GatherShuffleSeq,
6665                             SetVector<BasicBlock *> &CSEBlocks)
6666       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6667         CSEBlocks(CSEBlocks) {}
6668 
6669   /// Adds a mask, inverting it before applying.
6670   void addInversedMask(ArrayRef<unsigned> SubMask) {
6671     if (SubMask.empty())
6672       return;
6673     SmallVector<int, 4> NewMask;
6674     inversePermutation(SubMask, NewMask);
6675     addMask(NewMask);
6676   }
6677 
6678   /// Functions adds masks, merging them into  single one.
6679   void addMask(ArrayRef<unsigned> SubMask) {
6680     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6681     addMask(NewMask);
6682   }
6683 
6684   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6685 
6686   Value *finalize(Value *V) {
6687     IsFinalized = true;
6688     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6689     if (VF == ValueVF && Mask.empty())
6690       return V;
6691     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6692     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6693     addMask(NormalizedMask);
6694 
6695     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6696       return V;
6697     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6698     if (auto *I = dyn_cast<Instruction>(Vec)) {
6699       GatherShuffleSeq.insert(I);
6700       CSEBlocks.insert(I->getParent());
6701     }
6702     return Vec;
6703   }
6704 
6705   ~ShuffleInstructionBuilder() {
6706     assert((IsFinalized || Mask.empty()) &&
6707            "Shuffle construction must be finalized.");
6708   }
6709 };
6710 } // namespace
6711 
6712 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6713   const unsigned VF = VL.size();
6714   InstructionsState S = getSameOpcode(VL);
6715   if (S.getOpcode()) {
6716     if (TreeEntry *E = getTreeEntry(S.OpValue))
6717       if (E->isSame(VL)) {
6718         Value *V = vectorizeTree(E);
6719         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6720           if (!E->ReuseShuffleIndices.empty()) {
6721             // Reshuffle to get only unique values.
6722             // If some of the scalars are duplicated in the vectorization tree
6723             // entry, we do not vectorize them but instead generate a mask for
6724             // the reuses. But if there are several users of the same entry,
6725             // they may have different vectorization factors. This is especially
6726             // important for PHI nodes. In this case, we need to adapt the
6727             // resulting instruction for the user vectorization factor and have
6728             // to reshuffle it again to take only unique elements of the vector.
6729             // Without this code the function incorrectly returns reduced vector
6730             // instruction with the same elements, not with the unique ones.
6731 
6732             // block:
6733             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6734             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6735             // ... (use %2)
6736             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6737             // br %block
6738             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6739             SmallSet<int, 4> UsedIdxs;
6740             int Pos = 0;
6741             int Sz = VL.size();
6742             for (int Idx : E->ReuseShuffleIndices) {
6743               if (Idx != Sz && Idx != UndefMaskElem &&
6744                   UsedIdxs.insert(Idx).second)
6745                 UniqueIdxs[Idx] = Pos;
6746               ++Pos;
6747             }
6748             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6749                                             "less than original vector size.");
6750             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6751             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6752           } else {
6753             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6754                    "Expected vectorization factor less "
6755                    "than original vector size.");
6756             SmallVector<int> UniformMask(VF, 0);
6757             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6758             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6759           }
6760           if (auto *I = dyn_cast<Instruction>(V)) {
6761             GatherShuffleSeq.insert(I);
6762             CSEBlocks.insert(I->getParent());
6763           }
6764         }
6765         return V;
6766       }
6767   }
6768 
6769   // Can't vectorize this, so simply build a new vector with each lane
6770   // corresponding to the requested value.
6771   return createBuildVector(VL);
6772 }
6773 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6774   unsigned VF = VL.size();
6775   // Exploit possible reuse of values across lanes.
6776   SmallVector<int> ReuseShuffleIndicies;
6777   SmallVector<Value *> UniqueValues;
6778   if (VL.size() > 2) {
6779     DenseMap<Value *, unsigned> UniquePositions;
6780     unsigned NumValues =
6781         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6782                                     return !isa<UndefValue>(V);
6783                                   }).base());
6784     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6785     int UniqueVals = 0;
6786     for (Value *V : VL.drop_back(VL.size() - VF)) {
6787       if (isa<UndefValue>(V)) {
6788         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6789         continue;
6790       }
6791       if (isConstant(V)) {
6792         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6793         UniqueValues.emplace_back(V);
6794         continue;
6795       }
6796       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6797       ReuseShuffleIndicies.emplace_back(Res.first->second);
6798       if (Res.second) {
6799         UniqueValues.emplace_back(V);
6800         ++UniqueVals;
6801       }
6802     }
6803     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6804       // Emit pure splat vector.
6805       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6806                                   UndefMaskElem);
6807     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6808       ReuseShuffleIndicies.clear();
6809       UniqueValues.clear();
6810       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6811     }
6812     UniqueValues.append(VF - UniqueValues.size(),
6813                         PoisonValue::get(VL[0]->getType()));
6814     VL = UniqueValues;
6815   }
6816 
6817   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6818                                            CSEBlocks);
6819   Value *Vec = gather(VL);
6820   if (!ReuseShuffleIndicies.empty()) {
6821     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6822     Vec = ShuffleBuilder.finalize(Vec);
6823   }
6824   return Vec;
6825 }
6826 
6827 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6828   IRBuilder<>::InsertPointGuard Guard(Builder);
6829 
6830   if (E->VectorizedValue) {
6831     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6832     return E->VectorizedValue;
6833   }
6834 
6835   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6836   unsigned VF = E->getVectorFactor();
6837   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6838                                            CSEBlocks);
6839   if (E->State == TreeEntry::NeedToGather) {
6840     if (E->getMainOp())
6841       setInsertPointAfterBundle(E);
6842     Value *Vec;
6843     SmallVector<int> Mask;
6844     SmallVector<const TreeEntry *> Entries;
6845     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6846         isGatherShuffledEntry(E, Mask, Entries);
6847     if (Shuffle.hasValue()) {
6848       assert((Entries.size() == 1 || Entries.size() == 2) &&
6849              "Expected shuffle of 1 or 2 entries.");
6850       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6851                                         Entries.back()->VectorizedValue, Mask);
6852       if (auto *I = dyn_cast<Instruction>(Vec)) {
6853         GatherShuffleSeq.insert(I);
6854         CSEBlocks.insert(I->getParent());
6855       }
6856     } else {
6857       Vec = gather(E->Scalars);
6858     }
6859     if (NeedToShuffleReuses) {
6860       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6861       Vec = ShuffleBuilder.finalize(Vec);
6862     }
6863     E->VectorizedValue = Vec;
6864     return Vec;
6865   }
6866 
6867   assert((E->State == TreeEntry::Vectorize ||
6868           E->State == TreeEntry::ScatterVectorize) &&
6869          "Unhandled state");
6870   unsigned ShuffleOrOp =
6871       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6872   Instruction *VL0 = E->getMainOp();
6873   Type *ScalarTy = VL0->getType();
6874   if (auto *Store = dyn_cast<StoreInst>(VL0))
6875     ScalarTy = Store->getValueOperand()->getType();
6876   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6877     ScalarTy = IE->getOperand(1)->getType();
6878   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6879   switch (ShuffleOrOp) {
6880     case Instruction::PHI: {
6881       assert(
6882           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6883           "PHI reordering is free.");
6884       auto *PH = cast<PHINode>(VL0);
6885       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6886       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6887       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6888       Value *V = NewPhi;
6889 
6890       // Adjust insertion point once all PHI's have been generated.
6891       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6892       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6893 
6894       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6895       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6896       V = ShuffleBuilder.finalize(V);
6897 
6898       E->VectorizedValue = V;
6899 
6900       // PHINodes may have multiple entries from the same block. We want to
6901       // visit every block once.
6902       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6903 
6904       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6905         ValueList Operands;
6906         BasicBlock *IBB = PH->getIncomingBlock(i);
6907 
6908         if (!VisitedBBs.insert(IBB).second) {
6909           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6910           continue;
6911         }
6912 
6913         Builder.SetInsertPoint(IBB->getTerminator());
6914         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6915         Value *Vec = vectorizeTree(E->getOperand(i));
6916         NewPhi->addIncoming(Vec, IBB);
6917       }
6918 
6919       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6920              "Invalid number of incoming values");
6921       return V;
6922     }
6923 
6924     case Instruction::ExtractElement: {
6925       Value *V = E->getSingleOperand(0);
6926       Builder.SetInsertPoint(VL0);
6927       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6928       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6929       V = ShuffleBuilder.finalize(V);
6930       E->VectorizedValue = V;
6931       return V;
6932     }
6933     case Instruction::ExtractValue: {
6934       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6935       Builder.SetInsertPoint(LI);
6936       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6937       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6938       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6939       Value *NewV = propagateMetadata(V, E->Scalars);
6940       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6941       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6942       NewV = ShuffleBuilder.finalize(NewV);
6943       E->VectorizedValue = NewV;
6944       return NewV;
6945     }
6946     case Instruction::InsertElement: {
6947       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6948       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6949       Value *V = vectorizeTree(E->getOperand(1));
6950 
6951       // Create InsertVector shuffle if necessary
6952       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6953         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6954       }));
6955       const unsigned NumElts =
6956           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6957       const unsigned NumScalars = E->Scalars.size();
6958 
6959       unsigned Offset = *getInsertIndex(VL0);
6960       assert(Offset < NumElts && "Failed to find vector index offset");
6961 
6962       // Create shuffle to resize vector
6963       SmallVector<int> Mask;
6964       if (!E->ReorderIndices.empty()) {
6965         inversePermutation(E->ReorderIndices, Mask);
6966         Mask.append(NumElts - NumScalars, UndefMaskElem);
6967       } else {
6968         Mask.assign(NumElts, UndefMaskElem);
6969         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6970       }
6971       // Create InsertVector shuffle if necessary
6972       bool IsIdentity = true;
6973       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6974       Mask.swap(PrevMask);
6975       for (unsigned I = 0; I < NumScalars; ++I) {
6976         Value *Scalar = E->Scalars[PrevMask[I]];
6977         unsigned InsertIdx = *getInsertIndex(Scalar);
6978         IsIdentity &= InsertIdx - Offset == I;
6979         Mask[InsertIdx - Offset] = I;
6980       }
6981       if (!IsIdentity || NumElts != NumScalars) {
6982         V = Builder.CreateShuffleVector(V, Mask);
6983         if (auto *I = dyn_cast<Instruction>(V)) {
6984           GatherShuffleSeq.insert(I);
6985           CSEBlocks.insert(I->getParent());
6986         }
6987       }
6988 
6989       if ((!IsIdentity || Offset != 0 ||
6990            !isUndefVector(FirstInsert->getOperand(0))) &&
6991           NumElts != NumScalars) {
6992         SmallVector<int> InsertMask(NumElts);
6993         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6994         for (unsigned I = 0; I < NumElts; I++) {
6995           if (Mask[I] != UndefMaskElem)
6996             InsertMask[Offset + I] = NumElts + I;
6997         }
6998 
6999         V = Builder.CreateShuffleVector(
7000             FirstInsert->getOperand(0), V, InsertMask,
7001             cast<Instruction>(E->Scalars.back())->getName());
7002         if (auto *I = dyn_cast<Instruction>(V)) {
7003           GatherShuffleSeq.insert(I);
7004           CSEBlocks.insert(I->getParent());
7005         }
7006       }
7007 
7008       ++NumVectorInstructions;
7009       E->VectorizedValue = V;
7010       return V;
7011     }
7012     case Instruction::ZExt:
7013     case Instruction::SExt:
7014     case Instruction::FPToUI:
7015     case Instruction::FPToSI:
7016     case Instruction::FPExt:
7017     case Instruction::PtrToInt:
7018     case Instruction::IntToPtr:
7019     case Instruction::SIToFP:
7020     case Instruction::UIToFP:
7021     case Instruction::Trunc:
7022     case Instruction::FPTrunc:
7023     case Instruction::BitCast: {
7024       setInsertPointAfterBundle(E);
7025 
7026       Value *InVec = vectorizeTree(E->getOperand(0));
7027 
7028       if (E->VectorizedValue) {
7029         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7030         return E->VectorizedValue;
7031       }
7032 
7033       auto *CI = cast<CastInst>(VL0);
7034       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7035       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7036       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7037       V = ShuffleBuilder.finalize(V);
7038 
7039       E->VectorizedValue = V;
7040       ++NumVectorInstructions;
7041       return V;
7042     }
7043     case Instruction::FCmp:
7044     case Instruction::ICmp: {
7045       setInsertPointAfterBundle(E);
7046 
7047       Value *L = vectorizeTree(E->getOperand(0));
7048       Value *R = vectorizeTree(E->getOperand(1));
7049 
7050       if (E->VectorizedValue) {
7051         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7052         return E->VectorizedValue;
7053       }
7054 
7055       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7056       Value *V = Builder.CreateCmp(P0, L, R);
7057       propagateIRFlags(V, E->Scalars, VL0);
7058       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7059       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7060       V = ShuffleBuilder.finalize(V);
7061 
7062       E->VectorizedValue = V;
7063       ++NumVectorInstructions;
7064       return V;
7065     }
7066     case Instruction::Select: {
7067       setInsertPointAfterBundle(E);
7068 
7069       Value *Cond = vectorizeTree(E->getOperand(0));
7070       Value *True = vectorizeTree(E->getOperand(1));
7071       Value *False = vectorizeTree(E->getOperand(2));
7072 
7073       if (E->VectorizedValue) {
7074         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7075         return E->VectorizedValue;
7076       }
7077 
7078       Value *V = Builder.CreateSelect(Cond, True, False);
7079       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7080       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7081       V = ShuffleBuilder.finalize(V);
7082 
7083       E->VectorizedValue = V;
7084       ++NumVectorInstructions;
7085       return V;
7086     }
7087     case Instruction::FNeg: {
7088       setInsertPointAfterBundle(E);
7089 
7090       Value *Op = vectorizeTree(E->getOperand(0));
7091 
7092       if (E->VectorizedValue) {
7093         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7094         return E->VectorizedValue;
7095       }
7096 
7097       Value *V = Builder.CreateUnOp(
7098           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7099       propagateIRFlags(V, E->Scalars, VL0);
7100       if (auto *I = dyn_cast<Instruction>(V))
7101         V = propagateMetadata(I, E->Scalars);
7102 
7103       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7104       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7105       V = ShuffleBuilder.finalize(V);
7106 
7107       E->VectorizedValue = V;
7108       ++NumVectorInstructions;
7109 
7110       return V;
7111     }
7112     case Instruction::Add:
7113     case Instruction::FAdd:
7114     case Instruction::Sub:
7115     case Instruction::FSub:
7116     case Instruction::Mul:
7117     case Instruction::FMul:
7118     case Instruction::UDiv:
7119     case Instruction::SDiv:
7120     case Instruction::FDiv:
7121     case Instruction::URem:
7122     case Instruction::SRem:
7123     case Instruction::FRem:
7124     case Instruction::Shl:
7125     case Instruction::LShr:
7126     case Instruction::AShr:
7127     case Instruction::And:
7128     case Instruction::Or:
7129     case Instruction::Xor: {
7130       setInsertPointAfterBundle(E);
7131 
7132       Value *LHS = vectorizeTree(E->getOperand(0));
7133       Value *RHS = vectorizeTree(E->getOperand(1));
7134 
7135       if (E->VectorizedValue) {
7136         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7137         return E->VectorizedValue;
7138       }
7139 
7140       Value *V = Builder.CreateBinOp(
7141           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7142           RHS);
7143       propagateIRFlags(V, E->Scalars, VL0);
7144       if (auto *I = dyn_cast<Instruction>(V))
7145         V = propagateMetadata(I, E->Scalars);
7146 
7147       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7148       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7149       V = ShuffleBuilder.finalize(V);
7150 
7151       E->VectorizedValue = V;
7152       ++NumVectorInstructions;
7153 
7154       return V;
7155     }
7156     case Instruction::Load: {
7157       // Loads are inserted at the head of the tree because we don't want to
7158       // sink them all the way down past store instructions.
7159       setInsertPointAfterBundle(E);
7160 
7161       LoadInst *LI = cast<LoadInst>(VL0);
7162       Instruction *NewLI;
7163       unsigned AS = LI->getPointerAddressSpace();
7164       Value *PO = LI->getPointerOperand();
7165       if (E->State == TreeEntry::Vectorize) {
7166         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7167         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7168 
7169         // The pointer operand uses an in-tree scalar so we add the new BitCast
7170         // or LoadInst to ExternalUses list to make sure that an extract will
7171         // be generated in the future.
7172         if (TreeEntry *Entry = getTreeEntry(PO)) {
7173           // Find which lane we need to extract.
7174           unsigned FoundLane = Entry->findLaneForValue(PO);
7175           ExternalUses.emplace_back(
7176               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7177         }
7178       } else {
7179         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7180         Value *VecPtr = vectorizeTree(E->getOperand(0));
7181         // Use the minimum alignment of the gathered loads.
7182         Align CommonAlignment = LI->getAlign();
7183         for (Value *V : E->Scalars)
7184           CommonAlignment =
7185               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7186         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7187       }
7188       Value *V = propagateMetadata(NewLI, E->Scalars);
7189 
7190       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7191       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7192       V = ShuffleBuilder.finalize(V);
7193       E->VectorizedValue = V;
7194       ++NumVectorInstructions;
7195       return V;
7196     }
7197     case Instruction::Store: {
7198       auto *SI = cast<StoreInst>(VL0);
7199       unsigned AS = SI->getPointerAddressSpace();
7200 
7201       setInsertPointAfterBundle(E);
7202 
7203       Value *VecValue = vectorizeTree(E->getOperand(0));
7204       ShuffleBuilder.addMask(E->ReorderIndices);
7205       VecValue = ShuffleBuilder.finalize(VecValue);
7206 
7207       Value *ScalarPtr = SI->getPointerOperand();
7208       Value *VecPtr = Builder.CreateBitCast(
7209           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7210       StoreInst *ST =
7211           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7212 
7213       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7214       // StoreInst to ExternalUses to make sure that an extract will be
7215       // generated in the future.
7216       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7217         // Find which lane we need to extract.
7218         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7219         ExternalUses.push_back(ExternalUser(
7220             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7221             FoundLane));
7222       }
7223 
7224       Value *V = propagateMetadata(ST, E->Scalars);
7225 
7226       E->VectorizedValue = V;
7227       ++NumVectorInstructions;
7228       return V;
7229     }
7230     case Instruction::GetElementPtr: {
7231       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7232       setInsertPointAfterBundle(E);
7233 
7234       Value *Op0 = vectorizeTree(E->getOperand(0));
7235 
7236       SmallVector<Value *> OpVecs;
7237       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7238         Value *OpVec = vectorizeTree(E->getOperand(J));
7239         OpVecs.push_back(OpVec);
7240       }
7241 
7242       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7243       if (Instruction *I = dyn_cast<Instruction>(V))
7244         V = propagateMetadata(I, E->Scalars);
7245 
7246       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7247       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7248       V = ShuffleBuilder.finalize(V);
7249 
7250       E->VectorizedValue = V;
7251       ++NumVectorInstructions;
7252 
7253       return V;
7254     }
7255     case Instruction::Call: {
7256       CallInst *CI = cast<CallInst>(VL0);
7257       setInsertPointAfterBundle(E);
7258 
7259       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7260       if (Function *FI = CI->getCalledFunction())
7261         IID = FI->getIntrinsicID();
7262 
7263       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7264 
7265       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7266       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7267                           VecCallCosts.first <= VecCallCosts.second;
7268 
7269       Value *ScalarArg = nullptr;
7270       std::vector<Value *> OpVecs;
7271       SmallVector<Type *, 2> TysForDecl =
7272           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7273       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7274         ValueList OpVL;
7275         // Some intrinsics have scalar arguments. This argument should not be
7276         // vectorized.
7277         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7278           CallInst *CEI = cast<CallInst>(VL0);
7279           ScalarArg = CEI->getArgOperand(j);
7280           OpVecs.push_back(CEI->getArgOperand(j));
7281           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7282             TysForDecl.push_back(ScalarArg->getType());
7283           continue;
7284         }
7285 
7286         Value *OpVec = vectorizeTree(E->getOperand(j));
7287         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7288         OpVecs.push_back(OpVec);
7289       }
7290 
7291       Function *CF;
7292       if (!UseIntrinsic) {
7293         VFShape Shape =
7294             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7295                                   VecTy->getNumElements())),
7296                          false /*HasGlobalPred*/);
7297         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7298       } else {
7299         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7300       }
7301 
7302       SmallVector<OperandBundleDef, 1> OpBundles;
7303       CI->getOperandBundlesAsDefs(OpBundles);
7304       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7305 
7306       // The scalar argument uses an in-tree scalar so we add the new vectorized
7307       // call to ExternalUses list to make sure that an extract will be
7308       // generated in the future.
7309       if (ScalarArg) {
7310         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7311           // Find which lane we need to extract.
7312           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7313           ExternalUses.push_back(
7314               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7315         }
7316       }
7317 
7318       propagateIRFlags(V, E->Scalars, VL0);
7319       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7320       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7321       V = ShuffleBuilder.finalize(V);
7322 
7323       E->VectorizedValue = V;
7324       ++NumVectorInstructions;
7325       return V;
7326     }
7327     case Instruction::ShuffleVector: {
7328       assert(E->isAltShuffle() &&
7329              ((Instruction::isBinaryOp(E->getOpcode()) &&
7330                Instruction::isBinaryOp(E->getAltOpcode())) ||
7331               (Instruction::isCast(E->getOpcode()) &&
7332                Instruction::isCast(E->getAltOpcode())) ||
7333               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7334              "Invalid Shuffle Vector Operand");
7335 
7336       Value *LHS = nullptr, *RHS = nullptr;
7337       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7338         setInsertPointAfterBundle(E);
7339         LHS = vectorizeTree(E->getOperand(0));
7340         RHS = vectorizeTree(E->getOperand(1));
7341       } else {
7342         setInsertPointAfterBundle(E);
7343         LHS = vectorizeTree(E->getOperand(0));
7344       }
7345 
7346       if (E->VectorizedValue) {
7347         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7348         return E->VectorizedValue;
7349       }
7350 
7351       Value *V0, *V1;
7352       if (Instruction::isBinaryOp(E->getOpcode())) {
7353         V0 = Builder.CreateBinOp(
7354             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7355         V1 = Builder.CreateBinOp(
7356             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7357       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7358         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7359         auto *AltCI = cast<CmpInst>(E->getAltOp());
7360         CmpInst::Predicate AltPred = AltCI->getPredicate();
7361         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7362       } else {
7363         V0 = Builder.CreateCast(
7364             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7365         V1 = Builder.CreateCast(
7366             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7367       }
7368       // Add V0 and V1 to later analysis to try to find and remove matching
7369       // instruction, if any.
7370       for (Value *V : {V0, V1}) {
7371         if (auto *I = dyn_cast<Instruction>(V)) {
7372           GatherShuffleSeq.insert(I);
7373           CSEBlocks.insert(I->getParent());
7374         }
7375       }
7376 
7377       // Create shuffle to take alternate operations from the vector.
7378       // Also, gather up main and alt scalar ops to propagate IR flags to
7379       // each vector operation.
7380       ValueList OpScalars, AltScalars;
7381       SmallVector<int> Mask;
7382       buildShuffleEntryMask(
7383           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7384           [E](Instruction *I) {
7385             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7386             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7387           },
7388           Mask, &OpScalars, &AltScalars);
7389 
7390       propagateIRFlags(V0, OpScalars);
7391       propagateIRFlags(V1, AltScalars);
7392 
7393       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7394       if (auto *I = dyn_cast<Instruction>(V)) {
7395         V = propagateMetadata(I, E->Scalars);
7396         GatherShuffleSeq.insert(I);
7397         CSEBlocks.insert(I->getParent());
7398       }
7399       V = ShuffleBuilder.finalize(V);
7400 
7401       E->VectorizedValue = V;
7402       ++NumVectorInstructions;
7403 
7404       return V;
7405     }
7406     default:
7407     llvm_unreachable("unknown inst");
7408   }
7409   return nullptr;
7410 }
7411 
7412 Value *BoUpSLP::vectorizeTree() {
7413   ExtraValueToDebugLocsMap ExternallyUsedValues;
7414   return vectorizeTree(ExternallyUsedValues);
7415 }
7416 
7417 Value *
7418 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7419   // All blocks must be scheduled before any instructions are inserted.
7420   for (auto &BSIter : BlocksSchedules) {
7421     scheduleBlock(BSIter.second.get());
7422   }
7423 
7424   Builder.SetInsertPoint(&F->getEntryBlock().front());
7425   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7426 
7427   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7428   // vectorized root. InstCombine will then rewrite the entire expression. We
7429   // sign extend the extracted values below.
7430   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7431   if (MinBWs.count(ScalarRoot)) {
7432     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7433       // If current instr is a phi and not the last phi, insert it after the
7434       // last phi node.
7435       if (isa<PHINode>(I))
7436         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7437       else
7438         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7439     }
7440     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7441     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7442     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7443     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7444     VectorizableTree[0]->VectorizedValue = Trunc;
7445   }
7446 
7447   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7448                     << " values .\n");
7449 
7450   // Extract all of the elements with the external uses.
7451   for (const auto &ExternalUse : ExternalUses) {
7452     Value *Scalar = ExternalUse.Scalar;
7453     llvm::User *User = ExternalUse.User;
7454 
7455     // Skip users that we already RAUW. This happens when one instruction
7456     // has multiple uses of the same value.
7457     if (User && !is_contained(Scalar->users(), User))
7458       continue;
7459     TreeEntry *E = getTreeEntry(Scalar);
7460     assert(E && "Invalid scalar");
7461     assert(E->State != TreeEntry::NeedToGather &&
7462            "Extracting from a gather list");
7463 
7464     Value *Vec = E->VectorizedValue;
7465     assert(Vec && "Can't find vectorizable value");
7466 
7467     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7468     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7469       if (Scalar->getType() != Vec->getType()) {
7470         Value *Ex;
7471         // "Reuse" the existing extract to improve final codegen.
7472         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7473           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7474                                             ES->getOperand(1));
7475         } else {
7476           Ex = Builder.CreateExtractElement(Vec, Lane);
7477         }
7478         // If necessary, sign-extend or zero-extend ScalarRoot
7479         // to the larger type.
7480         if (!MinBWs.count(ScalarRoot))
7481           return Ex;
7482         if (MinBWs[ScalarRoot].second)
7483           return Builder.CreateSExt(Ex, Scalar->getType());
7484         return Builder.CreateZExt(Ex, Scalar->getType());
7485       }
7486       assert(isa<FixedVectorType>(Scalar->getType()) &&
7487              isa<InsertElementInst>(Scalar) &&
7488              "In-tree scalar of vector type is not insertelement?");
7489       return Vec;
7490     };
7491     // If User == nullptr, the Scalar is used as extra arg. Generate
7492     // ExtractElement instruction and update the record for this scalar in
7493     // ExternallyUsedValues.
7494     if (!User) {
7495       assert(ExternallyUsedValues.count(Scalar) &&
7496              "Scalar with nullptr as an external user must be registered in "
7497              "ExternallyUsedValues map");
7498       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7499         Builder.SetInsertPoint(VecI->getParent(),
7500                                std::next(VecI->getIterator()));
7501       } else {
7502         Builder.SetInsertPoint(&F->getEntryBlock().front());
7503       }
7504       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7505       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7506       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7507       auto It = ExternallyUsedValues.find(Scalar);
7508       assert(It != ExternallyUsedValues.end() &&
7509              "Externally used scalar is not found in ExternallyUsedValues");
7510       NewInstLocs.append(It->second);
7511       ExternallyUsedValues.erase(Scalar);
7512       // Required to update internally referenced instructions.
7513       Scalar->replaceAllUsesWith(NewInst);
7514       continue;
7515     }
7516 
7517     // Generate extracts for out-of-tree users.
7518     // Find the insertion point for the extractelement lane.
7519     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7520       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7521         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7522           if (PH->getIncomingValue(i) == Scalar) {
7523             Instruction *IncomingTerminator =
7524                 PH->getIncomingBlock(i)->getTerminator();
7525             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7526               Builder.SetInsertPoint(VecI->getParent(),
7527                                      std::next(VecI->getIterator()));
7528             } else {
7529               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7530             }
7531             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7532             CSEBlocks.insert(PH->getIncomingBlock(i));
7533             PH->setOperand(i, NewInst);
7534           }
7535         }
7536       } else {
7537         Builder.SetInsertPoint(cast<Instruction>(User));
7538         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7539         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7540         User->replaceUsesOfWith(Scalar, NewInst);
7541       }
7542     } else {
7543       Builder.SetInsertPoint(&F->getEntryBlock().front());
7544       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7545       CSEBlocks.insert(&F->getEntryBlock());
7546       User->replaceUsesOfWith(Scalar, NewInst);
7547     }
7548 
7549     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7550   }
7551 
7552   // For each vectorized value:
7553   for (auto &TEPtr : VectorizableTree) {
7554     TreeEntry *Entry = TEPtr.get();
7555 
7556     // No need to handle users of gathered values.
7557     if (Entry->State == TreeEntry::NeedToGather)
7558       continue;
7559 
7560     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7561 
7562     // For each lane:
7563     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7564       Value *Scalar = Entry->Scalars[Lane];
7565 
7566 #ifndef NDEBUG
7567       Type *Ty = Scalar->getType();
7568       if (!Ty->isVoidTy()) {
7569         for (User *U : Scalar->users()) {
7570           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7571 
7572           // It is legal to delete users in the ignorelist.
7573           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7574                   (isa_and_nonnull<Instruction>(U) &&
7575                    isDeleted(cast<Instruction>(U)))) &&
7576                  "Deleting out-of-tree value");
7577         }
7578       }
7579 #endif
7580       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7581       eraseInstruction(cast<Instruction>(Scalar));
7582     }
7583   }
7584 
7585   Builder.ClearInsertionPoint();
7586   InstrElementSize.clear();
7587 
7588   return VectorizableTree[0]->VectorizedValue;
7589 }
7590 
7591 void BoUpSLP::optimizeGatherSequence() {
7592   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7593                     << " gather sequences instructions.\n");
7594   // LICM InsertElementInst sequences.
7595   for (Instruction *I : GatherShuffleSeq) {
7596     if (isDeleted(I))
7597       continue;
7598 
7599     // Check if this block is inside a loop.
7600     Loop *L = LI->getLoopFor(I->getParent());
7601     if (!L)
7602       continue;
7603 
7604     // Check if it has a preheader.
7605     BasicBlock *PreHeader = L->getLoopPreheader();
7606     if (!PreHeader)
7607       continue;
7608 
7609     // If the vector or the element that we insert into it are
7610     // instructions that are defined in this basic block then we can't
7611     // hoist this instruction.
7612     if (any_of(I->operands(), [L](Value *V) {
7613           auto *OpI = dyn_cast<Instruction>(V);
7614           return OpI && L->contains(OpI);
7615         }))
7616       continue;
7617 
7618     // We can hoist this instruction. Move it to the pre-header.
7619     I->moveBefore(PreHeader->getTerminator());
7620   }
7621 
7622   // Make a list of all reachable blocks in our CSE queue.
7623   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7624   CSEWorkList.reserve(CSEBlocks.size());
7625   for (BasicBlock *BB : CSEBlocks)
7626     if (DomTreeNode *N = DT->getNode(BB)) {
7627       assert(DT->isReachableFromEntry(N));
7628       CSEWorkList.push_back(N);
7629     }
7630 
7631   // Sort blocks by domination. This ensures we visit a block after all blocks
7632   // dominating it are visited.
7633   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7634     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7635            "Different nodes should have different DFS numbers");
7636     return A->getDFSNumIn() < B->getDFSNumIn();
7637   });
7638 
7639   // Less defined shuffles can be replaced by the more defined copies.
7640   // Between two shuffles one is less defined if it has the same vector operands
7641   // and its mask indeces are the same as in the first one or undefs. E.g.
7642   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7643   // poison, <0, 0, 0, 0>.
7644   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7645                                            SmallVectorImpl<int> &NewMask) {
7646     if (I1->getType() != I2->getType())
7647       return false;
7648     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7649     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7650     if (!SI1 || !SI2)
7651       return I1->isIdenticalTo(I2);
7652     if (SI1->isIdenticalTo(SI2))
7653       return true;
7654     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7655       if (SI1->getOperand(I) != SI2->getOperand(I))
7656         return false;
7657     // Check if the second instruction is more defined than the first one.
7658     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7659     ArrayRef<int> SM1 = SI1->getShuffleMask();
7660     // Count trailing undefs in the mask to check the final number of used
7661     // registers.
7662     unsigned LastUndefsCnt = 0;
7663     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7664       if (SM1[I] == UndefMaskElem)
7665         ++LastUndefsCnt;
7666       else
7667         LastUndefsCnt = 0;
7668       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7669           NewMask[I] != SM1[I])
7670         return false;
7671       if (NewMask[I] == UndefMaskElem)
7672         NewMask[I] = SM1[I];
7673     }
7674     // Check if the last undefs actually change the final number of used vector
7675     // registers.
7676     return SM1.size() - LastUndefsCnt > 1 &&
7677            TTI->getNumberOfParts(SI1->getType()) ==
7678                TTI->getNumberOfParts(
7679                    FixedVectorType::get(SI1->getType()->getElementType(),
7680                                         SM1.size() - LastUndefsCnt));
7681   };
7682   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7683   // instructions. TODO: We can further optimize this scan if we split the
7684   // instructions into different buckets based on the insert lane.
7685   SmallVector<Instruction *, 16> Visited;
7686   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7687     assert(*I &&
7688            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7689            "Worklist not sorted properly!");
7690     BasicBlock *BB = (*I)->getBlock();
7691     // For all instructions in blocks containing gather sequences:
7692     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7693       if (isDeleted(&In))
7694         continue;
7695       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7696           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7697         continue;
7698 
7699       // Check if we can replace this instruction with any of the
7700       // visited instructions.
7701       bool Replaced = false;
7702       for (Instruction *&V : Visited) {
7703         SmallVector<int> NewMask;
7704         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7705             DT->dominates(V->getParent(), In.getParent())) {
7706           In.replaceAllUsesWith(V);
7707           eraseInstruction(&In);
7708           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7709             if (!NewMask.empty())
7710               SI->setShuffleMask(NewMask);
7711           Replaced = true;
7712           break;
7713         }
7714         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7715             GatherShuffleSeq.contains(V) &&
7716             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7717             DT->dominates(In.getParent(), V->getParent())) {
7718           In.moveAfter(V);
7719           V->replaceAllUsesWith(&In);
7720           eraseInstruction(V);
7721           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7722             if (!NewMask.empty())
7723               SI->setShuffleMask(NewMask);
7724           V = &In;
7725           Replaced = true;
7726           break;
7727         }
7728       }
7729       if (!Replaced) {
7730         assert(!is_contained(Visited, &In));
7731         Visited.push_back(&In);
7732       }
7733     }
7734   }
7735   CSEBlocks.clear();
7736   GatherShuffleSeq.clear();
7737 }
7738 
7739 BoUpSLP::ScheduleData *
7740 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7741   ScheduleData *Bundle = nullptr;
7742   ScheduleData *PrevInBundle = nullptr;
7743   for (Value *V : VL) {
7744     if (doesNotNeedToBeScheduled(V))
7745       continue;
7746     ScheduleData *BundleMember = getScheduleData(V);
7747     assert(BundleMember &&
7748            "no ScheduleData for bundle member "
7749            "(maybe not in same basic block)");
7750     assert(BundleMember->isSchedulingEntity() &&
7751            "bundle member already part of other bundle");
7752     if (PrevInBundle) {
7753       PrevInBundle->NextInBundle = BundleMember;
7754     } else {
7755       Bundle = BundleMember;
7756     }
7757 
7758     // Group the instructions to a bundle.
7759     BundleMember->FirstInBundle = Bundle;
7760     PrevInBundle = BundleMember;
7761   }
7762   assert(Bundle && "Failed to find schedule bundle");
7763   return Bundle;
7764 }
7765 
7766 // Groups the instructions to a bundle (which is then a single scheduling entity)
7767 // and schedules instructions until the bundle gets ready.
7768 Optional<BoUpSLP::ScheduleData *>
7769 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7770                                             const InstructionsState &S) {
7771   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7772   // instructions.
7773   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7774       doesNotNeedToSchedule(VL))
7775     return nullptr;
7776 
7777   // Initialize the instruction bundle.
7778   Instruction *OldScheduleEnd = ScheduleEnd;
7779   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7780 
7781   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7782                                                          ScheduleData *Bundle) {
7783     // The scheduling region got new instructions at the lower end (or it is a
7784     // new region for the first bundle). This makes it necessary to
7785     // recalculate all dependencies.
7786     // It is seldom that this needs to be done a second time after adding the
7787     // initial bundle to the region.
7788     if (ScheduleEnd != OldScheduleEnd) {
7789       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7790         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7791       ReSchedule = true;
7792     }
7793     if (Bundle) {
7794       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7795                         << " in block " << BB->getName() << "\n");
7796       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7797     }
7798 
7799     if (ReSchedule) {
7800       resetSchedule();
7801       initialFillReadyList(ReadyInsts);
7802     }
7803 
7804     // Now try to schedule the new bundle or (if no bundle) just calculate
7805     // dependencies. As soon as the bundle is "ready" it means that there are no
7806     // cyclic dependencies and we can schedule it. Note that's important that we
7807     // don't "schedule" the bundle yet (see cancelScheduling).
7808     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7809            !ReadyInsts.empty()) {
7810       ScheduleData *Picked = ReadyInsts.pop_back_val();
7811       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7812              "must be ready to schedule");
7813       schedule(Picked, ReadyInsts);
7814     }
7815   };
7816 
7817   // Make sure that the scheduling region contains all
7818   // instructions of the bundle.
7819   for (Value *V : VL) {
7820     if (doesNotNeedToBeScheduled(V))
7821       continue;
7822     if (!extendSchedulingRegion(V, S)) {
7823       // If the scheduling region got new instructions at the lower end (or it
7824       // is a new region for the first bundle). This makes it necessary to
7825       // recalculate all dependencies.
7826       // Otherwise the compiler may crash trying to incorrectly calculate
7827       // dependencies and emit instruction in the wrong order at the actual
7828       // scheduling.
7829       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7830       return None;
7831     }
7832   }
7833 
7834   bool ReSchedule = false;
7835   for (Value *V : VL) {
7836     if (doesNotNeedToBeScheduled(V))
7837       continue;
7838     ScheduleData *BundleMember = getScheduleData(V);
7839     assert(BundleMember &&
7840            "no ScheduleData for bundle member (maybe not in same basic block)");
7841 
7842     // Make sure we don't leave the pieces of the bundle in the ready list when
7843     // whole bundle might not be ready.
7844     ReadyInsts.remove(BundleMember);
7845 
7846     if (!BundleMember->IsScheduled)
7847       continue;
7848     // A bundle member was scheduled as single instruction before and now
7849     // needs to be scheduled as part of the bundle. We just get rid of the
7850     // existing schedule.
7851     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7852                       << " was already scheduled\n");
7853     ReSchedule = true;
7854   }
7855 
7856   auto *Bundle = buildBundle(VL);
7857   TryScheduleBundleImpl(ReSchedule, Bundle);
7858   if (!Bundle->isReady()) {
7859     cancelScheduling(VL, S.OpValue);
7860     return None;
7861   }
7862   return Bundle;
7863 }
7864 
7865 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7866                                                 Value *OpValue) {
7867   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7868       doesNotNeedToSchedule(VL))
7869     return;
7870 
7871   if (doesNotNeedToBeScheduled(OpValue))
7872     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7873   ScheduleData *Bundle = getScheduleData(OpValue);
7874   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7875   assert(!Bundle->IsScheduled &&
7876          "Can't cancel bundle which is already scheduled");
7877   assert(Bundle->isSchedulingEntity() &&
7878          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7879          "tried to unbundle something which is not a bundle");
7880 
7881   // Remove the bundle from the ready list.
7882   if (Bundle->isReady())
7883     ReadyInsts.remove(Bundle);
7884 
7885   // Un-bundle: make single instructions out of the bundle.
7886   ScheduleData *BundleMember = Bundle;
7887   while (BundleMember) {
7888     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7889     BundleMember->FirstInBundle = BundleMember;
7890     ScheduleData *Next = BundleMember->NextInBundle;
7891     BundleMember->NextInBundle = nullptr;
7892     BundleMember->TE = nullptr;
7893     if (BundleMember->unscheduledDepsInBundle() == 0) {
7894       ReadyInsts.insert(BundleMember);
7895     }
7896     BundleMember = Next;
7897   }
7898 }
7899 
7900 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7901   // Allocate a new ScheduleData for the instruction.
7902   if (ChunkPos >= ChunkSize) {
7903     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7904     ChunkPos = 0;
7905   }
7906   return &(ScheduleDataChunks.back()[ChunkPos++]);
7907 }
7908 
7909 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7910                                                       const InstructionsState &S) {
7911   if (getScheduleData(V, isOneOf(S, V)))
7912     return true;
7913   Instruction *I = dyn_cast<Instruction>(V);
7914   assert(I && "bundle member must be an instruction");
7915   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7916          !doesNotNeedToBeScheduled(I) &&
7917          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7918          "be scheduled");
7919   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7920     ScheduleData *ISD = getScheduleData(I);
7921     if (!ISD)
7922       return false;
7923     assert(isInSchedulingRegion(ISD) &&
7924            "ScheduleData not in scheduling region");
7925     ScheduleData *SD = allocateScheduleDataChunks();
7926     SD->Inst = I;
7927     SD->init(SchedulingRegionID, S.OpValue);
7928     ExtraScheduleDataMap[I][S.OpValue] = SD;
7929     return true;
7930   };
7931   if (CheckScheduleForI(I))
7932     return true;
7933   if (!ScheduleStart) {
7934     // It's the first instruction in the new region.
7935     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7936     ScheduleStart = I;
7937     ScheduleEnd = I->getNextNode();
7938     if (isOneOf(S, I) != I)
7939       CheckScheduleForI(I);
7940     assert(ScheduleEnd && "tried to vectorize a terminator?");
7941     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7942     return true;
7943   }
7944   // Search up and down at the same time, because we don't know if the new
7945   // instruction is above or below the existing scheduling region.
7946   BasicBlock::reverse_iterator UpIter =
7947       ++ScheduleStart->getIterator().getReverse();
7948   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7949   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7950   BasicBlock::iterator LowerEnd = BB->end();
7951   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7952          &*DownIter != I) {
7953     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7954       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7955       return false;
7956     }
7957 
7958     ++UpIter;
7959     ++DownIter;
7960   }
7961   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7962     assert(I->getParent() == ScheduleStart->getParent() &&
7963            "Instruction is in wrong basic block.");
7964     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7965     ScheduleStart = I;
7966     if (isOneOf(S, I) != I)
7967       CheckScheduleForI(I);
7968     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7969                       << "\n");
7970     return true;
7971   }
7972   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7973          "Expected to reach top of the basic block or instruction down the "
7974          "lower end.");
7975   assert(I->getParent() == ScheduleEnd->getParent() &&
7976          "Instruction is in wrong basic block.");
7977   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7978                    nullptr);
7979   ScheduleEnd = I->getNextNode();
7980   if (isOneOf(S, I) != I)
7981     CheckScheduleForI(I);
7982   assert(ScheduleEnd && "tried to vectorize a terminator?");
7983   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7984   return true;
7985 }
7986 
7987 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7988                                                 Instruction *ToI,
7989                                                 ScheduleData *PrevLoadStore,
7990                                                 ScheduleData *NextLoadStore) {
7991   ScheduleData *CurrentLoadStore = PrevLoadStore;
7992   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7993     // No need to allocate data for non-schedulable instructions.
7994     if (doesNotNeedToBeScheduled(I))
7995       continue;
7996     ScheduleData *SD = ScheduleDataMap.lookup(I);
7997     if (!SD) {
7998       SD = allocateScheduleDataChunks();
7999       ScheduleDataMap[I] = SD;
8000       SD->Inst = I;
8001     }
8002     assert(!isInSchedulingRegion(SD) &&
8003            "new ScheduleData already in scheduling region");
8004     SD->init(SchedulingRegionID, I);
8005 
8006     if (I->mayReadOrWriteMemory() &&
8007         (!isa<IntrinsicInst>(I) ||
8008          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8009           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8010               Intrinsic::pseudoprobe))) {
8011       // Update the linked list of memory accessing instructions.
8012       if (CurrentLoadStore) {
8013         CurrentLoadStore->NextLoadStore = SD;
8014       } else {
8015         FirstLoadStoreInRegion = SD;
8016       }
8017       CurrentLoadStore = SD;
8018     }
8019   }
8020   if (NextLoadStore) {
8021     if (CurrentLoadStore)
8022       CurrentLoadStore->NextLoadStore = NextLoadStore;
8023   } else {
8024     LastLoadStoreInRegion = CurrentLoadStore;
8025   }
8026 }
8027 
8028 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8029                                                      bool InsertInReadyList,
8030                                                      BoUpSLP *SLP) {
8031   assert(SD->isSchedulingEntity());
8032 
8033   SmallVector<ScheduleData *, 10> WorkList;
8034   WorkList.push_back(SD);
8035 
8036   while (!WorkList.empty()) {
8037     ScheduleData *SD = WorkList.pop_back_val();
8038     for (ScheduleData *BundleMember = SD; BundleMember;
8039          BundleMember = BundleMember->NextInBundle) {
8040       assert(isInSchedulingRegion(BundleMember));
8041       if (BundleMember->hasValidDependencies())
8042         continue;
8043 
8044       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8045                  << "\n");
8046       BundleMember->Dependencies = 0;
8047       BundleMember->resetUnscheduledDeps();
8048 
8049       // Handle def-use chain dependencies.
8050       if (BundleMember->OpValue != BundleMember->Inst) {
8051         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8052           BundleMember->Dependencies++;
8053           ScheduleData *DestBundle = UseSD->FirstInBundle;
8054           if (!DestBundle->IsScheduled)
8055             BundleMember->incrementUnscheduledDeps(1);
8056           if (!DestBundle->hasValidDependencies())
8057             WorkList.push_back(DestBundle);
8058         }
8059       } else {
8060         for (User *U : BundleMember->Inst->users()) {
8061           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8062             BundleMember->Dependencies++;
8063             ScheduleData *DestBundle = UseSD->FirstInBundle;
8064             if (!DestBundle->IsScheduled)
8065               BundleMember->incrementUnscheduledDeps(1);
8066             if (!DestBundle->hasValidDependencies())
8067               WorkList.push_back(DestBundle);
8068           }
8069         }
8070       }
8071 
8072       // Any instruction which isn't safe to speculate at the begining of the
8073       // block is control dependend on any early exit or non-willreturn call
8074       // which proceeds it.
8075       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8076         for (Instruction *I = BundleMember->Inst->getNextNode();
8077              I != ScheduleEnd; I = I->getNextNode()) {
8078           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8079             continue;
8080 
8081           // Add the dependency
8082           auto *DepDest = getScheduleData(I);
8083           assert(DepDest && "must be in schedule window");
8084           DepDest->ControlDependencies.push_back(BundleMember);
8085           BundleMember->Dependencies++;
8086           ScheduleData *DestBundle = DepDest->FirstInBundle;
8087           if (!DestBundle->IsScheduled)
8088             BundleMember->incrementUnscheduledDeps(1);
8089           if (!DestBundle->hasValidDependencies())
8090             WorkList.push_back(DestBundle);
8091 
8092           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8093             // Everything past here must be control dependent on I.
8094             break;
8095         }
8096       }
8097 
8098       // If we have an inalloc alloca instruction, it needs to be scheduled
8099       // after any preceeding stacksave.
8100       if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>())) {
8101         for (Instruction *I = BundleMember->Inst->getNextNode();
8102              I != ScheduleEnd; I = I->getNextNode()) {
8103           if (match(I, m_Intrinsic<Intrinsic::stacksave>()))
8104             // Any allocas past here must be control dependent on I, and I
8105             // must be memory dependend on BundleMember->Inst.
8106             break;
8107 
8108           if (!isa<AllocaInst>(I))
8109             continue;
8110 
8111           // Add the dependency
8112           auto *DepDest = getScheduleData(I);
8113           assert(DepDest && "must be in schedule window");
8114           DepDest->ControlDependencies.push_back(BundleMember);
8115           BundleMember->Dependencies++;
8116           ScheduleData *DestBundle = DepDest->FirstInBundle;
8117           if (!DestBundle->IsScheduled)
8118             BundleMember->incrementUnscheduledDeps(1);
8119           if (!DestBundle->hasValidDependencies())
8120             WorkList.push_back(DestBundle);
8121         }
8122       }
8123 
8124 
8125       // Handle the memory dependencies (if any).
8126       ScheduleData *DepDest = BundleMember->NextLoadStore;
8127       if (!DepDest)
8128         continue;
8129       Instruction *SrcInst = BundleMember->Inst;
8130       assert(SrcInst->mayReadOrWriteMemory() &&
8131              "NextLoadStore list for non memory effecting bundle?");
8132       MemoryLocation SrcLoc = getLocation(SrcInst);
8133       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8134       unsigned numAliased = 0;
8135       unsigned DistToSrc = 1;
8136 
8137       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8138         assert(isInSchedulingRegion(DepDest));
8139 
8140         // We have two limits to reduce the complexity:
8141         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8142         //    SLP->isAliased (which is the expensive part in this loop).
8143         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8144         //    the whole loop (even if the loop is fast, it's quadratic).
8145         //    It's important for the loop break condition (see below) to
8146         //    check this limit even between two read-only instructions.
8147         if (DistToSrc >= MaxMemDepDistance ||
8148             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8149              (numAliased >= AliasedCheckLimit ||
8150               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8151 
8152           // We increment the counter only if the locations are aliased
8153           // (instead of counting all alias checks). This gives a better
8154           // balance between reduced runtime and accurate dependencies.
8155           numAliased++;
8156 
8157           DepDest->MemoryDependencies.push_back(BundleMember);
8158           BundleMember->Dependencies++;
8159           ScheduleData *DestBundle = DepDest->FirstInBundle;
8160           if (!DestBundle->IsScheduled) {
8161             BundleMember->incrementUnscheduledDeps(1);
8162           }
8163           if (!DestBundle->hasValidDependencies()) {
8164             WorkList.push_back(DestBundle);
8165           }
8166         }
8167 
8168         // Example, explaining the loop break condition: Let's assume our
8169         // starting instruction is i0 and MaxMemDepDistance = 3.
8170         //
8171         //                      +--------v--v--v
8172         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8173         //             +--------^--^--^
8174         //
8175         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8176         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8177         // Previously we already added dependencies from i3 to i6,i7,i8
8178         // (because of MaxMemDepDistance). As we added a dependency from
8179         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8180         // and we can abort this loop at i6.
8181         if (DistToSrc >= 2 * MaxMemDepDistance)
8182           break;
8183         DistToSrc++;
8184       }
8185     }
8186     if (InsertInReadyList && SD->isReady()) {
8187       ReadyInsts.insert(SD);
8188       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8189                         << "\n");
8190     }
8191   }
8192 }
8193 
8194 void BoUpSLP::BlockScheduling::resetSchedule() {
8195   assert(ScheduleStart &&
8196          "tried to reset schedule on block which has not been scheduled");
8197   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8198     doForAllOpcodes(I, [&](ScheduleData *SD) {
8199       assert(isInSchedulingRegion(SD) &&
8200              "ScheduleData not in scheduling region");
8201       SD->IsScheduled = false;
8202       SD->resetUnscheduledDeps();
8203     });
8204   }
8205   ReadyInsts.clear();
8206 }
8207 
8208 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8209   if (!BS->ScheduleStart)
8210     return;
8211 
8212   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8213 
8214   BS->resetSchedule();
8215 
8216   // For the real scheduling we use a more sophisticated ready-list: it is
8217   // sorted by the original instruction location. This lets the final schedule
8218   // be as  close as possible to the original instruction order.
8219   // WARNING: If changing this order causes a correctness issue, that means
8220   // there is some missing dependence edge in the schedule data graph.
8221   struct ScheduleDataCompare {
8222     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8223       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8224     }
8225   };
8226   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8227 
8228   // Ensure that all dependency data is updated and fill the ready-list with
8229   // initial instructions.
8230   int Idx = 0;
8231   int NumToSchedule = 0;
8232   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8233        I = I->getNextNode()) {
8234     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8235       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8236       (void)SDTE;
8237       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8238               SD->isPartOfBundle() ==
8239                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8240              "scheduler and vectorizer bundle mismatch");
8241       SD->FirstInBundle->SchedulingPriority = Idx++;
8242       if (SD->isSchedulingEntity()) {
8243         BS->calculateDependencies(SD, false, this);
8244         NumToSchedule++;
8245       }
8246     });
8247   }
8248   BS->initialFillReadyList(ReadyInsts);
8249 
8250   Instruction *LastScheduledInst = BS->ScheduleEnd;
8251 
8252   // Do the "real" scheduling.
8253   while (!ReadyInsts.empty()) {
8254     ScheduleData *picked = *ReadyInsts.begin();
8255     ReadyInsts.erase(ReadyInsts.begin());
8256 
8257     // Move the scheduled instruction(s) to their dedicated places, if not
8258     // there yet.
8259     for (ScheduleData *BundleMember = picked; BundleMember;
8260          BundleMember = BundleMember->NextInBundle) {
8261       Instruction *pickedInst = BundleMember->Inst;
8262       if (pickedInst->getNextNode() != LastScheduledInst)
8263         pickedInst->moveBefore(LastScheduledInst);
8264       LastScheduledInst = pickedInst;
8265     }
8266 
8267     BS->schedule(picked, ReadyInsts);
8268     NumToSchedule--;
8269   }
8270   assert(NumToSchedule == 0 && "could not schedule all instructions");
8271 
8272   // Check that we didn't break any of our invariants.
8273 #ifdef EXPENSIVE_CHECKS
8274   BS->verify();
8275 #endif
8276 
8277 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8278   // Check that all schedulable entities got scheduled
8279   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8280     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8281       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8282         assert(SD->IsScheduled && "must be scheduled at this point");
8283       }
8284     });
8285   }
8286 #endif
8287 
8288   // Avoid duplicate scheduling of the block.
8289   BS->ScheduleStart = nullptr;
8290 }
8291 
8292 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8293   // If V is a store, just return the width of the stored value (or value
8294   // truncated just before storing) without traversing the expression tree.
8295   // This is the common case.
8296   if (auto *Store = dyn_cast<StoreInst>(V)) {
8297     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8298       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8299     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8300   }
8301 
8302   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8303     return getVectorElementSize(IEI->getOperand(1));
8304 
8305   auto E = InstrElementSize.find(V);
8306   if (E != InstrElementSize.end())
8307     return E->second;
8308 
8309   // If V is not a store, we can traverse the expression tree to find loads
8310   // that feed it. The type of the loaded value may indicate a more suitable
8311   // width than V's type. We want to base the vector element size on the width
8312   // of memory operations where possible.
8313   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8314   SmallPtrSet<Instruction *, 16> Visited;
8315   if (auto *I = dyn_cast<Instruction>(V)) {
8316     Worklist.emplace_back(I, I->getParent());
8317     Visited.insert(I);
8318   }
8319 
8320   // Traverse the expression tree in bottom-up order looking for loads. If we
8321   // encounter an instruction we don't yet handle, we give up.
8322   auto Width = 0u;
8323   while (!Worklist.empty()) {
8324     Instruction *I;
8325     BasicBlock *Parent;
8326     std::tie(I, Parent) = Worklist.pop_back_val();
8327 
8328     // We should only be looking at scalar instructions here. If the current
8329     // instruction has a vector type, skip.
8330     auto *Ty = I->getType();
8331     if (isa<VectorType>(Ty))
8332       continue;
8333 
8334     // If the current instruction is a load, update MaxWidth to reflect the
8335     // width of the loaded value.
8336     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8337         isa<ExtractValueInst>(I))
8338       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8339 
8340     // Otherwise, we need to visit the operands of the instruction. We only
8341     // handle the interesting cases from buildTree here. If an operand is an
8342     // instruction we haven't yet visited and from the same basic block as the
8343     // user or the use is a PHI node, we add it to the worklist.
8344     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8345              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8346              isa<UnaryOperator>(I)) {
8347       for (Use &U : I->operands())
8348         if (auto *J = dyn_cast<Instruction>(U.get()))
8349           if (Visited.insert(J).second &&
8350               (isa<PHINode>(I) || J->getParent() == Parent))
8351             Worklist.emplace_back(J, J->getParent());
8352     } else {
8353       break;
8354     }
8355   }
8356 
8357   // If we didn't encounter a memory access in the expression tree, or if we
8358   // gave up for some reason, just return the width of V. Otherwise, return the
8359   // maximum width we found.
8360   if (!Width) {
8361     if (auto *CI = dyn_cast<CmpInst>(V))
8362       V = CI->getOperand(0);
8363     Width = DL->getTypeSizeInBits(V->getType());
8364   }
8365 
8366   for (Instruction *I : Visited)
8367     InstrElementSize[I] = Width;
8368 
8369   return Width;
8370 }
8371 
8372 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8373 // smaller type with a truncation. We collect the values that will be demoted
8374 // in ToDemote and additional roots that require investigating in Roots.
8375 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8376                                   SmallVectorImpl<Value *> &ToDemote,
8377                                   SmallVectorImpl<Value *> &Roots) {
8378   // We can always demote constants.
8379   if (isa<Constant>(V)) {
8380     ToDemote.push_back(V);
8381     return true;
8382   }
8383 
8384   // If the value is not an instruction in the expression with only one use, it
8385   // cannot be demoted.
8386   auto *I = dyn_cast<Instruction>(V);
8387   if (!I || !I->hasOneUse() || !Expr.count(I))
8388     return false;
8389 
8390   switch (I->getOpcode()) {
8391 
8392   // We can always demote truncations and extensions. Since truncations can
8393   // seed additional demotion, we save the truncated value.
8394   case Instruction::Trunc:
8395     Roots.push_back(I->getOperand(0));
8396     break;
8397   case Instruction::ZExt:
8398   case Instruction::SExt:
8399     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8400         isa<InsertElementInst>(I->getOperand(0)))
8401       return false;
8402     break;
8403 
8404   // We can demote certain binary operations if we can demote both of their
8405   // operands.
8406   case Instruction::Add:
8407   case Instruction::Sub:
8408   case Instruction::Mul:
8409   case Instruction::And:
8410   case Instruction::Or:
8411   case Instruction::Xor:
8412     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8413         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8414       return false;
8415     break;
8416 
8417   // We can demote selects if we can demote their true and false values.
8418   case Instruction::Select: {
8419     SelectInst *SI = cast<SelectInst>(I);
8420     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8421         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8422       return false;
8423     break;
8424   }
8425 
8426   // We can demote phis if we can demote all their incoming operands. Note that
8427   // we don't need to worry about cycles since we ensure single use above.
8428   case Instruction::PHI: {
8429     PHINode *PN = cast<PHINode>(I);
8430     for (Value *IncValue : PN->incoming_values())
8431       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8432         return false;
8433     break;
8434   }
8435 
8436   // Otherwise, conservatively give up.
8437   default:
8438     return false;
8439   }
8440 
8441   // Record the value that we can demote.
8442   ToDemote.push_back(V);
8443   return true;
8444 }
8445 
8446 void BoUpSLP::computeMinimumValueSizes() {
8447   // If there are no external uses, the expression tree must be rooted by a
8448   // store. We can't demote in-memory values, so there is nothing to do here.
8449   if (ExternalUses.empty())
8450     return;
8451 
8452   // We only attempt to truncate integer expressions.
8453   auto &TreeRoot = VectorizableTree[0]->Scalars;
8454   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8455   if (!TreeRootIT)
8456     return;
8457 
8458   // If the expression is not rooted by a store, these roots should have
8459   // external uses. We will rely on InstCombine to rewrite the expression in
8460   // the narrower type. However, InstCombine only rewrites single-use values.
8461   // This means that if a tree entry other than a root is used externally, it
8462   // must have multiple uses and InstCombine will not rewrite it. The code
8463   // below ensures that only the roots are used externally.
8464   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8465   for (auto &EU : ExternalUses)
8466     if (!Expr.erase(EU.Scalar))
8467       return;
8468   if (!Expr.empty())
8469     return;
8470 
8471   // Collect the scalar values of the vectorizable expression. We will use this
8472   // context to determine which values can be demoted. If we see a truncation,
8473   // we mark it as seeding another demotion.
8474   for (auto &EntryPtr : VectorizableTree)
8475     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8476 
8477   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8478   // have a single external user that is not in the vectorizable tree.
8479   for (auto *Root : TreeRoot)
8480     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8481       return;
8482 
8483   // Conservatively determine if we can actually truncate the roots of the
8484   // expression. Collect the values that can be demoted in ToDemote and
8485   // additional roots that require investigating in Roots.
8486   SmallVector<Value *, 32> ToDemote;
8487   SmallVector<Value *, 4> Roots;
8488   for (auto *Root : TreeRoot)
8489     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8490       return;
8491 
8492   // The maximum bit width required to represent all the values that can be
8493   // demoted without loss of precision. It would be safe to truncate the roots
8494   // of the expression to this width.
8495   auto MaxBitWidth = 8u;
8496 
8497   // We first check if all the bits of the roots are demanded. If they're not,
8498   // we can truncate the roots to this narrower type.
8499   for (auto *Root : TreeRoot) {
8500     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8501     MaxBitWidth = std::max<unsigned>(
8502         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8503   }
8504 
8505   // True if the roots can be zero-extended back to their original type, rather
8506   // than sign-extended. We know that if the leading bits are not demanded, we
8507   // can safely zero-extend. So we initialize IsKnownPositive to True.
8508   bool IsKnownPositive = true;
8509 
8510   // If all the bits of the roots are demanded, we can try a little harder to
8511   // compute a narrower type. This can happen, for example, if the roots are
8512   // getelementptr indices. InstCombine promotes these indices to the pointer
8513   // width. Thus, all their bits are technically demanded even though the
8514   // address computation might be vectorized in a smaller type.
8515   //
8516   // We start by looking at each entry that can be demoted. We compute the
8517   // maximum bit width required to store the scalar by using ValueTracking to
8518   // compute the number of high-order bits we can truncate.
8519   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8520       llvm::all_of(TreeRoot, [](Value *R) {
8521         assert(R->hasOneUse() && "Root should have only one use!");
8522         return isa<GetElementPtrInst>(R->user_back());
8523       })) {
8524     MaxBitWidth = 8u;
8525 
8526     // Determine if the sign bit of all the roots is known to be zero. If not,
8527     // IsKnownPositive is set to False.
8528     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8529       KnownBits Known = computeKnownBits(R, *DL);
8530       return Known.isNonNegative();
8531     });
8532 
8533     // Determine the maximum number of bits required to store the scalar
8534     // values.
8535     for (auto *Scalar : ToDemote) {
8536       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8537       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8538       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8539     }
8540 
8541     // If we can't prove that the sign bit is zero, we must add one to the
8542     // maximum bit width to account for the unknown sign bit. This preserves
8543     // the existing sign bit so we can safely sign-extend the root back to the
8544     // original type. Otherwise, if we know the sign bit is zero, we will
8545     // zero-extend the root instead.
8546     //
8547     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8548     //        one to the maximum bit width will yield a larger-than-necessary
8549     //        type. In general, we need to add an extra bit only if we can't
8550     //        prove that the upper bit of the original type is equal to the
8551     //        upper bit of the proposed smaller type. If these two bits are the
8552     //        same (either zero or one) we know that sign-extending from the
8553     //        smaller type will result in the same value. Here, since we can't
8554     //        yet prove this, we are just making the proposed smaller type
8555     //        larger to ensure correctness.
8556     if (!IsKnownPositive)
8557       ++MaxBitWidth;
8558   }
8559 
8560   // Round MaxBitWidth up to the next power-of-two.
8561   if (!isPowerOf2_64(MaxBitWidth))
8562     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8563 
8564   // If the maximum bit width we compute is less than the with of the roots'
8565   // type, we can proceed with the narrowing. Otherwise, do nothing.
8566   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8567     return;
8568 
8569   // If we can truncate the root, we must collect additional values that might
8570   // be demoted as a result. That is, those seeded by truncations we will
8571   // modify.
8572   while (!Roots.empty())
8573     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8574 
8575   // Finally, map the values we can demote to the maximum bit with we computed.
8576   for (auto *Scalar : ToDemote)
8577     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8578 }
8579 
8580 namespace {
8581 
8582 /// The SLPVectorizer Pass.
8583 struct SLPVectorizer : public FunctionPass {
8584   SLPVectorizerPass Impl;
8585 
8586   /// Pass identification, replacement for typeid
8587   static char ID;
8588 
8589   explicit SLPVectorizer() : FunctionPass(ID) {
8590     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8591   }
8592 
8593   bool doInitialization(Module &M) override { return false; }
8594 
8595   bool runOnFunction(Function &F) override {
8596     if (skipFunction(F))
8597       return false;
8598 
8599     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8600     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8601     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8602     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8603     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8604     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8605     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8606     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8607     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8608     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8609 
8610     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8611   }
8612 
8613   void getAnalysisUsage(AnalysisUsage &AU) const override {
8614     FunctionPass::getAnalysisUsage(AU);
8615     AU.addRequired<AssumptionCacheTracker>();
8616     AU.addRequired<ScalarEvolutionWrapperPass>();
8617     AU.addRequired<AAResultsWrapperPass>();
8618     AU.addRequired<TargetTransformInfoWrapperPass>();
8619     AU.addRequired<LoopInfoWrapperPass>();
8620     AU.addRequired<DominatorTreeWrapperPass>();
8621     AU.addRequired<DemandedBitsWrapperPass>();
8622     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8623     AU.addRequired<InjectTLIMappingsLegacy>();
8624     AU.addPreserved<LoopInfoWrapperPass>();
8625     AU.addPreserved<DominatorTreeWrapperPass>();
8626     AU.addPreserved<AAResultsWrapperPass>();
8627     AU.addPreserved<GlobalsAAWrapperPass>();
8628     AU.setPreservesCFG();
8629   }
8630 };
8631 
8632 } // end anonymous namespace
8633 
8634 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8635   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8636   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8637   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8638   auto *AA = &AM.getResult<AAManager>(F);
8639   auto *LI = &AM.getResult<LoopAnalysis>(F);
8640   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8641   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8642   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8643   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8644 
8645   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8646   if (!Changed)
8647     return PreservedAnalyses::all();
8648 
8649   PreservedAnalyses PA;
8650   PA.preserveSet<CFGAnalyses>();
8651   return PA;
8652 }
8653 
8654 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8655                                 TargetTransformInfo *TTI_,
8656                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8657                                 LoopInfo *LI_, DominatorTree *DT_,
8658                                 AssumptionCache *AC_, DemandedBits *DB_,
8659                                 OptimizationRemarkEmitter *ORE_) {
8660   if (!RunSLPVectorization)
8661     return false;
8662   SE = SE_;
8663   TTI = TTI_;
8664   TLI = TLI_;
8665   AA = AA_;
8666   LI = LI_;
8667   DT = DT_;
8668   AC = AC_;
8669   DB = DB_;
8670   DL = &F.getParent()->getDataLayout();
8671 
8672   Stores.clear();
8673   GEPs.clear();
8674   bool Changed = false;
8675 
8676   // If the target claims to have no vector registers don't attempt
8677   // vectorization.
8678   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8679     LLVM_DEBUG(
8680         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8681     return false;
8682   }
8683 
8684   // Don't vectorize when the attribute NoImplicitFloat is used.
8685   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8686     return false;
8687 
8688   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8689 
8690   // Use the bottom up slp vectorizer to construct chains that start with
8691   // store instructions.
8692   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8693 
8694   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8695   // delete instructions.
8696 
8697   // Update DFS numbers now so that we can use them for ordering.
8698   DT->updateDFSNumbers();
8699 
8700   // Scan the blocks in the function in post order.
8701   for (auto BB : post_order(&F.getEntryBlock())) {
8702     collectSeedInstructions(BB);
8703 
8704     // Vectorize trees that end at stores.
8705     if (!Stores.empty()) {
8706       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8707                         << " underlying objects.\n");
8708       Changed |= vectorizeStoreChains(R);
8709     }
8710 
8711     // Vectorize trees that end at reductions.
8712     Changed |= vectorizeChainsInBlock(BB, R);
8713 
8714     // Vectorize the index computations of getelementptr instructions. This
8715     // is primarily intended to catch gather-like idioms ending at
8716     // non-consecutive loads.
8717     if (!GEPs.empty()) {
8718       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8719                         << " underlying objects.\n");
8720       Changed |= vectorizeGEPIndices(BB, R);
8721     }
8722   }
8723 
8724   if (Changed) {
8725     R.optimizeGatherSequence();
8726     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8727   }
8728   return Changed;
8729 }
8730 
8731 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8732                                             unsigned Idx) {
8733   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8734                     << "\n");
8735   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8736   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8737   unsigned VF = Chain.size();
8738 
8739   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8740     return false;
8741 
8742   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8743                     << "\n");
8744 
8745   R.buildTree(Chain);
8746   if (R.isTreeTinyAndNotFullyVectorizable())
8747     return false;
8748   if (R.isLoadCombineCandidate())
8749     return false;
8750   R.reorderTopToBottom();
8751   R.reorderBottomToTop();
8752   R.buildExternalUses();
8753 
8754   R.computeMinimumValueSizes();
8755 
8756   InstructionCost Cost = R.getTreeCost();
8757 
8758   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8759   if (Cost < -SLPCostThreshold) {
8760     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8761 
8762     using namespace ore;
8763 
8764     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8765                                         cast<StoreInst>(Chain[0]))
8766                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8767                      << " and with tree size "
8768                      << NV("TreeSize", R.getTreeSize()));
8769 
8770     R.vectorizeTree();
8771     return true;
8772   }
8773 
8774   return false;
8775 }
8776 
8777 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8778                                         BoUpSLP &R) {
8779   // We may run into multiple chains that merge into a single chain. We mark the
8780   // stores that we vectorized so that we don't visit the same store twice.
8781   BoUpSLP::ValueSet VectorizedStores;
8782   bool Changed = false;
8783 
8784   int E = Stores.size();
8785   SmallBitVector Tails(E, false);
8786   int MaxIter = MaxStoreLookup.getValue();
8787   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8788       E, std::make_pair(E, INT_MAX));
8789   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8790   int IterCnt;
8791   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8792                                   &CheckedPairs,
8793                                   &ConsecutiveChain](int K, int Idx) {
8794     if (IterCnt >= MaxIter)
8795       return true;
8796     if (CheckedPairs[Idx].test(K))
8797       return ConsecutiveChain[K].second == 1 &&
8798              ConsecutiveChain[K].first == Idx;
8799     ++IterCnt;
8800     CheckedPairs[Idx].set(K);
8801     CheckedPairs[K].set(Idx);
8802     Optional<int> Diff = getPointersDiff(
8803         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8804         Stores[Idx]->getValueOperand()->getType(),
8805         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8806     if (!Diff || *Diff == 0)
8807       return false;
8808     int Val = *Diff;
8809     if (Val < 0) {
8810       if (ConsecutiveChain[Idx].second > -Val) {
8811         Tails.set(K);
8812         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8813       }
8814       return false;
8815     }
8816     if (ConsecutiveChain[K].second <= Val)
8817       return false;
8818 
8819     Tails.set(Idx);
8820     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8821     return Val == 1;
8822   };
8823   // Do a quadratic search on all of the given stores in reverse order and find
8824   // all of the pairs of stores that follow each other.
8825   for (int Idx = E - 1; Idx >= 0; --Idx) {
8826     // If a store has multiple consecutive store candidates, search according
8827     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8828     // This is because usually pairing with immediate succeeding or preceding
8829     // candidate create the best chance to find slp vectorization opportunity.
8830     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8831     IterCnt = 0;
8832     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8833       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8834           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8835         break;
8836   }
8837 
8838   // Tracks if we tried to vectorize stores starting from the given tail
8839   // already.
8840   SmallBitVector TriedTails(E, false);
8841   // For stores that start but don't end a link in the chain:
8842   for (int Cnt = E; Cnt > 0; --Cnt) {
8843     int I = Cnt - 1;
8844     if (ConsecutiveChain[I].first == E || Tails.test(I))
8845       continue;
8846     // We found a store instr that starts a chain. Now follow the chain and try
8847     // to vectorize it.
8848     BoUpSLP::ValueList Operands;
8849     // Collect the chain into a list.
8850     while (I != E && !VectorizedStores.count(Stores[I])) {
8851       Operands.push_back(Stores[I]);
8852       Tails.set(I);
8853       if (ConsecutiveChain[I].second != 1) {
8854         // Mark the new end in the chain and go back, if required. It might be
8855         // required if the original stores come in reversed order, for example.
8856         if (ConsecutiveChain[I].first != E &&
8857             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8858             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8859           TriedTails.set(I);
8860           Tails.reset(ConsecutiveChain[I].first);
8861           if (Cnt < ConsecutiveChain[I].first + 2)
8862             Cnt = ConsecutiveChain[I].first + 2;
8863         }
8864         break;
8865       }
8866       // Move to the next value in the chain.
8867       I = ConsecutiveChain[I].first;
8868     }
8869     assert(!Operands.empty() && "Expected non-empty list of stores.");
8870 
8871     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8872     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8873     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8874 
8875     unsigned MinVF = R.getMinVF(EltSize);
8876     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8877                               MaxElts);
8878 
8879     // FIXME: Is division-by-2 the correct step? Should we assert that the
8880     // register size is a power-of-2?
8881     unsigned StartIdx = 0;
8882     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8883       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8884         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8885         if (!VectorizedStores.count(Slice.front()) &&
8886             !VectorizedStores.count(Slice.back()) &&
8887             vectorizeStoreChain(Slice, R, Cnt)) {
8888           // Mark the vectorized stores so that we don't vectorize them again.
8889           VectorizedStores.insert(Slice.begin(), Slice.end());
8890           Changed = true;
8891           // If we vectorized initial block, no need to try to vectorize it
8892           // again.
8893           if (Cnt == StartIdx)
8894             StartIdx += Size;
8895           Cnt += Size;
8896           continue;
8897         }
8898         ++Cnt;
8899       }
8900       // Check if the whole array was vectorized already - exit.
8901       if (StartIdx >= Operands.size())
8902         break;
8903     }
8904   }
8905 
8906   return Changed;
8907 }
8908 
8909 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8910   // Initialize the collections. We will make a single pass over the block.
8911   Stores.clear();
8912   GEPs.clear();
8913 
8914   // Visit the store and getelementptr instructions in BB and organize them in
8915   // Stores and GEPs according to the underlying objects of their pointer
8916   // operands.
8917   for (Instruction &I : *BB) {
8918     // Ignore store instructions that are volatile or have a pointer operand
8919     // that doesn't point to a scalar type.
8920     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8921       if (!SI->isSimple())
8922         continue;
8923       if (!isValidElementType(SI->getValueOperand()->getType()))
8924         continue;
8925       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8926     }
8927 
8928     // Ignore getelementptr instructions that have more than one index, a
8929     // constant index, or a pointer operand that doesn't point to a scalar
8930     // type.
8931     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8932       auto Idx = GEP->idx_begin()->get();
8933       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8934         continue;
8935       if (!isValidElementType(Idx->getType()))
8936         continue;
8937       if (GEP->getType()->isVectorTy())
8938         continue;
8939       GEPs[GEP->getPointerOperand()].push_back(GEP);
8940     }
8941   }
8942 }
8943 
8944 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8945   if (!A || !B)
8946     return false;
8947   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8948     return false;
8949   Value *VL[] = {A, B};
8950   return tryToVectorizeList(VL, R);
8951 }
8952 
8953 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8954                                            bool LimitForRegisterSize) {
8955   if (VL.size() < 2)
8956     return false;
8957 
8958   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8959                     << VL.size() << ".\n");
8960 
8961   // Check that all of the parts are instructions of the same type,
8962   // we permit an alternate opcode via InstructionsState.
8963   InstructionsState S = getSameOpcode(VL);
8964   if (!S.getOpcode())
8965     return false;
8966 
8967   Instruction *I0 = cast<Instruction>(S.OpValue);
8968   // Make sure invalid types (including vector type) are rejected before
8969   // determining vectorization factor for scalar instructions.
8970   for (Value *V : VL) {
8971     Type *Ty = V->getType();
8972     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8973       // NOTE: the following will give user internal llvm type name, which may
8974       // not be useful.
8975       R.getORE()->emit([&]() {
8976         std::string type_str;
8977         llvm::raw_string_ostream rso(type_str);
8978         Ty->print(rso);
8979         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8980                << "Cannot SLP vectorize list: type "
8981                << rso.str() + " is unsupported by vectorizer";
8982       });
8983       return false;
8984     }
8985   }
8986 
8987   unsigned Sz = R.getVectorElementSize(I0);
8988   unsigned MinVF = R.getMinVF(Sz);
8989   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8990   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8991   if (MaxVF < 2) {
8992     R.getORE()->emit([&]() {
8993       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8994              << "Cannot SLP vectorize list: vectorization factor "
8995              << "less than 2 is not supported";
8996     });
8997     return false;
8998   }
8999 
9000   bool Changed = false;
9001   bool CandidateFound = false;
9002   InstructionCost MinCost = SLPCostThreshold.getValue();
9003   Type *ScalarTy = VL[0]->getType();
9004   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9005     ScalarTy = IE->getOperand(1)->getType();
9006 
9007   unsigned NextInst = 0, MaxInst = VL.size();
9008   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9009     // No actual vectorization should happen, if number of parts is the same as
9010     // provided vectorization factor (i.e. the scalar type is used for vector
9011     // code during codegen).
9012     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9013     if (TTI->getNumberOfParts(VecTy) == VF)
9014       continue;
9015     for (unsigned I = NextInst; I < MaxInst; ++I) {
9016       unsigned OpsWidth = 0;
9017 
9018       if (I + VF > MaxInst)
9019         OpsWidth = MaxInst - I;
9020       else
9021         OpsWidth = VF;
9022 
9023       if (!isPowerOf2_32(OpsWidth))
9024         continue;
9025 
9026       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9027           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9028         break;
9029 
9030       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9031       // Check that a previous iteration of this loop did not delete the Value.
9032       if (llvm::any_of(Ops, [&R](Value *V) {
9033             auto *I = dyn_cast<Instruction>(V);
9034             return I && R.isDeleted(I);
9035           }))
9036         continue;
9037 
9038       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9039                         << "\n");
9040 
9041       R.buildTree(Ops);
9042       if (R.isTreeTinyAndNotFullyVectorizable())
9043         continue;
9044       R.reorderTopToBottom();
9045       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9046       R.buildExternalUses();
9047 
9048       R.computeMinimumValueSizes();
9049       InstructionCost Cost = R.getTreeCost();
9050       CandidateFound = true;
9051       MinCost = std::min(MinCost, Cost);
9052 
9053       if (Cost < -SLPCostThreshold) {
9054         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9055         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9056                                                     cast<Instruction>(Ops[0]))
9057                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9058                                  << " and with tree size "
9059                                  << ore::NV("TreeSize", R.getTreeSize()));
9060 
9061         R.vectorizeTree();
9062         // Move to the next bundle.
9063         I += VF - 1;
9064         NextInst = I + 1;
9065         Changed = true;
9066       }
9067     }
9068   }
9069 
9070   if (!Changed && CandidateFound) {
9071     R.getORE()->emit([&]() {
9072       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9073              << "List vectorization was possible but not beneficial with cost "
9074              << ore::NV("Cost", MinCost) << " >= "
9075              << ore::NV("Treshold", -SLPCostThreshold);
9076     });
9077   } else if (!Changed) {
9078     R.getORE()->emit([&]() {
9079       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9080              << "Cannot SLP vectorize list: vectorization was impossible"
9081              << " with available vectorization factors";
9082     });
9083   }
9084   return Changed;
9085 }
9086 
9087 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9088   if (!I)
9089     return false;
9090 
9091   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9092     return false;
9093 
9094   Value *P = I->getParent();
9095 
9096   // Vectorize in current basic block only.
9097   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9098   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9099   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9100     return false;
9101 
9102   // Try to vectorize V.
9103   if (tryToVectorizePair(Op0, Op1, R))
9104     return true;
9105 
9106   auto *A = dyn_cast<BinaryOperator>(Op0);
9107   auto *B = dyn_cast<BinaryOperator>(Op1);
9108   // Try to skip B.
9109   if (B && B->hasOneUse()) {
9110     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9111     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9112     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9113       return true;
9114     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9115       return true;
9116   }
9117 
9118   // Try to skip A.
9119   if (A && A->hasOneUse()) {
9120     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9121     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9122     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9123       return true;
9124     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9125       return true;
9126   }
9127   return false;
9128 }
9129 
9130 namespace {
9131 
9132 /// Model horizontal reductions.
9133 ///
9134 /// A horizontal reduction is a tree of reduction instructions that has values
9135 /// that can be put into a vector as its leaves. For example:
9136 ///
9137 /// mul mul mul mul
9138 ///  \  /    \  /
9139 ///   +       +
9140 ///    \     /
9141 ///       +
9142 /// This tree has "mul" as its leaf values and "+" as its reduction
9143 /// instructions. A reduction can feed into a store or a binary operation
9144 /// feeding a phi.
9145 ///    ...
9146 ///    \  /
9147 ///     +
9148 ///     |
9149 ///  phi +=
9150 ///
9151 ///  Or:
9152 ///    ...
9153 ///    \  /
9154 ///     +
9155 ///     |
9156 ///   *p =
9157 ///
9158 class HorizontalReduction {
9159   using ReductionOpsType = SmallVector<Value *, 16>;
9160   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9161   ReductionOpsListType ReductionOps;
9162   SmallVector<Value *, 32> ReducedVals;
9163   // Use map vector to make stable output.
9164   MapVector<Instruction *, Value *> ExtraArgs;
9165   WeakTrackingVH ReductionRoot;
9166   /// The type of reduction operation.
9167   RecurKind RdxKind;
9168 
9169   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9170 
9171   static bool isCmpSelMinMax(Instruction *I) {
9172     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9173            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9174   }
9175 
9176   // And/or are potentially poison-safe logical patterns like:
9177   // select x, y, false
9178   // select x, true, y
9179   static bool isBoolLogicOp(Instruction *I) {
9180     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9181            match(I, m_LogicalOr(m_Value(), m_Value()));
9182   }
9183 
9184   /// Checks if instruction is associative and can be vectorized.
9185   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9186     if (Kind == RecurKind::None)
9187       return false;
9188 
9189     // Integer ops that map to select instructions or intrinsics are fine.
9190     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9191         isBoolLogicOp(I))
9192       return true;
9193 
9194     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9195       // FP min/max are associative except for NaN and -0.0. We do not
9196       // have to rule out -0.0 here because the intrinsic semantics do not
9197       // specify a fixed result for it.
9198       return I->getFastMathFlags().noNaNs();
9199     }
9200 
9201     return I->isAssociative();
9202   }
9203 
9204   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9205     // Poison-safe 'or' takes the form: select X, true, Y
9206     // To make that work with the normal operand processing, we skip the
9207     // true value operand.
9208     // TODO: Change the code and data structures to handle this without a hack.
9209     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9210       return I->getOperand(2);
9211     return I->getOperand(Index);
9212   }
9213 
9214   /// Checks if the ParentStackElem.first should be marked as a reduction
9215   /// operation with an extra argument or as extra argument itself.
9216   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9217                     Value *ExtraArg) {
9218     if (ExtraArgs.count(ParentStackElem.first)) {
9219       ExtraArgs[ParentStackElem.first] = nullptr;
9220       // We ran into something like:
9221       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9222       // The whole ParentStackElem.first should be considered as an extra value
9223       // in this case.
9224       // Do not perform analysis of remaining operands of ParentStackElem.first
9225       // instruction, this whole instruction is an extra argument.
9226       ParentStackElem.second = INVALID_OPERAND_INDEX;
9227     } else {
9228       // We ran into something like:
9229       // ParentStackElem.first += ... + ExtraArg + ...
9230       ExtraArgs[ParentStackElem.first] = ExtraArg;
9231     }
9232   }
9233 
9234   /// Creates reduction operation with the current opcode.
9235   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9236                          Value *RHS, const Twine &Name, bool UseSelect) {
9237     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9238     switch (Kind) {
9239     case RecurKind::Or:
9240       if (UseSelect &&
9241           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9242         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9243       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9244                                  Name);
9245     case RecurKind::And:
9246       if (UseSelect &&
9247           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9248         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9249       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9250                                  Name);
9251     case RecurKind::Add:
9252     case RecurKind::Mul:
9253     case RecurKind::Xor:
9254     case RecurKind::FAdd:
9255     case RecurKind::FMul:
9256       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9257                                  Name);
9258     case RecurKind::FMax:
9259       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9260     case RecurKind::FMin:
9261       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9262     case RecurKind::SMax:
9263       if (UseSelect) {
9264         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9265         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9266       }
9267       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9268     case RecurKind::SMin:
9269       if (UseSelect) {
9270         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9271         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9272       }
9273       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9274     case RecurKind::UMax:
9275       if (UseSelect) {
9276         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9277         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9278       }
9279       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9280     case RecurKind::UMin:
9281       if (UseSelect) {
9282         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9283         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9284       }
9285       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9286     default:
9287       llvm_unreachable("Unknown reduction operation.");
9288     }
9289   }
9290 
9291   /// Creates reduction operation with the current opcode with the IR flags
9292   /// from \p ReductionOps.
9293   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9294                          Value *RHS, const Twine &Name,
9295                          const ReductionOpsListType &ReductionOps) {
9296     bool UseSelect = ReductionOps.size() == 2 ||
9297                      // Logical or/and.
9298                      (ReductionOps.size() == 1 &&
9299                       isa<SelectInst>(ReductionOps.front().front()));
9300     assert((!UseSelect || ReductionOps.size() != 2 ||
9301             isa<SelectInst>(ReductionOps[1][0])) &&
9302            "Expected cmp + select pairs for reduction");
9303     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9304     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9305       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9306         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9307         propagateIRFlags(Op, ReductionOps[1]);
9308         return Op;
9309       }
9310     }
9311     propagateIRFlags(Op, ReductionOps[0]);
9312     return Op;
9313   }
9314 
9315   /// Creates reduction operation with the current opcode with the IR flags
9316   /// from \p I.
9317   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9318                          Value *RHS, const Twine &Name, Instruction *I) {
9319     auto *SelI = dyn_cast<SelectInst>(I);
9320     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9321     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9322       if (auto *Sel = dyn_cast<SelectInst>(Op))
9323         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9324     }
9325     propagateIRFlags(Op, I);
9326     return Op;
9327   }
9328 
9329   static RecurKind getRdxKind(Instruction *I) {
9330     assert(I && "Expected instruction for reduction matching");
9331     if (match(I, m_Add(m_Value(), m_Value())))
9332       return RecurKind::Add;
9333     if (match(I, m_Mul(m_Value(), m_Value())))
9334       return RecurKind::Mul;
9335     if (match(I, m_And(m_Value(), m_Value())) ||
9336         match(I, m_LogicalAnd(m_Value(), m_Value())))
9337       return RecurKind::And;
9338     if (match(I, m_Or(m_Value(), m_Value())) ||
9339         match(I, m_LogicalOr(m_Value(), m_Value())))
9340       return RecurKind::Or;
9341     if (match(I, m_Xor(m_Value(), m_Value())))
9342       return RecurKind::Xor;
9343     if (match(I, m_FAdd(m_Value(), m_Value())))
9344       return RecurKind::FAdd;
9345     if (match(I, m_FMul(m_Value(), m_Value())))
9346       return RecurKind::FMul;
9347 
9348     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9349       return RecurKind::FMax;
9350     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9351       return RecurKind::FMin;
9352 
9353     // This matches either cmp+select or intrinsics. SLP is expected to handle
9354     // either form.
9355     // TODO: If we are canonicalizing to intrinsics, we can remove several
9356     //       special-case paths that deal with selects.
9357     if (match(I, m_SMax(m_Value(), m_Value())))
9358       return RecurKind::SMax;
9359     if (match(I, m_SMin(m_Value(), m_Value())))
9360       return RecurKind::SMin;
9361     if (match(I, m_UMax(m_Value(), m_Value())))
9362       return RecurKind::UMax;
9363     if (match(I, m_UMin(m_Value(), m_Value())))
9364       return RecurKind::UMin;
9365 
9366     if (auto *Select = dyn_cast<SelectInst>(I)) {
9367       // Try harder: look for min/max pattern based on instructions producing
9368       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9369       // During the intermediate stages of SLP, it's very common to have
9370       // pattern like this (since optimizeGatherSequence is run only once
9371       // at the end):
9372       // %1 = extractelement <2 x i32> %a, i32 0
9373       // %2 = extractelement <2 x i32> %a, i32 1
9374       // %cond = icmp sgt i32 %1, %2
9375       // %3 = extractelement <2 x i32> %a, i32 0
9376       // %4 = extractelement <2 x i32> %a, i32 1
9377       // %select = select i1 %cond, i32 %3, i32 %4
9378       CmpInst::Predicate Pred;
9379       Instruction *L1;
9380       Instruction *L2;
9381 
9382       Value *LHS = Select->getTrueValue();
9383       Value *RHS = Select->getFalseValue();
9384       Value *Cond = Select->getCondition();
9385 
9386       // TODO: Support inverse predicates.
9387       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9388         if (!isa<ExtractElementInst>(RHS) ||
9389             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9390           return RecurKind::None;
9391       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9392         if (!isa<ExtractElementInst>(LHS) ||
9393             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9394           return RecurKind::None;
9395       } else {
9396         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9397           return RecurKind::None;
9398         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9399             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9400             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9401           return RecurKind::None;
9402       }
9403 
9404       switch (Pred) {
9405       default:
9406         return RecurKind::None;
9407       case CmpInst::ICMP_SGT:
9408       case CmpInst::ICMP_SGE:
9409         return RecurKind::SMax;
9410       case CmpInst::ICMP_SLT:
9411       case CmpInst::ICMP_SLE:
9412         return RecurKind::SMin;
9413       case CmpInst::ICMP_UGT:
9414       case CmpInst::ICMP_UGE:
9415         return RecurKind::UMax;
9416       case CmpInst::ICMP_ULT:
9417       case CmpInst::ICMP_ULE:
9418         return RecurKind::UMin;
9419       }
9420     }
9421     return RecurKind::None;
9422   }
9423 
9424   /// Get the index of the first operand.
9425   static unsigned getFirstOperandIndex(Instruction *I) {
9426     return isCmpSelMinMax(I) ? 1 : 0;
9427   }
9428 
9429   /// Total number of operands in the reduction operation.
9430   static unsigned getNumberOfOperands(Instruction *I) {
9431     return isCmpSelMinMax(I) ? 3 : 2;
9432   }
9433 
9434   /// Checks if the instruction is in basic block \p BB.
9435   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9436   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9437     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9438       auto *Sel = cast<SelectInst>(I);
9439       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9440       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9441     }
9442     return I->getParent() == BB;
9443   }
9444 
9445   /// Expected number of uses for reduction operations/reduced values.
9446   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9447     if (IsCmpSelMinMax) {
9448       // SelectInst must be used twice while the condition op must have single
9449       // use only.
9450       if (auto *Sel = dyn_cast<SelectInst>(I))
9451         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9452       return I->hasNUses(2);
9453     }
9454 
9455     // Arithmetic reduction operation must be used once only.
9456     return I->hasOneUse();
9457   }
9458 
9459   /// Initializes the list of reduction operations.
9460   void initReductionOps(Instruction *I) {
9461     if (isCmpSelMinMax(I))
9462       ReductionOps.assign(2, ReductionOpsType());
9463     else
9464       ReductionOps.assign(1, ReductionOpsType());
9465   }
9466 
9467   /// Add all reduction operations for the reduction instruction \p I.
9468   void addReductionOps(Instruction *I) {
9469     if (isCmpSelMinMax(I)) {
9470       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9471       ReductionOps[1].emplace_back(I);
9472     } else {
9473       ReductionOps[0].emplace_back(I);
9474     }
9475   }
9476 
9477   static Value *getLHS(RecurKind Kind, Instruction *I) {
9478     if (Kind == RecurKind::None)
9479       return nullptr;
9480     return I->getOperand(getFirstOperandIndex(I));
9481   }
9482   static Value *getRHS(RecurKind Kind, Instruction *I) {
9483     if (Kind == RecurKind::None)
9484       return nullptr;
9485     return I->getOperand(getFirstOperandIndex(I) + 1);
9486   }
9487 
9488 public:
9489   HorizontalReduction() = default;
9490 
9491   /// Try to find a reduction tree.
9492   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9493     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9494            "Phi needs to use the binary operator");
9495     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9496             isa<IntrinsicInst>(Inst)) &&
9497            "Expected binop, select, or intrinsic for reduction matching");
9498     RdxKind = getRdxKind(Inst);
9499 
9500     // We could have a initial reductions that is not an add.
9501     //  r *= v1 + v2 + v3 + v4
9502     // In such a case start looking for a tree rooted in the first '+'.
9503     if (Phi) {
9504       if (getLHS(RdxKind, Inst) == Phi) {
9505         Phi = nullptr;
9506         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9507         if (!Inst)
9508           return false;
9509         RdxKind = getRdxKind(Inst);
9510       } else if (getRHS(RdxKind, Inst) == Phi) {
9511         Phi = nullptr;
9512         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9513         if (!Inst)
9514           return false;
9515         RdxKind = getRdxKind(Inst);
9516       }
9517     }
9518 
9519     if (!isVectorizable(RdxKind, Inst))
9520       return false;
9521 
9522     // Analyze "regular" integer/FP types for reductions - no target-specific
9523     // types or pointers.
9524     Type *Ty = Inst->getType();
9525     if (!isValidElementType(Ty) || Ty->isPointerTy())
9526       return false;
9527 
9528     // Though the ultimate reduction may have multiple uses, its condition must
9529     // have only single use.
9530     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9531       if (!Sel->getCondition()->hasOneUse())
9532         return false;
9533 
9534     ReductionRoot = Inst;
9535 
9536     // The opcode for leaf values that we perform a reduction on.
9537     // For example: load(x) + load(y) + load(z) + fptoui(w)
9538     // The leaf opcode for 'w' does not match, so we don't include it as a
9539     // potential candidate for the reduction.
9540     unsigned LeafOpcode = 0;
9541 
9542     // Post-order traverse the reduction tree starting at Inst. We only handle
9543     // true trees containing binary operators or selects.
9544     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9545     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9546     initReductionOps(Inst);
9547     while (!Stack.empty()) {
9548       Instruction *TreeN = Stack.back().first;
9549       unsigned EdgeToVisit = Stack.back().second++;
9550       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9551       bool IsReducedValue = TreeRdxKind != RdxKind;
9552 
9553       // Postorder visit.
9554       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9555         if (IsReducedValue)
9556           ReducedVals.push_back(TreeN);
9557         else {
9558           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9559           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9560             // Check if TreeN is an extra argument of its parent operation.
9561             if (Stack.size() <= 1) {
9562               // TreeN can't be an extra argument as it is a root reduction
9563               // operation.
9564               return false;
9565             }
9566             // Yes, TreeN is an extra argument, do not add it to a list of
9567             // reduction operations.
9568             // Stack[Stack.size() - 2] always points to the parent operation.
9569             markExtraArg(Stack[Stack.size() - 2], TreeN);
9570             ExtraArgs.erase(TreeN);
9571           } else
9572             addReductionOps(TreeN);
9573         }
9574         // Retract.
9575         Stack.pop_back();
9576         continue;
9577       }
9578 
9579       // Visit operands.
9580       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9581       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9582       if (!EdgeInst) {
9583         // Edge value is not a reduction instruction or a leaf instruction.
9584         // (It may be a constant, function argument, or something else.)
9585         markExtraArg(Stack.back(), EdgeVal);
9586         continue;
9587       }
9588       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9589       // Continue analysis if the next operand is a reduction operation or
9590       // (possibly) a leaf value. If the leaf value opcode is not set,
9591       // the first met operation != reduction operation is considered as the
9592       // leaf opcode.
9593       // Only handle trees in the current basic block.
9594       // Each tree node needs to have minimal number of users except for the
9595       // ultimate reduction.
9596       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9597       if (EdgeInst != Phi && EdgeInst != Inst &&
9598           hasSameParent(EdgeInst, Inst->getParent()) &&
9599           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9600           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9601         if (IsRdxInst) {
9602           // We need to be able to reassociate the reduction operations.
9603           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9604             // I is an extra argument for TreeN (its parent operation).
9605             markExtraArg(Stack.back(), EdgeInst);
9606             continue;
9607           }
9608         } else if (!LeafOpcode) {
9609           LeafOpcode = EdgeInst->getOpcode();
9610         }
9611         Stack.push_back(
9612             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9613         continue;
9614       }
9615       // I is an extra argument for TreeN (its parent operation).
9616       markExtraArg(Stack.back(), EdgeInst);
9617     }
9618     return true;
9619   }
9620 
9621   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9622   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9623     // If there are a sufficient number of reduction values, reduce
9624     // to a nearby power-of-2. We can safely generate oversized
9625     // vectors and rely on the backend to split them to legal sizes.
9626     unsigned NumReducedVals = ReducedVals.size();
9627     if (NumReducedVals < 4)
9628       return nullptr;
9629 
9630     // Intersect the fast-math-flags from all reduction operations.
9631     FastMathFlags RdxFMF;
9632     RdxFMF.set();
9633     for (ReductionOpsType &RdxOp : ReductionOps) {
9634       for (Value *RdxVal : RdxOp) {
9635         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9636           RdxFMF &= FPMO->getFastMathFlags();
9637       }
9638     }
9639 
9640     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9641     Builder.setFastMathFlags(RdxFMF);
9642 
9643     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9644     // The same extra argument may be used several times, so log each attempt
9645     // to use it.
9646     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9647       assert(Pair.first && "DebugLoc must be set.");
9648       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9649     }
9650 
9651     // The compare instruction of a min/max is the insertion point for new
9652     // instructions and may be replaced with a new compare instruction.
9653     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9654       assert(isa<SelectInst>(RdxRootInst) &&
9655              "Expected min/max reduction to have select root instruction");
9656       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9657       assert(isa<Instruction>(ScalarCond) &&
9658              "Expected min/max reduction to have compare condition");
9659       return cast<Instruction>(ScalarCond);
9660     };
9661 
9662     // The reduction root is used as the insertion point for new instructions,
9663     // so set it as externally used to prevent it from being deleted.
9664     ExternallyUsedValues[ReductionRoot];
9665     SmallVector<Value *, 16> IgnoreList;
9666     for (ReductionOpsType &RdxOp : ReductionOps)
9667       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9668 
9669     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9670     if (NumReducedVals > ReduxWidth) {
9671       // In the loop below, we are building a tree based on a window of
9672       // 'ReduxWidth' values.
9673       // If the operands of those values have common traits (compare predicate,
9674       // constant operand, etc), then we want to group those together to
9675       // minimize the cost of the reduction.
9676 
9677       // TODO: This should be extended to count common operands for
9678       //       compares and binops.
9679 
9680       // Step 1: Count the number of times each compare predicate occurs.
9681       SmallDenseMap<unsigned, unsigned> PredCountMap;
9682       for (Value *RdxVal : ReducedVals) {
9683         CmpInst::Predicate Pred;
9684         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9685           ++PredCountMap[Pred];
9686       }
9687       // Step 2: Sort the values so the most common predicates come first.
9688       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9689         CmpInst::Predicate PredA, PredB;
9690         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9691             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9692           return PredCountMap[PredA] > PredCountMap[PredB];
9693         }
9694         return false;
9695       });
9696     }
9697 
9698     Value *VectorizedTree = nullptr;
9699     unsigned i = 0;
9700     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9701       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9702       V.buildTree(VL, IgnoreList);
9703       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9704         break;
9705       if (V.isLoadCombineReductionCandidate(RdxKind))
9706         break;
9707       V.reorderTopToBottom();
9708       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9709       V.buildExternalUses(ExternallyUsedValues);
9710 
9711       // For a poison-safe boolean logic reduction, do not replace select
9712       // instructions with logic ops. All reduced values will be frozen (see
9713       // below) to prevent leaking poison.
9714       if (isa<SelectInst>(ReductionRoot) &&
9715           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9716           NumReducedVals != ReduxWidth)
9717         break;
9718 
9719       V.computeMinimumValueSizes();
9720 
9721       // Estimate cost.
9722       InstructionCost TreeCost =
9723           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9724       InstructionCost ReductionCost =
9725           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9726       InstructionCost Cost = TreeCost + ReductionCost;
9727       if (!Cost.isValid()) {
9728         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9729         return nullptr;
9730       }
9731       if (Cost >= -SLPCostThreshold) {
9732         V.getORE()->emit([&]() {
9733           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9734                                           cast<Instruction>(VL[0]))
9735                  << "Vectorizing horizontal reduction is possible"
9736                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9737                  << " and threshold "
9738                  << ore::NV("Threshold", -SLPCostThreshold);
9739         });
9740         break;
9741       }
9742 
9743       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9744                         << Cost << ". (HorRdx)\n");
9745       V.getORE()->emit([&]() {
9746         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9747                                   cast<Instruction>(VL[0]))
9748                << "Vectorized horizontal reduction with cost "
9749                << ore::NV("Cost", Cost) << " and with tree size "
9750                << ore::NV("TreeSize", V.getTreeSize());
9751       });
9752 
9753       // Vectorize a tree.
9754       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9755       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9756 
9757       // Emit a reduction. If the root is a select (min/max idiom), the insert
9758       // point is the compare condition of that select.
9759       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9760       if (isCmpSelMinMax(RdxRootInst))
9761         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9762       else
9763         Builder.SetInsertPoint(RdxRootInst);
9764 
9765       // To prevent poison from leaking across what used to be sequential, safe,
9766       // scalar boolean logic operations, the reduction operand must be frozen.
9767       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9768         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9769 
9770       Value *ReducedSubTree =
9771           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9772 
9773       if (!VectorizedTree) {
9774         // Initialize the final value in the reduction.
9775         VectorizedTree = ReducedSubTree;
9776       } else {
9777         // Update the final value in the reduction.
9778         Builder.SetCurrentDebugLocation(Loc);
9779         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9780                                   ReducedSubTree, "op.rdx", ReductionOps);
9781       }
9782       i += ReduxWidth;
9783       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9784     }
9785 
9786     if (VectorizedTree) {
9787       // Finish the reduction.
9788       for (; i < NumReducedVals; ++i) {
9789         auto *I = cast<Instruction>(ReducedVals[i]);
9790         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9791         VectorizedTree =
9792             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9793       }
9794       for (auto &Pair : ExternallyUsedValues) {
9795         // Add each externally used value to the final reduction.
9796         for (auto *I : Pair.second) {
9797           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9798           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9799                                     Pair.first, "op.extra", I);
9800         }
9801       }
9802 
9803       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9804 
9805       // Mark all scalar reduction ops for deletion, they are replaced by the
9806       // vector reductions.
9807       V.eraseInstructions(IgnoreList);
9808     }
9809     return VectorizedTree;
9810   }
9811 
9812   unsigned numReductionValues() const { return ReducedVals.size(); }
9813 
9814 private:
9815   /// Calculate the cost of a reduction.
9816   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9817                                    Value *FirstReducedVal, unsigned ReduxWidth,
9818                                    FastMathFlags FMF) {
9819     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9820     Type *ScalarTy = FirstReducedVal->getType();
9821     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9822     InstructionCost VectorCost, ScalarCost;
9823     switch (RdxKind) {
9824     case RecurKind::Add:
9825     case RecurKind::Mul:
9826     case RecurKind::Or:
9827     case RecurKind::And:
9828     case RecurKind::Xor:
9829     case RecurKind::FAdd:
9830     case RecurKind::FMul: {
9831       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9832       VectorCost =
9833           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9834       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9835       break;
9836     }
9837     case RecurKind::FMax:
9838     case RecurKind::FMin: {
9839       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9840       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9841       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9842                                                /*IsUnsigned=*/false, CostKind);
9843       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9844       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9845                                            SclCondTy, RdxPred, CostKind) +
9846                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9847                                            SclCondTy, RdxPred, CostKind);
9848       break;
9849     }
9850     case RecurKind::SMax:
9851     case RecurKind::SMin:
9852     case RecurKind::UMax:
9853     case RecurKind::UMin: {
9854       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9855       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9856       bool IsUnsigned =
9857           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9858       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9859                                                CostKind);
9860       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9861       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9862                                            SclCondTy, RdxPred, CostKind) +
9863                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9864                                            SclCondTy, RdxPred, CostKind);
9865       break;
9866     }
9867     default:
9868       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9869     }
9870 
9871     // Scalar cost is repeated for N-1 elements.
9872     ScalarCost *= (ReduxWidth - 1);
9873     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9874                       << " for reduction that starts with " << *FirstReducedVal
9875                       << " (It is a splitting reduction)\n");
9876     return VectorCost - ScalarCost;
9877   }
9878 
9879   /// Emit a horizontal reduction of the vectorized value.
9880   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9881                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9882     assert(VectorizedValue && "Need to have a vectorized tree node");
9883     assert(isPowerOf2_32(ReduxWidth) &&
9884            "We only handle power-of-two reductions for now");
9885     assert(RdxKind != RecurKind::FMulAdd &&
9886            "A call to the llvm.fmuladd intrinsic is not handled yet");
9887 
9888     ++NumVectorInstructions;
9889     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9890   }
9891 };
9892 
9893 } // end anonymous namespace
9894 
9895 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9896   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9897     return cast<FixedVectorType>(IE->getType())->getNumElements();
9898 
9899   unsigned AggregateSize = 1;
9900   auto *IV = cast<InsertValueInst>(InsertInst);
9901   Type *CurrentType = IV->getType();
9902   do {
9903     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9904       for (auto *Elt : ST->elements())
9905         if (Elt != ST->getElementType(0)) // check homogeneity
9906           return None;
9907       AggregateSize *= ST->getNumElements();
9908       CurrentType = ST->getElementType(0);
9909     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9910       AggregateSize *= AT->getNumElements();
9911       CurrentType = AT->getElementType();
9912     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9913       AggregateSize *= VT->getNumElements();
9914       return AggregateSize;
9915     } else if (CurrentType->isSingleValueType()) {
9916       return AggregateSize;
9917     } else {
9918       return None;
9919     }
9920   } while (true);
9921 }
9922 
9923 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9924                                    TargetTransformInfo *TTI,
9925                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9926                                    SmallVectorImpl<Value *> &InsertElts,
9927                                    unsigned OperandOffset) {
9928   do {
9929     Value *InsertedOperand = LastInsertInst->getOperand(1);
9930     Optional<unsigned> OperandIndex =
9931         getInsertIndex(LastInsertInst, OperandOffset);
9932     if (!OperandIndex)
9933       return;
9934     if (isa<InsertElementInst>(InsertedOperand) ||
9935         isa<InsertValueInst>(InsertedOperand)) {
9936       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9937                              BuildVectorOpds, InsertElts, *OperandIndex);
9938 
9939     } else {
9940       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9941       InsertElts[*OperandIndex] = LastInsertInst;
9942     }
9943     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9944   } while (LastInsertInst != nullptr &&
9945            (isa<InsertValueInst>(LastInsertInst) ||
9946             isa<InsertElementInst>(LastInsertInst)) &&
9947            LastInsertInst->hasOneUse());
9948 }
9949 
9950 /// Recognize construction of vectors like
9951 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9952 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9953 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9954 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9955 ///  starting from the last insertelement or insertvalue instruction.
9956 ///
9957 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9958 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9959 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9960 ///
9961 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9962 ///
9963 /// \return true if it matches.
9964 static bool findBuildAggregate(Instruction *LastInsertInst,
9965                                TargetTransformInfo *TTI,
9966                                SmallVectorImpl<Value *> &BuildVectorOpds,
9967                                SmallVectorImpl<Value *> &InsertElts) {
9968 
9969   assert((isa<InsertElementInst>(LastInsertInst) ||
9970           isa<InsertValueInst>(LastInsertInst)) &&
9971          "Expected insertelement or insertvalue instruction!");
9972 
9973   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9974          "Expected empty result vectors!");
9975 
9976   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9977   if (!AggregateSize)
9978     return false;
9979   BuildVectorOpds.resize(*AggregateSize);
9980   InsertElts.resize(*AggregateSize);
9981 
9982   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9983   llvm::erase_value(BuildVectorOpds, nullptr);
9984   llvm::erase_value(InsertElts, nullptr);
9985   if (BuildVectorOpds.size() >= 2)
9986     return true;
9987 
9988   return false;
9989 }
9990 
9991 /// Try and get a reduction value from a phi node.
9992 ///
9993 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9994 /// if they come from either \p ParentBB or a containing loop latch.
9995 ///
9996 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9997 /// if not possible.
9998 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9999                                 BasicBlock *ParentBB, LoopInfo *LI) {
10000   // There are situations where the reduction value is not dominated by the
10001   // reduction phi. Vectorizing such cases has been reported to cause
10002   // miscompiles. See PR25787.
10003   auto DominatedReduxValue = [&](Value *R) {
10004     return isa<Instruction>(R) &&
10005            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10006   };
10007 
10008   Value *Rdx = nullptr;
10009 
10010   // Return the incoming value if it comes from the same BB as the phi node.
10011   if (P->getIncomingBlock(0) == ParentBB) {
10012     Rdx = P->getIncomingValue(0);
10013   } else if (P->getIncomingBlock(1) == ParentBB) {
10014     Rdx = P->getIncomingValue(1);
10015   }
10016 
10017   if (Rdx && DominatedReduxValue(Rdx))
10018     return Rdx;
10019 
10020   // Otherwise, check whether we have a loop latch to look at.
10021   Loop *BBL = LI->getLoopFor(ParentBB);
10022   if (!BBL)
10023     return nullptr;
10024   BasicBlock *BBLatch = BBL->getLoopLatch();
10025   if (!BBLatch)
10026     return nullptr;
10027 
10028   // There is a loop latch, return the incoming value if it comes from
10029   // that. This reduction pattern occasionally turns up.
10030   if (P->getIncomingBlock(0) == BBLatch) {
10031     Rdx = P->getIncomingValue(0);
10032   } else if (P->getIncomingBlock(1) == BBLatch) {
10033     Rdx = P->getIncomingValue(1);
10034   }
10035 
10036   if (Rdx && DominatedReduxValue(Rdx))
10037     return Rdx;
10038 
10039   return nullptr;
10040 }
10041 
10042 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10043   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10044     return true;
10045   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10046     return true;
10047   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10048     return true;
10049   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10050     return true;
10051   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10052     return true;
10053   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10054     return true;
10055   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10056     return true;
10057   return false;
10058 }
10059 
10060 /// Attempt to reduce a horizontal reduction.
10061 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10062 /// with reduction operators \a Root (or one of its operands) in a basic block
10063 /// \a BB, then check if it can be done. If horizontal reduction is not found
10064 /// and root instruction is a binary operation, vectorization of the operands is
10065 /// attempted.
10066 /// \returns true if a horizontal reduction was matched and reduced or operands
10067 /// of one of the binary instruction were vectorized.
10068 /// \returns false if a horizontal reduction was not matched (or not possible)
10069 /// or no vectorization of any binary operation feeding \a Root instruction was
10070 /// performed.
10071 static bool tryToVectorizeHorReductionOrInstOperands(
10072     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10073     TargetTransformInfo *TTI,
10074     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10075   if (!ShouldVectorizeHor)
10076     return false;
10077 
10078   if (!Root)
10079     return false;
10080 
10081   if (Root->getParent() != BB || isa<PHINode>(Root))
10082     return false;
10083   // Start analysis starting from Root instruction. If horizontal reduction is
10084   // found, try to vectorize it. If it is not a horizontal reduction or
10085   // vectorization is not possible or not effective, and currently analyzed
10086   // instruction is a binary operation, try to vectorize the operands, using
10087   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10088   // the same procedure considering each operand as a possible root of the
10089   // horizontal reduction.
10090   // Interrupt the process if the Root instruction itself was vectorized or all
10091   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10092   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10093   // CmpInsts so we can skip extra attempts in
10094   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10095   std::queue<std::pair<Instruction *, unsigned>> Stack;
10096   Stack.emplace(Root, 0);
10097   SmallPtrSet<Value *, 8> VisitedInstrs;
10098   SmallVector<WeakTrackingVH> PostponedInsts;
10099   bool Res = false;
10100   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10101                                      Value *&B1) -> Value * {
10102     bool IsBinop = matchRdxBop(Inst, B0, B1);
10103     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10104     if (IsBinop || IsSelect) {
10105       HorizontalReduction HorRdx;
10106       if (HorRdx.matchAssociativeReduction(P, Inst))
10107         return HorRdx.tryToReduce(R, TTI);
10108     }
10109     return nullptr;
10110   };
10111   while (!Stack.empty()) {
10112     Instruction *Inst;
10113     unsigned Level;
10114     std::tie(Inst, Level) = Stack.front();
10115     Stack.pop();
10116     // Do not try to analyze instruction that has already been vectorized.
10117     // This may happen when we vectorize instruction operands on a previous
10118     // iteration while stack was populated before that happened.
10119     if (R.isDeleted(Inst))
10120       continue;
10121     Value *B0 = nullptr, *B1 = nullptr;
10122     if (Value *V = TryToReduce(Inst, B0, B1)) {
10123       Res = true;
10124       // Set P to nullptr to avoid re-analysis of phi node in
10125       // matchAssociativeReduction function unless this is the root node.
10126       P = nullptr;
10127       if (auto *I = dyn_cast<Instruction>(V)) {
10128         // Try to find another reduction.
10129         Stack.emplace(I, Level);
10130         continue;
10131       }
10132     } else {
10133       bool IsBinop = B0 && B1;
10134       if (P && IsBinop) {
10135         Inst = dyn_cast<Instruction>(B0);
10136         if (Inst == P)
10137           Inst = dyn_cast<Instruction>(B1);
10138         if (!Inst) {
10139           // Set P to nullptr to avoid re-analysis of phi node in
10140           // matchAssociativeReduction function unless this is the root node.
10141           P = nullptr;
10142           continue;
10143         }
10144       }
10145       // Set P to nullptr to avoid re-analysis of phi node in
10146       // matchAssociativeReduction function unless this is the root node.
10147       P = nullptr;
10148       // Do not try to vectorize CmpInst operands, this is done separately.
10149       // Final attempt for binop args vectorization should happen after the loop
10150       // to try to find reductions.
10151       if (!isa<CmpInst>(Inst))
10152         PostponedInsts.push_back(Inst);
10153     }
10154 
10155     // Try to vectorize operands.
10156     // Continue analysis for the instruction from the same basic block only to
10157     // save compile time.
10158     if (++Level < RecursionMaxDepth)
10159       for (auto *Op : Inst->operand_values())
10160         if (VisitedInstrs.insert(Op).second)
10161           if (auto *I = dyn_cast<Instruction>(Op))
10162             // Do not try to vectorize CmpInst operands,  this is done
10163             // separately.
10164             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10165                 I->getParent() == BB)
10166               Stack.emplace(I, Level);
10167   }
10168   // Try to vectorized binops where reductions were not found.
10169   for (Value *V : PostponedInsts)
10170     if (auto *Inst = dyn_cast<Instruction>(V))
10171       if (!R.isDeleted(Inst))
10172         Res |= Vectorize(Inst, R);
10173   return Res;
10174 }
10175 
10176 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10177                                                  BasicBlock *BB, BoUpSLP &R,
10178                                                  TargetTransformInfo *TTI) {
10179   auto *I = dyn_cast_or_null<Instruction>(V);
10180   if (!I)
10181     return false;
10182 
10183   if (!isa<BinaryOperator>(I))
10184     P = nullptr;
10185   // Try to match and vectorize a horizontal reduction.
10186   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10187     return tryToVectorize(I, R);
10188   };
10189   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10190                                                   ExtraVectorization);
10191 }
10192 
10193 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10194                                                  BasicBlock *BB, BoUpSLP &R) {
10195   const DataLayout &DL = BB->getModule()->getDataLayout();
10196   if (!R.canMapToVector(IVI->getType(), DL))
10197     return false;
10198 
10199   SmallVector<Value *, 16> BuildVectorOpds;
10200   SmallVector<Value *, 16> BuildVectorInsts;
10201   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10202     return false;
10203 
10204   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10205   // Aggregate value is unlikely to be processed in vector register.
10206   return tryToVectorizeList(BuildVectorOpds, R);
10207 }
10208 
10209 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10210                                                    BasicBlock *BB, BoUpSLP &R) {
10211   SmallVector<Value *, 16> BuildVectorInsts;
10212   SmallVector<Value *, 16> BuildVectorOpds;
10213   SmallVector<int> Mask;
10214   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10215       (llvm::all_of(
10216            BuildVectorOpds,
10217            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10218        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10219     return false;
10220 
10221   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10222   return tryToVectorizeList(BuildVectorInsts, R);
10223 }
10224 
10225 template <typename T>
10226 static bool
10227 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10228                        function_ref<unsigned(T *)> Limit,
10229                        function_ref<bool(T *, T *)> Comparator,
10230                        function_ref<bool(T *, T *)> AreCompatible,
10231                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10232                        bool LimitForRegisterSize) {
10233   bool Changed = false;
10234   // Sort by type, parent, operands.
10235   stable_sort(Incoming, Comparator);
10236 
10237   // Try to vectorize elements base on their type.
10238   SmallVector<T *> Candidates;
10239   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10240     // Look for the next elements with the same type, parent and operand
10241     // kinds.
10242     auto *SameTypeIt = IncIt;
10243     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10244       ++SameTypeIt;
10245 
10246     // Try to vectorize them.
10247     unsigned NumElts = (SameTypeIt - IncIt);
10248     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10249                       << NumElts << ")\n");
10250     // The vectorization is a 3-state attempt:
10251     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10252     // size of maximal register at first.
10253     // 2. Try to vectorize remaining instructions with the same type, if
10254     // possible. This may result in the better vectorization results rather than
10255     // if we try just to vectorize instructions with the same/alternate opcodes.
10256     // 3. Final attempt to try to vectorize all instructions with the
10257     // same/alternate ops only, this may result in some extra final
10258     // vectorization.
10259     if (NumElts > 1 &&
10260         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10261       // Success start over because instructions might have been changed.
10262       Changed = true;
10263     } else if (NumElts < Limit(*IncIt) &&
10264                (Candidates.empty() ||
10265                 Candidates.front()->getType() == (*IncIt)->getType())) {
10266       Candidates.append(IncIt, std::next(IncIt, NumElts));
10267     }
10268     // Final attempt to vectorize instructions with the same types.
10269     if (Candidates.size() > 1 &&
10270         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10271       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10272         // Success start over because instructions might have been changed.
10273         Changed = true;
10274       } else if (LimitForRegisterSize) {
10275         // Try to vectorize using small vectors.
10276         for (auto *It = Candidates.begin(), *End = Candidates.end();
10277              It != End;) {
10278           auto *SameTypeIt = It;
10279           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10280             ++SameTypeIt;
10281           unsigned NumElts = (SameTypeIt - It);
10282           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10283                                             /*LimitForRegisterSize=*/false))
10284             Changed = true;
10285           It = SameTypeIt;
10286         }
10287       }
10288       Candidates.clear();
10289     }
10290 
10291     // Start over at the next instruction of a different type (or the end).
10292     IncIt = SameTypeIt;
10293   }
10294   return Changed;
10295 }
10296 
10297 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10298 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10299 /// operands. If IsCompatibility is false, function implements strict weak
10300 /// ordering relation between two cmp instructions, returning true if the first
10301 /// instruction is "less" than the second, i.e. its predicate is less than the
10302 /// predicate of the second or the operands IDs are less than the operands IDs
10303 /// of the second cmp instruction.
10304 template <bool IsCompatibility>
10305 static bool compareCmp(Value *V, Value *V2,
10306                        function_ref<bool(Instruction *)> IsDeleted) {
10307   auto *CI1 = cast<CmpInst>(V);
10308   auto *CI2 = cast<CmpInst>(V2);
10309   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10310     return false;
10311   if (CI1->getOperand(0)->getType()->getTypeID() <
10312       CI2->getOperand(0)->getType()->getTypeID())
10313     return !IsCompatibility;
10314   if (CI1->getOperand(0)->getType()->getTypeID() >
10315       CI2->getOperand(0)->getType()->getTypeID())
10316     return false;
10317   CmpInst::Predicate Pred1 = CI1->getPredicate();
10318   CmpInst::Predicate Pred2 = CI2->getPredicate();
10319   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10320   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10321   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10322   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10323   if (BasePred1 < BasePred2)
10324     return !IsCompatibility;
10325   if (BasePred1 > BasePred2)
10326     return false;
10327   // Compare operands.
10328   bool LEPreds = Pred1 <= Pred2;
10329   bool GEPreds = Pred1 >= Pred2;
10330   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10331     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10332     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10333     if (Op1->getValueID() < Op2->getValueID())
10334       return !IsCompatibility;
10335     if (Op1->getValueID() > Op2->getValueID())
10336       return false;
10337     if (auto *I1 = dyn_cast<Instruction>(Op1))
10338       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10339         if (I1->getParent() != I2->getParent())
10340           return false;
10341         InstructionsState S = getSameOpcode({I1, I2});
10342         if (S.getOpcode())
10343           continue;
10344         return false;
10345       }
10346   }
10347   return IsCompatibility;
10348 }
10349 
10350 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10351     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10352     bool AtTerminator) {
10353   bool OpsChanged = false;
10354   SmallVector<Instruction *, 4> PostponedCmps;
10355   for (auto *I : reverse(Instructions)) {
10356     if (R.isDeleted(I))
10357       continue;
10358     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10359       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10360     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10361       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10362     else if (isa<CmpInst>(I))
10363       PostponedCmps.push_back(I);
10364   }
10365   if (AtTerminator) {
10366     // Try to find reductions first.
10367     for (Instruction *I : PostponedCmps) {
10368       if (R.isDeleted(I))
10369         continue;
10370       for (Value *Op : I->operands())
10371         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10372     }
10373     // Try to vectorize operands as vector bundles.
10374     for (Instruction *I : PostponedCmps) {
10375       if (R.isDeleted(I))
10376         continue;
10377       OpsChanged |= tryToVectorize(I, R);
10378     }
10379     // Try to vectorize list of compares.
10380     // Sort by type, compare predicate, etc.
10381     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10382       return compareCmp<false>(V, V2,
10383                                [&R](Instruction *I) { return R.isDeleted(I); });
10384     };
10385 
10386     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10387       if (V1 == V2)
10388         return true;
10389       return compareCmp<true>(V1, V2,
10390                               [&R](Instruction *I) { return R.isDeleted(I); });
10391     };
10392     auto Limit = [&R](Value *V) {
10393       unsigned EltSize = R.getVectorElementSize(V);
10394       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10395     };
10396 
10397     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10398     OpsChanged |= tryToVectorizeSequence<Value>(
10399         Vals, Limit, CompareSorter, AreCompatibleCompares,
10400         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10401           // Exclude possible reductions from other blocks.
10402           bool ArePossiblyReducedInOtherBlock =
10403               any_of(Candidates, [](Value *V) {
10404                 return any_of(V->users(), [V](User *U) {
10405                   return isa<SelectInst>(U) &&
10406                          cast<SelectInst>(U)->getParent() !=
10407                              cast<Instruction>(V)->getParent();
10408                 });
10409               });
10410           if (ArePossiblyReducedInOtherBlock)
10411             return false;
10412           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10413         },
10414         /*LimitForRegisterSize=*/true);
10415     Instructions.clear();
10416   } else {
10417     // Insert in reverse order since the PostponedCmps vector was filled in
10418     // reverse order.
10419     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10420   }
10421   return OpsChanged;
10422 }
10423 
10424 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10425   bool Changed = false;
10426   SmallVector<Value *, 4> Incoming;
10427   SmallPtrSet<Value *, 16> VisitedInstrs;
10428   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10429   // node. Allows better to identify the chains that can be vectorized in the
10430   // better way.
10431   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10432   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10433     assert(isValidElementType(V1->getType()) &&
10434            isValidElementType(V2->getType()) &&
10435            "Expected vectorizable types only.");
10436     // It is fine to compare type IDs here, since we expect only vectorizable
10437     // types, like ints, floats and pointers, we don't care about other type.
10438     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10439       return true;
10440     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10441       return false;
10442     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10443     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10444     if (Opcodes1.size() < Opcodes2.size())
10445       return true;
10446     if (Opcodes1.size() > Opcodes2.size())
10447       return false;
10448     Optional<bool> ConstOrder;
10449     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10450       // Undefs are compatible with any other value.
10451       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10452         if (!ConstOrder)
10453           ConstOrder =
10454               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10455         continue;
10456       }
10457       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10458         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10459           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10460           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10461           if (!NodeI1)
10462             return NodeI2 != nullptr;
10463           if (!NodeI2)
10464             return false;
10465           assert((NodeI1 == NodeI2) ==
10466                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10467                  "Different nodes should have different DFS numbers");
10468           if (NodeI1 != NodeI2)
10469             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10470           InstructionsState S = getSameOpcode({I1, I2});
10471           if (S.getOpcode())
10472             continue;
10473           return I1->getOpcode() < I2->getOpcode();
10474         }
10475       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10476         if (!ConstOrder)
10477           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10478         continue;
10479       }
10480       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10481         return true;
10482       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10483         return false;
10484     }
10485     return ConstOrder && *ConstOrder;
10486   };
10487   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10488     if (V1 == V2)
10489       return true;
10490     if (V1->getType() != V2->getType())
10491       return false;
10492     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10493     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10494     if (Opcodes1.size() != Opcodes2.size())
10495       return false;
10496     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10497       // Undefs are compatible with any other value.
10498       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10499         continue;
10500       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10501         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10502           if (I1->getParent() != I2->getParent())
10503             return false;
10504           InstructionsState S = getSameOpcode({I1, I2});
10505           if (S.getOpcode())
10506             continue;
10507           return false;
10508         }
10509       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10510         continue;
10511       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10512         return false;
10513     }
10514     return true;
10515   };
10516   auto Limit = [&R](Value *V) {
10517     unsigned EltSize = R.getVectorElementSize(V);
10518     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10519   };
10520 
10521   bool HaveVectorizedPhiNodes = false;
10522   do {
10523     // Collect the incoming values from the PHIs.
10524     Incoming.clear();
10525     for (Instruction &I : *BB) {
10526       PHINode *P = dyn_cast<PHINode>(&I);
10527       if (!P)
10528         break;
10529 
10530       // No need to analyze deleted, vectorized and non-vectorizable
10531       // instructions.
10532       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10533           isValidElementType(P->getType()))
10534         Incoming.push_back(P);
10535     }
10536 
10537     // Find the corresponding non-phi nodes for better matching when trying to
10538     // build the tree.
10539     for (Value *V : Incoming) {
10540       SmallVectorImpl<Value *> &Opcodes =
10541           PHIToOpcodes.try_emplace(V).first->getSecond();
10542       if (!Opcodes.empty())
10543         continue;
10544       SmallVector<Value *, 4> Nodes(1, V);
10545       SmallPtrSet<Value *, 4> Visited;
10546       while (!Nodes.empty()) {
10547         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10548         if (!Visited.insert(PHI).second)
10549           continue;
10550         for (Value *V : PHI->incoming_values()) {
10551           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10552             Nodes.push_back(PHI1);
10553             continue;
10554           }
10555           Opcodes.emplace_back(V);
10556         }
10557       }
10558     }
10559 
10560     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10561         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10562         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10563           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10564         },
10565         /*LimitForRegisterSize=*/true);
10566     Changed |= HaveVectorizedPhiNodes;
10567     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10568   } while (HaveVectorizedPhiNodes);
10569 
10570   VisitedInstrs.clear();
10571 
10572   SmallVector<Instruction *, 8> PostProcessInstructions;
10573   SmallDenseSet<Instruction *, 4> KeyNodes;
10574   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10575     // Skip instructions with scalable type. The num of elements is unknown at
10576     // compile-time for scalable type.
10577     if (isa<ScalableVectorType>(it->getType()))
10578       continue;
10579 
10580     // Skip instructions marked for the deletion.
10581     if (R.isDeleted(&*it))
10582       continue;
10583     // We may go through BB multiple times so skip the one we have checked.
10584     if (!VisitedInstrs.insert(&*it).second) {
10585       if (it->use_empty() && KeyNodes.contains(&*it) &&
10586           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10587                                       it->isTerminator())) {
10588         // We would like to start over since some instructions are deleted
10589         // and the iterator may become invalid value.
10590         Changed = true;
10591         it = BB->begin();
10592         e = BB->end();
10593       }
10594       continue;
10595     }
10596 
10597     if (isa<DbgInfoIntrinsic>(it))
10598       continue;
10599 
10600     // Try to vectorize reductions that use PHINodes.
10601     if (PHINode *P = dyn_cast<PHINode>(it)) {
10602       // Check that the PHI is a reduction PHI.
10603       if (P->getNumIncomingValues() == 2) {
10604         // Try to match and vectorize a horizontal reduction.
10605         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10606                                      TTI)) {
10607           Changed = true;
10608           it = BB->begin();
10609           e = BB->end();
10610           continue;
10611         }
10612       }
10613       // Try to vectorize the incoming values of the PHI, to catch reductions
10614       // that feed into PHIs.
10615       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10616         // Skip if the incoming block is the current BB for now. Also, bypass
10617         // unreachable IR for efficiency and to avoid crashing.
10618         // TODO: Collect the skipped incoming values and try to vectorize them
10619         // after processing BB.
10620         if (BB == P->getIncomingBlock(I) ||
10621             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10622           continue;
10623 
10624         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10625                                             P->getIncomingBlock(I), R, TTI);
10626       }
10627       continue;
10628     }
10629 
10630     // Ran into an instruction without users, like terminator, or function call
10631     // with ignored return value, store. Ignore unused instructions (basing on
10632     // instruction type, except for CallInst and InvokeInst).
10633     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10634                             isa<InvokeInst>(it))) {
10635       KeyNodes.insert(&*it);
10636       bool OpsChanged = false;
10637       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10638         for (auto *V : it->operand_values()) {
10639           // Try to match and vectorize a horizontal reduction.
10640           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10641         }
10642       }
10643       // Start vectorization of post-process list of instructions from the
10644       // top-tree instructions to try to vectorize as many instructions as
10645       // possible.
10646       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10647                                                 it->isTerminator());
10648       if (OpsChanged) {
10649         // We would like to start over since some instructions are deleted
10650         // and the iterator may become invalid value.
10651         Changed = true;
10652         it = BB->begin();
10653         e = BB->end();
10654         continue;
10655       }
10656     }
10657 
10658     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10659         isa<InsertValueInst>(it))
10660       PostProcessInstructions.push_back(&*it);
10661   }
10662 
10663   return Changed;
10664 }
10665 
10666 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10667   auto Changed = false;
10668   for (auto &Entry : GEPs) {
10669     // If the getelementptr list has fewer than two elements, there's nothing
10670     // to do.
10671     if (Entry.second.size() < 2)
10672       continue;
10673 
10674     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10675                       << Entry.second.size() << ".\n");
10676 
10677     // Process the GEP list in chunks suitable for the target's supported
10678     // vector size. If a vector register can't hold 1 element, we are done. We
10679     // are trying to vectorize the index computations, so the maximum number of
10680     // elements is based on the size of the index expression, rather than the
10681     // size of the GEP itself (the target's pointer size).
10682     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10683     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10684     if (MaxVecRegSize < EltSize)
10685       continue;
10686 
10687     unsigned MaxElts = MaxVecRegSize / EltSize;
10688     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10689       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10690       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10691 
10692       // Initialize a set a candidate getelementptrs. Note that we use a
10693       // SetVector here to preserve program order. If the index computations
10694       // are vectorizable and begin with loads, we want to minimize the chance
10695       // of having to reorder them later.
10696       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10697 
10698       // Some of the candidates may have already been vectorized after we
10699       // initially collected them. If so, they are marked as deleted, so remove
10700       // them from the set of candidates.
10701       Candidates.remove_if(
10702           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10703 
10704       // Remove from the set of candidates all pairs of getelementptrs with
10705       // constant differences. Such getelementptrs are likely not good
10706       // candidates for vectorization in a bottom-up phase since one can be
10707       // computed from the other. We also ensure all candidate getelementptr
10708       // indices are unique.
10709       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10710         auto *GEPI = GEPList[I];
10711         if (!Candidates.count(GEPI))
10712           continue;
10713         auto *SCEVI = SE->getSCEV(GEPList[I]);
10714         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10715           auto *GEPJ = GEPList[J];
10716           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10717           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10718             Candidates.remove(GEPI);
10719             Candidates.remove(GEPJ);
10720           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10721             Candidates.remove(GEPJ);
10722           }
10723         }
10724       }
10725 
10726       // We break out of the above computation as soon as we know there are
10727       // fewer than two candidates remaining.
10728       if (Candidates.size() < 2)
10729         continue;
10730 
10731       // Add the single, non-constant index of each candidate to the bundle. We
10732       // ensured the indices met these constraints when we originally collected
10733       // the getelementptrs.
10734       SmallVector<Value *, 16> Bundle(Candidates.size());
10735       auto BundleIndex = 0u;
10736       for (auto *V : Candidates) {
10737         auto *GEP = cast<GetElementPtrInst>(V);
10738         auto *GEPIdx = GEP->idx_begin()->get();
10739         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10740         Bundle[BundleIndex++] = GEPIdx;
10741       }
10742 
10743       // Try and vectorize the indices. We are currently only interested in
10744       // gather-like cases of the form:
10745       //
10746       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10747       //
10748       // where the loads of "a", the loads of "b", and the subtractions can be
10749       // performed in parallel. It's likely that detecting this pattern in a
10750       // bottom-up phase will be simpler and less costly than building a
10751       // full-blown top-down phase beginning at the consecutive loads.
10752       Changed |= tryToVectorizeList(Bundle, R);
10753     }
10754   }
10755   return Changed;
10756 }
10757 
10758 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10759   bool Changed = false;
10760   // Sort by type, base pointers and values operand. Value operands must be
10761   // compatible (have the same opcode, same parent), otherwise it is
10762   // definitely not profitable to try to vectorize them.
10763   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10764     if (V->getPointerOperandType()->getTypeID() <
10765         V2->getPointerOperandType()->getTypeID())
10766       return true;
10767     if (V->getPointerOperandType()->getTypeID() >
10768         V2->getPointerOperandType()->getTypeID())
10769       return false;
10770     // UndefValues are compatible with all other values.
10771     if (isa<UndefValue>(V->getValueOperand()) ||
10772         isa<UndefValue>(V2->getValueOperand()))
10773       return false;
10774     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10775       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10776         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10777             DT->getNode(I1->getParent());
10778         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10779             DT->getNode(I2->getParent());
10780         assert(NodeI1 && "Should only process reachable instructions");
10781         assert(NodeI1 && "Should only process reachable instructions");
10782         assert((NodeI1 == NodeI2) ==
10783                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10784                "Different nodes should have different DFS numbers");
10785         if (NodeI1 != NodeI2)
10786           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10787         InstructionsState S = getSameOpcode({I1, I2});
10788         if (S.getOpcode())
10789           return false;
10790         return I1->getOpcode() < I2->getOpcode();
10791       }
10792     if (isa<Constant>(V->getValueOperand()) &&
10793         isa<Constant>(V2->getValueOperand()))
10794       return false;
10795     return V->getValueOperand()->getValueID() <
10796            V2->getValueOperand()->getValueID();
10797   };
10798 
10799   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10800     if (V1 == V2)
10801       return true;
10802     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10803       return false;
10804     // Undefs are compatible with any other value.
10805     if (isa<UndefValue>(V1->getValueOperand()) ||
10806         isa<UndefValue>(V2->getValueOperand()))
10807       return true;
10808     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10809       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10810         if (I1->getParent() != I2->getParent())
10811           return false;
10812         InstructionsState S = getSameOpcode({I1, I2});
10813         return S.getOpcode() > 0;
10814       }
10815     if (isa<Constant>(V1->getValueOperand()) &&
10816         isa<Constant>(V2->getValueOperand()))
10817       return true;
10818     return V1->getValueOperand()->getValueID() ==
10819            V2->getValueOperand()->getValueID();
10820   };
10821   auto Limit = [&R, this](StoreInst *SI) {
10822     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10823     return R.getMinVF(EltSize);
10824   };
10825 
10826   // Attempt to sort and vectorize each of the store-groups.
10827   for (auto &Pair : Stores) {
10828     if (Pair.second.size() < 2)
10829       continue;
10830 
10831     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10832                       << Pair.second.size() << ".\n");
10833 
10834     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10835       continue;
10836 
10837     Changed |= tryToVectorizeSequence<StoreInst>(
10838         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10839         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10840           return vectorizeStores(Candidates, R);
10841         },
10842         /*LimitForRegisterSize=*/false);
10843   }
10844   return Changed;
10845 }
10846 
10847 char SLPVectorizer::ID = 0;
10848 
10849 static const char lv_name[] = "SLP Vectorizer";
10850 
10851 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10852 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10853 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10854 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10855 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10856 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10857 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10858 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10859 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10860 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10861 
10862 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10863