1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The Look-ahead heuristic goes through the users of the bundle to calculate
168 // the users cost in getExternalUsesCost(). To avoid compilation time increase
169 // we limit the number of users visited to this value.
170 static cl::opt<unsigned> LookAheadUsersBudget(
171     "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
172     cl::desc("The maximum number of users to visit while visiting the "
173              "predecessors. This prevents compilation time increase."));
174 
175 static cl::opt<bool>
176     ViewSLPTree("view-slp-tree", cl::Hidden,
177                 cl::desc("Display the SLP trees with Graphviz"));
178 
179 // Limit the number of alias checks. The limit is chosen so that
180 // it has no negative effect on the llvm benchmarks.
181 static const unsigned AliasedCheckLimit = 10;
182 
183 // Another limit for the alias checks: The maximum distance between load/store
184 // instructions where alias checks are done.
185 // This limit is useful for very large basic blocks.
186 static const unsigned MaxMemDepDistance = 160;
187 
188 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
189 /// regions to be handled.
190 static const int MinScheduleRegionSize = 16;
191 
192 /// Predicate for the element types that the SLP vectorizer supports.
193 ///
194 /// The most important thing to filter here are types which are invalid in LLVM
195 /// vectors. We also filter target specific types which have absolutely no
196 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
197 /// avoids spending time checking the cost model and realizing that they will
198 /// be inevitably scalarized.
199 static bool isValidElementType(Type *Ty) {
200   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
201          !Ty->isPPC_FP128Ty();
202 }
203 
204 /// \returns True if the value is a constant (but not globals/constant
205 /// expressions).
206 static bool isConstant(Value *V) {
207   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
208 }
209 
210 /// Checks if \p V is one of vector-like instructions, i.e. undef,
211 /// insertelement/extractelement with constant indices for fixed vector type or
212 /// extractvalue instruction.
213 static bool isVectorLikeInstWithConstOps(Value *V) {
214   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
215       !isa<ExtractValueInst, UndefValue>(V))
216     return false;
217   auto *I = dyn_cast<Instruction>(V);
218   if (!I || isa<ExtractValueInst>(I))
219     return true;
220   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
221     return false;
222   if (isa<ExtractElementInst>(I))
223     return isConstant(I->getOperand(1));
224   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
225   return isConstant(I->getOperand(2));
226 }
227 
228 /// \returns true if all of the instructions in \p VL are in the same block or
229 /// false otherwise.
230 static bool allSameBlock(ArrayRef<Value *> VL) {
231   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
232   if (!I0)
233     return false;
234   if (all_of(VL, isVectorLikeInstWithConstOps))
235     return true;
236 
237   BasicBlock *BB = I0->getParent();
238   for (int I = 1, E = VL.size(); I < E; I++) {
239     auto *II = dyn_cast<Instruction>(VL[I]);
240     if (!II)
241       return false;
242 
243     if (BB != II->getParent())
244       return false;
245   }
246   return true;
247 }
248 
249 /// \returns True if all of the values in \p VL are constants (but not
250 /// globals/constant expressions).
251 static bool allConstant(ArrayRef<Value *> VL) {
252   // Constant expressions and globals can't be vectorized like normal integer/FP
253   // constants.
254   return all_of(VL, isConstant);
255 }
256 
257 /// \returns True if all of the values in \p VL are identical or some of them
258 /// are UndefValue.
259 static bool isSplat(ArrayRef<Value *> VL) {
260   Value *FirstNonUndef = nullptr;
261   for (Value *V : VL) {
262     if (isa<UndefValue>(V))
263       continue;
264     if (!FirstNonUndef) {
265       FirstNonUndef = V;
266       continue;
267     }
268     if (V != FirstNonUndef)
269       return false;
270   }
271   return FirstNonUndef != nullptr;
272 }
273 
274 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
275 static bool isCommutative(Instruction *I) {
276   if (auto *Cmp = dyn_cast<CmpInst>(I))
277     return Cmp->isCommutative();
278   if (auto *BO = dyn_cast<BinaryOperator>(I))
279     return BO->isCommutative();
280   // TODO: This should check for generic Instruction::isCommutative(), but
281   //       we need to confirm that the caller code correctly handles Intrinsics
282   //       for example (does not have 2 operands).
283   return false;
284 }
285 
286 /// Checks if the given value is actually an undefined constant vector.
287 static bool isUndefVector(const Value *V) {
288   if (isa<UndefValue>(V))
289     return true;
290   auto *C = dyn_cast<Constant>(V);
291   if (!C)
292     return false;
293   if (!C->containsUndefOrPoisonElement())
294     return false;
295   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
296   if (!VecTy)
297     return false;
298   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
299     if (Constant *Elem = C->getAggregateElement(I))
300       if (!isa<UndefValue>(Elem))
301         return false;
302   }
303   return true;
304 }
305 
306 /// Checks if the vector of instructions can be represented as a shuffle, like:
307 /// %x0 = extractelement <4 x i8> %x, i32 0
308 /// %x3 = extractelement <4 x i8> %x, i32 3
309 /// %y1 = extractelement <4 x i8> %y, i32 1
310 /// %y2 = extractelement <4 x i8> %y, i32 2
311 /// %x0x0 = mul i8 %x0, %x0
312 /// %x3x3 = mul i8 %x3, %x3
313 /// %y1y1 = mul i8 %y1, %y1
314 /// %y2y2 = mul i8 %y2, %y2
315 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
316 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
317 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
318 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
319 /// ret <4 x i8> %ins4
320 /// can be transformed into:
321 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
322 ///                                                         i32 6>
323 /// %2 = mul <4 x i8> %1, %1
324 /// ret <4 x i8> %2
325 /// We convert this initially to something like:
326 /// %x0 = extractelement <4 x i8> %x, i32 0
327 /// %x3 = extractelement <4 x i8> %x, i32 3
328 /// %y1 = extractelement <4 x i8> %y, i32 1
329 /// %y2 = extractelement <4 x i8> %y, i32 2
330 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
331 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
332 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
333 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
334 /// %5 = mul <4 x i8> %4, %4
335 /// %6 = extractelement <4 x i8> %5, i32 0
336 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
337 /// %7 = extractelement <4 x i8> %5, i32 1
338 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
339 /// %8 = extractelement <4 x i8> %5, i32 2
340 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
341 /// %9 = extractelement <4 x i8> %5, i32 3
342 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
343 /// ret <4 x i8> %ins4
344 /// InstCombiner transforms this into a shuffle and vector mul
345 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
346 /// TODO: Can we split off and reuse the shuffle mask detection from
347 /// TargetTransformInfo::getInstructionThroughput?
348 static Optional<TargetTransformInfo::ShuffleKind>
349 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
350   const auto *It =
351       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
352   if (It == VL.end())
353     return None;
354   auto *EI0 = cast<ExtractElementInst>(*It);
355   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
356     return None;
357   unsigned Size =
358       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
359   Value *Vec1 = nullptr;
360   Value *Vec2 = nullptr;
361   enum ShuffleMode { Unknown, Select, Permute };
362   ShuffleMode CommonShuffleMode = Unknown;
363   Mask.assign(VL.size(), UndefMaskElem);
364   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
365     // Undef can be represented as an undef element in a vector.
366     if (isa<UndefValue>(VL[I]))
367       continue;
368     auto *EI = cast<ExtractElementInst>(VL[I]);
369     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
370       return None;
371     auto *Vec = EI->getVectorOperand();
372     // We can extractelement from undef or poison vector.
373     if (isUndefVector(Vec))
374       continue;
375     // All vector operands must have the same number of vector elements.
376     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
377       return None;
378     if (isa<UndefValue>(EI->getIndexOperand()))
379       continue;
380     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
381     if (!Idx)
382       return None;
383     // Undefined behavior if Idx is negative or >= Size.
384     if (Idx->getValue().uge(Size))
385       continue;
386     unsigned IntIdx = Idx->getValue().getZExtValue();
387     Mask[I] = IntIdx;
388     // For correct shuffling we have to have at most 2 different vector operands
389     // in all extractelement instructions.
390     if (!Vec1 || Vec1 == Vec) {
391       Vec1 = Vec;
392     } else if (!Vec2 || Vec2 == Vec) {
393       Vec2 = Vec;
394       Mask[I] += Size;
395     } else {
396       return None;
397     }
398     if (CommonShuffleMode == Permute)
399       continue;
400     // If the extract index is not the same as the operation number, it is a
401     // permutation.
402     if (IntIdx != I) {
403       CommonShuffleMode = Permute;
404       continue;
405     }
406     CommonShuffleMode = Select;
407   }
408   // If we're not crossing lanes in different vectors, consider it as blending.
409   if (CommonShuffleMode == Select && Vec2)
410     return TargetTransformInfo::SK_Select;
411   // If Vec2 was never used, we have a permutation of a single vector, otherwise
412   // we have permutation of 2 vectors.
413   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
414               : TargetTransformInfo::SK_PermuteSingleSrc;
415 }
416 
417 namespace {
418 
419 /// Main data required for vectorization of instructions.
420 struct InstructionsState {
421   /// The very first instruction in the list with the main opcode.
422   Value *OpValue = nullptr;
423 
424   /// The main/alternate instruction.
425   Instruction *MainOp = nullptr;
426   Instruction *AltOp = nullptr;
427 
428   /// The main/alternate opcodes for the list of instructions.
429   unsigned getOpcode() const {
430     return MainOp ? MainOp->getOpcode() : 0;
431   }
432 
433   unsigned getAltOpcode() const {
434     return AltOp ? AltOp->getOpcode() : 0;
435   }
436 
437   /// Some of the instructions in the list have alternate opcodes.
438   bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
439 
440   bool isOpcodeOrAlt(Instruction *I) const {
441     unsigned CheckedOpcode = I->getOpcode();
442     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
443   }
444 
445   InstructionsState() = delete;
446   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
447       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
448 };
449 
450 } // end anonymous namespace
451 
452 /// Chooses the correct key for scheduling data. If \p Op has the same (or
453 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
454 /// OpValue.
455 static Value *isOneOf(const InstructionsState &S, Value *Op) {
456   auto *I = dyn_cast<Instruction>(Op);
457   if (I && S.isOpcodeOrAlt(I))
458     return Op;
459   return S.OpValue;
460 }
461 
462 /// \returns true if \p Opcode is allowed as part of of the main/alternate
463 /// instruction for SLP vectorization.
464 ///
465 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
466 /// "shuffled out" lane would result in division by zero.
467 static bool isValidForAlternation(unsigned Opcode) {
468   if (Instruction::isIntDivRem(Opcode))
469     return false;
470 
471   return true;
472 }
473 
474 /// \returns analysis of the Instructions in \p VL described in
475 /// InstructionsState, the Opcode that we suppose the whole list
476 /// could be vectorized even if its structure is diverse.
477 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
478                                        unsigned BaseIndex = 0) {
479   // Make sure these are all Instructions.
480   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
481     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
482 
483   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
484   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
485   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
486   unsigned AltOpcode = Opcode;
487   unsigned AltIndex = BaseIndex;
488 
489   // Check for one alternate opcode from another BinaryOperator.
490   // TODO - generalize to support all operators (types, calls etc.).
491   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
492     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
493     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
494       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
495         continue;
496       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
497           isValidForAlternation(Opcode)) {
498         AltOpcode = InstOpcode;
499         AltIndex = Cnt;
500         continue;
501       }
502     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
503       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
504       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
505       if (Ty0 == Ty1) {
506         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
507           continue;
508         if (Opcode == AltOpcode) {
509           assert(isValidForAlternation(Opcode) &&
510                  isValidForAlternation(InstOpcode) &&
511                  "Cast isn't safe for alternation, logic needs to be updated!");
512           AltOpcode = InstOpcode;
513           AltIndex = Cnt;
514           continue;
515         }
516       }
517     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518       continue;
519     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
520   }
521 
522   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
523                            cast<Instruction>(VL[AltIndex]));
524 }
525 
526 /// \returns true if all of the values in \p VL have the same type or false
527 /// otherwise.
528 static bool allSameType(ArrayRef<Value *> VL) {
529   Type *Ty = VL[0]->getType();
530   for (int i = 1, e = VL.size(); i < e; i++)
531     if (VL[i]->getType() != Ty)
532       return false;
533 
534   return true;
535 }
536 
537 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
538 static Optional<unsigned> getExtractIndex(Instruction *E) {
539   unsigned Opcode = E->getOpcode();
540   assert((Opcode == Instruction::ExtractElement ||
541           Opcode == Instruction::ExtractValue) &&
542          "Expected extractelement or extractvalue instruction.");
543   if (Opcode == Instruction::ExtractElement) {
544     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
545     if (!CI)
546       return None;
547     return CI->getZExtValue();
548   }
549   ExtractValueInst *EI = cast<ExtractValueInst>(E);
550   if (EI->getNumIndices() != 1)
551     return None;
552   return *EI->idx_begin();
553 }
554 
555 /// \returns True if in-tree use also needs extract. This refers to
556 /// possible scalar operand in vectorized instruction.
557 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
558                                     TargetLibraryInfo *TLI) {
559   unsigned Opcode = UserInst->getOpcode();
560   switch (Opcode) {
561   case Instruction::Load: {
562     LoadInst *LI = cast<LoadInst>(UserInst);
563     return (LI->getPointerOperand() == Scalar);
564   }
565   case Instruction::Store: {
566     StoreInst *SI = cast<StoreInst>(UserInst);
567     return (SI->getPointerOperand() == Scalar);
568   }
569   case Instruction::Call: {
570     CallInst *CI = cast<CallInst>(UserInst);
571     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
572     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
573       if (hasVectorInstrinsicScalarOpd(ID, i))
574         return (CI->getArgOperand(i) == Scalar);
575     }
576     LLVM_FALLTHROUGH;
577   }
578   default:
579     return false;
580   }
581 }
582 
583 /// \returns the AA location that is being access by the instruction.
584 static MemoryLocation getLocation(Instruction *I, AAResults *AA) {
585   if (StoreInst *SI = dyn_cast<StoreInst>(I))
586     return MemoryLocation::get(SI);
587   if (LoadInst *LI = dyn_cast<LoadInst>(I))
588     return MemoryLocation::get(LI);
589   return MemoryLocation();
590 }
591 
592 /// \returns True if the instruction is not a volatile or atomic load/store.
593 static bool isSimple(Instruction *I) {
594   if (LoadInst *LI = dyn_cast<LoadInst>(I))
595     return LI->isSimple();
596   if (StoreInst *SI = dyn_cast<StoreInst>(I))
597     return SI->isSimple();
598   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
599     return !MI->isVolatile();
600   return true;
601 }
602 
603 /// Shuffles \p Mask in accordance with the given \p SubMask.
604 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
605   if (SubMask.empty())
606     return;
607   if (Mask.empty()) {
608     Mask.append(SubMask.begin(), SubMask.end());
609     return;
610   }
611   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
612   int TermValue = std::min(Mask.size(), SubMask.size());
613   for (int I = 0, E = SubMask.size(); I < E; ++I) {
614     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
615         Mask[SubMask[I]] >= TermValue)
616       continue;
617     NewMask[I] = Mask[SubMask[I]];
618   }
619   Mask.swap(NewMask);
620 }
621 
622 /// Order may have elements assigned special value (size) which is out of
623 /// bounds. Such indices only appear on places which correspond to undef values
624 /// (see canReuseExtract for details) and used in order to avoid undef values
625 /// have effect on operands ordering.
626 /// The first loop below simply finds all unused indices and then the next loop
627 /// nest assigns these indices for undef values positions.
628 /// As an example below Order has two undef positions and they have assigned
629 /// values 3 and 7 respectively:
630 /// before:  6 9 5 4 9 2 1 0
631 /// after:   6 3 5 4 7 2 1 0
632 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
633   const unsigned Sz = Order.size();
634   SmallBitVector UsedIndices(Sz);
635   SmallVector<int> MaskedIndices;
636   for (unsigned I = 0; I < Sz; ++I) {
637     if (Order[I] < Sz)
638       UsedIndices.set(Order[I]);
639     else
640       MaskedIndices.push_back(I);
641   }
642   if (MaskedIndices.empty())
643     return;
644   SmallVector<int> AvailableIndices(MaskedIndices.size());
645   unsigned Cnt = 0;
646   int Idx = UsedIndices.find_first();
647   do {
648     AvailableIndices[Cnt] = Idx;
649     Idx = UsedIndices.find_next(Idx);
650     ++Cnt;
651   } while (Idx > 0);
652   assert(Cnt == MaskedIndices.size() && "Non-synced masked/available indices.");
653   for (int I = 0, E = MaskedIndices.size(); I < E; ++I)
654     Order[MaskedIndices[I]] = AvailableIndices[I];
655 }
656 
657 namespace llvm {
658 
659 static void inversePermutation(ArrayRef<unsigned> Indices,
660                                SmallVectorImpl<int> &Mask) {
661   Mask.clear();
662   const unsigned E = Indices.size();
663   Mask.resize(E, UndefMaskElem);
664   for (unsigned I = 0; I < E; ++I)
665     Mask[Indices[I]] = I;
666 }
667 
668 /// \returns inserting index of InsertElement or InsertValue instruction,
669 /// using Offset as base offset for index.
670 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
671   int Index = Offset;
672   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
673     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
674       auto *VT = cast<FixedVectorType>(IE->getType());
675       if (CI->getValue().uge(VT->getNumElements()))
676         return UndefMaskElem;
677       Index *= VT->getNumElements();
678       Index += CI->getZExtValue();
679       return Index;
680     }
681     if (isa<UndefValue>(IE->getOperand(2)))
682       return UndefMaskElem;
683     return None;
684   }
685 
686   auto *IV = cast<InsertValueInst>(InsertInst);
687   Type *CurrentType = IV->getType();
688   for (unsigned I : IV->indices()) {
689     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
690       Index *= ST->getNumElements();
691       CurrentType = ST->getElementType(I);
692     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
693       Index *= AT->getNumElements();
694       CurrentType = AT->getElementType();
695     } else {
696       return None;
697     }
698     Index += I;
699   }
700   return Index;
701 }
702 
703 /// Reorders the list of scalars in accordance with the given \p Order and then
704 /// the \p Mask. \p Order - is the original order of the scalars, need to
705 /// reorder scalars into an unordered state at first according to the given
706 /// order. Then the ordered scalars are shuffled once again in accordance with
707 /// the provided mask.
708 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
709                            ArrayRef<int> Mask) {
710   assert(!Mask.empty() && "Expected non-empty mask.");
711   SmallVector<Value *> Prev(Scalars.size(),
712                             UndefValue::get(Scalars.front()->getType()));
713   Prev.swap(Scalars);
714   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
715     if (Mask[I] != UndefMaskElem)
716       Scalars[Mask[I]] = Prev[I];
717 }
718 
719 namespace slpvectorizer {
720 
721 /// Bottom Up SLP Vectorizer.
722 class BoUpSLP {
723   struct TreeEntry;
724   struct ScheduleData;
725 
726 public:
727   using ValueList = SmallVector<Value *, 8>;
728   using InstrList = SmallVector<Instruction *, 16>;
729   using ValueSet = SmallPtrSet<Value *, 16>;
730   using StoreList = SmallVector<StoreInst *, 8>;
731   using ExtraValueToDebugLocsMap =
732       MapVector<Value *, SmallVector<Instruction *, 2>>;
733   using OrdersType = SmallVector<unsigned, 4>;
734 
735   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
736           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
737           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
738           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
739       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
740         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
741     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
742     // Use the vector register size specified by the target unless overridden
743     // by a command-line option.
744     // TODO: It would be better to limit the vectorization factor based on
745     //       data type rather than just register size. For example, x86 AVX has
746     //       256-bit registers, but it does not support integer operations
747     //       at that width (that requires AVX2).
748     if (MaxVectorRegSizeOption.getNumOccurrences())
749       MaxVecRegSize = MaxVectorRegSizeOption;
750     else
751       MaxVecRegSize =
752           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
753               .getFixedSize();
754 
755     if (MinVectorRegSizeOption.getNumOccurrences())
756       MinVecRegSize = MinVectorRegSizeOption;
757     else
758       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
759   }
760 
761   /// Vectorize the tree that starts with the elements in \p VL.
762   /// Returns the vectorized root.
763   Value *vectorizeTree();
764 
765   /// Vectorize the tree but with the list of externally used values \p
766   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
767   /// generated extractvalue instructions.
768   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
769 
770   /// \returns the cost incurred by unwanted spills and fills, caused by
771   /// holding live values over call sites.
772   InstructionCost getSpillCost() const;
773 
774   /// \returns the vectorization cost of the subtree that starts at \p VL.
775   /// A negative number means that this is profitable.
776   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
777 
778   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
779   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
780   void buildTree(ArrayRef<Value *> Roots,
781                  ArrayRef<Value *> UserIgnoreLst = None);
782 
783   /// Builds external uses of the vectorized scalars, i.e. the list of
784   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
785   /// ExternallyUsedValues contains additional list of external uses to handle
786   /// vectorization of reductions.
787   void
788   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
789 
790   /// Clear the internal data structures that are created by 'buildTree'.
791   void deleteTree() {
792     VectorizableTree.clear();
793     ScalarToTreeEntry.clear();
794     MustGather.clear();
795     ExternalUses.clear();
796     for (auto &Iter : BlocksSchedules) {
797       BlockScheduling *BS = Iter.second.get();
798       BS->clear();
799     }
800     MinBWs.clear();
801     InstrElementSize.clear();
802   }
803 
804   unsigned getTreeSize() const { return VectorizableTree.size(); }
805 
806   /// Perform LICM and CSE on the newly generated gather sequences.
807   void optimizeGatherSequence();
808 
809   /// Checks if the specified gather tree entry \p TE can be represented as a
810   /// shuffled vector entry + (possibly) permutation with other gathers. It
811   /// implements the checks only for possibly ordered scalars (Loads,
812   /// ExtractElement, ExtractValue), which can be part of the graph.
813   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
814 
815   /// Reorders the current graph to the most profitable order starting from the
816   /// root node to the leaf nodes. The best order is chosen only from the nodes
817   /// of the same size (vectorization factor). Smaller nodes are considered
818   /// parts of subgraph with smaller VF and they are reordered independently. We
819   /// can make it because we still need to extend smaller nodes to the wider VF
820   /// and we can merge reordering shuffles with the widening shuffles.
821   void reorderTopToBottom();
822 
823   /// Reorders the current graph to the most profitable order starting from
824   /// leaves to the root. It allows to rotate small subgraphs and reduce the
825   /// number of reshuffles if the leaf nodes use the same order. In this case we
826   /// can merge the orders and just shuffle user node instead of shuffling its
827   /// operands. Plus, even the leaf nodes have different orders, it allows to
828   /// sink reordering in the graph closer to the root node and merge it later
829   /// during analysis.
830   void reorderBottomToTop(bool IgnoreReorder = false);
831 
832   /// \return The vector element size in bits to use when vectorizing the
833   /// expression tree ending at \p V. If V is a store, the size is the width of
834   /// the stored value. Otherwise, the size is the width of the largest loaded
835   /// value reaching V. This method is used by the vectorizer to calculate
836   /// vectorization factors.
837   unsigned getVectorElementSize(Value *V);
838 
839   /// Compute the minimum type sizes required to represent the entries in a
840   /// vectorizable tree.
841   void computeMinimumValueSizes();
842 
843   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
844   unsigned getMaxVecRegSize() const {
845     return MaxVecRegSize;
846   }
847 
848   // \returns minimum vector register size as set by cl::opt.
849   unsigned getMinVecRegSize() const {
850     return MinVecRegSize;
851   }
852 
853   unsigned getMinVF(unsigned Sz) const {
854     return std::max(2U, getMinVecRegSize() / Sz);
855   }
856 
857   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
858     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
859       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
860     return MaxVF ? MaxVF : UINT_MAX;
861   }
862 
863   /// Check if homogeneous aggregate is isomorphic to some VectorType.
864   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
865   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
866   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
867   ///
868   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
869   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
870 
871   /// \returns True if the VectorizableTree is both tiny and not fully
872   /// vectorizable. We do not vectorize such trees.
873   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
874 
875   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
876   /// can be load combined in the backend. Load combining may not be allowed in
877   /// the IR optimizer, so we do not want to alter the pattern. For example,
878   /// partially transforming a scalar bswap() pattern into vector code is
879   /// effectively impossible for the backend to undo.
880   /// TODO: If load combining is allowed in the IR optimizer, this analysis
881   ///       may not be necessary.
882   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
883 
884   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
885   /// can be load combined in the backend. Load combining may not be allowed in
886   /// the IR optimizer, so we do not want to alter the pattern. For example,
887   /// partially transforming a scalar bswap() pattern into vector code is
888   /// effectively impossible for the backend to undo.
889   /// TODO: If load combining is allowed in the IR optimizer, this analysis
890   ///       may not be necessary.
891   bool isLoadCombineCandidate() const;
892 
893   OptimizationRemarkEmitter *getORE() { return ORE; }
894 
895   /// This structure holds any data we need about the edges being traversed
896   /// during buildTree_rec(). We keep track of:
897   /// (i) the user TreeEntry index, and
898   /// (ii) the index of the edge.
899   struct EdgeInfo {
900     EdgeInfo() = default;
901     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
902         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
903     /// The user TreeEntry.
904     TreeEntry *UserTE = nullptr;
905     /// The operand index of the use.
906     unsigned EdgeIdx = UINT_MAX;
907 #ifndef NDEBUG
908     friend inline raw_ostream &operator<<(raw_ostream &OS,
909                                           const BoUpSLP::EdgeInfo &EI) {
910       EI.dump(OS);
911       return OS;
912     }
913     /// Debug print.
914     void dump(raw_ostream &OS) const {
915       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
916          << " EdgeIdx:" << EdgeIdx << "}";
917     }
918     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
919 #endif
920   };
921 
922   /// A helper data structure to hold the operands of a vector of instructions.
923   /// This supports a fixed vector length for all operand vectors.
924   class VLOperands {
925     /// For each operand we need (i) the value, and (ii) the opcode that it
926     /// would be attached to if the expression was in a left-linearized form.
927     /// This is required to avoid illegal operand reordering.
928     /// For example:
929     /// \verbatim
930     ///                         0 Op1
931     ///                         |/
932     /// Op1 Op2   Linearized    + Op2
933     ///   \ /     ---------->   |/
934     ///    -                    -
935     ///
936     /// Op1 - Op2            (0 + Op1) - Op2
937     /// \endverbatim
938     ///
939     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
940     ///
941     /// Another way to think of this is to track all the operations across the
942     /// path from the operand all the way to the root of the tree and to
943     /// calculate the operation that corresponds to this path. For example, the
944     /// path from Op2 to the root crosses the RHS of the '-', therefore the
945     /// corresponding operation is a '-' (which matches the one in the
946     /// linearized tree, as shown above).
947     ///
948     /// For lack of a better term, we refer to this operation as Accumulated
949     /// Path Operation (APO).
950     struct OperandData {
951       OperandData() = default;
952       OperandData(Value *V, bool APO, bool IsUsed)
953           : V(V), APO(APO), IsUsed(IsUsed) {}
954       /// The operand value.
955       Value *V = nullptr;
956       /// TreeEntries only allow a single opcode, or an alternate sequence of
957       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
958       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
959       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
960       /// (e.g., Add/Mul)
961       bool APO = false;
962       /// Helper data for the reordering function.
963       bool IsUsed = false;
964     };
965 
966     /// During operand reordering, we are trying to select the operand at lane
967     /// that matches best with the operand at the neighboring lane. Our
968     /// selection is based on the type of value we are looking for. For example,
969     /// if the neighboring lane has a load, we need to look for a load that is
970     /// accessing a consecutive address. These strategies are summarized in the
971     /// 'ReorderingMode' enumerator.
972     enum class ReorderingMode {
973       Load,     ///< Matching loads to consecutive memory addresses
974       Opcode,   ///< Matching instructions based on opcode (same or alternate)
975       Constant, ///< Matching constants
976       Splat,    ///< Matching the same instruction multiple times (broadcast)
977       Failed,   ///< We failed to create a vectorizable group
978     };
979 
980     using OperandDataVec = SmallVector<OperandData, 2>;
981 
982     /// A vector of operand vectors.
983     SmallVector<OperandDataVec, 4> OpsVec;
984 
985     const DataLayout &DL;
986     ScalarEvolution &SE;
987     const BoUpSLP &R;
988 
989     /// \returns the operand data at \p OpIdx and \p Lane.
990     OperandData &getData(unsigned OpIdx, unsigned Lane) {
991       return OpsVec[OpIdx][Lane];
992     }
993 
994     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
995     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
996       return OpsVec[OpIdx][Lane];
997     }
998 
999     /// Clears the used flag for all entries.
1000     void clearUsed() {
1001       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1002            OpIdx != NumOperands; ++OpIdx)
1003         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1004              ++Lane)
1005           OpsVec[OpIdx][Lane].IsUsed = false;
1006     }
1007 
1008     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1009     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1010       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1011     }
1012 
1013     // The hard-coded scores listed here are not very important. When computing
1014     // the scores of matching one sub-tree with another, we are basically
1015     // counting the number of values that are matching. So even if all scores
1016     // are set to 1, we would still get a decent matching result.
1017     // However, sometimes we have to break ties. For example we may have to
1018     // choose between matching loads vs matching opcodes. This is what these
1019     // scores are helping us with: they provide the order of preference.
1020 
1021     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1022     static const int ScoreConsecutiveLoads = 3;
1023     /// ExtractElementInst from same vector and consecutive indexes.
1024     static const int ScoreConsecutiveExtracts = 3;
1025     /// Constants.
1026     static const int ScoreConstants = 2;
1027     /// Instructions with the same opcode.
1028     static const int ScoreSameOpcode = 2;
1029     /// Instructions with alt opcodes (e.g, add + sub).
1030     static const int ScoreAltOpcodes = 1;
1031     /// Identical instructions (a.k.a. splat or broadcast).
1032     static const int ScoreSplat = 1;
1033     /// Matching with an undef is preferable to failing.
1034     static const int ScoreUndef = 1;
1035     /// Score for failing to find a decent match.
1036     static const int ScoreFail = 0;
1037     /// User exteranl to the vectorized code.
1038     static const int ExternalUseCost = 1;
1039     /// The user is internal but in a different lane.
1040     static const int UserInDiffLaneCost = ExternalUseCost;
1041 
1042     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1043     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1044                                ScalarEvolution &SE) {
1045       auto *LI1 = dyn_cast<LoadInst>(V1);
1046       auto *LI2 = dyn_cast<LoadInst>(V2);
1047       if (LI1 && LI2) {
1048         if (LI1->getParent() != LI2->getParent())
1049           return VLOperands::ScoreFail;
1050 
1051         Optional<int> Dist = getPointersDiff(
1052             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1053             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1054         return (Dist && *Dist == 1) ? VLOperands::ScoreConsecutiveLoads
1055                                     : VLOperands::ScoreFail;
1056       }
1057 
1058       auto *C1 = dyn_cast<Constant>(V1);
1059       auto *C2 = dyn_cast<Constant>(V2);
1060       if (C1 && C2)
1061         return VLOperands::ScoreConstants;
1062 
1063       // Extracts from consecutive indexes of the same vector better score as
1064       // the extracts could be optimized away.
1065       Value *EV;
1066       ConstantInt *Ex1Idx, *Ex2Idx;
1067       if (match(V1, m_ExtractElt(m_Value(EV), m_ConstantInt(Ex1Idx))) &&
1068           match(V2, m_ExtractElt(m_Deferred(EV), m_ConstantInt(Ex2Idx))) &&
1069           Ex1Idx->getZExtValue() + 1 == Ex2Idx->getZExtValue())
1070         return VLOperands::ScoreConsecutiveExtracts;
1071 
1072       auto *I1 = dyn_cast<Instruction>(V1);
1073       auto *I2 = dyn_cast<Instruction>(V2);
1074       if (I1 && I2) {
1075         if (I1 == I2)
1076           return VLOperands::ScoreSplat;
1077         InstructionsState S = getSameOpcode({I1, I2});
1078         // Note: Only consider instructions with <= 2 operands to avoid
1079         // complexity explosion.
1080         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1081           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1082                                   : VLOperands::ScoreSameOpcode;
1083       }
1084 
1085       if (isa<UndefValue>(V2))
1086         return VLOperands::ScoreUndef;
1087 
1088       return VLOperands::ScoreFail;
1089     }
1090 
1091     /// Holds the values and their lane that are taking part in the look-ahead
1092     /// score calculation. This is used in the external uses cost calculation.
1093     SmallDenseMap<Value *, int> InLookAheadValues;
1094 
1095     /// \Returns the additinal cost due to uses of \p LHS and \p RHS that are
1096     /// either external to the vectorized code, or require shuffling.
1097     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1098                             const std::pair<Value *, int> &RHS) {
1099       int Cost = 0;
1100       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1101       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1102         Value *V = Values[Idx].first;
1103         if (isa<Constant>(V)) {
1104           // Since this is a function pass, it doesn't make semantic sense to
1105           // walk the users of a subclass of Constant. The users could be in
1106           // another function, or even another module that happens to be in
1107           // the same LLVMContext.
1108           continue;
1109         }
1110 
1111         // Calculate the absolute lane, using the minimum relative lane of LHS
1112         // and RHS as base and Idx as the offset.
1113         int Ln = std::min(LHS.second, RHS.second) + Idx;
1114         assert(Ln >= 0 && "Bad lane calculation");
1115         unsigned UsersBudget = LookAheadUsersBudget;
1116         for (User *U : V->users()) {
1117           if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1118             // The user is in the VectorizableTree. Check if we need to insert.
1119             auto It = llvm::find(UserTE->Scalars, U);
1120             assert(It != UserTE->Scalars.end() && "U is in UserTE");
1121             int UserLn = std::distance(UserTE->Scalars.begin(), It);
1122             assert(UserLn >= 0 && "Bad lane");
1123             if (UserLn != Ln)
1124               Cost += UserInDiffLaneCost;
1125           } else {
1126             // Check if the user is in the look-ahead code.
1127             auto It2 = InLookAheadValues.find(U);
1128             if (It2 != InLookAheadValues.end()) {
1129               // The user is in the look-ahead code. Check the lane.
1130               if (It2->second != Ln)
1131                 Cost += UserInDiffLaneCost;
1132             } else {
1133               // The user is neither in SLP tree nor in the look-ahead code.
1134               Cost += ExternalUseCost;
1135             }
1136           }
1137           // Limit the number of visited uses to cap compilation time.
1138           if (--UsersBudget == 0)
1139             break;
1140         }
1141       }
1142       return Cost;
1143     }
1144 
1145     /// Go through the operands of \p LHS and \p RHS recursively until \p
1146     /// MaxLevel, and return the cummulative score. For example:
1147     /// \verbatim
1148     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1149     ///     \ /         \ /         \ /        \ /
1150     ///      +           +           +          +
1151     ///     G1          G2          G3         G4
1152     /// \endverbatim
1153     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1154     /// each level recursively, accumulating the score. It starts from matching
1155     /// the additions at level 0, then moves on to the loads (level 1). The
1156     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1157     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1158     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1159     /// Please note that the order of the operands does not matter, as we
1160     /// evaluate the score of all profitable combinations of operands. In
1161     /// other words the score of G1 and G4 is the same as G1 and G2. This
1162     /// heuristic is based on ideas described in:
1163     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1164     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1165     ///   Luís F. W. Góes
1166     int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1167                            const std::pair<Value *, int> &RHS, int CurrLevel,
1168                            int MaxLevel) {
1169 
1170       Value *V1 = LHS.first;
1171       Value *V2 = RHS.first;
1172       // Get the shallow score of V1 and V2.
1173       int ShallowScoreAtThisLevel =
1174           std::max((int)ScoreFail, getShallowScore(V1, V2, DL, SE) -
1175                                        getExternalUsesCost(LHS, RHS));
1176       int Lane1 = LHS.second;
1177       int Lane2 = RHS.second;
1178 
1179       // If reached MaxLevel,
1180       //  or if V1 and V2 are not instructions,
1181       //  or if they are SPLAT,
1182       //  or if they are not consecutive, early return the current cost.
1183       auto *I1 = dyn_cast<Instruction>(V1);
1184       auto *I2 = dyn_cast<Instruction>(V2);
1185       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1186           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1187           (isa<LoadInst>(I1) && isa<LoadInst>(I2) && ShallowScoreAtThisLevel))
1188         return ShallowScoreAtThisLevel;
1189       assert(I1 && I2 && "Should have early exited.");
1190 
1191       // Keep track of in-tree values for determining the external-use cost.
1192       InLookAheadValues[V1] = Lane1;
1193       InLookAheadValues[V2] = Lane2;
1194 
1195       // Contains the I2 operand indexes that got matched with I1 operands.
1196       SmallSet<unsigned, 4> Op2Used;
1197 
1198       // Recursion towards the operands of I1 and I2. We are trying all possbile
1199       // operand pairs, and keeping track of the best score.
1200       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1201            OpIdx1 != NumOperands1; ++OpIdx1) {
1202         // Try to pair op1I with the best operand of I2.
1203         int MaxTmpScore = 0;
1204         unsigned MaxOpIdx2 = 0;
1205         bool FoundBest = false;
1206         // If I2 is commutative try all combinations.
1207         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1208         unsigned ToIdx = isCommutative(I2)
1209                              ? I2->getNumOperands()
1210                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1211         assert(FromIdx <= ToIdx && "Bad index");
1212         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1213           // Skip operands already paired with OpIdx1.
1214           if (Op2Used.count(OpIdx2))
1215             continue;
1216           // Recursively calculate the cost at each level
1217           int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1218                                             {I2->getOperand(OpIdx2), Lane2},
1219                                             CurrLevel + 1, MaxLevel);
1220           // Look for the best score.
1221           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1222             MaxTmpScore = TmpScore;
1223             MaxOpIdx2 = OpIdx2;
1224             FoundBest = true;
1225           }
1226         }
1227         if (FoundBest) {
1228           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1229           Op2Used.insert(MaxOpIdx2);
1230           ShallowScoreAtThisLevel += MaxTmpScore;
1231         }
1232       }
1233       return ShallowScoreAtThisLevel;
1234     }
1235 
1236     /// \Returns the look-ahead score, which tells us how much the sub-trees
1237     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1238     /// score. This helps break ties in an informed way when we cannot decide on
1239     /// the order of the operands by just considering the immediate
1240     /// predecessors.
1241     int getLookAheadScore(const std::pair<Value *, int> &LHS,
1242                           const std::pair<Value *, int> &RHS) {
1243       InLookAheadValues.clear();
1244       return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1245     }
1246 
1247     // Search all operands in Ops[*][Lane] for the one that matches best
1248     // Ops[OpIdx][LastLane] and return its opreand index.
1249     // If no good match can be found, return None.
1250     Optional<unsigned>
1251     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1252                    ArrayRef<ReorderingMode> ReorderingModes) {
1253       unsigned NumOperands = getNumOperands();
1254 
1255       // The operand of the previous lane at OpIdx.
1256       Value *OpLastLane = getData(OpIdx, LastLane).V;
1257 
1258       // Our strategy mode for OpIdx.
1259       ReorderingMode RMode = ReorderingModes[OpIdx];
1260 
1261       // The linearized opcode of the operand at OpIdx, Lane.
1262       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1263 
1264       // The best operand index and its score.
1265       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1266       // are using the score to differentiate between the two.
1267       struct BestOpData {
1268         Optional<unsigned> Idx = None;
1269         unsigned Score = 0;
1270       } BestOp;
1271 
1272       // Iterate through all unused operands and look for the best.
1273       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1274         // Get the operand at Idx and Lane.
1275         OperandData &OpData = getData(Idx, Lane);
1276         Value *Op = OpData.V;
1277         bool OpAPO = OpData.APO;
1278 
1279         // Skip already selected operands.
1280         if (OpData.IsUsed)
1281           continue;
1282 
1283         // Skip if we are trying to move the operand to a position with a
1284         // different opcode in the linearized tree form. This would break the
1285         // semantics.
1286         if (OpAPO != OpIdxAPO)
1287           continue;
1288 
1289         // Look for an operand that matches the current mode.
1290         switch (RMode) {
1291         case ReorderingMode::Load:
1292         case ReorderingMode::Constant:
1293         case ReorderingMode::Opcode: {
1294           bool LeftToRight = Lane > LastLane;
1295           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1296           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1297           unsigned Score =
1298               getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1299           if (Score > BestOp.Score) {
1300             BestOp.Idx = Idx;
1301             BestOp.Score = Score;
1302           }
1303           break;
1304         }
1305         case ReorderingMode::Splat:
1306           if (Op == OpLastLane)
1307             BestOp.Idx = Idx;
1308           break;
1309         case ReorderingMode::Failed:
1310           return None;
1311         }
1312       }
1313 
1314       if (BestOp.Idx) {
1315         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1316         return BestOp.Idx;
1317       }
1318       // If we could not find a good match return None.
1319       return None;
1320     }
1321 
1322     /// Helper for reorderOperandVecs. \Returns the lane that we should start
1323     /// reordering from. This is the one which has the least number of operands
1324     /// that can freely move about.
1325     unsigned getBestLaneToStartReordering() const {
1326       unsigned BestLane = 0;
1327       unsigned Min = UINT_MAX;
1328       for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1329            ++Lane) {
1330         unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane);
1331         if (NumFreeOps < Min) {
1332           Min = NumFreeOps;
1333           BestLane = Lane;
1334         }
1335       }
1336       return BestLane;
1337     }
1338 
1339     /// \Returns the maximum number of operands that are allowed to be reordered
1340     /// for \p Lane. This is used as a heuristic for selecting the first lane to
1341     /// start operand reordering.
1342     unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1343       unsigned CntTrue = 0;
1344       unsigned NumOperands = getNumOperands();
1345       // Operands with the same APO can be reordered. We therefore need to count
1346       // how many of them we have for each APO, like this: Cnt[APO] = x.
1347       // Since we only have two APOs, namely true and false, we can avoid using
1348       // a map. Instead we can simply count the number of operands that
1349       // correspond to one of them (in this case the 'true' APO), and calculate
1350       // the other by subtracting it from the total number of operands.
1351       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx)
1352         if (getData(OpIdx, Lane).APO)
1353           ++CntTrue;
1354       unsigned CntFalse = NumOperands - CntTrue;
1355       return std::max(CntTrue, CntFalse);
1356     }
1357 
1358     /// Go through the instructions in VL and append their operands.
1359     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1360       assert(!VL.empty() && "Bad VL");
1361       assert((empty() || VL.size() == getNumLanes()) &&
1362              "Expected same number of lanes");
1363       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1364       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1365       OpsVec.resize(NumOperands);
1366       unsigned NumLanes = VL.size();
1367       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1368         OpsVec[OpIdx].resize(NumLanes);
1369         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1370           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1371           // Our tree has just 3 nodes: the root and two operands.
1372           // It is therefore trivial to get the APO. We only need to check the
1373           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1374           // RHS operand. The LHS operand of both add and sub is never attached
1375           // to an inversese operation in the linearized form, therefore its APO
1376           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1377 
1378           // Since operand reordering is performed on groups of commutative
1379           // operations or alternating sequences (e.g., +, -), we can safely
1380           // tell the inverse operations by checking commutativity.
1381           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1382           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1383           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1384                                  APO, false};
1385         }
1386       }
1387     }
1388 
1389     /// \returns the number of operands.
1390     unsigned getNumOperands() const { return OpsVec.size(); }
1391 
1392     /// \returns the number of lanes.
1393     unsigned getNumLanes() const { return OpsVec[0].size(); }
1394 
1395     /// \returns the operand value at \p OpIdx and \p Lane.
1396     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1397       return getData(OpIdx, Lane).V;
1398     }
1399 
1400     /// \returns true if the data structure is empty.
1401     bool empty() const { return OpsVec.empty(); }
1402 
1403     /// Clears the data.
1404     void clear() { OpsVec.clear(); }
1405 
1406     /// \Returns true if there are enough operands identical to \p Op to fill
1407     /// the whole vector.
1408     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1409     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1410       bool OpAPO = getData(OpIdx, Lane).APO;
1411       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1412         if (Ln == Lane)
1413           continue;
1414         // This is set to true if we found a candidate for broadcast at Lane.
1415         bool FoundCandidate = false;
1416         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1417           OperandData &Data = getData(OpI, Ln);
1418           if (Data.APO != OpAPO || Data.IsUsed)
1419             continue;
1420           if (Data.V == Op) {
1421             FoundCandidate = true;
1422             Data.IsUsed = true;
1423             break;
1424           }
1425         }
1426         if (!FoundCandidate)
1427           return false;
1428       }
1429       return true;
1430     }
1431 
1432   public:
1433     /// Initialize with all the operands of the instruction vector \p RootVL.
1434     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1435                ScalarEvolution &SE, const BoUpSLP &R)
1436         : DL(DL), SE(SE), R(R) {
1437       // Append all the operands of RootVL.
1438       appendOperandsOfVL(RootVL);
1439     }
1440 
1441     /// \Returns a value vector with the operands across all lanes for the
1442     /// opearnd at \p OpIdx.
1443     ValueList getVL(unsigned OpIdx) const {
1444       ValueList OpVL(OpsVec[OpIdx].size());
1445       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1446              "Expected same num of lanes across all operands");
1447       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1448         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1449       return OpVL;
1450     }
1451 
1452     // Performs operand reordering for 2 or more operands.
1453     // The original operands are in OrigOps[OpIdx][Lane].
1454     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1455     void reorder() {
1456       unsigned NumOperands = getNumOperands();
1457       unsigned NumLanes = getNumLanes();
1458       // Each operand has its own mode. We are using this mode to help us select
1459       // the instructions for each lane, so that they match best with the ones
1460       // we have selected so far.
1461       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1462 
1463       // This is a greedy single-pass algorithm. We are going over each lane
1464       // once and deciding on the best order right away with no back-tracking.
1465       // However, in order to increase its effectiveness, we start with the lane
1466       // that has operands that can move the least. For example, given the
1467       // following lanes:
1468       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1469       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1470       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1471       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1472       // we will start at Lane 1, since the operands of the subtraction cannot
1473       // be reordered. Then we will visit the rest of the lanes in a circular
1474       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1475 
1476       // Find the first lane that we will start our search from.
1477       unsigned FirstLane = getBestLaneToStartReordering();
1478 
1479       // Initialize the modes.
1480       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1481         Value *OpLane0 = getValue(OpIdx, FirstLane);
1482         // Keep track if we have instructions with all the same opcode on one
1483         // side.
1484         if (isa<LoadInst>(OpLane0))
1485           ReorderingModes[OpIdx] = ReorderingMode::Load;
1486         else if (isa<Instruction>(OpLane0)) {
1487           // Check if OpLane0 should be broadcast.
1488           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1489             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1490           else
1491             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1492         }
1493         else if (isa<Constant>(OpLane0))
1494           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1495         else if (isa<Argument>(OpLane0))
1496           // Our best hope is a Splat. It may save some cost in some cases.
1497           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1498         else
1499           // NOTE: This should be unreachable.
1500           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1501       }
1502 
1503       // If the initial strategy fails for any of the operand indexes, then we
1504       // perform reordering again in a second pass. This helps avoid assigning
1505       // high priority to the failed strategy, and should improve reordering for
1506       // the non-failed operand indexes.
1507       for (int Pass = 0; Pass != 2; ++Pass) {
1508         // Skip the second pass if the first pass did not fail.
1509         bool StrategyFailed = false;
1510         // Mark all operand data as free to use.
1511         clearUsed();
1512         // We keep the original operand order for the FirstLane, so reorder the
1513         // rest of the lanes. We are visiting the nodes in a circular fashion,
1514         // using FirstLane as the center point and increasing the radius
1515         // distance.
1516         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1517           // Visit the lane on the right and then the lane on the left.
1518           for (int Direction : {+1, -1}) {
1519             int Lane = FirstLane + Direction * Distance;
1520             if (Lane < 0 || Lane >= (int)NumLanes)
1521               continue;
1522             int LastLane = Lane - Direction;
1523             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1524                    "Out of bounds");
1525             // Look for a good match for each operand.
1526             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1527               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1528               Optional<unsigned> BestIdx =
1529                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1530               // By not selecting a value, we allow the operands that follow to
1531               // select a better matching value. We will get a non-null value in
1532               // the next run of getBestOperand().
1533               if (BestIdx) {
1534                 // Swap the current operand with the one returned by
1535                 // getBestOperand().
1536                 swap(OpIdx, BestIdx.getValue(), Lane);
1537               } else {
1538                 // We failed to find a best operand, set mode to 'Failed'.
1539                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1540                 // Enable the second pass.
1541                 StrategyFailed = true;
1542               }
1543             }
1544           }
1545         }
1546         // Skip second pass if the strategy did not fail.
1547         if (!StrategyFailed)
1548           break;
1549       }
1550     }
1551 
1552 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1553     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1554       switch (RMode) {
1555       case ReorderingMode::Load:
1556         return "Load";
1557       case ReorderingMode::Opcode:
1558         return "Opcode";
1559       case ReorderingMode::Constant:
1560         return "Constant";
1561       case ReorderingMode::Splat:
1562         return "Splat";
1563       case ReorderingMode::Failed:
1564         return "Failed";
1565       }
1566       llvm_unreachable("Unimplemented Reordering Type");
1567     }
1568 
1569     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1570                                                    raw_ostream &OS) {
1571       return OS << getModeStr(RMode);
1572     }
1573 
1574     /// Debug print.
1575     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1576       printMode(RMode, dbgs());
1577     }
1578 
1579     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1580       return printMode(RMode, OS);
1581     }
1582 
1583     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1584       const unsigned Indent = 2;
1585       unsigned Cnt = 0;
1586       for (const OperandDataVec &OpDataVec : OpsVec) {
1587         OS << "Operand " << Cnt++ << "\n";
1588         for (const OperandData &OpData : OpDataVec) {
1589           OS.indent(Indent) << "{";
1590           if (Value *V = OpData.V)
1591             OS << *V;
1592           else
1593             OS << "null";
1594           OS << ", APO:" << OpData.APO << "}\n";
1595         }
1596         OS << "\n";
1597       }
1598       return OS;
1599     }
1600 
1601     /// Debug print.
1602     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1603 #endif
1604   };
1605 
1606   /// Checks if the instruction is marked for deletion.
1607   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1608 
1609   /// Marks values operands for later deletion by replacing them with Undefs.
1610   void eraseInstructions(ArrayRef<Value *> AV);
1611 
1612   ~BoUpSLP();
1613 
1614 private:
1615   /// Checks if all users of \p I are the part of the vectorization tree.
1616   bool areAllUsersVectorized(Instruction *I,
1617                              ArrayRef<Value *> VectorizedVals) const;
1618 
1619   /// \returns the cost of the vectorizable entry.
1620   InstructionCost getEntryCost(const TreeEntry *E,
1621                                ArrayRef<Value *> VectorizedVals);
1622 
1623   /// This is the recursive part of buildTree.
1624   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1625                      const EdgeInfo &EI);
1626 
1627   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1628   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1629   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1630   /// returns false, setting \p CurrentOrder to either an empty vector or a
1631   /// non-identity permutation that allows to reuse extract instructions.
1632   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1633                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1634 
1635   /// Vectorize a single entry in the tree.
1636   Value *vectorizeTree(TreeEntry *E);
1637 
1638   /// Vectorize a single entry in the tree, starting in \p VL.
1639   Value *vectorizeTree(ArrayRef<Value *> VL);
1640 
1641   /// \returns the scalarization cost for this type. Scalarization in this
1642   /// context means the creation of vectors from a group of scalars. If \p
1643   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1644   /// vector elements.
1645   InstructionCost getGatherCost(FixedVectorType *Ty,
1646                                 const DenseSet<unsigned> &ShuffledIndices,
1647                                 bool NeedToShuffle) const;
1648 
1649   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1650   /// tree entries.
1651   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1652   /// previous tree entries. \p Mask is filled with the shuffle mask.
1653   Optional<TargetTransformInfo::ShuffleKind>
1654   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1655                         SmallVectorImpl<const TreeEntry *> &Entries);
1656 
1657   /// \returns the scalarization cost for this list of values. Assuming that
1658   /// this subtree gets vectorized, we may need to extract the values from the
1659   /// roots. This method calculates the cost of extracting the values.
1660   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1661 
1662   /// Set the Builder insert point to one after the last instruction in
1663   /// the bundle
1664   void setInsertPointAfterBundle(const TreeEntry *E);
1665 
1666   /// \returns a vector from a collection of scalars in \p VL.
1667   Value *gather(ArrayRef<Value *> VL);
1668 
1669   /// \returns whether the VectorizableTree is fully vectorizable and will
1670   /// be beneficial even the tree height is tiny.
1671   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1672 
1673   /// Reorder commutative or alt operands to get better probability of
1674   /// generating vectorized code.
1675   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1676                                              SmallVectorImpl<Value *> &Left,
1677                                              SmallVectorImpl<Value *> &Right,
1678                                              const DataLayout &DL,
1679                                              ScalarEvolution &SE,
1680                                              const BoUpSLP &R);
1681   struct TreeEntry {
1682     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1683     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1684 
1685     /// \returns true if the scalars in VL are equal to this entry.
1686     bool isSame(ArrayRef<Value *> VL) const {
1687       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1688         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1689           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1690         return VL.size() == Mask.size() &&
1691                std::equal(VL.begin(), VL.end(), Mask.begin(),
1692                           [Scalars](Value *V, int Idx) {
1693                             return (isa<UndefValue>(V) &&
1694                                     Idx == UndefMaskElem) ||
1695                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1696                           });
1697       };
1698       if (!ReorderIndices.empty()) {
1699         // TODO: implement matching if the nodes are just reordered, still can
1700         // treat the vector as the same if the list of scalars matches VL
1701         // directly, without reordering.
1702         SmallVector<int> Mask;
1703         inversePermutation(ReorderIndices, Mask);
1704         if (VL.size() == Scalars.size())
1705           return IsSame(Scalars, Mask);
1706         if (VL.size() == ReuseShuffleIndices.size()) {
1707           ::addMask(Mask, ReuseShuffleIndices);
1708           return IsSame(Scalars, Mask);
1709         }
1710         return false;
1711       }
1712       return IsSame(Scalars, ReuseShuffleIndices);
1713     }
1714 
1715     /// \returns true if current entry has same operands as \p TE.
1716     bool hasEqualOperands(const TreeEntry &TE) const {
1717       if (TE.getNumOperands() != getNumOperands())
1718         return false;
1719       SmallBitVector Used(getNumOperands());
1720       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1721         unsigned PrevCount = Used.count();
1722         for (unsigned K = 0; K < E; ++K) {
1723           if (Used.test(K))
1724             continue;
1725           if (getOperand(K) == TE.getOperand(I)) {
1726             Used.set(K);
1727             break;
1728           }
1729         }
1730         // Check if we actually found the matching operand.
1731         if (PrevCount == Used.count())
1732           return false;
1733       }
1734       return true;
1735     }
1736 
1737     /// \return Final vectorization factor for the node. Defined by the total
1738     /// number of vectorized scalars, including those, used several times in the
1739     /// entry and counted in the \a ReuseShuffleIndices, if any.
1740     unsigned getVectorFactor() const {
1741       if (!ReuseShuffleIndices.empty())
1742         return ReuseShuffleIndices.size();
1743       return Scalars.size();
1744     };
1745 
1746     /// A vector of scalars.
1747     ValueList Scalars;
1748 
1749     /// The Scalars are vectorized into this value. It is initialized to Null.
1750     Value *VectorizedValue = nullptr;
1751 
1752     /// Do we need to gather this sequence or vectorize it
1753     /// (either with vector instruction or with scatter/gather
1754     /// intrinsics for store/load)?
1755     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
1756     EntryState State;
1757 
1758     /// Does this sequence require some shuffling?
1759     SmallVector<int, 4> ReuseShuffleIndices;
1760 
1761     /// Does this entry require reordering?
1762     SmallVector<unsigned, 4> ReorderIndices;
1763 
1764     /// Points back to the VectorizableTree.
1765     ///
1766     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
1767     /// to be a pointer and needs to be able to initialize the child iterator.
1768     /// Thus we need a reference back to the container to translate the indices
1769     /// to entries.
1770     VecTreeTy &Container;
1771 
1772     /// The TreeEntry index containing the user of this entry.  We can actually
1773     /// have multiple users so the data structure is not truly a tree.
1774     SmallVector<EdgeInfo, 1> UserTreeIndices;
1775 
1776     /// The index of this treeEntry in VectorizableTree.
1777     int Idx = -1;
1778 
1779   private:
1780     /// The operands of each instruction in each lane Operands[op_index][lane].
1781     /// Note: This helps avoid the replication of the code that performs the
1782     /// reordering of operands during buildTree_rec() and vectorizeTree().
1783     SmallVector<ValueList, 2> Operands;
1784 
1785     /// The main/alternate instruction.
1786     Instruction *MainOp = nullptr;
1787     Instruction *AltOp = nullptr;
1788 
1789   public:
1790     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1791     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
1792       if (Operands.size() < OpIdx + 1)
1793         Operands.resize(OpIdx + 1);
1794       assert(Operands[OpIdx].empty() && "Already resized?");
1795       Operands[OpIdx].resize(Scalars.size());
1796       for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane)
1797         Operands[OpIdx][Lane] = OpVL[Lane];
1798     }
1799 
1800     /// Set the operands of this bundle in their original order.
1801     void setOperandsInOrder() {
1802       assert(Operands.empty() && "Already initialized?");
1803       auto *I0 = cast<Instruction>(Scalars[0]);
1804       Operands.resize(I0->getNumOperands());
1805       unsigned NumLanes = Scalars.size();
1806       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1807            OpIdx != NumOperands; ++OpIdx) {
1808         Operands[OpIdx].resize(NumLanes);
1809         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1810           auto *I = cast<Instruction>(Scalars[Lane]);
1811           assert(I->getNumOperands() == NumOperands &&
1812                  "Expected same number of operands");
1813           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
1814         }
1815       }
1816     }
1817 
1818     /// Reorders operands of the node to the given mask \p Mask.
1819     void reorderOperands(ArrayRef<int> Mask) {
1820       for (ValueList &Operand : Operands)
1821         reorderScalars(Operand, Mask);
1822     }
1823 
1824     /// \returns the \p OpIdx operand of this TreeEntry.
1825     ValueList &getOperand(unsigned OpIdx) {
1826       assert(OpIdx < Operands.size() && "Off bounds");
1827       return Operands[OpIdx];
1828     }
1829 
1830     /// \returns the \p OpIdx operand of this TreeEntry.
1831     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
1832       assert(OpIdx < Operands.size() && "Off bounds");
1833       return Operands[OpIdx];
1834     }
1835 
1836     /// \returns the number of operands.
1837     unsigned getNumOperands() const { return Operands.size(); }
1838 
1839     /// \return the single \p OpIdx operand.
1840     Value *getSingleOperand(unsigned OpIdx) const {
1841       assert(OpIdx < Operands.size() && "Off bounds");
1842       assert(!Operands[OpIdx].empty() && "No operand available");
1843       return Operands[OpIdx][0];
1844     }
1845 
1846     /// Some of the instructions in the list have alternate opcodes.
1847     bool isAltShuffle() const {
1848       return getOpcode() != getAltOpcode();
1849     }
1850 
1851     bool isOpcodeOrAlt(Instruction *I) const {
1852       unsigned CheckedOpcode = I->getOpcode();
1853       return (getOpcode() == CheckedOpcode ||
1854               getAltOpcode() == CheckedOpcode);
1855     }
1856 
1857     /// Chooses the correct key for scheduling data. If \p Op has the same (or
1858     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
1859     /// \p OpValue.
1860     Value *isOneOf(Value *Op) const {
1861       auto *I = dyn_cast<Instruction>(Op);
1862       if (I && isOpcodeOrAlt(I))
1863         return Op;
1864       return MainOp;
1865     }
1866 
1867     void setOperations(const InstructionsState &S) {
1868       MainOp = S.MainOp;
1869       AltOp = S.AltOp;
1870     }
1871 
1872     Instruction *getMainOp() const {
1873       return MainOp;
1874     }
1875 
1876     Instruction *getAltOp() const {
1877       return AltOp;
1878     }
1879 
1880     /// The main/alternate opcodes for the list of instructions.
1881     unsigned getOpcode() const {
1882       return MainOp ? MainOp->getOpcode() : 0;
1883     }
1884 
1885     unsigned getAltOpcode() const {
1886       return AltOp ? AltOp->getOpcode() : 0;
1887     }
1888 
1889     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
1890     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
1891     int findLaneForValue(Value *V) const {
1892       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
1893       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
1894       if (!ReorderIndices.empty())
1895         FoundLane = ReorderIndices[FoundLane];
1896       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
1897       if (!ReuseShuffleIndices.empty()) {
1898         FoundLane = std::distance(ReuseShuffleIndices.begin(),
1899                                   find(ReuseShuffleIndices, FoundLane));
1900       }
1901       return FoundLane;
1902     }
1903 
1904 #ifndef NDEBUG
1905     /// Debug printer.
1906     LLVM_DUMP_METHOD void dump() const {
1907       dbgs() << Idx << ".\n";
1908       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
1909         dbgs() << "Operand " << OpI << ":\n";
1910         for (const Value *V : Operands[OpI])
1911           dbgs().indent(2) << *V << "\n";
1912       }
1913       dbgs() << "Scalars: \n";
1914       for (Value *V : Scalars)
1915         dbgs().indent(2) << *V << "\n";
1916       dbgs() << "State: ";
1917       switch (State) {
1918       case Vectorize:
1919         dbgs() << "Vectorize\n";
1920         break;
1921       case ScatterVectorize:
1922         dbgs() << "ScatterVectorize\n";
1923         break;
1924       case NeedToGather:
1925         dbgs() << "NeedToGather\n";
1926         break;
1927       }
1928       dbgs() << "MainOp: ";
1929       if (MainOp)
1930         dbgs() << *MainOp << "\n";
1931       else
1932         dbgs() << "NULL\n";
1933       dbgs() << "AltOp: ";
1934       if (AltOp)
1935         dbgs() << *AltOp << "\n";
1936       else
1937         dbgs() << "NULL\n";
1938       dbgs() << "VectorizedValue: ";
1939       if (VectorizedValue)
1940         dbgs() << *VectorizedValue << "\n";
1941       else
1942         dbgs() << "NULL\n";
1943       dbgs() << "ReuseShuffleIndices: ";
1944       if (ReuseShuffleIndices.empty())
1945         dbgs() << "Empty";
1946       else
1947         for (unsigned ReuseIdx : ReuseShuffleIndices)
1948           dbgs() << ReuseIdx << ", ";
1949       dbgs() << "\n";
1950       dbgs() << "ReorderIndices: ";
1951       for (unsigned ReorderIdx : ReorderIndices)
1952         dbgs() << ReorderIdx << ", ";
1953       dbgs() << "\n";
1954       dbgs() << "UserTreeIndices: ";
1955       for (const auto &EInfo : UserTreeIndices)
1956         dbgs() << EInfo << ", ";
1957       dbgs() << "\n";
1958     }
1959 #endif
1960   };
1961 
1962 #ifndef NDEBUG
1963   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
1964                      InstructionCost VecCost,
1965                      InstructionCost ScalarCost) const {
1966     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
1967     dbgs() << "SLP: Costs:\n";
1968     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
1969     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
1970     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
1971     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
1972                ReuseShuffleCost + VecCost - ScalarCost << "\n";
1973   }
1974 #endif
1975 
1976   /// Create a new VectorizableTree entry.
1977   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
1978                           const InstructionsState &S,
1979                           const EdgeInfo &UserTreeIdx,
1980                           ArrayRef<int> ReuseShuffleIndices = None,
1981                           ArrayRef<unsigned> ReorderIndices = None) {
1982     TreeEntry::EntryState EntryState =
1983         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
1984     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
1985                         ReuseShuffleIndices, ReorderIndices);
1986   }
1987 
1988   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
1989                           TreeEntry::EntryState EntryState,
1990                           Optional<ScheduleData *> Bundle,
1991                           const InstructionsState &S,
1992                           const EdgeInfo &UserTreeIdx,
1993                           ArrayRef<int> ReuseShuffleIndices = None,
1994                           ArrayRef<unsigned> ReorderIndices = None) {
1995     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
1996             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
1997            "Need to vectorize gather entry?");
1998     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
1999     TreeEntry *Last = VectorizableTree.back().get();
2000     Last->Idx = VectorizableTree.size() - 1;
2001     Last->State = EntryState;
2002     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2003                                      ReuseShuffleIndices.end());
2004     if (ReorderIndices.empty()) {
2005       Last->Scalars.assign(VL.begin(), VL.end());
2006       Last->setOperations(S);
2007     } else {
2008       // Reorder scalars and build final mask.
2009       Last->Scalars.assign(VL.size(), nullptr);
2010       transform(ReorderIndices, Last->Scalars.begin(),
2011                 [VL](unsigned Idx) -> Value * {
2012                   if (Idx >= VL.size())
2013                     return UndefValue::get(VL.front()->getType());
2014                   return VL[Idx];
2015                 });
2016       InstructionsState S = getSameOpcode(Last->Scalars);
2017       Last->setOperations(S);
2018       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2019     }
2020     if (Last->State != TreeEntry::NeedToGather) {
2021       for (Value *V : VL) {
2022         assert(!getTreeEntry(V) && "Scalar already in tree!");
2023         ScalarToTreeEntry[V] = Last;
2024       }
2025       // Update the scheduler bundle to point to this TreeEntry.
2026       unsigned Lane = 0;
2027       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2028            BundleMember = BundleMember->NextInBundle) {
2029         BundleMember->TE = Last;
2030         BundleMember->Lane = Lane;
2031         ++Lane;
2032       }
2033       assert((!Bundle.getValue() || Lane == VL.size()) &&
2034              "Bundle and VL out of sync");
2035     } else {
2036       MustGather.insert(VL.begin(), VL.end());
2037     }
2038 
2039     if (UserTreeIdx.UserTE)
2040       Last->UserTreeIndices.push_back(UserTreeIdx);
2041 
2042     return Last;
2043   }
2044 
2045   /// -- Vectorization State --
2046   /// Holds all of the tree entries.
2047   TreeEntry::VecTreeTy VectorizableTree;
2048 
2049 #ifndef NDEBUG
2050   /// Debug printer.
2051   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2052     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2053       VectorizableTree[Id]->dump();
2054       dbgs() << "\n";
2055     }
2056   }
2057 #endif
2058 
2059   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2060 
2061   const TreeEntry *getTreeEntry(Value *V) const {
2062     return ScalarToTreeEntry.lookup(V);
2063   }
2064 
2065   /// Maps a specific scalar to its tree entry.
2066   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2067 
2068   /// Maps a value to the proposed vectorizable size.
2069   SmallDenseMap<Value *, unsigned> InstrElementSize;
2070 
2071   /// A list of scalars that we found that we need to keep as scalars.
2072   ValueSet MustGather;
2073 
2074   /// This POD struct describes one external user in the vectorized tree.
2075   struct ExternalUser {
2076     ExternalUser(Value *S, llvm::User *U, int L)
2077         : Scalar(S), User(U), Lane(L) {}
2078 
2079     // Which scalar in our function.
2080     Value *Scalar;
2081 
2082     // Which user that uses the scalar.
2083     llvm::User *User;
2084 
2085     // Which lane does the scalar belong to.
2086     int Lane;
2087   };
2088   using UserList = SmallVector<ExternalUser, 16>;
2089 
2090   /// Checks if two instructions may access the same memory.
2091   ///
2092   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2093   /// is invariant in the calling loop.
2094   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2095                  Instruction *Inst2) {
2096     // First check if the result is already in the cache.
2097     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2098     Optional<bool> &result = AliasCache[key];
2099     if (result.hasValue()) {
2100       return result.getValue();
2101     }
2102     bool aliased = true;
2103     if (Loc1.Ptr && isSimple(Inst1))
2104       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2105     // Store the result in the cache.
2106     result = aliased;
2107     return aliased;
2108   }
2109 
2110   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2111 
2112   /// Cache for alias results.
2113   /// TODO: consider moving this to the AliasAnalysis itself.
2114   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2115 
2116   /// Removes an instruction from its block and eventually deletes it.
2117   /// It's like Instruction::eraseFromParent() except that the actual deletion
2118   /// is delayed until BoUpSLP is destructed.
2119   /// This is required to ensure that there are no incorrect collisions in the
2120   /// AliasCache, which can happen if a new instruction is allocated at the
2121   /// same address as a previously deleted instruction.
2122   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2123     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2124     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2125   }
2126 
2127   /// Temporary store for deleted instructions. Instructions will be deleted
2128   /// eventually when the BoUpSLP is destructed.
2129   DenseMap<Instruction *, bool> DeletedInstructions;
2130 
2131   /// A list of values that need to extracted out of the tree.
2132   /// This list holds pairs of (Internal Scalar : External User). External User
2133   /// can be nullptr, it means that this Internal Scalar will be used later,
2134   /// after vectorization.
2135   UserList ExternalUses;
2136 
2137   /// Values used only by @llvm.assume calls.
2138   SmallPtrSet<const Value *, 32> EphValues;
2139 
2140   /// Holds all of the instructions that we gathered.
2141   SetVector<Instruction *> GatherShuffleSeq;
2142 
2143   /// A list of blocks that we are going to CSE.
2144   SetVector<BasicBlock *> CSEBlocks;
2145 
2146   /// Contains all scheduling relevant data for an instruction.
2147   /// A ScheduleData either represents a single instruction or a member of an
2148   /// instruction bundle (= a group of instructions which is combined into a
2149   /// vector instruction).
2150   struct ScheduleData {
2151     // The initial value for the dependency counters. It means that the
2152     // dependencies are not calculated yet.
2153     enum { InvalidDeps = -1 };
2154 
2155     ScheduleData() = default;
2156 
2157     void init(int BlockSchedulingRegionID, Value *OpVal) {
2158       FirstInBundle = this;
2159       NextInBundle = nullptr;
2160       NextLoadStore = nullptr;
2161       IsScheduled = false;
2162       SchedulingRegionID = BlockSchedulingRegionID;
2163       UnscheduledDepsInBundle = UnscheduledDeps;
2164       clearDependencies();
2165       OpValue = OpVal;
2166       TE = nullptr;
2167       Lane = -1;
2168     }
2169 
2170     /// Returns true if the dependency information has been calculated.
2171     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2172 
2173     /// Returns true for single instructions and for bundle representatives
2174     /// (= the head of a bundle).
2175     bool isSchedulingEntity() const { return FirstInBundle == this; }
2176 
2177     /// Returns true if it represents an instruction bundle and not only a
2178     /// single instruction.
2179     bool isPartOfBundle() const {
2180       return NextInBundle != nullptr || FirstInBundle != this;
2181     }
2182 
2183     /// Returns true if it is ready for scheduling, i.e. it has no more
2184     /// unscheduled depending instructions/bundles.
2185     bool isReady() const {
2186       assert(isSchedulingEntity() &&
2187              "can't consider non-scheduling entity for ready list");
2188       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2189     }
2190 
2191     /// Modifies the number of unscheduled dependencies, also updating it for
2192     /// the whole bundle.
2193     int incrementUnscheduledDeps(int Incr) {
2194       UnscheduledDeps += Incr;
2195       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2196     }
2197 
2198     /// Sets the number of unscheduled dependencies to the number of
2199     /// dependencies.
2200     void resetUnscheduledDeps() {
2201       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2202     }
2203 
2204     /// Clears all dependency information.
2205     void clearDependencies() {
2206       Dependencies = InvalidDeps;
2207       resetUnscheduledDeps();
2208       MemoryDependencies.clear();
2209     }
2210 
2211     void dump(raw_ostream &os) const {
2212       if (!isSchedulingEntity()) {
2213         os << "/ " << *Inst;
2214       } else if (NextInBundle) {
2215         os << '[' << *Inst;
2216         ScheduleData *SD = NextInBundle;
2217         while (SD) {
2218           os << ';' << *SD->Inst;
2219           SD = SD->NextInBundle;
2220         }
2221         os << ']';
2222       } else {
2223         os << *Inst;
2224       }
2225     }
2226 
2227     Instruction *Inst = nullptr;
2228 
2229     /// Points to the head in an instruction bundle (and always to this for
2230     /// single instructions).
2231     ScheduleData *FirstInBundle = nullptr;
2232 
2233     /// Single linked list of all instructions in a bundle. Null if it is a
2234     /// single instruction.
2235     ScheduleData *NextInBundle = nullptr;
2236 
2237     /// Single linked list of all memory instructions (e.g. load, store, call)
2238     /// in the block - until the end of the scheduling region.
2239     ScheduleData *NextLoadStore = nullptr;
2240 
2241     /// The dependent memory instructions.
2242     /// This list is derived on demand in calculateDependencies().
2243     SmallVector<ScheduleData *, 4> MemoryDependencies;
2244 
2245     /// This ScheduleData is in the current scheduling region if this matches
2246     /// the current SchedulingRegionID of BlockScheduling.
2247     int SchedulingRegionID = 0;
2248 
2249     /// Used for getting a "good" final ordering of instructions.
2250     int SchedulingPriority = 0;
2251 
2252     /// The number of dependencies. Constitutes of the number of users of the
2253     /// instruction plus the number of dependent memory instructions (if any).
2254     /// This value is calculated on demand.
2255     /// If InvalidDeps, the number of dependencies is not calculated yet.
2256     int Dependencies = InvalidDeps;
2257 
2258     /// The number of dependencies minus the number of dependencies of scheduled
2259     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2260     /// for scheduling.
2261     /// Note that this is negative as long as Dependencies is not calculated.
2262     int UnscheduledDeps = InvalidDeps;
2263 
2264     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2265     /// single instructions.
2266     int UnscheduledDepsInBundle = InvalidDeps;
2267 
2268     /// True if this instruction is scheduled (or considered as scheduled in the
2269     /// dry-run).
2270     bool IsScheduled = false;
2271 
2272     /// Opcode of the current instruction in the schedule data.
2273     Value *OpValue = nullptr;
2274 
2275     /// The TreeEntry that this instruction corresponds to.
2276     TreeEntry *TE = nullptr;
2277 
2278     /// The lane of this node in the TreeEntry.
2279     int Lane = -1;
2280   };
2281 
2282 #ifndef NDEBUG
2283   friend inline raw_ostream &operator<<(raw_ostream &os,
2284                                         const BoUpSLP::ScheduleData &SD) {
2285     SD.dump(os);
2286     return os;
2287   }
2288 #endif
2289 
2290   friend struct GraphTraits<BoUpSLP *>;
2291   friend struct DOTGraphTraits<BoUpSLP *>;
2292 
2293   /// Contains all scheduling data for a basic block.
2294   struct BlockScheduling {
2295     BlockScheduling(BasicBlock *BB)
2296         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2297 
2298     void clear() {
2299       ReadyInsts.clear();
2300       ScheduleStart = nullptr;
2301       ScheduleEnd = nullptr;
2302       FirstLoadStoreInRegion = nullptr;
2303       LastLoadStoreInRegion = nullptr;
2304 
2305       // Reduce the maximum schedule region size by the size of the
2306       // previous scheduling run.
2307       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2308       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2309         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2310       ScheduleRegionSize = 0;
2311 
2312       // Make a new scheduling region, i.e. all existing ScheduleData is not
2313       // in the new region yet.
2314       ++SchedulingRegionID;
2315     }
2316 
2317     ScheduleData *getScheduleData(Value *V) {
2318       ScheduleData *SD = ScheduleDataMap[V];
2319       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2320         return SD;
2321       return nullptr;
2322     }
2323 
2324     ScheduleData *getScheduleData(Value *V, Value *Key) {
2325       if (V == Key)
2326         return getScheduleData(V);
2327       auto I = ExtraScheduleDataMap.find(V);
2328       if (I != ExtraScheduleDataMap.end()) {
2329         ScheduleData *SD = I->second[Key];
2330         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2331           return SD;
2332       }
2333       return nullptr;
2334     }
2335 
2336     bool isInSchedulingRegion(ScheduleData *SD) const {
2337       return SD->SchedulingRegionID == SchedulingRegionID;
2338     }
2339 
2340     /// Marks an instruction as scheduled and puts all dependent ready
2341     /// instructions into the ready-list.
2342     template <typename ReadyListType>
2343     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2344       SD->IsScheduled = true;
2345       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2346 
2347       ScheduleData *BundleMember = SD;
2348       while (BundleMember) {
2349         if (BundleMember->Inst != BundleMember->OpValue) {
2350           BundleMember = BundleMember->NextInBundle;
2351           continue;
2352         }
2353         // Handle the def-use chain dependencies.
2354 
2355         // Decrement the unscheduled counter and insert to ready list if ready.
2356         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2357           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2358             if (OpDef && OpDef->hasValidDependencies() &&
2359                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2360               // There are no more unscheduled dependencies after
2361               // decrementing, so we can put the dependent instruction
2362               // into the ready list.
2363               ScheduleData *DepBundle = OpDef->FirstInBundle;
2364               assert(!DepBundle->IsScheduled &&
2365                      "already scheduled bundle gets ready");
2366               ReadyList.insert(DepBundle);
2367               LLVM_DEBUG(dbgs()
2368                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2369             }
2370           });
2371         };
2372 
2373         // If BundleMember is a vector bundle, its operands may have been
2374         // reordered duiring buildTree(). We therefore need to get its operands
2375         // through the TreeEntry.
2376         if (TreeEntry *TE = BundleMember->TE) {
2377           int Lane = BundleMember->Lane;
2378           assert(Lane >= 0 && "Lane not set");
2379 
2380           // Since vectorization tree is being built recursively this assertion
2381           // ensures that the tree entry has all operands set before reaching
2382           // this code. Couple of exceptions known at the moment are extracts
2383           // where their second (immediate) operand is not added. Since
2384           // immediates do not affect scheduler behavior this is considered
2385           // okay.
2386           auto *In = TE->getMainOp();
2387           assert(In &&
2388                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2389                   In->getNumOperands() == TE->getNumOperands()) &&
2390                  "Missed TreeEntry operands?");
2391           (void)In; // fake use to avoid build failure when assertions disabled
2392 
2393           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2394                OpIdx != NumOperands; ++OpIdx)
2395             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2396               DecrUnsched(I);
2397         } else {
2398           // If BundleMember is a stand-alone instruction, no operand reordering
2399           // has taken place, so we directly access its operands.
2400           for (Use &U : BundleMember->Inst->operands())
2401             if (auto *I = dyn_cast<Instruction>(U.get()))
2402               DecrUnsched(I);
2403         }
2404         // Handle the memory dependencies.
2405         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2406           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2407             // There are no more unscheduled dependencies after decrementing,
2408             // so we can put the dependent instruction into the ready list.
2409             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2410             assert(!DepBundle->IsScheduled &&
2411                    "already scheduled bundle gets ready");
2412             ReadyList.insert(DepBundle);
2413             LLVM_DEBUG(dbgs()
2414                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2415           }
2416         }
2417         BundleMember = BundleMember->NextInBundle;
2418       }
2419     }
2420 
2421     void doForAllOpcodes(Value *V,
2422                          function_ref<void(ScheduleData *SD)> Action) {
2423       if (ScheduleData *SD = getScheduleData(V))
2424         Action(SD);
2425       auto I = ExtraScheduleDataMap.find(V);
2426       if (I != ExtraScheduleDataMap.end())
2427         for (auto &P : I->second)
2428           if (P.second->SchedulingRegionID == SchedulingRegionID)
2429             Action(P.second);
2430     }
2431 
2432     /// Put all instructions into the ReadyList which are ready for scheduling.
2433     template <typename ReadyListType>
2434     void initialFillReadyList(ReadyListType &ReadyList) {
2435       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2436         doForAllOpcodes(I, [&](ScheduleData *SD) {
2437           if (SD->isSchedulingEntity() && SD->isReady()) {
2438             ReadyList.insert(SD);
2439             LLVM_DEBUG(dbgs()
2440                        << "SLP:    initially in ready list: " << *I << "\n");
2441           }
2442         });
2443       }
2444     }
2445 
2446     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2447     /// cyclic dependencies. This is only a dry-run, no instructions are
2448     /// actually moved at this stage.
2449     /// \returns the scheduling bundle. The returned Optional value is non-None
2450     /// if \p VL is allowed to be scheduled.
2451     Optional<ScheduleData *>
2452     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2453                       const InstructionsState &S);
2454 
2455     /// Un-bundles a group of instructions.
2456     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2457 
2458     /// Allocates schedule data chunk.
2459     ScheduleData *allocateScheduleDataChunks();
2460 
2461     /// Extends the scheduling region so that V is inside the region.
2462     /// \returns true if the region size is within the limit.
2463     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2464 
2465     /// Initialize the ScheduleData structures for new instructions in the
2466     /// scheduling region.
2467     void initScheduleData(Instruction *FromI, Instruction *ToI,
2468                           ScheduleData *PrevLoadStore,
2469                           ScheduleData *NextLoadStore);
2470 
2471     /// Updates the dependency information of a bundle and of all instructions/
2472     /// bundles which depend on the original bundle.
2473     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2474                                BoUpSLP *SLP);
2475 
2476     /// Sets all instruction in the scheduling region to un-scheduled.
2477     void resetSchedule();
2478 
2479     BasicBlock *BB;
2480 
2481     /// Simple memory allocation for ScheduleData.
2482     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2483 
2484     /// The size of a ScheduleData array in ScheduleDataChunks.
2485     int ChunkSize;
2486 
2487     /// The allocator position in the current chunk, which is the last entry
2488     /// of ScheduleDataChunks.
2489     int ChunkPos;
2490 
2491     /// Attaches ScheduleData to Instruction.
2492     /// Note that the mapping survives during all vectorization iterations, i.e.
2493     /// ScheduleData structures are recycled.
2494     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2495 
2496     /// Attaches ScheduleData to Instruction with the leading key.
2497     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2498         ExtraScheduleDataMap;
2499 
2500     struct ReadyList : SmallVector<ScheduleData *, 8> {
2501       void insert(ScheduleData *SD) { push_back(SD); }
2502     };
2503 
2504     /// The ready-list for scheduling (only used for the dry-run).
2505     ReadyList ReadyInsts;
2506 
2507     /// The first instruction of the scheduling region.
2508     Instruction *ScheduleStart = nullptr;
2509 
2510     /// The first instruction _after_ the scheduling region.
2511     Instruction *ScheduleEnd = nullptr;
2512 
2513     /// The first memory accessing instruction in the scheduling region
2514     /// (can be null).
2515     ScheduleData *FirstLoadStoreInRegion = nullptr;
2516 
2517     /// The last memory accessing instruction in the scheduling region
2518     /// (can be null).
2519     ScheduleData *LastLoadStoreInRegion = nullptr;
2520 
2521     /// The current size of the scheduling region.
2522     int ScheduleRegionSize = 0;
2523 
2524     /// The maximum size allowed for the scheduling region.
2525     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2526 
2527     /// The ID of the scheduling region. For a new vectorization iteration this
2528     /// is incremented which "removes" all ScheduleData from the region.
2529     // Make sure that the initial SchedulingRegionID is greater than the
2530     // initial SchedulingRegionID in ScheduleData (which is 0).
2531     int SchedulingRegionID = 1;
2532   };
2533 
2534   /// Attaches the BlockScheduling structures to basic blocks.
2535   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2536 
2537   /// Performs the "real" scheduling. Done before vectorization is actually
2538   /// performed in a basic block.
2539   void scheduleBlock(BlockScheduling *BS);
2540 
2541   /// List of users to ignore during scheduling and that don't need extracting.
2542   ArrayRef<Value *> UserIgnoreList;
2543 
2544   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2545   /// sorted SmallVectors of unsigned.
2546   struct OrdersTypeDenseMapInfo {
2547     static OrdersType getEmptyKey() {
2548       OrdersType V;
2549       V.push_back(~1U);
2550       return V;
2551     }
2552 
2553     static OrdersType getTombstoneKey() {
2554       OrdersType V;
2555       V.push_back(~2U);
2556       return V;
2557     }
2558 
2559     static unsigned getHashValue(const OrdersType &V) {
2560       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2561     }
2562 
2563     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2564       return LHS == RHS;
2565     }
2566   };
2567 
2568   // Analysis and block reference.
2569   Function *F;
2570   ScalarEvolution *SE;
2571   TargetTransformInfo *TTI;
2572   TargetLibraryInfo *TLI;
2573   AAResults *AA;
2574   LoopInfo *LI;
2575   DominatorTree *DT;
2576   AssumptionCache *AC;
2577   DemandedBits *DB;
2578   const DataLayout *DL;
2579   OptimizationRemarkEmitter *ORE;
2580 
2581   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2582   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2583 
2584   /// Instruction builder to construct the vectorized tree.
2585   IRBuilder<> Builder;
2586 
2587   /// A map of scalar integer values to the smallest bit width with which they
2588   /// can legally be represented. The values map to (width, signed) pairs,
2589   /// where "width" indicates the minimum bit width and "signed" is True if the
2590   /// value must be signed-extended, rather than zero-extended, back to its
2591   /// original width.
2592   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2593 };
2594 
2595 } // end namespace slpvectorizer
2596 
2597 template <> struct GraphTraits<BoUpSLP *> {
2598   using TreeEntry = BoUpSLP::TreeEntry;
2599 
2600   /// NodeRef has to be a pointer per the GraphWriter.
2601   using NodeRef = TreeEntry *;
2602 
2603   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2604 
2605   /// Add the VectorizableTree to the index iterator to be able to return
2606   /// TreeEntry pointers.
2607   struct ChildIteratorType
2608       : public iterator_adaptor_base<
2609             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2610     ContainerTy &VectorizableTree;
2611 
2612     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2613                       ContainerTy &VT)
2614         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2615 
2616     NodeRef operator*() { return I->UserTE; }
2617   };
2618 
2619   static NodeRef getEntryNode(BoUpSLP &R) {
2620     return R.VectorizableTree[0].get();
2621   }
2622 
2623   static ChildIteratorType child_begin(NodeRef N) {
2624     return {N->UserTreeIndices.begin(), N->Container};
2625   }
2626 
2627   static ChildIteratorType child_end(NodeRef N) {
2628     return {N->UserTreeIndices.end(), N->Container};
2629   }
2630 
2631   /// For the node iterator we just need to turn the TreeEntry iterator into a
2632   /// TreeEntry* iterator so that it dereferences to NodeRef.
2633   class nodes_iterator {
2634     using ItTy = ContainerTy::iterator;
2635     ItTy It;
2636 
2637   public:
2638     nodes_iterator(const ItTy &It2) : It(It2) {}
2639     NodeRef operator*() { return It->get(); }
2640     nodes_iterator operator++() {
2641       ++It;
2642       return *this;
2643     }
2644     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2645   };
2646 
2647   static nodes_iterator nodes_begin(BoUpSLP *R) {
2648     return nodes_iterator(R->VectorizableTree.begin());
2649   }
2650 
2651   static nodes_iterator nodes_end(BoUpSLP *R) {
2652     return nodes_iterator(R->VectorizableTree.end());
2653   }
2654 
2655   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2656 };
2657 
2658 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2659   using TreeEntry = BoUpSLP::TreeEntry;
2660 
2661   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2662 
2663   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2664     std::string Str;
2665     raw_string_ostream OS(Str);
2666     if (isSplat(Entry->Scalars))
2667       OS << "<splat> ";
2668     for (auto V : Entry->Scalars) {
2669       OS << *V;
2670       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2671             return EU.Scalar == V;
2672           }))
2673         OS << " <extract>";
2674       OS << "\n";
2675     }
2676     return Str;
2677   }
2678 
2679   static std::string getNodeAttributes(const TreeEntry *Entry,
2680                                        const BoUpSLP *) {
2681     if (Entry->State == TreeEntry::NeedToGather)
2682       return "color=red";
2683     return "";
2684   }
2685 };
2686 
2687 } // end namespace llvm
2688 
2689 BoUpSLP::~BoUpSLP() {
2690   for (const auto &Pair : DeletedInstructions) {
2691     // Replace operands of ignored instructions with Undefs in case if they were
2692     // marked for deletion.
2693     if (Pair.getSecond()) {
2694       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2695       Pair.getFirst()->replaceAllUsesWith(Undef);
2696     }
2697     Pair.getFirst()->dropAllReferences();
2698   }
2699   for (const auto &Pair : DeletedInstructions) {
2700     assert(Pair.getFirst()->use_empty() &&
2701            "trying to erase instruction with users.");
2702     Pair.getFirst()->eraseFromParent();
2703   }
2704 #ifdef EXPENSIVE_CHECKS
2705   // If we could guarantee that this call is not extremely slow, we could
2706   // remove the ifdef limitation (see PR47712).
2707   assert(!verifyFunction(*F, &dbgs()));
2708 #endif
2709 }
2710 
2711 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2712   for (auto *V : AV) {
2713     if (auto *I = dyn_cast<Instruction>(V))
2714       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2715   };
2716 }
2717 
2718 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
2719 /// contains original mask for the scalars reused in the node. Procedure
2720 /// transform this mask in accordance with the given \p Mask.
2721 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
2722   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
2723          "Expected non-empty mask.");
2724   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
2725   Prev.swap(Reuses);
2726   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
2727     if (Mask[I] != UndefMaskElem)
2728       Reuses[Mask[I]] = Prev[I];
2729 }
2730 
2731 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
2732 /// the original order of the scalars. Procedure transforms the provided order
2733 /// in accordance with the given \p Mask. If the resulting \p Order is just an
2734 /// identity order, \p Order is cleared.
2735 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
2736   assert(!Mask.empty() && "Expected non-empty mask.");
2737   SmallVector<int> MaskOrder;
2738   if (Order.empty()) {
2739     MaskOrder.resize(Mask.size());
2740     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
2741   } else {
2742     inversePermutation(Order, MaskOrder);
2743   }
2744   reorderReuses(MaskOrder, Mask);
2745   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
2746     Order.clear();
2747     return;
2748   }
2749   Order.assign(Mask.size(), Mask.size());
2750   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
2751     if (MaskOrder[I] != UndefMaskElem)
2752       Order[MaskOrder[I]] = I;
2753   fixupOrderingIndices(Order);
2754 }
2755 
2756 Optional<BoUpSLP::OrdersType>
2757 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
2758   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
2759   unsigned NumScalars = TE.Scalars.size();
2760   OrdersType CurrentOrder(NumScalars, NumScalars);
2761   SmallVector<int> Positions;
2762   SmallBitVector UsedPositions(NumScalars);
2763   const TreeEntry *STE = nullptr;
2764   // Try to find all gathered scalars that are gets vectorized in other
2765   // vectorize node. Here we can have only one single tree vector node to
2766   // correctly identify order of the gathered scalars.
2767   for (unsigned I = 0; I < NumScalars; ++I) {
2768     Value *V = TE.Scalars[I];
2769     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
2770       continue;
2771     if (const auto *LocalSTE = getTreeEntry(V)) {
2772       if (!STE)
2773         STE = LocalSTE;
2774       else if (STE != LocalSTE)
2775         // Take the order only from the single vector node.
2776         return None;
2777       unsigned Lane =
2778           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
2779       if (Lane >= NumScalars)
2780         return None;
2781       if (CurrentOrder[Lane] != NumScalars) {
2782         if (Lane != I)
2783           continue;
2784         UsedPositions.reset(CurrentOrder[Lane]);
2785       }
2786       // The partial identity (where only some elements of the gather node are
2787       // in the identity order) is good.
2788       CurrentOrder[Lane] = I;
2789       UsedPositions.set(I);
2790     }
2791   }
2792   // Need to keep the order if we have a vector entry and at least 2 scalars or
2793   // the vectorized entry has just 2 scalars.
2794   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
2795     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
2796       for (unsigned I = 0; I < NumScalars; ++I)
2797         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
2798           return false;
2799       return true;
2800     };
2801     if (IsIdentityOrder(CurrentOrder)) {
2802       CurrentOrder.clear();
2803       return CurrentOrder;
2804     }
2805     auto *It = CurrentOrder.begin();
2806     for (unsigned I = 0; I < NumScalars;) {
2807       if (UsedPositions.test(I)) {
2808         ++I;
2809         continue;
2810       }
2811       if (*It == NumScalars) {
2812         *It = I;
2813         ++I;
2814       }
2815       ++It;
2816     }
2817     return CurrentOrder;
2818   }
2819   return None;
2820 }
2821 
2822 void BoUpSLP::reorderTopToBottom() {
2823   // Maps VF to the graph nodes.
2824   DenseMap<unsigned, SmallPtrSet<TreeEntry *, 4>> VFToOrderedEntries;
2825   // ExtractElement gather nodes which can be vectorized and need to handle
2826   // their ordering.
2827   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
2828   // Find all reorderable nodes with the given VF.
2829   // Currently the are vectorized loads,extracts + some gathering of extracts.
2830   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
2831                                  const std::unique_ptr<TreeEntry> &TE) {
2832     // No need to reorder if need to shuffle reuses, still need to shuffle the
2833     // node.
2834     if (!TE->ReuseShuffleIndices.empty())
2835       return;
2836     if (TE->State == TreeEntry::Vectorize &&
2837         isa<LoadInst, ExtractElementInst, ExtractValueInst, StoreInst,
2838             InsertElementInst>(TE->getMainOp()) &&
2839         !TE->isAltShuffle()) {
2840       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
2841       return;
2842     }
2843     if (TE->State == TreeEntry::NeedToGather) {
2844       if (TE->getOpcode() == Instruction::ExtractElement &&
2845           !TE->isAltShuffle() &&
2846           isa<FixedVectorType>(cast<ExtractElementInst>(TE->getMainOp())
2847                                    ->getVectorOperandType()) &&
2848           allSameType(TE->Scalars) && allSameBlock(TE->Scalars)) {
2849         // Check that gather of extractelements can be represented as
2850         // just a shuffle of a single vector.
2851         OrdersType CurrentOrder;
2852         bool Reuse =
2853             canReuseExtract(TE->Scalars, TE->getMainOp(), CurrentOrder);
2854         if (Reuse || !CurrentOrder.empty()) {
2855           VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
2856           GathersToOrders.try_emplace(TE.get(), CurrentOrder);
2857           return;
2858         }
2859       }
2860       if (Optional<OrdersType> CurrentOrder =
2861               findReusedOrderedScalars(*TE.get())) {
2862         VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
2863         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
2864       }
2865     }
2866   });
2867 
2868   // Reorder the graph nodes according to their vectorization factor.
2869   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
2870        VF /= 2) {
2871     auto It = VFToOrderedEntries.find(VF);
2872     if (It == VFToOrderedEntries.end())
2873       continue;
2874     // Try to find the most profitable order. We just are looking for the most
2875     // used order and reorder scalar elements in the nodes according to this
2876     // mostly used order.
2877     const SmallPtrSetImpl<TreeEntry *> &OrderedEntries = It->getSecond();
2878     // All operands are reordered and used only in this node - propagate the
2879     // most used order to the user node.
2880     MapVector<OrdersType, unsigned,
2881               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
2882         OrdersUses;
2883     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
2884     for (const TreeEntry *OpTE : OrderedEntries) {
2885       // No need to reorder this nodes, still need to extend and to use shuffle,
2886       // just need to merge reordering shuffle and the reuse shuffle.
2887       if (!OpTE->ReuseShuffleIndices.empty())
2888         continue;
2889       // Count number of orders uses.
2890       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
2891         if (OpTE->State == TreeEntry::NeedToGather)
2892           return GathersToOrders.find(OpTE)->second;
2893         return OpTE->ReorderIndices;
2894       }();
2895       // Stores actually store the mask, not the order, need to invert.
2896       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
2897           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
2898         SmallVector<int> Mask;
2899         inversePermutation(Order, Mask);
2900         unsigned E = Order.size();
2901         OrdersType CurrentOrder(E, E);
2902         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
2903           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
2904         });
2905         fixupOrderingIndices(CurrentOrder);
2906         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
2907       } else {
2908         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
2909       }
2910     }
2911     // Set order of the user node.
2912     if (OrdersUses.empty())
2913       continue;
2914     // Choose the most used order.
2915     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
2916     unsigned Cnt = OrdersUses.front().second;
2917     for (const auto &Pair : drop_begin(OrdersUses)) {
2918       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
2919         BestOrder = Pair.first;
2920         Cnt = Pair.second;
2921       }
2922     }
2923     // Set order of the user node.
2924     if (BestOrder.empty())
2925       continue;
2926     SmallVector<int> Mask;
2927     inversePermutation(BestOrder, Mask);
2928     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
2929     unsigned E = BestOrder.size();
2930     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
2931       return I < E ? static_cast<int>(I) : UndefMaskElem;
2932     });
2933     // Do an actual reordering, if profitable.
2934     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
2935       // Just do the reordering for the nodes with the given VF.
2936       if (TE->Scalars.size() != VF) {
2937         if (TE->ReuseShuffleIndices.size() == VF) {
2938           // Need to reorder the reuses masks of the operands with smaller VF to
2939           // be able to find the match between the graph nodes and scalar
2940           // operands of the given node during vectorization/cost estimation.
2941           assert(all_of(TE->UserTreeIndices,
2942                         [VF, &TE](const EdgeInfo &EI) {
2943                           return EI.UserTE->Scalars.size() == VF ||
2944                                  EI.UserTE->Scalars.size() ==
2945                                      TE->Scalars.size();
2946                         }) &&
2947                  "All users must be of VF size.");
2948           // Update ordering of the operands with the smaller VF than the given
2949           // one.
2950           reorderReuses(TE->ReuseShuffleIndices, Mask);
2951         }
2952         continue;
2953       }
2954       if (TE->State == TreeEntry::Vectorize &&
2955           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
2956               InsertElementInst>(TE->getMainOp()) &&
2957           !TE->isAltShuffle()) {
2958         // Build correct orders for extract{element,value}, loads and
2959         // stores.
2960         reorderOrder(TE->ReorderIndices, Mask);
2961         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
2962           TE->reorderOperands(Mask);
2963       } else {
2964         // Reorder the node and its operands.
2965         TE->reorderOperands(Mask);
2966         assert(TE->ReorderIndices.empty() &&
2967                "Expected empty reorder sequence.");
2968         reorderScalars(TE->Scalars, Mask);
2969       }
2970       if (!TE->ReuseShuffleIndices.empty()) {
2971         // Apply reversed order to keep the original ordering of the reused
2972         // elements to avoid extra reorder indices shuffling.
2973         OrdersType CurrentOrder;
2974         reorderOrder(CurrentOrder, MaskOrder);
2975         SmallVector<int> NewReuses;
2976         inversePermutation(CurrentOrder, NewReuses);
2977         addMask(NewReuses, TE->ReuseShuffleIndices);
2978         TE->ReuseShuffleIndices.swap(NewReuses);
2979       }
2980     }
2981   }
2982 }
2983 
2984 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
2985   SetVector<TreeEntry *> OrderedEntries;
2986   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
2987   // Find all reorderable leaf nodes with the given VF.
2988   // Currently the are vectorized loads,extracts without alternate operands +
2989   // some gathering of extracts.
2990   SmallVector<TreeEntry *> NonVectorized;
2991   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
2992                               &NonVectorized](
2993                                  const std::unique_ptr<TreeEntry> &TE) {
2994     if (TE->State != TreeEntry::Vectorize)
2995       NonVectorized.push_back(TE.get());
2996     // No need to reorder if need to shuffle reuses, still need to shuffle the
2997     // node.
2998     if (!TE->ReuseShuffleIndices.empty())
2999       return;
3000     if (TE->State == TreeEntry::Vectorize &&
3001         isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE->getMainOp()) &&
3002         !TE->isAltShuffle()) {
3003       OrderedEntries.insert(TE.get());
3004       return;
3005     }
3006     if (TE->State == TreeEntry::NeedToGather) {
3007       if (TE->getOpcode() == Instruction::ExtractElement &&
3008           !TE->isAltShuffle() &&
3009           isa<FixedVectorType>(cast<ExtractElementInst>(TE->getMainOp())
3010                                    ->getVectorOperandType()) &&
3011           allSameType(TE->Scalars) && allSameBlock(TE->Scalars)) {
3012         // Check that gather of extractelements can be represented as
3013         // just a shuffle of a single vector with a single user only.
3014         OrdersType CurrentOrder;
3015         bool Reuse =
3016             canReuseExtract(TE->Scalars, TE->getMainOp(), CurrentOrder);
3017         if ((Reuse || !CurrentOrder.empty()) &&
3018             !any_of(VectorizableTree,
3019                     [&TE](const std::unique_ptr<TreeEntry> &Entry) {
3020                       return Entry->State == TreeEntry::NeedToGather &&
3021                              Entry.get() != TE.get() &&
3022                              Entry->isSame(TE->Scalars);
3023                     })) {
3024           OrderedEntries.insert(TE.get());
3025           GathersToOrders.try_emplace(TE.get(), CurrentOrder);
3026           return;
3027         }
3028       }
3029       if (Optional<OrdersType> CurrentOrder =
3030               findReusedOrderedScalars(*TE.get())) {
3031         OrderedEntries.insert(TE.get());
3032         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3033       }
3034     }
3035   });
3036 
3037   // Checks if the operands of the users are reordarable and have only single
3038   // use.
3039   auto &&CheckOperands =
3040       [this, &NonVectorized](const auto &Data,
3041                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3042         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3043           if (any_of(Data.second,
3044                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3045                        return OpData.first == I &&
3046                               OpData.second->State == TreeEntry::Vectorize;
3047                      }))
3048             continue;
3049           ArrayRef<Value *> VL = Data.first->getOperand(I);
3050           const TreeEntry *TE = nullptr;
3051           const auto *It = find_if(VL, [this, &TE](Value *V) {
3052             TE = getTreeEntry(V);
3053             return TE;
3054           });
3055           if (It != VL.end() && TE->isSame(VL))
3056             return false;
3057           TreeEntry *Gather = nullptr;
3058           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3059                 assert(TE->State != TreeEntry::Vectorize &&
3060                        "Only non-vectorized nodes are expected.");
3061                 if (TE->isSame(VL)) {
3062                   Gather = TE;
3063                   return true;
3064                 }
3065                 return false;
3066               }) > 1)
3067             return false;
3068           if (Gather)
3069             GatherOps.push_back(Gather);
3070         }
3071         return true;
3072       };
3073   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3074   // I.e., if the node has operands, that are reordered, try to make at least
3075   // one operand order in the natural order and reorder others + reorder the
3076   // user node itself.
3077   SmallPtrSet<const TreeEntry *, 4> Visited;
3078   while (!OrderedEntries.empty()) {
3079     // 1. Filter out only reordered nodes.
3080     // 2. If the entry has multiple uses - skip it and jump to the next node.
3081     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3082     SmallVector<TreeEntry *> Filtered;
3083     for (TreeEntry *TE : OrderedEntries) {
3084       if (!(TE->State == TreeEntry::Vectorize ||
3085             (TE->State == TreeEntry::NeedToGather &&
3086              GathersToOrders.count(TE))) ||
3087           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3088           !all_of(drop_begin(TE->UserTreeIndices),
3089                   [TE](const EdgeInfo &EI) {
3090                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3091                   }) ||
3092           !Visited.insert(TE).second) {
3093         Filtered.push_back(TE);
3094         continue;
3095       }
3096       // Build a map between user nodes and their operands order to speedup
3097       // search. The graph currently does not provide this dependency directly.
3098       for (EdgeInfo &EI : TE->UserTreeIndices) {
3099         TreeEntry *UserTE = EI.UserTE;
3100         auto It = Users.find(UserTE);
3101         if (It == Users.end())
3102           It = Users.insert({UserTE, {}}).first;
3103         It->second.emplace_back(EI.EdgeIdx, TE);
3104       }
3105     }
3106     // Erase filtered entries.
3107     for_each(Filtered,
3108              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3109     for (const auto &Data : Users) {
3110       // Check that operands are used only in the User node.
3111       SmallVector<TreeEntry *> GatherOps;
3112       if (!CheckOperands(Data, GatherOps)) {
3113         for_each(Data.second,
3114                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3115                    OrderedEntries.remove(Op.second);
3116                  });
3117         continue;
3118       }
3119       // All operands are reordered and used only in this node - propagate the
3120       // most used order to the user node.
3121       MapVector<OrdersType, unsigned,
3122                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3123           OrdersUses;
3124       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3125       for (const auto &Op : Data.second) {
3126         TreeEntry *OpTE = Op.second;
3127         if (!OpTE->ReuseShuffleIndices.empty() ||
3128             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3129           continue;
3130         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3131           if (OpTE->State == TreeEntry::NeedToGather)
3132             return GathersToOrders.find(OpTE)->second;
3133           return OpTE->ReorderIndices;
3134         }();
3135         // Stores actually store the mask, not the order, need to invert.
3136         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3137             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3138           SmallVector<int> Mask;
3139           inversePermutation(Order, Mask);
3140           unsigned E = Order.size();
3141           OrdersType CurrentOrder(E, E);
3142           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3143             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3144           });
3145           fixupOrderingIndices(CurrentOrder);
3146           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3147         } else {
3148           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3149         }
3150         if (VisitedOps.insert(OpTE).second)
3151           OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3152               OpTE->UserTreeIndices.size();
3153         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3154         --OrdersUses[{}];
3155       }
3156       // If no orders - skip current nodes and jump to the next one, if any.
3157       if (OrdersUses.empty()) {
3158         for_each(Data.second,
3159                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3160                    OrderedEntries.remove(Op.second);
3161                  });
3162         continue;
3163       }
3164       // Choose the best order.
3165       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3166       unsigned Cnt = OrdersUses.front().second;
3167       for (const auto &Pair : drop_begin(OrdersUses)) {
3168         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3169           BestOrder = Pair.first;
3170           Cnt = Pair.second;
3171         }
3172       }
3173       // Set order of the user node (reordering of operands and user nodes).
3174       if (BestOrder.empty()) {
3175         for_each(Data.second,
3176                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3177                    OrderedEntries.remove(Op.second);
3178                  });
3179         continue;
3180       }
3181       // Erase operands from OrderedEntries list and adjust their orders.
3182       VisitedOps.clear();
3183       SmallVector<int> Mask;
3184       inversePermutation(BestOrder, Mask);
3185       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3186       unsigned E = BestOrder.size();
3187       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3188         return I < E ? static_cast<int>(I) : UndefMaskElem;
3189       });
3190       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3191         TreeEntry *TE = Op.second;
3192         OrderedEntries.remove(TE);
3193         if (!VisitedOps.insert(TE).second)
3194           continue;
3195         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3196           // Just reorder reuses indices.
3197           reorderReuses(TE->ReuseShuffleIndices, Mask);
3198           continue;
3199         }
3200         // Gathers are processed separately.
3201         if (TE->State != TreeEntry::Vectorize)
3202           continue;
3203         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3204                 TE->ReorderIndices.empty()) &&
3205                "Non-matching sizes of user/operand entries.");
3206         reorderOrder(TE->ReorderIndices, Mask);
3207       }
3208       // For gathers just need to reorder its scalars.
3209       for (TreeEntry *Gather : GatherOps) {
3210         assert(Gather->ReorderIndices.empty() &&
3211                "Unexpected reordering of gathers.");
3212         if (!Gather->ReuseShuffleIndices.empty()) {
3213           // Just reorder reuses indices.
3214           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3215           continue;
3216         }
3217         reorderScalars(Gather->Scalars, Mask);
3218         OrderedEntries.remove(Gather);
3219       }
3220       // Reorder operands of the user node and set the ordering for the user
3221       // node itself.
3222       if (Data.first->State != TreeEntry::Vectorize ||
3223           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3224               Data.first->getMainOp()) ||
3225           Data.first->isAltShuffle())
3226         Data.first->reorderOperands(Mask);
3227       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3228           Data.first->isAltShuffle()) {
3229         reorderScalars(Data.first->Scalars, Mask);
3230         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3231         if (Data.first->ReuseShuffleIndices.empty() &&
3232             !Data.first->ReorderIndices.empty() &&
3233             !Data.first->isAltShuffle()) {
3234           // Insert user node to the list to try to sink reordering deeper in
3235           // the graph.
3236           OrderedEntries.insert(Data.first);
3237         }
3238       } else {
3239         reorderOrder(Data.first->ReorderIndices, Mask);
3240       }
3241     }
3242   }
3243   // If the reordering is unnecessary, just remove the reorder.
3244   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3245       VectorizableTree.front()->ReuseShuffleIndices.empty())
3246     VectorizableTree.front()->ReorderIndices.clear();
3247 }
3248 
3249 void BoUpSLP::buildExternalUses(
3250     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3251   // Collect the values that we need to extract from the tree.
3252   for (auto &TEPtr : VectorizableTree) {
3253     TreeEntry *Entry = TEPtr.get();
3254 
3255     // No need to handle users of gathered values.
3256     if (Entry->State == TreeEntry::NeedToGather)
3257       continue;
3258 
3259     // For each lane:
3260     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3261       Value *Scalar = Entry->Scalars[Lane];
3262       int FoundLane = Entry->findLaneForValue(Scalar);
3263 
3264       // Check if the scalar is externally used as an extra arg.
3265       auto ExtI = ExternallyUsedValues.find(Scalar);
3266       if (ExtI != ExternallyUsedValues.end()) {
3267         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3268                           << Lane << " from " << *Scalar << ".\n");
3269         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3270       }
3271       for (User *U : Scalar->users()) {
3272         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3273 
3274         Instruction *UserInst = dyn_cast<Instruction>(U);
3275         if (!UserInst)
3276           continue;
3277 
3278         if (isDeleted(UserInst))
3279           continue;
3280 
3281         // Skip in-tree scalars that become vectors
3282         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3283           Value *UseScalar = UseEntry->Scalars[0];
3284           // Some in-tree scalars will remain as scalar in vectorized
3285           // instructions. If that is the case, the one in Lane 0 will
3286           // be used.
3287           if (UseScalar != U ||
3288               UseEntry->State == TreeEntry::ScatterVectorize ||
3289               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3290             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3291                               << ".\n");
3292             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3293             continue;
3294           }
3295         }
3296 
3297         // Ignore users in the user ignore list.
3298         if (is_contained(UserIgnoreList, UserInst))
3299           continue;
3300 
3301         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3302                           << Lane << " from " << *Scalar << ".\n");
3303         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3304       }
3305     }
3306   }
3307 }
3308 
3309 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3310                         ArrayRef<Value *> UserIgnoreLst) {
3311   deleteTree();
3312   UserIgnoreList = UserIgnoreLst;
3313   if (!allSameType(Roots))
3314     return;
3315   buildTree_rec(Roots, 0, EdgeInfo());
3316 }
3317 
3318 namespace {
3319 /// Tracks the state we can represent the loads in the given sequence.
3320 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3321 } // anonymous namespace
3322 
3323 /// Checks if the given array of loads can be represented as a vectorized,
3324 /// scatter or just simple gather.
3325 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3326                                     const TargetTransformInfo &TTI,
3327                                     const DataLayout &DL, ScalarEvolution &SE,
3328                                     SmallVectorImpl<unsigned> &Order,
3329                                     SmallVectorImpl<Value *> &PointerOps) {
3330   // Check that a vectorized load would load the same memory as a scalar
3331   // load. For example, we don't want to vectorize loads that are smaller
3332   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3333   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3334   // from such a struct, we read/write packed bits disagreeing with the
3335   // unvectorized version.
3336   Type *ScalarTy = VL0->getType();
3337 
3338   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3339     return LoadsState::Gather;
3340 
3341   // Make sure all loads in the bundle are simple - we can't vectorize
3342   // atomic or volatile loads.
3343   PointerOps.clear();
3344   PointerOps.resize(VL.size());
3345   auto *POIter = PointerOps.begin();
3346   for (Value *V : VL) {
3347     auto *L = cast<LoadInst>(V);
3348     if (!L->isSimple())
3349       return LoadsState::Gather;
3350     *POIter = L->getPointerOperand();
3351     ++POIter;
3352   }
3353 
3354   Order.clear();
3355   // Check the order of pointer operands.
3356   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3357     Value *Ptr0;
3358     Value *PtrN;
3359     if (Order.empty()) {
3360       Ptr0 = PointerOps.front();
3361       PtrN = PointerOps.back();
3362     } else {
3363       Ptr0 = PointerOps[Order.front()];
3364       PtrN = PointerOps[Order.back()];
3365     }
3366     Optional<int> Diff =
3367         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3368     // Check that the sorted loads are consecutive.
3369     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3370       return LoadsState::Vectorize;
3371     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3372     for (Value *V : VL)
3373       CommonAlignment =
3374           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3375     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3376                                 CommonAlignment))
3377       return LoadsState::ScatterVectorize;
3378   }
3379 
3380   return LoadsState::Gather;
3381 }
3382 
3383 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3384                             const EdgeInfo &UserTreeIdx) {
3385   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3386 
3387   SmallVector<int> ReuseShuffleIndicies;
3388   SmallVector<Value *> UniqueValues;
3389   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3390                                 &UserTreeIdx,
3391                                 this](const InstructionsState &S) {
3392     // Check that every instruction appears once in this bundle.
3393     DenseMap<Value *, unsigned> UniquePositions;
3394     for (Value *V : VL) {
3395       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3396       ReuseShuffleIndicies.emplace_back(isa<UndefValue>(V) ? -1
3397                                                            : Res.first->second);
3398       if (Res.second)
3399         UniqueValues.emplace_back(V);
3400     }
3401     size_t NumUniqueScalarValues = UniqueValues.size();
3402     if (NumUniqueScalarValues == VL.size()) {
3403       ReuseShuffleIndicies.clear();
3404     } else {
3405       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3406       if (NumUniqueScalarValues <= 1 ||
3407           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3408         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3409         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3410         return false;
3411       }
3412       VL = UniqueValues;
3413     }
3414     return true;
3415   };
3416 
3417   InstructionsState S = getSameOpcode(VL);
3418   if (Depth == RecursionMaxDepth) {
3419     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3420     if (TryToFindDuplicates(S))
3421       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3422                    ReuseShuffleIndicies);
3423     return;
3424   }
3425 
3426   // Don't handle scalable vectors
3427   if (S.getOpcode() == Instruction::ExtractElement &&
3428       isa<ScalableVectorType>(
3429           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3430     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3431     if (TryToFindDuplicates(S))
3432       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3433                    ReuseShuffleIndicies);
3434     return;
3435   }
3436 
3437   // Don't handle vectors.
3438   if (S.OpValue->getType()->isVectorTy() &&
3439       !isa<InsertElementInst>(S.OpValue)) {
3440     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3441     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3442     return;
3443   }
3444 
3445   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3446     if (SI->getValueOperand()->getType()->isVectorTy()) {
3447       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3448       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3449       return;
3450     }
3451 
3452   // If all of the operands are identical or constant we have a simple solution.
3453   // If we deal with insert/extract instructions, they all must have constant
3454   // indices, otherwise we should gather them, not try to vectorize.
3455   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3456       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3457        !all_of(VL, isVectorLikeInstWithConstOps))) {
3458     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3459     if (TryToFindDuplicates(S))
3460       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3461                    ReuseShuffleIndicies);
3462     return;
3463   }
3464 
3465   // We now know that this is a vector of instructions of the same type from
3466   // the same block.
3467 
3468   // Don't vectorize ephemeral values.
3469   for (Value *V : VL) {
3470     if (EphValues.count(V)) {
3471       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3472                         << ") is ephemeral.\n");
3473       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3474       return;
3475     }
3476   }
3477 
3478   // Check if this is a duplicate of another entry.
3479   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3480     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3481     if (!E->isSame(VL)) {
3482       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3483       if (TryToFindDuplicates(S))
3484         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3485                      ReuseShuffleIndicies);
3486       return;
3487     }
3488     // Record the reuse of the tree node.  FIXME, currently this is only used to
3489     // properly draw the graph rather than for the actual vectorization.
3490     E->UserTreeIndices.push_back(UserTreeIdx);
3491     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3492                       << ".\n");
3493     return;
3494   }
3495 
3496   // Check that none of the instructions in the bundle are already in the tree.
3497   for (Value *V : VL) {
3498     auto *I = dyn_cast<Instruction>(V);
3499     if (!I)
3500       continue;
3501     if (getTreeEntry(I)) {
3502       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3503                         << ") is already in tree.\n");
3504       if (TryToFindDuplicates(S))
3505         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3506                      ReuseShuffleIndicies);
3507       return;
3508     }
3509   }
3510 
3511   // If any of the scalars is marked as a value that needs to stay scalar, then
3512   // we need to gather the scalars.
3513   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3514   for (Value *V : VL) {
3515     if (MustGather.count(V) || is_contained(UserIgnoreList, V)) {
3516       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3517       if (TryToFindDuplicates(S))
3518         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3519                      ReuseShuffleIndicies);
3520       return;
3521     }
3522   }
3523 
3524   // Check that all of the users of the scalars that we want to vectorize are
3525   // schedulable.
3526   auto *VL0 = cast<Instruction>(S.OpValue);
3527   BasicBlock *BB = VL0->getParent();
3528 
3529   if (!DT->isReachableFromEntry(BB)) {
3530     // Don't go into unreachable blocks. They may contain instructions with
3531     // dependency cycles which confuse the final scheduling.
3532     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3533     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3534     return;
3535   }
3536 
3537   // Check that every instruction appears once in this bundle.
3538   if (!TryToFindDuplicates(S))
3539     return;
3540 
3541   auto &BSRef = BlocksSchedules[BB];
3542   if (!BSRef)
3543     BSRef = std::make_unique<BlockScheduling>(BB);
3544 
3545   BlockScheduling &BS = *BSRef.get();
3546 
3547   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3548   if (!Bundle) {
3549     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3550     assert((!BS.getScheduleData(VL0) ||
3551             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3552            "tryScheduleBundle should cancelScheduling on failure");
3553     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3554                  ReuseShuffleIndicies);
3555     return;
3556   }
3557   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3558 
3559   unsigned ShuffleOrOp = S.isAltShuffle() ?
3560                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3561   switch (ShuffleOrOp) {
3562     case Instruction::PHI: {
3563       auto *PH = cast<PHINode>(VL0);
3564 
3565       // Check for terminator values (e.g. invoke).
3566       for (Value *V : VL)
3567         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3568           Instruction *Term = dyn_cast<Instruction>(
3569               cast<PHINode>(V)->getIncomingValueForBlock(
3570                   PH->getIncomingBlock(I)));
3571           if (Term && Term->isTerminator()) {
3572             LLVM_DEBUG(dbgs()
3573                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3574             BS.cancelScheduling(VL, VL0);
3575             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3576                          ReuseShuffleIndicies);
3577             return;
3578           }
3579         }
3580 
3581       TreeEntry *TE =
3582           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3583       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3584 
3585       // Keeps the reordered operands to avoid code duplication.
3586       SmallVector<ValueList, 2> OperandsVec;
3587       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3588         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3589           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3590           TE->setOperand(I, Operands);
3591           OperandsVec.push_back(Operands);
3592           continue;
3593         }
3594         ValueList Operands;
3595         // Prepare the operand vector.
3596         for (Value *V : VL)
3597           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3598               PH->getIncomingBlock(I)));
3599         TE->setOperand(I, Operands);
3600         OperandsVec.push_back(Operands);
3601       }
3602       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3603         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3604       return;
3605     }
3606     case Instruction::ExtractValue:
3607     case Instruction::ExtractElement: {
3608       OrdersType CurrentOrder;
3609       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3610       if (Reuse) {
3611         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3612         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3613                      ReuseShuffleIndicies);
3614         // This is a special case, as it does not gather, but at the same time
3615         // we are not extending buildTree_rec() towards the operands.
3616         ValueList Op0;
3617         Op0.assign(VL.size(), VL0->getOperand(0));
3618         VectorizableTree.back()->setOperand(0, Op0);
3619         return;
3620       }
3621       if (!CurrentOrder.empty()) {
3622         LLVM_DEBUG({
3623           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3624                     "with order";
3625           for (unsigned Idx : CurrentOrder)
3626             dbgs() << " " << Idx;
3627           dbgs() << "\n";
3628         });
3629         fixupOrderingIndices(CurrentOrder);
3630         // Insert new order with initial value 0, if it does not exist,
3631         // otherwise return the iterator to the existing one.
3632         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3633                      ReuseShuffleIndicies, CurrentOrder);
3634         // This is a special case, as it does not gather, but at the same time
3635         // we are not extending buildTree_rec() towards the operands.
3636         ValueList Op0;
3637         Op0.assign(VL.size(), VL0->getOperand(0));
3638         VectorizableTree.back()->setOperand(0, Op0);
3639         return;
3640       }
3641       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3642       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3643                    ReuseShuffleIndicies);
3644       BS.cancelScheduling(VL, VL0);
3645       return;
3646     }
3647     case Instruction::InsertElement: {
3648       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3649 
3650       // Check that we have a buildvector and not a shuffle of 2 or more
3651       // different vectors.
3652       ValueSet SourceVectors;
3653       int MinIdx = std::numeric_limits<int>::max();
3654       for (Value *V : VL) {
3655         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3656         Optional<int> Idx = *getInsertIndex(V, 0);
3657         if (!Idx || *Idx == UndefMaskElem)
3658           continue;
3659         MinIdx = std::min(MinIdx, *Idx);
3660       }
3661 
3662       if (count_if(VL, [&SourceVectors](Value *V) {
3663             return !SourceVectors.contains(V);
3664           }) >= 2) {
3665         // Found 2nd source vector - cancel.
3666         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3667                              "different source vectors.\n");
3668         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3669         BS.cancelScheduling(VL, VL0);
3670         return;
3671       }
3672 
3673       auto OrdCompare = [](const std::pair<int, int> &P1,
3674                            const std::pair<int, int> &P2) {
3675         return P1.first > P2.first;
3676       };
3677       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3678                     decltype(OrdCompare)>
3679           Indices(OrdCompare);
3680       for (int I = 0, E = VL.size(); I < E; ++I) {
3681         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3682         if (!Idx || *Idx == UndefMaskElem)
3683           continue;
3684         Indices.emplace(*Idx, I);
3685       }
3686       OrdersType CurrentOrder(VL.size(), VL.size());
3687       bool IsIdentity = true;
3688       for (int I = 0, E = VL.size(); I < E; ++I) {
3689         CurrentOrder[Indices.top().second] = I;
3690         IsIdentity &= Indices.top().second == I;
3691         Indices.pop();
3692       }
3693       if (IsIdentity)
3694         CurrentOrder.clear();
3695       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3696                                    None, CurrentOrder);
3697       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3698 
3699       constexpr int NumOps = 2;
3700       ValueList VectorOperands[NumOps];
3701       for (int I = 0; I < NumOps; ++I) {
3702         for (Value *V : VL)
3703           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3704 
3705         TE->setOperand(I, VectorOperands[I]);
3706       }
3707       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3708       return;
3709     }
3710     case Instruction::Load: {
3711       // Check that a vectorized load would load the same memory as a scalar
3712       // load. For example, we don't want to vectorize loads that are smaller
3713       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3714       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3715       // from such a struct, we read/write packed bits disagreeing with the
3716       // unvectorized version.
3717       SmallVector<Value *> PointerOps;
3718       OrdersType CurrentOrder;
3719       TreeEntry *TE = nullptr;
3720       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3721                                 PointerOps)) {
3722       case LoadsState::Vectorize:
3723         if (CurrentOrder.empty()) {
3724           // Original loads are consecutive and does not require reordering.
3725           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3726                             ReuseShuffleIndicies);
3727           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3728         } else {
3729           fixupOrderingIndices(CurrentOrder);
3730           // Need to reorder.
3731           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3732                             ReuseShuffleIndicies, CurrentOrder);
3733           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
3734         }
3735         TE->setOperandsInOrder();
3736         break;
3737       case LoadsState::ScatterVectorize:
3738         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3739         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
3740                           UserTreeIdx, ReuseShuffleIndicies);
3741         TE->setOperandsInOrder();
3742         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
3743         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
3744         break;
3745       case LoadsState::Gather:
3746         BS.cancelScheduling(VL, VL0);
3747         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3748                      ReuseShuffleIndicies);
3749 #ifndef NDEBUG
3750         Type *ScalarTy = VL0->getType();
3751         if (DL->getTypeSizeInBits(ScalarTy) !=
3752             DL->getTypeAllocSizeInBits(ScalarTy))
3753           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
3754         else if (any_of(VL, [](Value *V) {
3755                    return !cast<LoadInst>(V)->isSimple();
3756                  }))
3757           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
3758         else
3759           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
3760 #endif // NDEBUG
3761         break;
3762       }
3763       return;
3764     }
3765     case Instruction::ZExt:
3766     case Instruction::SExt:
3767     case Instruction::FPToUI:
3768     case Instruction::FPToSI:
3769     case Instruction::FPExt:
3770     case Instruction::PtrToInt:
3771     case Instruction::IntToPtr:
3772     case Instruction::SIToFP:
3773     case Instruction::UIToFP:
3774     case Instruction::Trunc:
3775     case Instruction::FPTrunc:
3776     case Instruction::BitCast: {
3777       Type *SrcTy = VL0->getOperand(0)->getType();
3778       for (Value *V : VL) {
3779         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
3780         if (Ty != SrcTy || !isValidElementType(Ty)) {
3781           BS.cancelScheduling(VL, VL0);
3782           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3783                        ReuseShuffleIndicies);
3784           LLVM_DEBUG(dbgs()
3785                      << "SLP: Gathering casts with different src types.\n");
3786           return;
3787         }
3788       }
3789       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3790                                    ReuseShuffleIndicies);
3791       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
3792 
3793       TE->setOperandsInOrder();
3794       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3795         ValueList Operands;
3796         // Prepare the operand vector.
3797         for (Value *V : VL)
3798           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3799 
3800         buildTree_rec(Operands, Depth + 1, {TE, i});
3801       }
3802       return;
3803     }
3804     case Instruction::ICmp:
3805     case Instruction::FCmp: {
3806       // Check that all of the compares have the same predicate.
3807       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3808       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
3809       Type *ComparedTy = VL0->getOperand(0)->getType();
3810       for (Value *V : VL) {
3811         CmpInst *Cmp = cast<CmpInst>(V);
3812         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
3813             Cmp->getOperand(0)->getType() != ComparedTy) {
3814           BS.cancelScheduling(VL, VL0);
3815           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3816                        ReuseShuffleIndicies);
3817           LLVM_DEBUG(dbgs()
3818                      << "SLP: Gathering cmp with different predicate.\n");
3819           return;
3820         }
3821       }
3822 
3823       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3824                                    ReuseShuffleIndicies);
3825       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
3826 
3827       ValueList Left, Right;
3828       if (cast<CmpInst>(VL0)->isCommutative()) {
3829         // Commutative predicate - collect + sort operands of the instructions
3830         // so that each side is more likely to have the same opcode.
3831         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
3832         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3833       } else {
3834         // Collect operands - commute if it uses the swapped predicate.
3835         for (Value *V : VL) {
3836           auto *Cmp = cast<CmpInst>(V);
3837           Value *LHS = Cmp->getOperand(0);
3838           Value *RHS = Cmp->getOperand(1);
3839           if (Cmp->getPredicate() != P0)
3840             std::swap(LHS, RHS);
3841           Left.push_back(LHS);
3842           Right.push_back(RHS);
3843         }
3844       }
3845       TE->setOperand(0, Left);
3846       TE->setOperand(1, Right);
3847       buildTree_rec(Left, Depth + 1, {TE, 0});
3848       buildTree_rec(Right, Depth + 1, {TE, 1});
3849       return;
3850     }
3851     case Instruction::Select:
3852     case Instruction::FNeg:
3853     case Instruction::Add:
3854     case Instruction::FAdd:
3855     case Instruction::Sub:
3856     case Instruction::FSub:
3857     case Instruction::Mul:
3858     case Instruction::FMul:
3859     case Instruction::UDiv:
3860     case Instruction::SDiv:
3861     case Instruction::FDiv:
3862     case Instruction::URem:
3863     case Instruction::SRem:
3864     case Instruction::FRem:
3865     case Instruction::Shl:
3866     case Instruction::LShr:
3867     case Instruction::AShr:
3868     case Instruction::And:
3869     case Instruction::Or:
3870     case Instruction::Xor: {
3871       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3872                                    ReuseShuffleIndicies);
3873       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
3874 
3875       // Sort operands of the instructions so that each side is more likely to
3876       // have the same opcode.
3877       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
3878         ValueList Left, Right;
3879         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3880         TE->setOperand(0, Left);
3881         TE->setOperand(1, Right);
3882         buildTree_rec(Left, Depth + 1, {TE, 0});
3883         buildTree_rec(Right, Depth + 1, {TE, 1});
3884         return;
3885       }
3886 
3887       TE->setOperandsInOrder();
3888       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3889         ValueList Operands;
3890         // Prepare the operand vector.
3891         for (Value *V : VL)
3892           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3893 
3894         buildTree_rec(Operands, Depth + 1, {TE, i});
3895       }
3896       return;
3897     }
3898     case Instruction::GetElementPtr: {
3899       // We don't combine GEPs with complicated (nested) indexing.
3900       for (Value *V : VL) {
3901         if (cast<Instruction>(V)->getNumOperands() != 2) {
3902           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
3903           BS.cancelScheduling(VL, VL0);
3904           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3905                        ReuseShuffleIndicies);
3906           return;
3907         }
3908       }
3909 
3910       // We can't combine several GEPs into one vector if they operate on
3911       // different types.
3912       Type *Ty0 = VL0->getOperand(0)->getType();
3913       for (Value *V : VL) {
3914         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
3915         if (Ty0 != CurTy) {
3916           LLVM_DEBUG(dbgs()
3917                      << "SLP: not-vectorizable GEP (different types).\n");
3918           BS.cancelScheduling(VL, VL0);
3919           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3920                        ReuseShuffleIndicies);
3921           return;
3922         }
3923       }
3924 
3925       // We don't combine GEPs with non-constant indexes.
3926       Type *Ty1 = VL0->getOperand(1)->getType();
3927       for (Value *V : VL) {
3928         auto Op = cast<Instruction>(V)->getOperand(1);
3929         if (!isa<ConstantInt>(Op) ||
3930             (Op->getType() != Ty1 &&
3931              Op->getType()->getScalarSizeInBits() >
3932                  DL->getIndexSizeInBits(
3933                      V->getType()->getPointerAddressSpace()))) {
3934           LLVM_DEBUG(dbgs()
3935                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
3936           BS.cancelScheduling(VL, VL0);
3937           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3938                        ReuseShuffleIndicies);
3939           return;
3940         }
3941       }
3942 
3943       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3944                                    ReuseShuffleIndicies);
3945       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
3946       SmallVector<ValueList, 2> Operands(2);
3947       // Prepare the operand vector for pointer operands.
3948       for (Value *V : VL)
3949         Operands.front().push_back(
3950             cast<GetElementPtrInst>(V)->getPointerOperand());
3951       TE->setOperand(0, Operands.front());
3952       // Need to cast all indices to the same type before vectorization to
3953       // avoid crash.
3954       // Required to be able to find correct matches between different gather
3955       // nodes and reuse the vectorized values rather than trying to gather them
3956       // again.
3957       int IndexIdx = 1;
3958       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
3959       Type *Ty = all_of(VL,
3960                         [VL0Ty, IndexIdx](Value *V) {
3961                           return VL0Ty == cast<GetElementPtrInst>(V)
3962                                               ->getOperand(IndexIdx)
3963                                               ->getType();
3964                         })
3965                      ? VL0Ty
3966                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
3967                                             ->getPointerOperandType()
3968                                             ->getScalarType());
3969       // Prepare the operand vector.
3970       for (Value *V : VL) {
3971         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
3972         auto *CI = cast<ConstantInt>(Op);
3973         Operands.back().push_back(ConstantExpr::getIntegerCast(
3974             CI, Ty, CI->getValue().isSignBitSet()));
3975       }
3976       TE->setOperand(IndexIdx, Operands.back());
3977 
3978       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
3979         buildTree_rec(Operands[I], Depth + 1, {TE, I});
3980       return;
3981     }
3982     case Instruction::Store: {
3983       // Check if the stores are consecutive or if we need to swizzle them.
3984       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
3985       // Avoid types that are padded when being allocated as scalars, while
3986       // being packed together in a vector (such as i1).
3987       if (DL->getTypeSizeInBits(ScalarTy) !=
3988           DL->getTypeAllocSizeInBits(ScalarTy)) {
3989         BS.cancelScheduling(VL, VL0);
3990         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3991                      ReuseShuffleIndicies);
3992         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
3993         return;
3994       }
3995       // Make sure all stores in the bundle are simple - we can't vectorize
3996       // atomic or volatile stores.
3997       SmallVector<Value *, 4> PointerOps(VL.size());
3998       ValueList Operands(VL.size());
3999       auto POIter = PointerOps.begin();
4000       auto OIter = Operands.begin();
4001       for (Value *V : VL) {
4002         auto *SI = cast<StoreInst>(V);
4003         if (!SI->isSimple()) {
4004           BS.cancelScheduling(VL, VL0);
4005           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4006                        ReuseShuffleIndicies);
4007           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4008           return;
4009         }
4010         *POIter = SI->getPointerOperand();
4011         *OIter = SI->getValueOperand();
4012         ++POIter;
4013         ++OIter;
4014       }
4015 
4016       OrdersType CurrentOrder;
4017       // Check the order of pointer operands.
4018       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4019         Value *Ptr0;
4020         Value *PtrN;
4021         if (CurrentOrder.empty()) {
4022           Ptr0 = PointerOps.front();
4023           PtrN = PointerOps.back();
4024         } else {
4025           Ptr0 = PointerOps[CurrentOrder.front()];
4026           PtrN = PointerOps[CurrentOrder.back()];
4027         }
4028         Optional<int> Dist =
4029             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4030         // Check that the sorted pointer operands are consecutive.
4031         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4032           if (CurrentOrder.empty()) {
4033             // Original stores are consecutive and does not require reordering.
4034             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4035                                          UserTreeIdx, ReuseShuffleIndicies);
4036             TE->setOperandsInOrder();
4037             buildTree_rec(Operands, Depth + 1, {TE, 0});
4038             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4039           } else {
4040             fixupOrderingIndices(CurrentOrder);
4041             TreeEntry *TE =
4042                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4043                              ReuseShuffleIndicies, CurrentOrder);
4044             TE->setOperandsInOrder();
4045             buildTree_rec(Operands, Depth + 1, {TE, 0});
4046             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4047           }
4048           return;
4049         }
4050       }
4051 
4052       BS.cancelScheduling(VL, VL0);
4053       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4054                    ReuseShuffleIndicies);
4055       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4056       return;
4057     }
4058     case Instruction::Call: {
4059       // Check if the calls are all to the same vectorizable intrinsic or
4060       // library function.
4061       CallInst *CI = cast<CallInst>(VL0);
4062       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4063 
4064       VFShape Shape = VFShape::get(
4065           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4066           false /*HasGlobalPred*/);
4067       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4068 
4069       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4070         BS.cancelScheduling(VL, VL0);
4071         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4072                      ReuseShuffleIndicies);
4073         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4074         return;
4075       }
4076       Function *F = CI->getCalledFunction();
4077       unsigned NumArgs = CI->arg_size();
4078       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4079       for (unsigned j = 0; j != NumArgs; ++j)
4080         if (hasVectorInstrinsicScalarOpd(ID, j))
4081           ScalarArgs[j] = CI->getArgOperand(j);
4082       for (Value *V : VL) {
4083         CallInst *CI2 = dyn_cast<CallInst>(V);
4084         if (!CI2 || CI2->getCalledFunction() != F ||
4085             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4086             (VecFunc &&
4087              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4088             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4089           BS.cancelScheduling(VL, VL0);
4090           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4091                        ReuseShuffleIndicies);
4092           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4093                             << "\n");
4094           return;
4095         }
4096         // Some intrinsics have scalar arguments and should be same in order for
4097         // them to be vectorized.
4098         for (unsigned j = 0; j != NumArgs; ++j) {
4099           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4100             Value *A1J = CI2->getArgOperand(j);
4101             if (ScalarArgs[j] != A1J) {
4102               BS.cancelScheduling(VL, VL0);
4103               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4104                            ReuseShuffleIndicies);
4105               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4106                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4107                                 << "\n");
4108               return;
4109             }
4110           }
4111         }
4112         // Verify that the bundle operands are identical between the two calls.
4113         if (CI->hasOperandBundles() &&
4114             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4115                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4116                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4117           BS.cancelScheduling(VL, VL0);
4118           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4119                        ReuseShuffleIndicies);
4120           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4121                             << *CI << "!=" << *V << '\n');
4122           return;
4123         }
4124       }
4125 
4126       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4127                                    ReuseShuffleIndicies);
4128       TE->setOperandsInOrder();
4129       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4130         // For scalar operands no need to to create an entry since no need to
4131         // vectorize it.
4132         if (hasVectorInstrinsicScalarOpd(ID, i))
4133           continue;
4134         ValueList Operands;
4135         // Prepare the operand vector.
4136         for (Value *V : VL) {
4137           auto *CI2 = cast<CallInst>(V);
4138           Operands.push_back(CI2->getArgOperand(i));
4139         }
4140         buildTree_rec(Operands, Depth + 1, {TE, i});
4141       }
4142       return;
4143     }
4144     case Instruction::ShuffleVector: {
4145       // If this is not an alternate sequence of opcode like add-sub
4146       // then do not vectorize this instruction.
4147       if (!S.isAltShuffle()) {
4148         BS.cancelScheduling(VL, VL0);
4149         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4150                      ReuseShuffleIndicies);
4151         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4152         return;
4153       }
4154       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4155                                    ReuseShuffleIndicies);
4156       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4157 
4158       // Reorder operands if reordering would enable vectorization.
4159       if (isa<BinaryOperator>(VL0)) {
4160         ValueList Left, Right;
4161         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4162         TE->setOperand(0, Left);
4163         TE->setOperand(1, Right);
4164         buildTree_rec(Left, Depth + 1, {TE, 0});
4165         buildTree_rec(Right, Depth + 1, {TE, 1});
4166         return;
4167       }
4168 
4169       TE->setOperandsInOrder();
4170       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4171         ValueList Operands;
4172         // Prepare the operand vector.
4173         for (Value *V : VL)
4174           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4175 
4176         buildTree_rec(Operands, Depth + 1, {TE, i});
4177       }
4178       return;
4179     }
4180     default:
4181       BS.cancelScheduling(VL, VL0);
4182       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4183                    ReuseShuffleIndicies);
4184       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4185       return;
4186   }
4187 }
4188 
4189 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4190   unsigned N = 1;
4191   Type *EltTy = T;
4192 
4193   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4194          isa<VectorType>(EltTy)) {
4195     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4196       // Check that struct is homogeneous.
4197       for (const auto *Ty : ST->elements())
4198         if (Ty != *ST->element_begin())
4199           return 0;
4200       N *= ST->getNumElements();
4201       EltTy = *ST->element_begin();
4202     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4203       N *= AT->getNumElements();
4204       EltTy = AT->getElementType();
4205     } else {
4206       auto *VT = cast<FixedVectorType>(EltTy);
4207       N *= VT->getNumElements();
4208       EltTy = VT->getElementType();
4209     }
4210   }
4211 
4212   if (!isValidElementType(EltTy))
4213     return 0;
4214   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4215   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4216     return 0;
4217   return N;
4218 }
4219 
4220 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4221                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4222   Instruction *E0 = cast<Instruction>(OpValue);
4223   assert(E0->getOpcode() == Instruction::ExtractElement ||
4224          E0->getOpcode() == Instruction::ExtractValue);
4225   assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
4226   // Check if all of the extracts come from the same vector and from the
4227   // correct offset.
4228   Value *Vec = E0->getOperand(0);
4229 
4230   CurrentOrder.clear();
4231 
4232   // We have to extract from a vector/aggregate with the same number of elements.
4233   unsigned NElts;
4234   if (E0->getOpcode() == Instruction::ExtractValue) {
4235     const DataLayout &DL = E0->getModule()->getDataLayout();
4236     NElts = canMapToVector(Vec->getType(), DL);
4237     if (!NElts)
4238       return false;
4239     // Check if load can be rewritten as load of vector.
4240     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4241     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4242       return false;
4243   } else {
4244     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4245   }
4246 
4247   if (NElts != VL.size())
4248     return false;
4249 
4250   // Check that all of the indices extract from the correct offset.
4251   bool ShouldKeepOrder = true;
4252   unsigned E = VL.size();
4253   // Assign to all items the initial value E + 1 so we can check if the extract
4254   // instruction index was used already.
4255   // Also, later we can check that all the indices are used and we have a
4256   // consecutive access in the extract instructions, by checking that no
4257   // element of CurrentOrder still has value E + 1.
4258   CurrentOrder.assign(E, E + 1);
4259   unsigned I = 0;
4260   for (; I < E; ++I) {
4261     auto *Inst = cast<Instruction>(VL[I]);
4262     if (Inst->getOperand(0) != Vec)
4263       break;
4264     Optional<unsigned> Idx = getExtractIndex(Inst);
4265     if (!Idx)
4266       break;
4267     const unsigned ExtIdx = *Idx;
4268     if (ExtIdx != I) {
4269       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
4270         break;
4271       ShouldKeepOrder = false;
4272       CurrentOrder[ExtIdx] = I;
4273     } else {
4274       if (CurrentOrder[I] != E + 1)
4275         break;
4276       CurrentOrder[I] = I;
4277     }
4278   }
4279   if (I < E) {
4280     CurrentOrder.clear();
4281     return false;
4282   }
4283 
4284   return ShouldKeepOrder;
4285 }
4286 
4287 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4288                                     ArrayRef<Value *> VectorizedVals) const {
4289   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4290          all_of(I->users(), [this](User *U) {
4291            return ScalarToTreeEntry.count(U) > 0 || MustGather.contains(U);
4292          });
4293 }
4294 
4295 static std::pair<InstructionCost, InstructionCost>
4296 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4297                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4298   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4299 
4300   // Calculate the cost of the scalar and vector calls.
4301   SmallVector<Type *, 4> VecTys;
4302   for (Use &Arg : CI->args())
4303     VecTys.push_back(
4304         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4305   FastMathFlags FMF;
4306   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4307     FMF = FPCI->getFastMathFlags();
4308   SmallVector<const Value *> Arguments(CI->args());
4309   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4310                                     dyn_cast<IntrinsicInst>(CI));
4311   auto IntrinsicCost =
4312     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4313 
4314   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4315                                      VecTy->getNumElements())),
4316                             false /*HasGlobalPred*/);
4317   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4318   auto LibCost = IntrinsicCost;
4319   if (!CI->isNoBuiltin() && VecFunc) {
4320     // Calculate the cost of the vector library call.
4321     // If the corresponding vector call is cheaper, return its cost.
4322     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4323                                     TTI::TCK_RecipThroughput);
4324   }
4325   return {IntrinsicCost, LibCost};
4326 }
4327 
4328 /// Compute the cost of creating a vector of type \p VecTy containing the
4329 /// extracted values from \p VL.
4330 static InstructionCost
4331 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4332                    TargetTransformInfo::ShuffleKind ShuffleKind,
4333                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4334   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4335 
4336   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4337       VecTy->getNumElements() < NumOfParts)
4338     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4339 
4340   bool AllConsecutive = true;
4341   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4342   unsigned Idx = -1;
4343   InstructionCost Cost = 0;
4344 
4345   // Process extracts in blocks of EltsPerVector to check if the source vector
4346   // operand can be re-used directly. If not, add the cost of creating a shuffle
4347   // to extract the values into a vector register.
4348   for (auto *V : VL) {
4349     ++Idx;
4350 
4351     // Need to exclude undefs from analysis.
4352     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4353       continue;
4354 
4355     // Reached the start of a new vector registers.
4356     if (Idx % EltsPerVector == 0) {
4357       AllConsecutive = true;
4358       continue;
4359     }
4360 
4361     // Check all extracts for a vector register on the target directly
4362     // extract values in order.
4363     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4364     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4365       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4366       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4367                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4368     }
4369 
4370     if (AllConsecutive)
4371       continue;
4372 
4373     // Skip all indices, except for the last index per vector block.
4374     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4375       continue;
4376 
4377     // If we have a series of extracts which are not consecutive and hence
4378     // cannot re-use the source vector register directly, compute the shuffle
4379     // cost to extract the a vector with EltsPerVector elements.
4380     Cost += TTI.getShuffleCost(
4381         TargetTransformInfo::SK_PermuteSingleSrc,
4382         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4383   }
4384   return Cost;
4385 }
4386 
4387 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4388 /// operations operands.
4389 static void
4390 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4391                      ArrayRef<int> ReusesIndices,
4392                      const function_ref<bool(Instruction *)> IsAltOp,
4393                      SmallVectorImpl<int> &Mask,
4394                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4395                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4396   unsigned Sz = VL.size();
4397   Mask.assign(Sz, UndefMaskElem);
4398   SmallVector<int> OrderMask;
4399   if (!ReorderIndices.empty())
4400     inversePermutation(ReorderIndices, OrderMask);
4401   for (unsigned I = 0; I < Sz; ++I) {
4402     unsigned Idx = I;
4403     if (!ReorderIndices.empty())
4404       Idx = OrderMask[I];
4405     auto *OpInst = cast<Instruction>(VL[Idx]);
4406     if (IsAltOp(OpInst)) {
4407       Mask[I] = Sz + Idx;
4408       if (AltScalars)
4409         AltScalars->push_back(OpInst);
4410     } else {
4411       Mask[I] = Idx;
4412       if (OpScalars)
4413         OpScalars->push_back(OpInst);
4414     }
4415   }
4416   if (!ReusesIndices.empty()) {
4417     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4418     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4419       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4420     });
4421     Mask.swap(NewMask);
4422   }
4423 }
4424 
4425 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4426                                       ArrayRef<Value *> VectorizedVals) {
4427   ArrayRef<Value*> VL = E->Scalars;
4428 
4429   Type *ScalarTy = VL[0]->getType();
4430   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4431     ScalarTy = SI->getValueOperand()->getType();
4432   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4433     ScalarTy = CI->getOperand(0)->getType();
4434   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4435     ScalarTy = IE->getOperand(1)->getType();
4436   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4437   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4438 
4439   // If we have computed a smaller type for the expression, update VecTy so
4440   // that the costs will be accurate.
4441   if (MinBWs.count(VL[0]))
4442     VecTy = FixedVectorType::get(
4443         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4444   unsigned EntryVF = E->getVectorFactor();
4445   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4446 
4447   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4448   // FIXME: it tries to fix a problem with MSVC buildbots.
4449   TargetTransformInfo &TTIRef = *TTI;
4450   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4451                                VectorizedVals, E](InstructionCost &Cost) {
4452     DenseMap<Value *, int> ExtractVectorsTys;
4453     SmallPtrSet<Value *, 4> CheckedExtracts;
4454     for (auto *V : VL) {
4455       if (isa<UndefValue>(V))
4456         continue;
4457       // If all users of instruction are going to be vectorized and this
4458       // instruction itself is not going to be vectorized, consider this
4459       // instruction as dead and remove its cost from the final cost of the
4460       // vectorized tree.
4461       // Also, avoid adjusting the cost for extractelements with multiple uses
4462       // in different graph entries.
4463       const TreeEntry *VE = getTreeEntry(V);
4464       if (!CheckedExtracts.insert(V).second ||
4465           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4466           (VE && VE != E))
4467         continue;
4468       auto *EE = cast<ExtractElementInst>(V);
4469       Optional<unsigned> EEIdx = getExtractIndex(EE);
4470       if (!EEIdx)
4471         continue;
4472       unsigned Idx = *EEIdx;
4473       if (TTIRef.getNumberOfParts(VecTy) !=
4474           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4475         auto It =
4476             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4477         It->getSecond() = std::min<int>(It->second, Idx);
4478       }
4479       // Take credit for instruction that will become dead.
4480       if (EE->hasOneUse()) {
4481         Instruction *Ext = EE->user_back();
4482         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4483             all_of(Ext->users(),
4484                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4485           // Use getExtractWithExtendCost() to calculate the cost of
4486           // extractelement/ext pair.
4487           Cost -=
4488               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4489                                               EE->getVectorOperandType(), Idx);
4490           // Add back the cost of s|zext which is subtracted separately.
4491           Cost += TTIRef.getCastInstrCost(
4492               Ext->getOpcode(), Ext->getType(), EE->getType(),
4493               TTI::getCastContextHint(Ext), CostKind, Ext);
4494           continue;
4495         }
4496       }
4497       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4498                                         EE->getVectorOperandType(), Idx);
4499     }
4500     // Add a cost for subvector extracts/inserts if required.
4501     for (const auto &Data : ExtractVectorsTys) {
4502       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4503       unsigned NumElts = VecTy->getNumElements();
4504       if (Data.second % NumElts == 0)
4505         continue;
4506       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4507         unsigned Idx = (Data.second / NumElts) * NumElts;
4508         unsigned EENumElts = EEVTy->getNumElements();
4509         if (Idx + NumElts <= EENumElts) {
4510           Cost +=
4511               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4512                                     EEVTy, None, Idx, VecTy);
4513         } else {
4514           // Need to round up the subvector type vectorization factor to avoid a
4515           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4516           // <= EENumElts.
4517           auto *SubVT =
4518               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4519           Cost +=
4520               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4521                                     EEVTy, None, Idx, SubVT);
4522         }
4523       } else {
4524         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4525                                       VecTy, None, 0, EEVTy);
4526       }
4527     }
4528   };
4529   if (E->State == TreeEntry::NeedToGather) {
4530     if (allConstant(VL))
4531       return 0;
4532     if (isa<InsertElementInst>(VL[0]))
4533       return InstructionCost::getInvalid();
4534     SmallVector<int> Mask;
4535     SmallVector<const TreeEntry *> Entries;
4536     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4537         isGatherShuffledEntry(E, Mask, Entries);
4538     if (Shuffle.hasValue()) {
4539       InstructionCost GatherCost = 0;
4540       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4541         // Perfect match in the graph, will reuse the previously vectorized
4542         // node. Cost is 0.
4543         LLVM_DEBUG(
4544             dbgs()
4545             << "SLP: perfect diamond match for gather bundle that starts with "
4546             << *VL.front() << ".\n");
4547         if (NeedToShuffleReuses)
4548           GatherCost =
4549               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4550                                   FinalVecTy, E->ReuseShuffleIndices);
4551       } else {
4552         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4553                           << " entries for bundle that starts with "
4554                           << *VL.front() << ".\n");
4555         // Detected that instead of gather we can emit a shuffle of single/two
4556         // previously vectorized nodes. Add the cost of the permutation rather
4557         // than gather.
4558         ::addMask(Mask, E->ReuseShuffleIndices);
4559         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4560       }
4561       return GatherCost;
4562     }
4563     if ((E->getOpcode() == Instruction::ExtractElement ||
4564          all_of(E->Scalars,
4565                 [](Value *V) {
4566                   return isa<ExtractElementInst, UndefValue>(V);
4567                 })) &&
4568         allSameType(VL)) {
4569       // Check that gather of extractelements can be represented as just a
4570       // shuffle of a single/two vectors the scalars are extracted from.
4571       SmallVector<int> Mask;
4572       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4573           isFixedVectorShuffle(VL, Mask);
4574       if (ShuffleKind.hasValue()) {
4575         // Found the bunch of extractelement instructions that must be gathered
4576         // into a vector and can be represented as a permutation elements in a
4577         // single input vector or of 2 input vectors.
4578         InstructionCost Cost =
4579             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4580         AdjustExtractsCost(Cost);
4581         if (NeedToShuffleReuses)
4582           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4583                                       FinalVecTy, E->ReuseShuffleIndices);
4584         return Cost;
4585       }
4586     }
4587     if (isSplat(VL)) {
4588       // Found the broadcasting of the single scalar, calculate the cost as the
4589       // broadcast.
4590       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4591     }
4592     InstructionCost ReuseShuffleCost = 0;
4593     if (NeedToShuffleReuses)
4594       ReuseShuffleCost = TTI->getShuffleCost(
4595           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4596     // Improve gather cost for gather of loads, if we can group some of the
4597     // loads into vector loads.
4598     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4599         !E->isAltShuffle()) {
4600       BoUpSLP::ValueSet VectorizedLoads;
4601       unsigned StartIdx = 0;
4602       unsigned VF = VL.size() / 2;
4603       unsigned VectorizedCnt = 0;
4604       unsigned ScatterVectorizeCnt = 0;
4605       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4606       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4607         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4608              Cnt += VF) {
4609           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4610           if (!VectorizedLoads.count(Slice.front()) &&
4611               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4612             SmallVector<Value *> PointerOps;
4613             OrdersType CurrentOrder;
4614             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4615                                               *SE, CurrentOrder, PointerOps);
4616             switch (LS) {
4617             case LoadsState::Vectorize:
4618             case LoadsState::ScatterVectorize:
4619               // Mark the vectorized loads so that we don't vectorize them
4620               // again.
4621               if (LS == LoadsState::Vectorize)
4622                 ++VectorizedCnt;
4623               else
4624                 ++ScatterVectorizeCnt;
4625               VectorizedLoads.insert(Slice.begin(), Slice.end());
4626               // If we vectorized initial block, no need to try to vectorize it
4627               // again.
4628               if (Cnt == StartIdx)
4629                 StartIdx += VF;
4630               break;
4631             case LoadsState::Gather:
4632               break;
4633             }
4634           }
4635         }
4636         // Check if the whole array was vectorized already - exit.
4637         if (StartIdx >= VL.size())
4638           break;
4639         // Found vectorizable parts - exit.
4640         if (!VectorizedLoads.empty())
4641           break;
4642       }
4643       if (!VectorizedLoads.empty()) {
4644         InstructionCost GatherCost = 0;
4645         unsigned NumParts = TTI->getNumberOfParts(VecTy);
4646         bool NeedInsertSubvectorAnalysis =
4647             !NumParts || (VL.size() / VF) > NumParts;
4648         // Get the cost for gathered loads.
4649         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4650           if (VectorizedLoads.contains(VL[I]))
4651             continue;
4652           GatherCost += getGatherCost(VL.slice(I, VF));
4653         }
4654         // The cost for vectorized loads.
4655         InstructionCost ScalarsCost = 0;
4656         for (Value *V : VectorizedLoads) {
4657           auto *LI = cast<LoadInst>(V);
4658           ScalarsCost += TTI->getMemoryOpCost(
4659               Instruction::Load, LI->getType(), LI->getAlign(),
4660               LI->getPointerAddressSpace(), CostKind, LI);
4661         }
4662         auto *LI = cast<LoadInst>(E->getMainOp());
4663         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4664         Align Alignment = LI->getAlign();
4665         GatherCost +=
4666             VectorizedCnt *
4667             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4668                                  LI->getPointerAddressSpace(), CostKind, LI);
4669         GatherCost += ScatterVectorizeCnt *
4670                       TTI->getGatherScatterOpCost(
4671                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4672                           /*VariableMask=*/false, Alignment, CostKind, LI);
4673         if (NeedInsertSubvectorAnalysis) {
4674           // Add the cost for the subvectors insert.
4675           for (int I = VF, E = VL.size(); I < E; I += VF)
4676             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
4677                                               None, I, LoadTy);
4678         }
4679         return ReuseShuffleCost + GatherCost - ScalarsCost;
4680       }
4681     }
4682     return ReuseShuffleCost + getGatherCost(VL);
4683   }
4684   InstructionCost CommonCost = 0;
4685   SmallVector<int> Mask;
4686   if (!E->ReorderIndices.empty()) {
4687     SmallVector<int> NewMask;
4688     if (E->getOpcode() == Instruction::Store) {
4689       // For stores the order is actually a mask.
4690       NewMask.resize(E->ReorderIndices.size());
4691       copy(E->ReorderIndices, NewMask.begin());
4692     } else {
4693       inversePermutation(E->ReorderIndices, NewMask);
4694     }
4695     ::addMask(Mask, NewMask);
4696   }
4697   if (NeedToShuffleReuses)
4698     ::addMask(Mask, E->ReuseShuffleIndices);
4699   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
4700     CommonCost =
4701         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
4702   assert((E->State == TreeEntry::Vectorize ||
4703           E->State == TreeEntry::ScatterVectorize) &&
4704          "Unhandled state");
4705   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
4706   Instruction *VL0 = E->getMainOp();
4707   unsigned ShuffleOrOp =
4708       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4709   switch (ShuffleOrOp) {
4710     case Instruction::PHI:
4711       return 0;
4712 
4713     case Instruction::ExtractValue:
4714     case Instruction::ExtractElement: {
4715       // The common cost of removal ExtractElement/ExtractValue instructions +
4716       // the cost of shuffles, if required to resuffle the original vector.
4717       if (NeedToShuffleReuses) {
4718         unsigned Idx = 0;
4719         for (unsigned I : E->ReuseShuffleIndices) {
4720           if (ShuffleOrOp == Instruction::ExtractElement) {
4721             auto *EE = cast<ExtractElementInst>(VL[I]);
4722             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4723                                                   EE->getVectorOperandType(),
4724                                                   *getExtractIndex(EE));
4725           } else {
4726             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4727                                                   VecTy, Idx);
4728             ++Idx;
4729           }
4730         }
4731         Idx = EntryVF;
4732         for (Value *V : VL) {
4733           if (ShuffleOrOp == Instruction::ExtractElement) {
4734             auto *EE = cast<ExtractElementInst>(V);
4735             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4736                                                   EE->getVectorOperandType(),
4737                                                   *getExtractIndex(EE));
4738           } else {
4739             --Idx;
4740             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4741                                                   VecTy, Idx);
4742           }
4743         }
4744       }
4745       if (ShuffleOrOp == Instruction::ExtractValue) {
4746         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
4747           auto *EI = cast<Instruction>(VL[I]);
4748           // Take credit for instruction that will become dead.
4749           if (EI->hasOneUse()) {
4750             Instruction *Ext = EI->user_back();
4751             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4752                 all_of(Ext->users(),
4753                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
4754               // Use getExtractWithExtendCost() to calculate the cost of
4755               // extractelement/ext pair.
4756               CommonCost -= TTI->getExtractWithExtendCost(
4757                   Ext->getOpcode(), Ext->getType(), VecTy, I);
4758               // Add back the cost of s|zext which is subtracted separately.
4759               CommonCost += TTI->getCastInstrCost(
4760                   Ext->getOpcode(), Ext->getType(), EI->getType(),
4761                   TTI::getCastContextHint(Ext), CostKind, Ext);
4762               continue;
4763             }
4764           }
4765           CommonCost -=
4766               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
4767         }
4768       } else {
4769         AdjustExtractsCost(CommonCost);
4770       }
4771       return CommonCost;
4772     }
4773     case Instruction::InsertElement: {
4774       assert(E->ReuseShuffleIndices.empty() &&
4775              "Unique insertelements only are expected.");
4776       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
4777 
4778       unsigned const NumElts = SrcVecTy->getNumElements();
4779       unsigned const NumScalars = VL.size();
4780       APInt DemandedElts = APInt::getZero(NumElts);
4781       // TODO: Add support for Instruction::InsertValue.
4782       SmallVector<int> Mask;
4783       if (!E->ReorderIndices.empty()) {
4784         inversePermutation(E->ReorderIndices, Mask);
4785         Mask.append(NumElts - NumScalars, UndefMaskElem);
4786       } else {
4787         Mask.assign(NumElts, UndefMaskElem);
4788         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
4789       }
4790       unsigned Offset = *getInsertIndex(VL0, 0);
4791       bool IsIdentity = true;
4792       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
4793       Mask.swap(PrevMask);
4794       for (unsigned I = 0; I < NumScalars; ++I) {
4795         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
4796         if (!InsertIdx || *InsertIdx == UndefMaskElem)
4797           continue;
4798         DemandedElts.setBit(*InsertIdx);
4799         IsIdentity &= *InsertIdx - Offset == I;
4800         Mask[*InsertIdx - Offset] = I;
4801       }
4802       assert(Offset < NumElts && "Failed to find vector index offset");
4803 
4804       InstructionCost Cost = 0;
4805       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
4806                                             /*Insert*/ true, /*Extract*/ false);
4807 
4808       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
4809         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
4810         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
4811         Cost += TTI->getShuffleCost(
4812             TargetTransformInfo::SK_PermuteSingleSrc,
4813             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
4814       } else if (!IsIdentity) {
4815         auto *FirstInsert =
4816             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
4817               return !is_contained(E->Scalars,
4818                                    cast<Instruction>(V)->getOperand(0));
4819             }));
4820         if (isUndefVector(FirstInsert->getOperand(0))) {
4821           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
4822         } else {
4823           SmallVector<int> InsertMask(NumElts);
4824           std::iota(InsertMask.begin(), InsertMask.end(), 0);
4825           for (unsigned I = 0; I < NumElts; I++) {
4826             if (Mask[I] != UndefMaskElem)
4827               InsertMask[Offset + I] = NumElts + I;
4828           }
4829           Cost +=
4830               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
4831         }
4832       }
4833 
4834       return Cost;
4835     }
4836     case Instruction::ZExt:
4837     case Instruction::SExt:
4838     case Instruction::FPToUI:
4839     case Instruction::FPToSI:
4840     case Instruction::FPExt:
4841     case Instruction::PtrToInt:
4842     case Instruction::IntToPtr:
4843     case Instruction::SIToFP:
4844     case Instruction::UIToFP:
4845     case Instruction::Trunc:
4846     case Instruction::FPTrunc:
4847     case Instruction::BitCast: {
4848       Type *SrcTy = VL0->getOperand(0)->getType();
4849       InstructionCost ScalarEltCost =
4850           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
4851                                 TTI::getCastContextHint(VL0), CostKind, VL0);
4852       if (NeedToShuffleReuses) {
4853         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
4854       }
4855 
4856       // Calculate the cost of this instruction.
4857       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
4858 
4859       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
4860       InstructionCost VecCost = 0;
4861       // Check if the values are candidates to demote.
4862       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
4863         VecCost = CommonCost + TTI->getCastInstrCost(
4864                                    E->getOpcode(), VecTy, SrcVecTy,
4865                                    TTI::getCastContextHint(VL0), CostKind, VL0);
4866       }
4867       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4868       return VecCost - ScalarCost;
4869     }
4870     case Instruction::FCmp:
4871     case Instruction::ICmp:
4872     case Instruction::Select: {
4873       // Calculate the cost of this instruction.
4874       InstructionCost ScalarEltCost =
4875           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
4876                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
4877       if (NeedToShuffleReuses) {
4878         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
4879       }
4880       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
4881       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4882 
4883       // Check if all entries in VL are either compares or selects with compares
4884       // as condition that have the same predicates.
4885       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
4886       bool First = true;
4887       for (auto *V : VL) {
4888         CmpInst::Predicate CurrentPred;
4889         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
4890         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
4891              !match(V, MatchCmp)) ||
4892             (!First && VecPred != CurrentPred)) {
4893           VecPred = CmpInst::BAD_ICMP_PREDICATE;
4894           break;
4895         }
4896         First = false;
4897         VecPred = CurrentPred;
4898       }
4899 
4900       InstructionCost VecCost = TTI->getCmpSelInstrCost(
4901           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
4902       // Check if it is possible and profitable to use min/max for selects in
4903       // VL.
4904       //
4905       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
4906       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
4907         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
4908                                           {VecTy, VecTy});
4909         InstructionCost IntrinsicCost =
4910             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4911         // If the selects are the only uses of the compares, they will be dead
4912         // and we can adjust the cost by removing their cost.
4913         if (IntrinsicAndUse.second)
4914           IntrinsicCost -=
4915               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
4916                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
4917         VecCost = std::min(VecCost, IntrinsicCost);
4918       }
4919       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4920       return CommonCost + VecCost - ScalarCost;
4921     }
4922     case Instruction::FNeg:
4923     case Instruction::Add:
4924     case Instruction::FAdd:
4925     case Instruction::Sub:
4926     case Instruction::FSub:
4927     case Instruction::Mul:
4928     case Instruction::FMul:
4929     case Instruction::UDiv:
4930     case Instruction::SDiv:
4931     case Instruction::FDiv:
4932     case Instruction::URem:
4933     case Instruction::SRem:
4934     case Instruction::FRem:
4935     case Instruction::Shl:
4936     case Instruction::LShr:
4937     case Instruction::AShr:
4938     case Instruction::And:
4939     case Instruction::Or:
4940     case Instruction::Xor: {
4941       // Certain instructions can be cheaper to vectorize if they have a
4942       // constant second vector operand.
4943       TargetTransformInfo::OperandValueKind Op1VK =
4944           TargetTransformInfo::OK_AnyValue;
4945       TargetTransformInfo::OperandValueKind Op2VK =
4946           TargetTransformInfo::OK_UniformConstantValue;
4947       TargetTransformInfo::OperandValueProperties Op1VP =
4948           TargetTransformInfo::OP_None;
4949       TargetTransformInfo::OperandValueProperties Op2VP =
4950           TargetTransformInfo::OP_PowerOf2;
4951 
4952       // If all operands are exactly the same ConstantInt then set the
4953       // operand kind to OK_UniformConstantValue.
4954       // If instead not all operands are constants, then set the operand kind
4955       // to OK_AnyValue. If all operands are constants but not the same,
4956       // then set the operand kind to OK_NonUniformConstantValue.
4957       ConstantInt *CInt0 = nullptr;
4958       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
4959         const Instruction *I = cast<Instruction>(VL[i]);
4960         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
4961         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
4962         if (!CInt) {
4963           Op2VK = TargetTransformInfo::OK_AnyValue;
4964           Op2VP = TargetTransformInfo::OP_None;
4965           break;
4966         }
4967         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
4968             !CInt->getValue().isPowerOf2())
4969           Op2VP = TargetTransformInfo::OP_None;
4970         if (i == 0) {
4971           CInt0 = CInt;
4972           continue;
4973         }
4974         if (CInt0 != CInt)
4975           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4976       }
4977 
4978       SmallVector<const Value *, 4> Operands(VL0->operand_values());
4979       InstructionCost ScalarEltCost =
4980           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
4981                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4982       if (NeedToShuffleReuses) {
4983         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
4984       }
4985       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4986       InstructionCost VecCost =
4987           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
4988                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4989       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4990       return CommonCost + VecCost - ScalarCost;
4991     }
4992     case Instruction::GetElementPtr: {
4993       TargetTransformInfo::OperandValueKind Op1VK =
4994           TargetTransformInfo::OK_AnyValue;
4995       TargetTransformInfo::OperandValueKind Op2VK =
4996           TargetTransformInfo::OK_UniformConstantValue;
4997 
4998       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
4999           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5000       if (NeedToShuffleReuses) {
5001         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5002       }
5003       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5004       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5005           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5006       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5007       return CommonCost + VecCost - ScalarCost;
5008     }
5009     case Instruction::Load: {
5010       // Cost of wide load - cost of scalar loads.
5011       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5012       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5013           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5014       if (NeedToShuffleReuses) {
5015         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5016       }
5017       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5018       InstructionCost VecLdCost;
5019       if (E->State == TreeEntry::Vectorize) {
5020         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5021                                          CostKind, VL0);
5022       } else {
5023         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5024         Align CommonAlignment = Alignment;
5025         for (Value *V : VL)
5026           CommonAlignment =
5027               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5028         VecLdCost = TTI->getGatherScatterOpCost(
5029             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5030             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5031       }
5032       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5033       return CommonCost + VecLdCost - ScalarLdCost;
5034     }
5035     case Instruction::Store: {
5036       // We know that we can merge the stores. Calculate the cost.
5037       bool IsReorder = !E->ReorderIndices.empty();
5038       auto *SI =
5039           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5040       Align Alignment = SI->getAlign();
5041       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5042           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5043       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5044       InstructionCost VecStCost = TTI->getMemoryOpCost(
5045           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5046       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5047       return CommonCost + VecStCost - ScalarStCost;
5048     }
5049     case Instruction::Call: {
5050       CallInst *CI = cast<CallInst>(VL0);
5051       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5052 
5053       // Calculate the cost of the scalar and vector calls.
5054       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5055       InstructionCost ScalarEltCost =
5056           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5057       if (NeedToShuffleReuses) {
5058         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5059       }
5060       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5061 
5062       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5063       InstructionCost VecCallCost =
5064           std::min(VecCallCosts.first, VecCallCosts.second);
5065 
5066       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5067                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5068                         << " for " << *CI << "\n");
5069 
5070       return CommonCost + VecCallCost - ScalarCallCost;
5071     }
5072     case Instruction::ShuffleVector: {
5073       assert(E->isAltShuffle() &&
5074              ((Instruction::isBinaryOp(E->getOpcode()) &&
5075                Instruction::isBinaryOp(E->getAltOpcode())) ||
5076               (Instruction::isCast(E->getOpcode()) &&
5077                Instruction::isCast(E->getAltOpcode()))) &&
5078              "Invalid Shuffle Vector Operand");
5079       InstructionCost ScalarCost = 0;
5080       if (NeedToShuffleReuses) {
5081         for (unsigned Idx : E->ReuseShuffleIndices) {
5082           Instruction *I = cast<Instruction>(VL[Idx]);
5083           CommonCost -= TTI->getInstructionCost(I, CostKind);
5084         }
5085         for (Value *V : VL) {
5086           Instruction *I = cast<Instruction>(V);
5087           CommonCost += TTI->getInstructionCost(I, CostKind);
5088         }
5089       }
5090       for (Value *V : VL) {
5091         Instruction *I = cast<Instruction>(V);
5092         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5093         ScalarCost += TTI->getInstructionCost(I, CostKind);
5094       }
5095       // VecCost is equal to sum of the cost of creating 2 vectors
5096       // and the cost of creating shuffle.
5097       InstructionCost VecCost = 0;
5098       // Try to find the previous shuffle node with the same operands and same
5099       // main/alternate ops.
5100       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5101         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5102           if (TE.get() == E)
5103             break;
5104           if (TE->isAltShuffle() &&
5105               ((TE->getOpcode() == E->getOpcode() &&
5106                 TE->getAltOpcode() == E->getAltOpcode()) ||
5107                (TE->getOpcode() == E->getAltOpcode() &&
5108                 TE->getAltOpcode() == E->getOpcode())) &&
5109               TE->hasEqualOperands(*E))
5110             return true;
5111         }
5112         return false;
5113       };
5114       if (TryFindNodeWithEqualOperands()) {
5115         LLVM_DEBUG({
5116           dbgs() << "SLP: diamond match for alternate node found.\n";
5117           E->dump();
5118         });
5119         // No need to add new vector costs here since we're going to reuse
5120         // same main/alternate vector ops, just do different shuffling.
5121       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5122         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5123         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5124                                                CostKind);
5125       } else {
5126         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5127         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5128         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5129         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5130         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5131                                         TTI::CastContextHint::None, CostKind);
5132         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5133                                          TTI::CastContextHint::None, CostKind);
5134       }
5135 
5136       SmallVector<int> Mask;
5137       buildSuffleEntryMask(
5138           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5139           [E](Instruction *I) {
5140             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5141             return I->getOpcode() == E->getAltOpcode();
5142           },
5143           Mask);
5144       CommonCost =
5145           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5146       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5147       return CommonCost + VecCost - ScalarCost;
5148     }
5149     default:
5150       llvm_unreachable("Unknown instruction");
5151   }
5152 }
5153 
5154 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5155   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5156                     << VectorizableTree.size() << " is fully vectorizable .\n");
5157 
5158   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5159     SmallVector<int> Mask;
5160     return TE->State == TreeEntry::NeedToGather &&
5161            !any_of(TE->Scalars,
5162                    [this](Value *V) { return EphValues.contains(V); }) &&
5163            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5164             TE->Scalars.size() < Limit ||
5165             ((TE->getOpcode() == Instruction::ExtractElement ||
5166               all_of(TE->Scalars,
5167                      [](Value *V) {
5168                        return isa<ExtractElementInst, UndefValue>(V);
5169                      })) &&
5170              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5171             (TE->State == TreeEntry::NeedToGather &&
5172              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5173   };
5174 
5175   // We only handle trees of heights 1 and 2.
5176   if (VectorizableTree.size() == 1 &&
5177       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5178        (ForReduction &&
5179         AreVectorizableGathers(VectorizableTree[0].get(),
5180                                VectorizableTree[0]->Scalars.size()) &&
5181         VectorizableTree[0]->getVectorFactor() > 2)))
5182     return true;
5183 
5184   if (VectorizableTree.size() != 2)
5185     return false;
5186 
5187   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5188   // with the second gather nodes if they have less scalar operands rather than
5189   // the initial tree element (may be profitable to shuffle the second gather)
5190   // or they are extractelements, which form shuffle.
5191   SmallVector<int> Mask;
5192   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5193       AreVectorizableGathers(VectorizableTree[1].get(),
5194                              VectorizableTree[0]->Scalars.size()))
5195     return true;
5196 
5197   // Gathering cost would be too much for tiny trees.
5198   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5199       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5200        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5201     return false;
5202 
5203   return true;
5204 }
5205 
5206 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5207                                        TargetTransformInfo *TTI,
5208                                        bool MustMatchOrInst) {
5209   // Look past the root to find a source value. Arbitrarily follow the
5210   // path through operand 0 of any 'or'. Also, peek through optional
5211   // shift-left-by-multiple-of-8-bits.
5212   Value *ZextLoad = Root;
5213   const APInt *ShAmtC;
5214   bool FoundOr = false;
5215   while (!isa<ConstantExpr>(ZextLoad) &&
5216          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5217           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5218            ShAmtC->urem(8) == 0))) {
5219     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5220     ZextLoad = BinOp->getOperand(0);
5221     if (BinOp->getOpcode() == Instruction::Or)
5222       FoundOr = true;
5223   }
5224   // Check if the input is an extended load of the required or/shift expression.
5225   Value *LoadPtr;
5226   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5227       !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
5228     return false;
5229 
5230   // Require that the total load bit width is a legal integer type.
5231   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5232   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5233   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
5234   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5235   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5236     return false;
5237 
5238   // Everything matched - assume that we can fold the whole sequence using
5239   // load combining.
5240   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5241              << *(cast<Instruction>(Root)) << "\n");
5242 
5243   return true;
5244 }
5245 
5246 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5247   if (RdxKind != RecurKind::Or)
5248     return false;
5249 
5250   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5251   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5252   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5253                                     /* MatchOr */ false);
5254 }
5255 
5256 bool BoUpSLP::isLoadCombineCandidate() const {
5257   // Peek through a final sequence of stores and check if all operations are
5258   // likely to be load-combined.
5259   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5260   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5261     Value *X;
5262     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5263         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5264       return false;
5265   }
5266   return true;
5267 }
5268 
5269 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5270   // No need to vectorize inserts of gathered values.
5271   if (VectorizableTree.size() == 2 &&
5272       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5273       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5274     return true;
5275 
5276   // We can vectorize the tree if its size is greater than or equal to the
5277   // minimum size specified by the MinTreeSize command line option.
5278   if (VectorizableTree.size() >= MinTreeSize)
5279     return false;
5280 
5281   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5282   // can vectorize it if we can prove it fully vectorizable.
5283   if (isFullyVectorizableTinyTree(ForReduction))
5284     return false;
5285 
5286   assert(VectorizableTree.empty()
5287              ? ExternalUses.empty()
5288              : true && "We shouldn't have any external users");
5289 
5290   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5291   // vectorizable.
5292   return true;
5293 }
5294 
5295 InstructionCost BoUpSLP::getSpillCost() const {
5296   // Walk from the bottom of the tree to the top, tracking which values are
5297   // live. When we see a call instruction that is not part of our tree,
5298   // query TTI to see if there is a cost to keeping values live over it
5299   // (for example, if spills and fills are required).
5300   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5301   InstructionCost Cost = 0;
5302 
5303   SmallPtrSet<Instruction*, 4> LiveValues;
5304   Instruction *PrevInst = nullptr;
5305 
5306   // The entries in VectorizableTree are not necessarily ordered by their
5307   // position in basic blocks. Collect them and order them by dominance so later
5308   // instructions are guaranteed to be visited first. For instructions in
5309   // different basic blocks, we only scan to the beginning of the block, so
5310   // their order does not matter, as long as all instructions in a basic block
5311   // are grouped together. Using dominance ensures a deterministic order.
5312   SmallVector<Instruction *, 16> OrderedScalars;
5313   for (const auto &TEPtr : VectorizableTree) {
5314     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5315     if (!Inst)
5316       continue;
5317     OrderedScalars.push_back(Inst);
5318   }
5319   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5320     auto *NodeA = DT->getNode(A->getParent());
5321     auto *NodeB = DT->getNode(B->getParent());
5322     assert(NodeA && "Should only process reachable instructions");
5323     assert(NodeB && "Should only process reachable instructions");
5324     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5325            "Different nodes should have different DFS numbers");
5326     if (NodeA != NodeB)
5327       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5328     return B->comesBefore(A);
5329   });
5330 
5331   for (Instruction *Inst : OrderedScalars) {
5332     if (!PrevInst) {
5333       PrevInst = Inst;
5334       continue;
5335     }
5336 
5337     // Update LiveValues.
5338     LiveValues.erase(PrevInst);
5339     for (auto &J : PrevInst->operands()) {
5340       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5341         LiveValues.insert(cast<Instruction>(&*J));
5342     }
5343 
5344     LLVM_DEBUG({
5345       dbgs() << "SLP: #LV: " << LiveValues.size();
5346       for (auto *X : LiveValues)
5347         dbgs() << " " << X->getName();
5348       dbgs() << ", Looking at ";
5349       Inst->dump();
5350     });
5351 
5352     // Now find the sequence of instructions between PrevInst and Inst.
5353     unsigned NumCalls = 0;
5354     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5355                                  PrevInstIt =
5356                                      PrevInst->getIterator().getReverse();
5357     while (InstIt != PrevInstIt) {
5358       if (PrevInstIt == PrevInst->getParent()->rend()) {
5359         PrevInstIt = Inst->getParent()->rbegin();
5360         continue;
5361       }
5362 
5363       // Debug information does not impact spill cost.
5364       if ((isa<CallInst>(&*PrevInstIt) &&
5365            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5366           &*PrevInstIt != PrevInst)
5367         NumCalls++;
5368 
5369       ++PrevInstIt;
5370     }
5371 
5372     if (NumCalls) {
5373       SmallVector<Type*, 4> V;
5374       for (auto *II : LiveValues) {
5375         auto *ScalarTy = II->getType();
5376         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5377           ScalarTy = VectorTy->getElementType();
5378         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5379       }
5380       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5381     }
5382 
5383     PrevInst = Inst;
5384   }
5385 
5386   return Cost;
5387 }
5388 
5389 /// Check if two insertelement instructions are from the same buildvector.
5390 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5391                                             InsertElementInst *V) {
5392   // Instructions must be from the same basic blocks.
5393   if (VU->getParent() != V->getParent())
5394     return false;
5395   // Checks if 2 insertelements are from the same buildvector.
5396   if (VU->getType() != V->getType())
5397     return false;
5398   // Multiple used inserts are separate nodes.
5399   if (!VU->hasOneUse() && !V->hasOneUse())
5400     return false;
5401   auto *IE1 = VU;
5402   auto *IE2 = V;
5403   // Go through the vector operand of insertelement instructions trying to find
5404   // either VU as the original vector for IE2 or V as the original vector for
5405   // IE1.
5406   do {
5407     if (IE2 == VU || IE1 == V)
5408       return true;
5409     if (IE1) {
5410       if (IE1 != VU && !IE1->hasOneUse())
5411         IE1 = nullptr;
5412       else
5413         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5414     }
5415     if (IE2) {
5416       if (IE2 != V && !IE2->hasOneUse())
5417         IE2 = nullptr;
5418       else
5419         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5420     }
5421   } while (IE1 || IE2);
5422   return false;
5423 }
5424 
5425 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5426   InstructionCost Cost = 0;
5427   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5428                     << VectorizableTree.size() << ".\n");
5429 
5430   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5431 
5432   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5433     TreeEntry &TE = *VectorizableTree[I].get();
5434 
5435     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5436     Cost += C;
5437     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5438                       << " for bundle that starts with " << *TE.Scalars[0]
5439                       << ".\n"
5440                       << "SLP: Current total cost = " << Cost << "\n");
5441   }
5442 
5443   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5444   InstructionCost ExtractCost = 0;
5445   SmallVector<unsigned> VF;
5446   SmallVector<SmallVector<int>> ShuffleMask;
5447   SmallVector<Value *> FirstUsers;
5448   SmallVector<APInt> DemandedElts;
5449   for (ExternalUser &EU : ExternalUses) {
5450     // We only add extract cost once for the same scalar.
5451     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5452         !ExtractCostCalculated.insert(EU.Scalar).second)
5453       continue;
5454 
5455     // Uses by ephemeral values are free (because the ephemeral value will be
5456     // removed prior to code generation, and so the extraction will be
5457     // removed as well).
5458     if (EphValues.count(EU.User))
5459       continue;
5460 
5461     // No extract cost for vector "scalar"
5462     if (isa<FixedVectorType>(EU.Scalar->getType()))
5463       continue;
5464 
5465     // Already counted the cost for external uses when tried to adjust the cost
5466     // for extractelements, no need to add it again.
5467     if (isa<ExtractElementInst>(EU.Scalar))
5468       continue;
5469 
5470     // If found user is an insertelement, do not calculate extract cost but try
5471     // to detect it as a final shuffled/identity match.
5472     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5473       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5474         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5475         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5476           continue;
5477         auto *It = find_if(FirstUsers, [VU](Value *V) {
5478           return areTwoInsertFromSameBuildVector(VU,
5479                                                  cast<InsertElementInst>(V));
5480         });
5481         int VecId = -1;
5482         if (It == FirstUsers.end()) {
5483           VF.push_back(FTy->getNumElements());
5484           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5485           // Find the insertvector, vectorized in tree, if any.
5486           Value *Base = VU;
5487           while (isa<InsertElementInst>(Base)) {
5488             // Build the mask for the vectorized insertelement instructions.
5489             if (const TreeEntry *E = getTreeEntry(Base)) {
5490               VU = cast<InsertElementInst>(Base);
5491               do {
5492                 int Idx = E->findLaneForValue(Base);
5493                 ShuffleMask.back()[Idx] = Idx;
5494                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5495               } while (E == getTreeEntry(Base));
5496               break;
5497             }
5498             Base = cast<InsertElementInst>(Base)->getOperand(0);
5499           }
5500           FirstUsers.push_back(VU);
5501           DemandedElts.push_back(APInt::getZero(VF.back()));
5502           VecId = FirstUsers.size() - 1;
5503         } else {
5504           VecId = std::distance(FirstUsers.begin(), It);
5505         }
5506         int Idx = *InsertIdx;
5507         ShuffleMask[VecId][Idx] = EU.Lane;
5508         DemandedElts[VecId].setBit(Idx);
5509         continue;
5510       }
5511     }
5512 
5513     // If we plan to rewrite the tree in a smaller type, we will need to sign
5514     // extend the extracted value back to the original type. Here, we account
5515     // for the extract and the added cost of the sign extend if needed.
5516     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5517     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5518     if (MinBWs.count(ScalarRoot)) {
5519       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5520       auto Extend =
5521           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5522       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5523       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5524                                                    VecTy, EU.Lane);
5525     } else {
5526       ExtractCost +=
5527           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5528     }
5529   }
5530 
5531   InstructionCost SpillCost = getSpillCost();
5532   Cost += SpillCost + ExtractCost;
5533   if (FirstUsers.size() == 1) {
5534     int Limit = ShuffleMask.front().size() * 2;
5535     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5536         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5537       InstructionCost C = TTI->getShuffleCost(
5538           TTI::SK_PermuteSingleSrc,
5539           cast<FixedVectorType>(FirstUsers.front()->getType()),
5540           ShuffleMask.front());
5541       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5542                         << " for final shuffle of insertelement external users "
5543                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5544                         << "SLP: Current total cost = " << Cost << "\n");
5545       Cost += C;
5546     }
5547     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5548         cast<FixedVectorType>(FirstUsers.front()->getType()),
5549         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5550     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5551                       << " for insertelements gather.\n"
5552                       << "SLP: Current total cost = " << Cost << "\n");
5553     Cost -= InsertCost;
5554   } else if (FirstUsers.size() >= 2) {
5555     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5556     // Combined masks of the first 2 vectors.
5557     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5558     copy(ShuffleMask.front(), CombinedMask.begin());
5559     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5560     auto *VecTy = FixedVectorType::get(
5561         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5562         MaxVF);
5563     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5564       if (ShuffleMask[1][I] != UndefMaskElem) {
5565         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5566         CombinedDemandedElts.setBit(I);
5567       }
5568     }
5569     InstructionCost C =
5570         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5571     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5572                       << " for final shuffle of vector node and external "
5573                          "insertelement users "
5574                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5575                       << "SLP: Current total cost = " << Cost << "\n");
5576     Cost += C;
5577     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5578         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5579     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5580                       << " for insertelements gather.\n"
5581                       << "SLP: Current total cost = " << Cost << "\n");
5582     Cost -= InsertCost;
5583     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5584       // Other elements - permutation of 2 vectors (the initial one and the
5585       // next Ith incoming vector).
5586       unsigned VF = ShuffleMask[I].size();
5587       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5588         int Mask = ShuffleMask[I][Idx];
5589         if (Mask != UndefMaskElem)
5590           CombinedMask[Idx] = MaxVF + Mask;
5591         else if (CombinedMask[Idx] != UndefMaskElem)
5592           CombinedMask[Idx] = Idx;
5593       }
5594       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5595         if (CombinedMask[Idx] != UndefMaskElem)
5596           CombinedMask[Idx] = Idx;
5597       InstructionCost C =
5598           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5599       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5600                         << " for final shuffle of vector node and external "
5601                            "insertelement users "
5602                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5603                         << "SLP: Current total cost = " << Cost << "\n");
5604       Cost += C;
5605       InstructionCost InsertCost = TTI->getScalarizationOverhead(
5606           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5607           /*Insert*/ true, /*Extract*/ false);
5608       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5609                         << " for insertelements gather.\n"
5610                         << "SLP: Current total cost = " << Cost << "\n");
5611       Cost -= InsertCost;
5612     }
5613   }
5614 
5615 #ifndef NDEBUG
5616   SmallString<256> Str;
5617   {
5618     raw_svector_ostream OS(Str);
5619     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5620        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5621        << "SLP: Total Cost = " << Cost << ".\n";
5622   }
5623   LLVM_DEBUG(dbgs() << Str);
5624   if (ViewSLPTree)
5625     ViewGraph(this, "SLP" + F->getName(), false, Str);
5626 #endif
5627 
5628   return Cost;
5629 }
5630 
5631 Optional<TargetTransformInfo::ShuffleKind>
5632 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5633                                SmallVectorImpl<const TreeEntry *> &Entries) {
5634   // TODO: currently checking only for Scalars in the tree entry, need to count
5635   // reused elements too for better cost estimation.
5636   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5637   Entries.clear();
5638   // Build a lists of values to tree entries.
5639   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5640   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5641     if (EntryPtr.get() == TE)
5642       break;
5643     if (EntryPtr->State != TreeEntry::NeedToGather)
5644       continue;
5645     for (Value *V : EntryPtr->Scalars)
5646       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5647   }
5648   // Find all tree entries used by the gathered values. If no common entries
5649   // found - not a shuffle.
5650   // Here we build a set of tree nodes for each gathered value and trying to
5651   // find the intersection between these sets. If we have at least one common
5652   // tree node for each gathered value - we have just a permutation of the
5653   // single vector. If we have 2 different sets, we're in situation where we
5654   // have a permutation of 2 input vectors.
5655   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5656   DenseMap<Value *, int> UsedValuesEntry;
5657   for (Value *V : TE->Scalars) {
5658     if (isa<UndefValue>(V))
5659       continue;
5660     // Build a list of tree entries where V is used.
5661     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5662     auto It = ValueToTEs.find(V);
5663     if (It != ValueToTEs.end())
5664       VToTEs = It->second;
5665     if (const TreeEntry *VTE = getTreeEntry(V))
5666       VToTEs.insert(VTE);
5667     if (VToTEs.empty())
5668       return None;
5669     if (UsedTEs.empty()) {
5670       // The first iteration, just insert the list of nodes to vector.
5671       UsedTEs.push_back(VToTEs);
5672     } else {
5673       // Need to check if there are any previously used tree nodes which use V.
5674       // If there are no such nodes, consider that we have another one input
5675       // vector.
5676       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
5677       unsigned Idx = 0;
5678       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
5679         // Do we have a non-empty intersection of previously listed tree entries
5680         // and tree entries using current V?
5681         set_intersect(VToTEs, Set);
5682         if (!VToTEs.empty()) {
5683           // Yes, write the new subset and continue analysis for the next
5684           // scalar.
5685           Set.swap(VToTEs);
5686           break;
5687         }
5688         VToTEs = SavedVToTEs;
5689         ++Idx;
5690       }
5691       // No non-empty intersection found - need to add a second set of possible
5692       // source vectors.
5693       if (Idx == UsedTEs.size()) {
5694         // If the number of input vectors is greater than 2 - not a permutation,
5695         // fallback to the regular gather.
5696         if (UsedTEs.size() == 2)
5697           return None;
5698         UsedTEs.push_back(SavedVToTEs);
5699         Idx = UsedTEs.size() - 1;
5700       }
5701       UsedValuesEntry.try_emplace(V, Idx);
5702     }
5703   }
5704 
5705   unsigned VF = 0;
5706   if (UsedTEs.size() == 1) {
5707     // Try to find the perfect match in another gather node at first.
5708     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
5709       return EntryPtr->isSame(TE->Scalars);
5710     });
5711     if (It != UsedTEs.front().end()) {
5712       Entries.push_back(*It);
5713       std::iota(Mask.begin(), Mask.end(), 0);
5714       return TargetTransformInfo::SK_PermuteSingleSrc;
5715     }
5716     // No perfect match, just shuffle, so choose the first tree node.
5717     Entries.push_back(*UsedTEs.front().begin());
5718   } else {
5719     // Try to find nodes with the same vector factor.
5720     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
5721     DenseMap<int, const TreeEntry *> VFToTE;
5722     for (const TreeEntry *TE : UsedTEs.front())
5723       VFToTE.try_emplace(TE->getVectorFactor(), TE);
5724     for (const TreeEntry *TE : UsedTEs.back()) {
5725       auto It = VFToTE.find(TE->getVectorFactor());
5726       if (It != VFToTE.end()) {
5727         VF = It->first;
5728         Entries.push_back(It->second);
5729         Entries.push_back(TE);
5730         break;
5731       }
5732     }
5733     // No 2 source vectors with the same vector factor - give up and do regular
5734     // gather.
5735     if (Entries.empty())
5736       return None;
5737   }
5738 
5739   // Build a shuffle mask for better cost estimation and vector emission.
5740   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
5741     Value *V = TE->Scalars[I];
5742     if (isa<UndefValue>(V))
5743       continue;
5744     unsigned Idx = UsedValuesEntry.lookup(V);
5745     const TreeEntry *VTE = Entries[Idx];
5746     int FoundLane = VTE->findLaneForValue(V);
5747     Mask[I] = Idx * VF + FoundLane;
5748     // Extra check required by isSingleSourceMaskImpl function (called by
5749     // ShuffleVectorInst::isSingleSourceMask).
5750     if (Mask[I] >= 2 * E)
5751       return None;
5752   }
5753   switch (Entries.size()) {
5754   case 1:
5755     return TargetTransformInfo::SK_PermuteSingleSrc;
5756   case 2:
5757     return TargetTransformInfo::SK_PermuteTwoSrc;
5758   default:
5759     break;
5760   }
5761   return None;
5762 }
5763 
5764 InstructionCost
5765 BoUpSLP::getGatherCost(FixedVectorType *Ty,
5766                        const DenseSet<unsigned> &ShuffledIndices,
5767                        bool NeedToShuffle) const {
5768   unsigned NumElts = Ty->getNumElements();
5769   APInt DemandedElts = APInt::getZero(NumElts);
5770   for (unsigned I = 0; I < NumElts; ++I)
5771     if (!ShuffledIndices.count(I))
5772       DemandedElts.setBit(I);
5773   InstructionCost Cost =
5774       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
5775                                     /*Extract*/ false);
5776   if (NeedToShuffle)
5777     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
5778   return Cost;
5779 }
5780 
5781 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
5782   // Find the type of the operands in VL.
5783   Type *ScalarTy = VL[0]->getType();
5784   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5785     ScalarTy = SI->getValueOperand()->getType();
5786   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5787   bool DuplicateNonConst = false;
5788   // Find the cost of inserting/extracting values from the vector.
5789   // Check if the same elements are inserted several times and count them as
5790   // shuffle candidates.
5791   DenseSet<unsigned> ShuffledElements;
5792   DenseSet<Value *> UniqueElements;
5793   // Iterate in reverse order to consider insert elements with the high cost.
5794   for (unsigned I = VL.size(); I > 0; --I) {
5795     unsigned Idx = I - 1;
5796     // No need to shuffle duplicates for constants.
5797     if (isConstant(VL[Idx])) {
5798       ShuffledElements.insert(Idx);
5799       continue;
5800     }
5801     if (!UniqueElements.insert(VL[Idx]).second) {
5802       DuplicateNonConst = true;
5803       ShuffledElements.insert(Idx);
5804     }
5805   }
5806   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
5807 }
5808 
5809 // Perform operand reordering on the instructions in VL and return the reordered
5810 // operands in Left and Right.
5811 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
5812                                              SmallVectorImpl<Value *> &Left,
5813                                              SmallVectorImpl<Value *> &Right,
5814                                              const DataLayout &DL,
5815                                              ScalarEvolution &SE,
5816                                              const BoUpSLP &R) {
5817   if (VL.empty())
5818     return;
5819   VLOperands Ops(VL, DL, SE, R);
5820   // Reorder the operands in place.
5821   Ops.reorder();
5822   Left = Ops.getVL(0);
5823   Right = Ops.getVL(1);
5824 }
5825 
5826 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
5827   // Get the basic block this bundle is in. All instructions in the bundle
5828   // should be in this block.
5829   auto *Front = E->getMainOp();
5830   auto *BB = Front->getParent();
5831   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
5832     auto *I = cast<Instruction>(V);
5833     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
5834   }));
5835 
5836   // The last instruction in the bundle in program order.
5837   Instruction *LastInst = nullptr;
5838 
5839   // Find the last instruction. The common case should be that BB has been
5840   // scheduled, and the last instruction is VL.back(). So we start with
5841   // VL.back() and iterate over schedule data until we reach the end of the
5842   // bundle. The end of the bundle is marked by null ScheduleData.
5843   if (BlocksSchedules.count(BB)) {
5844     auto *Bundle =
5845         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
5846     if (Bundle && Bundle->isPartOfBundle())
5847       for (; Bundle; Bundle = Bundle->NextInBundle)
5848         if (Bundle->OpValue == Bundle->Inst)
5849           LastInst = Bundle->Inst;
5850   }
5851 
5852   // LastInst can still be null at this point if there's either not an entry
5853   // for BB in BlocksSchedules or there's no ScheduleData available for
5854   // VL.back(). This can be the case if buildTree_rec aborts for various
5855   // reasons (e.g., the maximum recursion depth is reached, the maximum region
5856   // size is reached, etc.). ScheduleData is initialized in the scheduling
5857   // "dry-run".
5858   //
5859   // If this happens, we can still find the last instruction by brute force. We
5860   // iterate forwards from Front (inclusive) until we either see all
5861   // instructions in the bundle or reach the end of the block. If Front is the
5862   // last instruction in program order, LastInst will be set to Front, and we
5863   // will visit all the remaining instructions in the block.
5864   //
5865   // One of the reasons we exit early from buildTree_rec is to place an upper
5866   // bound on compile-time. Thus, taking an additional compile-time hit here is
5867   // not ideal. However, this should be exceedingly rare since it requires that
5868   // we both exit early from buildTree_rec and that the bundle be out-of-order
5869   // (causing us to iterate all the way to the end of the block).
5870   if (!LastInst) {
5871     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
5872     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
5873       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
5874         LastInst = &I;
5875       if (Bundle.empty())
5876         break;
5877     }
5878   }
5879   assert(LastInst && "Failed to find last instruction in bundle");
5880 
5881   // Set the insertion point after the last instruction in the bundle. Set the
5882   // debug location to Front.
5883   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
5884   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
5885 }
5886 
5887 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
5888   // List of instructions/lanes from current block and/or the blocks which are
5889   // part of the current loop. These instructions will be inserted at the end to
5890   // make it possible to optimize loops and hoist invariant instructions out of
5891   // the loops body with better chances for success.
5892   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
5893   SmallSet<int, 4> PostponedIndices;
5894   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
5895   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
5896     SmallPtrSet<BasicBlock *, 4> Visited;
5897     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
5898       InsertBB = InsertBB->getSinglePredecessor();
5899     return InsertBB && InsertBB == InstBB;
5900   };
5901   for (int I = 0, E = VL.size(); I < E; ++I) {
5902     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
5903       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
5904            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
5905           PostponedIndices.insert(I).second)
5906         PostponedInsts.emplace_back(Inst, I);
5907   }
5908 
5909   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
5910     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
5911     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
5912     if (!InsElt)
5913       return Vec;
5914     GatherShuffleSeq.insert(InsElt);
5915     CSEBlocks.insert(InsElt->getParent());
5916     // Add to our 'need-to-extract' list.
5917     if (TreeEntry *Entry = getTreeEntry(V)) {
5918       // Find which lane we need to extract.
5919       unsigned FoundLane = Entry->findLaneForValue(V);
5920       ExternalUses.emplace_back(V, InsElt, FoundLane);
5921     }
5922     return Vec;
5923   };
5924   Value *Val0 =
5925       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
5926   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
5927   Value *Vec = PoisonValue::get(VecTy);
5928   SmallVector<int> NonConsts;
5929   // Insert constant values at first.
5930   for (int I = 0, E = VL.size(); I < E; ++I) {
5931     if (PostponedIndices.contains(I))
5932       continue;
5933     if (!isConstant(VL[I])) {
5934       NonConsts.push_back(I);
5935       continue;
5936     }
5937     Vec = CreateInsertElement(Vec, VL[I], I);
5938   }
5939   // Insert non-constant values.
5940   for (int I : NonConsts)
5941     Vec = CreateInsertElement(Vec, VL[I], I);
5942   // Append instructions, which are/may be part of the loop, in the end to make
5943   // it possible to hoist non-loop-based instructions.
5944   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
5945     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
5946 
5947   return Vec;
5948 }
5949 
5950 namespace {
5951 /// Merges shuffle masks and emits final shuffle instruction, if required.
5952 class ShuffleInstructionBuilder {
5953   IRBuilderBase &Builder;
5954   const unsigned VF = 0;
5955   bool IsFinalized = false;
5956   SmallVector<int, 4> Mask;
5957   /// Holds all of the instructions that we gathered.
5958   SetVector<Instruction *> &GatherShuffleSeq;
5959   /// A list of blocks that we are going to CSE.
5960   SetVector<BasicBlock *> &CSEBlocks;
5961 
5962 public:
5963   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
5964                             SetVector<Instruction *> &GatherShuffleSeq,
5965                             SetVector<BasicBlock *> &CSEBlocks)
5966       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
5967         CSEBlocks(CSEBlocks) {}
5968 
5969   /// Adds a mask, inverting it before applying.
5970   void addInversedMask(ArrayRef<unsigned> SubMask) {
5971     if (SubMask.empty())
5972       return;
5973     SmallVector<int, 4> NewMask;
5974     inversePermutation(SubMask, NewMask);
5975     addMask(NewMask);
5976   }
5977 
5978   /// Functions adds masks, merging them into  single one.
5979   void addMask(ArrayRef<unsigned> SubMask) {
5980     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
5981     addMask(NewMask);
5982   }
5983 
5984   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
5985 
5986   Value *finalize(Value *V) {
5987     IsFinalized = true;
5988     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
5989     if (VF == ValueVF && Mask.empty())
5990       return V;
5991     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
5992     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
5993     addMask(NormalizedMask);
5994 
5995     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
5996       return V;
5997     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
5998     if (auto *I = dyn_cast<Instruction>(Vec)) {
5999       GatherShuffleSeq.insert(I);
6000       CSEBlocks.insert(I->getParent());
6001     }
6002     return Vec;
6003   }
6004 
6005   ~ShuffleInstructionBuilder() {
6006     assert((IsFinalized || Mask.empty()) &&
6007            "Shuffle construction must be finalized.");
6008   }
6009 };
6010 } // namespace
6011 
6012 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6013   unsigned VF = VL.size();
6014   InstructionsState S = getSameOpcode(VL);
6015   if (S.getOpcode()) {
6016     if (TreeEntry *E = getTreeEntry(S.OpValue))
6017       if (E->isSame(VL)) {
6018         Value *V = vectorizeTree(E);
6019         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6020           if (!E->ReuseShuffleIndices.empty()) {
6021             // Reshuffle to get only unique values.
6022             // If some of the scalars are duplicated in the vectorization tree
6023             // entry, we do not vectorize them but instead generate a mask for
6024             // the reuses. But if there are several users of the same entry,
6025             // they may have different vectorization factors. This is especially
6026             // important for PHI nodes. In this case, we need to adapt the
6027             // resulting instruction for the user vectorization factor and have
6028             // to reshuffle it again to take only unique elements of the vector.
6029             // Without this code the function incorrectly returns reduced vector
6030             // instruction with the same elements, not with the unique ones.
6031 
6032             // block:
6033             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6034             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6035             // ... (use %2)
6036             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6037             // br %block
6038             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6039             SmallSet<int, 4> UsedIdxs;
6040             int Pos = 0;
6041             int Sz = VL.size();
6042             for (int Idx : E->ReuseShuffleIndices) {
6043               if (Idx != Sz && Idx != UndefMaskElem &&
6044                   UsedIdxs.insert(Idx).second)
6045                 UniqueIdxs[Idx] = Pos;
6046               ++Pos;
6047             }
6048             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6049                                             "less than original vector size.");
6050             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6051             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6052           } else {
6053             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6054                    "Expected vectorization factor less "
6055                    "than original vector size.");
6056             SmallVector<int> UniformMask(VF, 0);
6057             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6058             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6059           }
6060           if (auto *I = dyn_cast<Instruction>(V)) {
6061             GatherShuffleSeq.insert(I);
6062             CSEBlocks.insert(I->getParent());
6063           }
6064         }
6065         return V;
6066       }
6067   }
6068 
6069   // Check that every instruction appears once in this bundle.
6070   SmallVector<int> ReuseShuffleIndicies;
6071   SmallVector<Value *> UniqueValues;
6072   if (VL.size() > 2) {
6073     DenseMap<Value *, unsigned> UniquePositions;
6074     unsigned NumValues =
6075         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6076                                     return !isa<UndefValue>(V);
6077                                   }).base());
6078     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6079     int UniqueVals = 0;
6080     for (Value *V : VL.drop_back(VL.size() - VF)) {
6081       if (isa<UndefValue>(V)) {
6082         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6083         continue;
6084       }
6085       if (isConstant(V)) {
6086         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6087         UniqueValues.emplace_back(V);
6088         continue;
6089       }
6090       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6091       ReuseShuffleIndicies.emplace_back(Res.first->second);
6092       if (Res.second) {
6093         UniqueValues.emplace_back(V);
6094         ++UniqueVals;
6095       }
6096     }
6097     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6098       // Emit pure splat vector.
6099       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6100                                   UndefMaskElem);
6101     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6102       ReuseShuffleIndicies.clear();
6103       UniqueValues.clear();
6104       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6105     }
6106     UniqueValues.append(VF - UniqueValues.size(),
6107                         PoisonValue::get(VL[0]->getType()));
6108     VL = UniqueValues;
6109   }
6110 
6111   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6112                                            CSEBlocks);
6113   Value *Vec = gather(VL);
6114   if (!ReuseShuffleIndicies.empty()) {
6115     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6116     Vec = ShuffleBuilder.finalize(Vec);
6117   }
6118   return Vec;
6119 }
6120 
6121 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6122   IRBuilder<>::InsertPointGuard Guard(Builder);
6123 
6124   if (E->VectorizedValue) {
6125     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6126     return E->VectorizedValue;
6127   }
6128 
6129   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6130   unsigned VF = E->getVectorFactor();
6131   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6132                                            CSEBlocks);
6133   if (E->State == TreeEntry::NeedToGather) {
6134     if (E->getMainOp())
6135       setInsertPointAfterBundle(E);
6136     Value *Vec;
6137     SmallVector<int> Mask;
6138     SmallVector<const TreeEntry *> Entries;
6139     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6140         isGatherShuffledEntry(E, Mask, Entries);
6141     if (Shuffle.hasValue()) {
6142       assert((Entries.size() == 1 || Entries.size() == 2) &&
6143              "Expected shuffle of 1 or 2 entries.");
6144       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6145                                         Entries.back()->VectorizedValue, Mask);
6146       if (auto *I = dyn_cast<Instruction>(Vec)) {
6147         GatherShuffleSeq.insert(I);
6148         CSEBlocks.insert(I->getParent());
6149       }
6150     } else {
6151       Vec = gather(E->Scalars);
6152     }
6153     if (NeedToShuffleReuses) {
6154       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6155       Vec = ShuffleBuilder.finalize(Vec);
6156     }
6157     E->VectorizedValue = Vec;
6158     return Vec;
6159   }
6160 
6161   assert((E->State == TreeEntry::Vectorize ||
6162           E->State == TreeEntry::ScatterVectorize) &&
6163          "Unhandled state");
6164   unsigned ShuffleOrOp =
6165       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6166   Instruction *VL0 = E->getMainOp();
6167   Type *ScalarTy = VL0->getType();
6168   if (auto *Store = dyn_cast<StoreInst>(VL0))
6169     ScalarTy = Store->getValueOperand()->getType();
6170   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6171     ScalarTy = IE->getOperand(1)->getType();
6172   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6173   switch (ShuffleOrOp) {
6174     case Instruction::PHI: {
6175       assert(
6176           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6177           "PHI reordering is free.");
6178       auto *PH = cast<PHINode>(VL0);
6179       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6180       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6181       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6182       Value *V = NewPhi;
6183       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6184       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6185       V = ShuffleBuilder.finalize(V);
6186 
6187       E->VectorizedValue = V;
6188 
6189       // PHINodes may have multiple entries from the same block. We want to
6190       // visit every block once.
6191       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6192 
6193       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6194         ValueList Operands;
6195         BasicBlock *IBB = PH->getIncomingBlock(i);
6196 
6197         if (!VisitedBBs.insert(IBB).second) {
6198           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6199           continue;
6200         }
6201 
6202         Builder.SetInsertPoint(IBB->getTerminator());
6203         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6204         Value *Vec = vectorizeTree(E->getOperand(i));
6205         NewPhi->addIncoming(Vec, IBB);
6206       }
6207 
6208       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6209              "Invalid number of incoming values");
6210       return V;
6211     }
6212 
6213     case Instruction::ExtractElement: {
6214       Value *V = E->getSingleOperand(0);
6215       Builder.SetInsertPoint(VL0);
6216       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6217       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6218       V = ShuffleBuilder.finalize(V);
6219       E->VectorizedValue = V;
6220       return V;
6221     }
6222     case Instruction::ExtractValue: {
6223       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6224       Builder.SetInsertPoint(LI);
6225       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6226       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6227       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6228       Value *NewV = propagateMetadata(V, E->Scalars);
6229       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6230       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6231       NewV = ShuffleBuilder.finalize(NewV);
6232       E->VectorizedValue = NewV;
6233       return NewV;
6234     }
6235     case Instruction::InsertElement: {
6236       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6237       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6238       Value *V = vectorizeTree(E->getOperand(1));
6239 
6240       // Create InsertVector shuffle if necessary
6241       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6242         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6243       }));
6244       const unsigned NumElts =
6245           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6246       const unsigned NumScalars = E->Scalars.size();
6247 
6248       unsigned Offset = *getInsertIndex(VL0, 0);
6249       assert(Offset < NumElts && "Failed to find vector index offset");
6250 
6251       // Create shuffle to resize vector
6252       SmallVector<int> Mask;
6253       if (!E->ReorderIndices.empty()) {
6254         inversePermutation(E->ReorderIndices, Mask);
6255         Mask.append(NumElts - NumScalars, UndefMaskElem);
6256       } else {
6257         Mask.assign(NumElts, UndefMaskElem);
6258         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6259       }
6260       // Create InsertVector shuffle if necessary
6261       bool IsIdentity = true;
6262       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6263       Mask.swap(PrevMask);
6264       for (unsigned I = 0; I < NumScalars; ++I) {
6265         Value *Scalar = E->Scalars[PrevMask[I]];
6266         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6267         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6268           continue;
6269         IsIdentity &= *InsertIdx - Offset == I;
6270         Mask[*InsertIdx - Offset] = I;
6271       }
6272       if (!IsIdentity || NumElts != NumScalars) {
6273         V = Builder.CreateShuffleVector(V, Mask);
6274         if (auto *I = dyn_cast<Instruction>(V)) {
6275           GatherShuffleSeq.insert(I);
6276           CSEBlocks.insert(I->getParent());
6277         }
6278       }
6279 
6280       if ((!IsIdentity || Offset != 0 ||
6281            !isUndefVector(FirstInsert->getOperand(0))) &&
6282           NumElts != NumScalars) {
6283         SmallVector<int> InsertMask(NumElts);
6284         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6285         for (unsigned I = 0; I < NumElts; I++) {
6286           if (Mask[I] != UndefMaskElem)
6287             InsertMask[Offset + I] = NumElts + I;
6288         }
6289 
6290         V = Builder.CreateShuffleVector(
6291             FirstInsert->getOperand(0), V, InsertMask,
6292             cast<Instruction>(E->Scalars.back())->getName());
6293         if (auto *I = dyn_cast<Instruction>(V)) {
6294           GatherShuffleSeq.insert(I);
6295           CSEBlocks.insert(I->getParent());
6296         }
6297       }
6298 
6299       ++NumVectorInstructions;
6300       E->VectorizedValue = V;
6301       return V;
6302     }
6303     case Instruction::ZExt:
6304     case Instruction::SExt:
6305     case Instruction::FPToUI:
6306     case Instruction::FPToSI:
6307     case Instruction::FPExt:
6308     case Instruction::PtrToInt:
6309     case Instruction::IntToPtr:
6310     case Instruction::SIToFP:
6311     case Instruction::UIToFP:
6312     case Instruction::Trunc:
6313     case Instruction::FPTrunc:
6314     case Instruction::BitCast: {
6315       setInsertPointAfterBundle(E);
6316 
6317       Value *InVec = vectorizeTree(E->getOperand(0));
6318 
6319       if (E->VectorizedValue) {
6320         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6321         return E->VectorizedValue;
6322       }
6323 
6324       auto *CI = cast<CastInst>(VL0);
6325       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6326       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6327       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6328       V = ShuffleBuilder.finalize(V);
6329 
6330       E->VectorizedValue = V;
6331       ++NumVectorInstructions;
6332       return V;
6333     }
6334     case Instruction::FCmp:
6335     case Instruction::ICmp: {
6336       setInsertPointAfterBundle(E);
6337 
6338       Value *L = vectorizeTree(E->getOperand(0));
6339       Value *R = vectorizeTree(E->getOperand(1));
6340 
6341       if (E->VectorizedValue) {
6342         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6343         return E->VectorizedValue;
6344       }
6345 
6346       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6347       Value *V = Builder.CreateCmp(P0, L, R);
6348       propagateIRFlags(V, E->Scalars, VL0);
6349       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6350       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6351       V = ShuffleBuilder.finalize(V);
6352 
6353       E->VectorizedValue = V;
6354       ++NumVectorInstructions;
6355       return V;
6356     }
6357     case Instruction::Select: {
6358       setInsertPointAfterBundle(E);
6359 
6360       Value *Cond = vectorizeTree(E->getOperand(0));
6361       Value *True = vectorizeTree(E->getOperand(1));
6362       Value *False = vectorizeTree(E->getOperand(2));
6363 
6364       if (E->VectorizedValue) {
6365         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6366         return E->VectorizedValue;
6367       }
6368 
6369       Value *V = Builder.CreateSelect(Cond, True, False);
6370       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6371       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6372       V = ShuffleBuilder.finalize(V);
6373 
6374       E->VectorizedValue = V;
6375       ++NumVectorInstructions;
6376       return V;
6377     }
6378     case Instruction::FNeg: {
6379       setInsertPointAfterBundle(E);
6380 
6381       Value *Op = vectorizeTree(E->getOperand(0));
6382 
6383       if (E->VectorizedValue) {
6384         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6385         return E->VectorizedValue;
6386       }
6387 
6388       Value *V = Builder.CreateUnOp(
6389           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6390       propagateIRFlags(V, E->Scalars, VL0);
6391       if (auto *I = dyn_cast<Instruction>(V))
6392         V = propagateMetadata(I, E->Scalars);
6393 
6394       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6395       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6396       V = ShuffleBuilder.finalize(V);
6397 
6398       E->VectorizedValue = V;
6399       ++NumVectorInstructions;
6400 
6401       return V;
6402     }
6403     case Instruction::Add:
6404     case Instruction::FAdd:
6405     case Instruction::Sub:
6406     case Instruction::FSub:
6407     case Instruction::Mul:
6408     case Instruction::FMul:
6409     case Instruction::UDiv:
6410     case Instruction::SDiv:
6411     case Instruction::FDiv:
6412     case Instruction::URem:
6413     case Instruction::SRem:
6414     case Instruction::FRem:
6415     case Instruction::Shl:
6416     case Instruction::LShr:
6417     case Instruction::AShr:
6418     case Instruction::And:
6419     case Instruction::Or:
6420     case Instruction::Xor: {
6421       setInsertPointAfterBundle(E);
6422 
6423       Value *LHS = vectorizeTree(E->getOperand(0));
6424       Value *RHS = vectorizeTree(E->getOperand(1));
6425 
6426       if (E->VectorizedValue) {
6427         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6428         return E->VectorizedValue;
6429       }
6430 
6431       Value *V = Builder.CreateBinOp(
6432           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6433           RHS);
6434       propagateIRFlags(V, E->Scalars, VL0);
6435       if (auto *I = dyn_cast<Instruction>(V))
6436         V = propagateMetadata(I, E->Scalars);
6437 
6438       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6439       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6440       V = ShuffleBuilder.finalize(V);
6441 
6442       E->VectorizedValue = V;
6443       ++NumVectorInstructions;
6444 
6445       return V;
6446     }
6447     case Instruction::Load: {
6448       // Loads are inserted at the head of the tree because we don't want to
6449       // sink them all the way down past store instructions.
6450       setInsertPointAfterBundle(E);
6451 
6452       LoadInst *LI = cast<LoadInst>(VL0);
6453       Instruction *NewLI;
6454       unsigned AS = LI->getPointerAddressSpace();
6455       Value *PO = LI->getPointerOperand();
6456       if (E->State == TreeEntry::Vectorize) {
6457 
6458         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6459 
6460         // The pointer operand uses an in-tree scalar so we add the new BitCast
6461         // to ExternalUses list to make sure that an extract will be generated
6462         // in the future.
6463         if (TreeEntry *Entry = getTreeEntry(PO)) {
6464           // Find which lane we need to extract.
6465           unsigned FoundLane = Entry->findLaneForValue(PO);
6466           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6467         }
6468 
6469         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6470       } else {
6471         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6472         Value *VecPtr = vectorizeTree(E->getOperand(0));
6473         // Use the minimum alignment of the gathered loads.
6474         Align CommonAlignment = LI->getAlign();
6475         for (Value *V : E->Scalars)
6476           CommonAlignment =
6477               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6478         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6479       }
6480       Value *V = propagateMetadata(NewLI, E->Scalars);
6481 
6482       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6483       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6484       V = ShuffleBuilder.finalize(V);
6485       E->VectorizedValue = V;
6486       ++NumVectorInstructions;
6487       return V;
6488     }
6489     case Instruction::Store: {
6490       auto *SI = cast<StoreInst>(VL0);
6491       unsigned AS = SI->getPointerAddressSpace();
6492 
6493       setInsertPointAfterBundle(E);
6494 
6495       Value *VecValue = vectorizeTree(E->getOperand(0));
6496       ShuffleBuilder.addMask(E->ReorderIndices);
6497       VecValue = ShuffleBuilder.finalize(VecValue);
6498 
6499       Value *ScalarPtr = SI->getPointerOperand();
6500       Value *VecPtr = Builder.CreateBitCast(
6501           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6502       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6503                                                  SI->getAlign());
6504 
6505       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6506       // ExternalUses to make sure that an extract will be generated in the
6507       // future.
6508       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6509         // Find which lane we need to extract.
6510         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6511         ExternalUses.push_back(
6512             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6513       }
6514 
6515       Value *V = propagateMetadata(ST, E->Scalars);
6516 
6517       E->VectorizedValue = V;
6518       ++NumVectorInstructions;
6519       return V;
6520     }
6521     case Instruction::GetElementPtr: {
6522       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6523       setInsertPointAfterBundle(E);
6524 
6525       Value *Op0 = vectorizeTree(E->getOperand(0));
6526 
6527       SmallVector<Value *> OpVecs;
6528       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6529         Value *OpVec = vectorizeTree(E->getOperand(J));
6530         OpVecs.push_back(OpVec);
6531       }
6532 
6533       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6534       if (Instruction *I = dyn_cast<Instruction>(V))
6535         V = propagateMetadata(I, E->Scalars);
6536 
6537       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6538       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6539       V = ShuffleBuilder.finalize(V);
6540 
6541       E->VectorizedValue = V;
6542       ++NumVectorInstructions;
6543 
6544       return V;
6545     }
6546     case Instruction::Call: {
6547       CallInst *CI = cast<CallInst>(VL0);
6548       setInsertPointAfterBundle(E);
6549 
6550       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6551       if (Function *FI = CI->getCalledFunction())
6552         IID = FI->getIntrinsicID();
6553 
6554       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6555 
6556       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6557       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6558                           VecCallCosts.first <= VecCallCosts.second;
6559 
6560       Value *ScalarArg = nullptr;
6561       std::vector<Value *> OpVecs;
6562       SmallVector<Type *, 2> TysForDecl =
6563           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6564       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6565         ValueList OpVL;
6566         // Some intrinsics have scalar arguments. This argument should not be
6567         // vectorized.
6568         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6569           CallInst *CEI = cast<CallInst>(VL0);
6570           ScalarArg = CEI->getArgOperand(j);
6571           OpVecs.push_back(CEI->getArgOperand(j));
6572           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6573             TysForDecl.push_back(ScalarArg->getType());
6574           continue;
6575         }
6576 
6577         Value *OpVec = vectorizeTree(E->getOperand(j));
6578         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6579         OpVecs.push_back(OpVec);
6580       }
6581 
6582       Function *CF;
6583       if (!UseIntrinsic) {
6584         VFShape Shape =
6585             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6586                                   VecTy->getNumElements())),
6587                          false /*HasGlobalPred*/);
6588         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6589       } else {
6590         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6591       }
6592 
6593       SmallVector<OperandBundleDef, 1> OpBundles;
6594       CI->getOperandBundlesAsDefs(OpBundles);
6595       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6596 
6597       // The scalar argument uses an in-tree scalar so we add the new vectorized
6598       // call to ExternalUses list to make sure that an extract will be
6599       // generated in the future.
6600       if (ScalarArg) {
6601         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6602           // Find which lane we need to extract.
6603           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6604           ExternalUses.push_back(
6605               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6606         }
6607       }
6608 
6609       propagateIRFlags(V, E->Scalars, VL0);
6610       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6611       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6612       V = ShuffleBuilder.finalize(V);
6613 
6614       E->VectorizedValue = V;
6615       ++NumVectorInstructions;
6616       return V;
6617     }
6618     case Instruction::ShuffleVector: {
6619       assert(E->isAltShuffle() &&
6620              ((Instruction::isBinaryOp(E->getOpcode()) &&
6621                Instruction::isBinaryOp(E->getAltOpcode())) ||
6622               (Instruction::isCast(E->getOpcode()) &&
6623                Instruction::isCast(E->getAltOpcode()))) &&
6624              "Invalid Shuffle Vector Operand");
6625 
6626       Value *LHS = nullptr, *RHS = nullptr;
6627       if (Instruction::isBinaryOp(E->getOpcode())) {
6628         setInsertPointAfterBundle(E);
6629         LHS = vectorizeTree(E->getOperand(0));
6630         RHS = vectorizeTree(E->getOperand(1));
6631       } else {
6632         setInsertPointAfterBundle(E);
6633         LHS = vectorizeTree(E->getOperand(0));
6634       }
6635 
6636       if (E->VectorizedValue) {
6637         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6638         return E->VectorizedValue;
6639       }
6640 
6641       Value *V0, *V1;
6642       if (Instruction::isBinaryOp(E->getOpcode())) {
6643         V0 = Builder.CreateBinOp(
6644             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6645         V1 = Builder.CreateBinOp(
6646             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6647       } else {
6648         V0 = Builder.CreateCast(
6649             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6650         V1 = Builder.CreateCast(
6651             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6652       }
6653       // Add V0 and V1 to later analysis to try to find and remove matching
6654       // instruction, if any.
6655       for (Value *V : {V0, V1}) {
6656         if (auto *I = dyn_cast<Instruction>(V)) {
6657           GatherShuffleSeq.insert(I);
6658           CSEBlocks.insert(I->getParent());
6659         }
6660       }
6661 
6662       // Create shuffle to take alternate operations from the vector.
6663       // Also, gather up main and alt scalar ops to propagate IR flags to
6664       // each vector operation.
6665       ValueList OpScalars, AltScalars;
6666       SmallVector<int> Mask;
6667       buildSuffleEntryMask(
6668           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6669           [E](Instruction *I) {
6670             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6671             return I->getOpcode() == E->getAltOpcode();
6672           },
6673           Mask, &OpScalars, &AltScalars);
6674 
6675       propagateIRFlags(V0, OpScalars);
6676       propagateIRFlags(V1, AltScalars);
6677 
6678       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
6679       if (auto *I = dyn_cast<Instruction>(V)) {
6680         V = propagateMetadata(I, E->Scalars);
6681         GatherShuffleSeq.insert(I);
6682         CSEBlocks.insert(I->getParent());
6683       }
6684       V = ShuffleBuilder.finalize(V);
6685 
6686       E->VectorizedValue = V;
6687       ++NumVectorInstructions;
6688 
6689       return V;
6690     }
6691     default:
6692     llvm_unreachable("unknown inst");
6693   }
6694   return nullptr;
6695 }
6696 
6697 Value *BoUpSLP::vectorizeTree() {
6698   ExtraValueToDebugLocsMap ExternallyUsedValues;
6699   return vectorizeTree(ExternallyUsedValues);
6700 }
6701 
6702 Value *
6703 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
6704   // All blocks must be scheduled before any instructions are inserted.
6705   for (auto &BSIter : BlocksSchedules) {
6706     scheduleBlock(BSIter.second.get());
6707   }
6708 
6709   Builder.SetInsertPoint(&F->getEntryBlock().front());
6710   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
6711 
6712   // If the vectorized tree can be rewritten in a smaller type, we truncate the
6713   // vectorized root. InstCombine will then rewrite the entire expression. We
6714   // sign extend the extracted values below.
6715   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6716   if (MinBWs.count(ScalarRoot)) {
6717     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
6718       // If current instr is a phi and not the last phi, insert it after the
6719       // last phi node.
6720       if (isa<PHINode>(I))
6721         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
6722       else
6723         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
6724     }
6725     auto BundleWidth = VectorizableTree[0]->Scalars.size();
6726     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6727     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
6728     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
6729     VectorizableTree[0]->VectorizedValue = Trunc;
6730   }
6731 
6732   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
6733                     << " values .\n");
6734 
6735   // Extract all of the elements with the external uses.
6736   for (const auto &ExternalUse : ExternalUses) {
6737     Value *Scalar = ExternalUse.Scalar;
6738     llvm::User *User = ExternalUse.User;
6739 
6740     // Skip users that we already RAUW. This happens when one instruction
6741     // has multiple uses of the same value.
6742     if (User && !is_contained(Scalar->users(), User))
6743       continue;
6744     TreeEntry *E = getTreeEntry(Scalar);
6745     assert(E && "Invalid scalar");
6746     assert(E->State != TreeEntry::NeedToGather &&
6747            "Extracting from a gather list");
6748 
6749     Value *Vec = E->VectorizedValue;
6750     assert(Vec && "Can't find vectorizable value");
6751 
6752     Value *Lane = Builder.getInt32(ExternalUse.Lane);
6753     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
6754       if (Scalar->getType() != Vec->getType()) {
6755         Value *Ex;
6756         // "Reuse" the existing extract to improve final codegen.
6757         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
6758           Ex = Builder.CreateExtractElement(ES->getOperand(0),
6759                                             ES->getOperand(1));
6760         } else {
6761           Ex = Builder.CreateExtractElement(Vec, Lane);
6762         }
6763         // If necessary, sign-extend or zero-extend ScalarRoot
6764         // to the larger type.
6765         if (!MinBWs.count(ScalarRoot))
6766           return Ex;
6767         if (MinBWs[ScalarRoot].second)
6768           return Builder.CreateSExt(Ex, Scalar->getType());
6769         return Builder.CreateZExt(Ex, Scalar->getType());
6770       }
6771       assert(isa<FixedVectorType>(Scalar->getType()) &&
6772              isa<InsertElementInst>(Scalar) &&
6773              "In-tree scalar of vector type is not insertelement?");
6774       return Vec;
6775     };
6776     // If User == nullptr, the Scalar is used as extra arg. Generate
6777     // ExtractElement instruction and update the record for this scalar in
6778     // ExternallyUsedValues.
6779     if (!User) {
6780       assert(ExternallyUsedValues.count(Scalar) &&
6781              "Scalar with nullptr as an external user must be registered in "
6782              "ExternallyUsedValues map");
6783       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6784         Builder.SetInsertPoint(VecI->getParent(),
6785                                std::next(VecI->getIterator()));
6786       } else {
6787         Builder.SetInsertPoint(&F->getEntryBlock().front());
6788       }
6789       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6790       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
6791       auto &NewInstLocs = ExternallyUsedValues[NewInst];
6792       auto It = ExternallyUsedValues.find(Scalar);
6793       assert(It != ExternallyUsedValues.end() &&
6794              "Externally used scalar is not found in ExternallyUsedValues");
6795       NewInstLocs.append(It->second);
6796       ExternallyUsedValues.erase(Scalar);
6797       // Required to update internally referenced instructions.
6798       Scalar->replaceAllUsesWith(NewInst);
6799       continue;
6800     }
6801 
6802     // Generate extracts for out-of-tree users.
6803     // Find the insertion point for the extractelement lane.
6804     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6805       if (PHINode *PH = dyn_cast<PHINode>(User)) {
6806         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
6807           if (PH->getIncomingValue(i) == Scalar) {
6808             Instruction *IncomingTerminator =
6809                 PH->getIncomingBlock(i)->getTerminator();
6810             if (isa<CatchSwitchInst>(IncomingTerminator)) {
6811               Builder.SetInsertPoint(VecI->getParent(),
6812                                      std::next(VecI->getIterator()));
6813             } else {
6814               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
6815             }
6816             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6817             CSEBlocks.insert(PH->getIncomingBlock(i));
6818             PH->setOperand(i, NewInst);
6819           }
6820         }
6821       } else {
6822         Builder.SetInsertPoint(cast<Instruction>(User));
6823         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6824         CSEBlocks.insert(cast<Instruction>(User)->getParent());
6825         User->replaceUsesOfWith(Scalar, NewInst);
6826       }
6827     } else {
6828       Builder.SetInsertPoint(&F->getEntryBlock().front());
6829       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6830       CSEBlocks.insert(&F->getEntryBlock());
6831       User->replaceUsesOfWith(Scalar, NewInst);
6832     }
6833 
6834     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
6835   }
6836 
6837   // For each vectorized value:
6838   for (auto &TEPtr : VectorizableTree) {
6839     TreeEntry *Entry = TEPtr.get();
6840 
6841     // No need to handle users of gathered values.
6842     if (Entry->State == TreeEntry::NeedToGather)
6843       continue;
6844 
6845     assert(Entry->VectorizedValue && "Can't find vectorizable value");
6846 
6847     // For each lane:
6848     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
6849       Value *Scalar = Entry->Scalars[Lane];
6850 
6851 #ifndef NDEBUG
6852       Type *Ty = Scalar->getType();
6853       if (!Ty->isVoidTy()) {
6854         for (User *U : Scalar->users()) {
6855           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
6856 
6857           // It is legal to delete users in the ignorelist.
6858           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
6859                   (isa_and_nonnull<Instruction>(U) &&
6860                    isDeleted(cast<Instruction>(U)))) &&
6861                  "Deleting out-of-tree value");
6862         }
6863       }
6864 #endif
6865       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
6866       eraseInstruction(cast<Instruction>(Scalar));
6867     }
6868   }
6869 
6870   Builder.ClearInsertionPoint();
6871   InstrElementSize.clear();
6872 
6873   return VectorizableTree[0]->VectorizedValue;
6874 }
6875 
6876 void BoUpSLP::optimizeGatherSequence() {
6877   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
6878                     << " gather sequences instructions.\n");
6879   // LICM InsertElementInst sequences.
6880   for (Instruction *I : GatherShuffleSeq) {
6881     if (isDeleted(I))
6882       continue;
6883 
6884     // Check if this block is inside a loop.
6885     Loop *L = LI->getLoopFor(I->getParent());
6886     if (!L)
6887       continue;
6888 
6889     // Check if it has a preheader.
6890     BasicBlock *PreHeader = L->getLoopPreheader();
6891     if (!PreHeader)
6892       continue;
6893 
6894     // If the vector or the element that we insert into it are
6895     // instructions that are defined in this basic block then we can't
6896     // hoist this instruction.
6897     if (any_of(I->operands(), [L](Value *V) {
6898           auto *OpI = dyn_cast<Instruction>(V);
6899           return OpI && L->contains(OpI);
6900         }))
6901       continue;
6902 
6903     // We can hoist this instruction. Move it to the pre-header.
6904     I->moveBefore(PreHeader->getTerminator());
6905   }
6906 
6907   // Make a list of all reachable blocks in our CSE queue.
6908   SmallVector<const DomTreeNode *, 8> CSEWorkList;
6909   CSEWorkList.reserve(CSEBlocks.size());
6910   for (BasicBlock *BB : CSEBlocks)
6911     if (DomTreeNode *N = DT->getNode(BB)) {
6912       assert(DT->isReachableFromEntry(N));
6913       CSEWorkList.push_back(N);
6914     }
6915 
6916   // Sort blocks by domination. This ensures we visit a block after all blocks
6917   // dominating it are visited.
6918   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
6919     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
6920            "Different nodes should have different DFS numbers");
6921     return A->getDFSNumIn() < B->getDFSNumIn();
6922   });
6923 
6924   // Less defined shuffles can be replaced by the more defined copies.
6925   // Between two shuffles one is less defined if it has the same vector operands
6926   // and its mask indeces are the same as in the first one or undefs. E.g.
6927   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
6928   // poison, <0, 0, 0, 0>.
6929   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
6930                                            SmallVectorImpl<int> &NewMask) {
6931     if (I1->getType() != I2->getType())
6932       return false;
6933     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
6934     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
6935     if (!SI1 || !SI2)
6936       return I1->isIdenticalTo(I2);
6937     if (SI1->isIdenticalTo(SI2))
6938       return true;
6939     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
6940       if (SI1->getOperand(I) != SI2->getOperand(I))
6941         return false;
6942     // Check if the second instruction is more defined than the first one.
6943     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
6944     ArrayRef<int> SM1 = SI1->getShuffleMask();
6945     // Count trailing undefs in the mask to check the final number of used
6946     // registers.
6947     unsigned LastUndefsCnt = 0;
6948     for (int I = 0, E = NewMask.size(); I < E; ++I) {
6949       if (SM1[I] == UndefMaskElem)
6950         ++LastUndefsCnt;
6951       else
6952         LastUndefsCnt = 0;
6953       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
6954           NewMask[I] != SM1[I])
6955         return false;
6956       if (NewMask[I] == UndefMaskElem)
6957         NewMask[I] = SM1[I];
6958     }
6959     // Check if the last undefs actually change the final number of used vector
6960     // registers.
6961     return SM1.size() - LastUndefsCnt > 1 &&
6962            TTI->getNumberOfParts(SI1->getType()) ==
6963                TTI->getNumberOfParts(
6964                    FixedVectorType::get(SI1->getType()->getElementType(),
6965                                         SM1.size() - LastUndefsCnt));
6966   };
6967   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
6968   // instructions. TODO: We can further optimize this scan if we split the
6969   // instructions into different buckets based on the insert lane.
6970   SmallVector<Instruction *, 16> Visited;
6971   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
6972     assert(*I &&
6973            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
6974            "Worklist not sorted properly!");
6975     BasicBlock *BB = (*I)->getBlock();
6976     // For all instructions in blocks containing gather sequences:
6977     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
6978       if (isDeleted(&In))
6979         continue;
6980       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
6981           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
6982         continue;
6983 
6984       // Check if we can replace this instruction with any of the
6985       // visited instructions.
6986       bool Replaced = false;
6987       for (Instruction *&V : Visited) {
6988         SmallVector<int> NewMask;
6989         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
6990             DT->dominates(V->getParent(), In.getParent())) {
6991           In.replaceAllUsesWith(V);
6992           eraseInstruction(&In);
6993           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
6994             if (!NewMask.empty())
6995               SI->setShuffleMask(NewMask);
6996           Replaced = true;
6997           break;
6998         }
6999         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7000             GatherShuffleSeq.contains(V) &&
7001             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7002             DT->dominates(In.getParent(), V->getParent())) {
7003           In.moveAfter(V);
7004           V->replaceAllUsesWith(&In);
7005           eraseInstruction(V);
7006           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7007             if (!NewMask.empty())
7008               SI->setShuffleMask(NewMask);
7009           V = &In;
7010           Replaced = true;
7011           break;
7012         }
7013       }
7014       if (!Replaced) {
7015         assert(!is_contained(Visited, &In));
7016         Visited.push_back(&In);
7017       }
7018     }
7019   }
7020   CSEBlocks.clear();
7021   GatherShuffleSeq.clear();
7022 }
7023 
7024 // Groups the instructions to a bundle (which is then a single scheduling entity)
7025 // and schedules instructions until the bundle gets ready.
7026 Optional<BoUpSLP::ScheduleData *>
7027 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7028                                             const InstructionsState &S) {
7029   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7030   // instructions.
7031   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7032     return nullptr;
7033 
7034   // Initialize the instruction bundle.
7035   Instruction *OldScheduleEnd = ScheduleEnd;
7036   ScheduleData *PrevInBundle = nullptr;
7037   ScheduleData *Bundle = nullptr;
7038   bool ReSchedule = false;
7039   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7040 
7041   auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule,
7042                                                          ScheduleData *Bundle) {
7043     // The scheduling region got new instructions at the lower end (or it is a
7044     // new region for the first bundle). This makes it necessary to
7045     // recalculate all dependencies.
7046     // It is seldom that this needs to be done a second time after adding the
7047     // initial bundle to the region.
7048     if (ScheduleEnd != OldScheduleEnd) {
7049       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7050         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7051       ReSchedule = true;
7052     }
7053     if (ReSchedule) {
7054       resetSchedule();
7055       initialFillReadyList(ReadyInsts);
7056     }
7057     if (Bundle) {
7058       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7059                         << " in block " << BB->getName() << "\n");
7060       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7061     }
7062 
7063     // Now try to schedule the new bundle or (if no bundle) just calculate
7064     // dependencies. As soon as the bundle is "ready" it means that there are no
7065     // cyclic dependencies and we can schedule it. Note that's important that we
7066     // don't "schedule" the bundle yet (see cancelScheduling).
7067     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7068            !ReadyInsts.empty()) {
7069       ScheduleData *Picked = ReadyInsts.pop_back_val();
7070       if (Picked->isSchedulingEntity() && Picked->isReady())
7071         schedule(Picked, ReadyInsts);
7072     }
7073   };
7074 
7075   // Make sure that the scheduling region contains all
7076   // instructions of the bundle.
7077   for (Value *V : VL) {
7078     if (!extendSchedulingRegion(V, S)) {
7079       // If the scheduling region got new instructions at the lower end (or it
7080       // is a new region for the first bundle). This makes it necessary to
7081       // recalculate all dependencies.
7082       // Otherwise the compiler may crash trying to incorrectly calculate
7083       // dependencies and emit instruction in the wrong order at the actual
7084       // scheduling.
7085       TryScheduleBundle(/*ReSchedule=*/false, nullptr);
7086       return None;
7087     }
7088   }
7089 
7090   for (Value *V : VL) {
7091     ScheduleData *BundleMember = getScheduleData(V);
7092     assert(BundleMember &&
7093            "no ScheduleData for bundle member (maybe not in same basic block)");
7094     if (BundleMember->IsScheduled) {
7095       // A bundle member was scheduled as single instruction before and now
7096       // needs to be scheduled as part of the bundle. We just get rid of the
7097       // existing schedule.
7098       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7099                         << " was already scheduled\n");
7100       ReSchedule = true;
7101     }
7102     assert(BundleMember->isSchedulingEntity() &&
7103            "bundle member already part of other bundle");
7104     if (PrevInBundle) {
7105       PrevInBundle->NextInBundle = BundleMember;
7106     } else {
7107       Bundle = BundleMember;
7108     }
7109     BundleMember->UnscheduledDepsInBundle = 0;
7110     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7111 
7112     // Group the instructions to a bundle.
7113     BundleMember->FirstInBundle = Bundle;
7114     PrevInBundle = BundleMember;
7115   }
7116   assert(Bundle && "Failed to find schedule bundle");
7117   TryScheduleBundle(ReSchedule, Bundle);
7118   if (!Bundle->isReady()) {
7119     cancelScheduling(VL, S.OpValue);
7120     return None;
7121   }
7122   return Bundle;
7123 }
7124 
7125 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7126                                                 Value *OpValue) {
7127   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7128     return;
7129 
7130   ScheduleData *Bundle = getScheduleData(OpValue);
7131   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7132   assert(!Bundle->IsScheduled &&
7133          "Can't cancel bundle which is already scheduled");
7134   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7135          "tried to unbundle something which is not a bundle");
7136 
7137   // Un-bundle: make single instructions out of the bundle.
7138   ScheduleData *BundleMember = Bundle;
7139   while (BundleMember) {
7140     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7141     BundleMember->FirstInBundle = BundleMember;
7142     ScheduleData *Next = BundleMember->NextInBundle;
7143     BundleMember->NextInBundle = nullptr;
7144     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7145     if (BundleMember->UnscheduledDepsInBundle == 0) {
7146       ReadyInsts.insert(BundleMember);
7147     }
7148     BundleMember = Next;
7149   }
7150 }
7151 
7152 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7153   // Allocate a new ScheduleData for the instruction.
7154   if (ChunkPos >= ChunkSize) {
7155     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7156     ChunkPos = 0;
7157   }
7158   return &(ScheduleDataChunks.back()[ChunkPos++]);
7159 }
7160 
7161 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7162                                                       const InstructionsState &S) {
7163   if (getScheduleData(V, isOneOf(S, V)))
7164     return true;
7165   Instruction *I = dyn_cast<Instruction>(V);
7166   assert(I && "bundle member must be an instruction");
7167   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7168          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7169          "be scheduled");
7170   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7171     ScheduleData *ISD = getScheduleData(I);
7172     if (!ISD)
7173       return false;
7174     assert(isInSchedulingRegion(ISD) &&
7175            "ScheduleData not in scheduling region");
7176     ScheduleData *SD = allocateScheduleDataChunks();
7177     SD->Inst = I;
7178     SD->init(SchedulingRegionID, S.OpValue);
7179     ExtraScheduleDataMap[I][S.OpValue] = SD;
7180     return true;
7181   };
7182   if (CheckSheduleForI(I))
7183     return true;
7184   if (!ScheduleStart) {
7185     // It's the first instruction in the new region.
7186     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7187     ScheduleStart = I;
7188     ScheduleEnd = I->getNextNode();
7189     if (isOneOf(S, I) != I)
7190       CheckSheduleForI(I);
7191     assert(ScheduleEnd && "tried to vectorize a terminator?");
7192     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7193     return true;
7194   }
7195   // Search up and down at the same time, because we don't know if the new
7196   // instruction is above or below the existing scheduling region.
7197   BasicBlock::reverse_iterator UpIter =
7198       ++ScheduleStart->getIterator().getReverse();
7199   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7200   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7201   BasicBlock::iterator LowerEnd = BB->end();
7202   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7203          &*DownIter != I) {
7204     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7205       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7206       return false;
7207     }
7208 
7209     ++UpIter;
7210     ++DownIter;
7211   }
7212   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7213     assert(I->getParent() == ScheduleStart->getParent() &&
7214            "Instruction is in wrong basic block.");
7215     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7216     ScheduleStart = I;
7217     if (isOneOf(S, I) != I)
7218       CheckSheduleForI(I);
7219     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7220                       << "\n");
7221     return true;
7222   }
7223   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7224          "Expected to reach top of the basic block or instruction down the "
7225          "lower end.");
7226   assert(I->getParent() == ScheduleEnd->getParent() &&
7227          "Instruction is in wrong basic block.");
7228   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7229                    nullptr);
7230   ScheduleEnd = I->getNextNode();
7231   if (isOneOf(S, I) != I)
7232     CheckSheduleForI(I);
7233   assert(ScheduleEnd && "tried to vectorize a terminator?");
7234   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7235   return true;
7236 }
7237 
7238 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7239                                                 Instruction *ToI,
7240                                                 ScheduleData *PrevLoadStore,
7241                                                 ScheduleData *NextLoadStore) {
7242   ScheduleData *CurrentLoadStore = PrevLoadStore;
7243   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7244     ScheduleData *SD = ScheduleDataMap[I];
7245     if (!SD) {
7246       SD = allocateScheduleDataChunks();
7247       ScheduleDataMap[I] = SD;
7248       SD->Inst = I;
7249     }
7250     assert(!isInSchedulingRegion(SD) &&
7251            "new ScheduleData already in scheduling region");
7252     SD->init(SchedulingRegionID, I);
7253 
7254     if (I->mayReadOrWriteMemory() &&
7255         (!isa<IntrinsicInst>(I) ||
7256          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7257           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7258               Intrinsic::pseudoprobe))) {
7259       // Update the linked list of memory accessing instructions.
7260       if (CurrentLoadStore) {
7261         CurrentLoadStore->NextLoadStore = SD;
7262       } else {
7263         FirstLoadStoreInRegion = SD;
7264       }
7265       CurrentLoadStore = SD;
7266     }
7267   }
7268   if (NextLoadStore) {
7269     if (CurrentLoadStore)
7270       CurrentLoadStore->NextLoadStore = NextLoadStore;
7271   } else {
7272     LastLoadStoreInRegion = CurrentLoadStore;
7273   }
7274 }
7275 
7276 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7277                                                      bool InsertInReadyList,
7278                                                      BoUpSLP *SLP) {
7279   assert(SD->isSchedulingEntity());
7280 
7281   SmallVector<ScheduleData *, 10> WorkList;
7282   WorkList.push_back(SD);
7283 
7284   while (!WorkList.empty()) {
7285     ScheduleData *SD = WorkList.pop_back_val();
7286 
7287     ScheduleData *BundleMember = SD;
7288     while (BundleMember) {
7289       assert(isInSchedulingRegion(BundleMember));
7290       if (!BundleMember->hasValidDependencies()) {
7291 
7292         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7293                           << "\n");
7294         BundleMember->Dependencies = 0;
7295         BundleMember->resetUnscheduledDeps();
7296 
7297         // Handle def-use chain dependencies.
7298         if (BundleMember->OpValue != BundleMember->Inst) {
7299           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7300           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7301             BundleMember->Dependencies++;
7302             ScheduleData *DestBundle = UseSD->FirstInBundle;
7303             if (!DestBundle->IsScheduled)
7304               BundleMember->incrementUnscheduledDeps(1);
7305             if (!DestBundle->hasValidDependencies())
7306               WorkList.push_back(DestBundle);
7307           }
7308         } else {
7309           for (User *U : BundleMember->Inst->users()) {
7310             if (isa<Instruction>(U)) {
7311               ScheduleData *UseSD = getScheduleData(U);
7312               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7313                 BundleMember->Dependencies++;
7314                 ScheduleData *DestBundle = UseSD->FirstInBundle;
7315                 if (!DestBundle->IsScheduled)
7316                   BundleMember->incrementUnscheduledDeps(1);
7317                 if (!DestBundle->hasValidDependencies())
7318                   WorkList.push_back(DestBundle);
7319               }
7320             } else {
7321               // I'm not sure if this can ever happen. But we need to be safe.
7322               // This lets the instruction/bundle never be scheduled and
7323               // eventually disable vectorization.
7324               BundleMember->Dependencies++;
7325               BundleMember->incrementUnscheduledDeps(1);
7326             }
7327           }
7328         }
7329 
7330         // Handle the memory dependencies.
7331         ScheduleData *DepDest = BundleMember->NextLoadStore;
7332         if (DepDest) {
7333           Instruction *SrcInst = BundleMember->Inst;
7334           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
7335           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7336           unsigned numAliased = 0;
7337           unsigned DistToSrc = 1;
7338 
7339           while (DepDest) {
7340             assert(isInSchedulingRegion(DepDest));
7341 
7342             // We have two limits to reduce the complexity:
7343             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7344             //    SLP->isAliased (which is the expensive part in this loop).
7345             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7346             //    the whole loop (even if the loop is fast, it's quadratic).
7347             //    It's important for the loop break condition (see below) to
7348             //    check this limit even between two read-only instructions.
7349             if (DistToSrc >= MaxMemDepDistance ||
7350                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7351                      (numAliased >= AliasedCheckLimit ||
7352                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7353 
7354               // We increment the counter only if the locations are aliased
7355               // (instead of counting all alias checks). This gives a better
7356               // balance between reduced runtime and accurate dependencies.
7357               numAliased++;
7358 
7359               DepDest->MemoryDependencies.push_back(BundleMember);
7360               BundleMember->Dependencies++;
7361               ScheduleData *DestBundle = DepDest->FirstInBundle;
7362               if (!DestBundle->IsScheduled) {
7363                 BundleMember->incrementUnscheduledDeps(1);
7364               }
7365               if (!DestBundle->hasValidDependencies()) {
7366                 WorkList.push_back(DestBundle);
7367               }
7368             }
7369             DepDest = DepDest->NextLoadStore;
7370 
7371             // Example, explaining the loop break condition: Let's assume our
7372             // starting instruction is i0 and MaxMemDepDistance = 3.
7373             //
7374             //                      +--------v--v--v
7375             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7376             //             +--------^--^--^
7377             //
7378             // MaxMemDepDistance let us stop alias-checking at i3 and we add
7379             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7380             // Previously we already added dependencies from i3 to i6,i7,i8
7381             // (because of MaxMemDepDistance). As we added a dependency from
7382             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7383             // and we can abort this loop at i6.
7384             if (DistToSrc >= 2 * MaxMemDepDistance)
7385               break;
7386             DistToSrc++;
7387           }
7388         }
7389       }
7390       BundleMember = BundleMember->NextInBundle;
7391     }
7392     if (InsertInReadyList && SD->isReady()) {
7393       ReadyInsts.push_back(SD);
7394       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7395                         << "\n");
7396     }
7397   }
7398 }
7399 
7400 void BoUpSLP::BlockScheduling::resetSchedule() {
7401   assert(ScheduleStart &&
7402          "tried to reset schedule on block which has not been scheduled");
7403   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7404     doForAllOpcodes(I, [&](ScheduleData *SD) {
7405       assert(isInSchedulingRegion(SD) &&
7406              "ScheduleData not in scheduling region");
7407       SD->IsScheduled = false;
7408       SD->resetUnscheduledDeps();
7409     });
7410   }
7411   ReadyInsts.clear();
7412 }
7413 
7414 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7415   if (!BS->ScheduleStart)
7416     return;
7417 
7418   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7419 
7420   BS->resetSchedule();
7421 
7422   // For the real scheduling we use a more sophisticated ready-list: it is
7423   // sorted by the original instruction location. This lets the final schedule
7424   // be as  close as possible to the original instruction order.
7425   struct ScheduleDataCompare {
7426     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7427       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7428     }
7429   };
7430   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7431 
7432   // Ensure that all dependency data is updated and fill the ready-list with
7433   // initial instructions.
7434   int Idx = 0;
7435   int NumToSchedule = 0;
7436   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7437        I = I->getNextNode()) {
7438     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7439       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7440               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7441              "scheduler and vectorizer bundle mismatch");
7442       SD->FirstInBundle->SchedulingPriority = Idx++;
7443       if (SD->isSchedulingEntity()) {
7444         BS->calculateDependencies(SD, false, this);
7445         NumToSchedule++;
7446       }
7447     });
7448   }
7449   BS->initialFillReadyList(ReadyInsts);
7450 
7451   Instruction *LastScheduledInst = BS->ScheduleEnd;
7452 
7453   // Do the "real" scheduling.
7454   while (!ReadyInsts.empty()) {
7455     ScheduleData *picked = *ReadyInsts.begin();
7456     ReadyInsts.erase(ReadyInsts.begin());
7457 
7458     // Move the scheduled instruction(s) to their dedicated places, if not
7459     // there yet.
7460     ScheduleData *BundleMember = picked;
7461     while (BundleMember) {
7462       Instruction *pickedInst = BundleMember->Inst;
7463       if (pickedInst->getNextNode() != LastScheduledInst) {
7464         BS->BB->getInstList().remove(pickedInst);
7465         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
7466                                      pickedInst);
7467       }
7468       LastScheduledInst = pickedInst;
7469       BundleMember = BundleMember->NextInBundle;
7470     }
7471 
7472     BS->schedule(picked, ReadyInsts);
7473     NumToSchedule--;
7474   }
7475   assert(NumToSchedule == 0 && "could not schedule all instructions");
7476 
7477   // Avoid duplicate scheduling of the block.
7478   BS->ScheduleStart = nullptr;
7479 }
7480 
7481 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7482   // If V is a store, just return the width of the stored value (or value
7483   // truncated just before storing) without traversing the expression tree.
7484   // This is the common case.
7485   if (auto *Store = dyn_cast<StoreInst>(V)) {
7486     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7487       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7488     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7489   }
7490 
7491   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7492     return getVectorElementSize(IEI->getOperand(1));
7493 
7494   auto E = InstrElementSize.find(V);
7495   if (E != InstrElementSize.end())
7496     return E->second;
7497 
7498   // If V is not a store, we can traverse the expression tree to find loads
7499   // that feed it. The type of the loaded value may indicate a more suitable
7500   // width than V's type. We want to base the vector element size on the width
7501   // of memory operations where possible.
7502   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7503   SmallPtrSet<Instruction *, 16> Visited;
7504   if (auto *I = dyn_cast<Instruction>(V)) {
7505     Worklist.emplace_back(I, I->getParent());
7506     Visited.insert(I);
7507   }
7508 
7509   // Traverse the expression tree in bottom-up order looking for loads. If we
7510   // encounter an instruction we don't yet handle, we give up.
7511   auto Width = 0u;
7512   while (!Worklist.empty()) {
7513     Instruction *I;
7514     BasicBlock *Parent;
7515     std::tie(I, Parent) = Worklist.pop_back_val();
7516 
7517     // We should only be looking at scalar instructions here. If the current
7518     // instruction has a vector type, skip.
7519     auto *Ty = I->getType();
7520     if (isa<VectorType>(Ty))
7521       continue;
7522 
7523     // If the current instruction is a load, update MaxWidth to reflect the
7524     // width of the loaded value.
7525     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7526         isa<ExtractValueInst>(I))
7527       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7528 
7529     // Otherwise, we need to visit the operands of the instruction. We only
7530     // handle the interesting cases from buildTree here. If an operand is an
7531     // instruction we haven't yet visited and from the same basic block as the
7532     // user or the use is a PHI node, we add it to the worklist.
7533     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7534              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7535              isa<UnaryOperator>(I)) {
7536       for (Use &U : I->operands())
7537         if (auto *J = dyn_cast<Instruction>(U.get()))
7538           if (Visited.insert(J).second &&
7539               (isa<PHINode>(I) || J->getParent() == Parent))
7540             Worklist.emplace_back(J, J->getParent());
7541     } else {
7542       break;
7543     }
7544   }
7545 
7546   // If we didn't encounter a memory access in the expression tree, or if we
7547   // gave up for some reason, just return the width of V. Otherwise, return the
7548   // maximum width we found.
7549   if (!Width) {
7550     if (auto *CI = dyn_cast<CmpInst>(V))
7551       V = CI->getOperand(0);
7552     Width = DL->getTypeSizeInBits(V->getType());
7553   }
7554 
7555   for (Instruction *I : Visited)
7556     InstrElementSize[I] = Width;
7557 
7558   return Width;
7559 }
7560 
7561 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7562 // smaller type with a truncation. We collect the values that will be demoted
7563 // in ToDemote and additional roots that require investigating in Roots.
7564 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7565                                   SmallVectorImpl<Value *> &ToDemote,
7566                                   SmallVectorImpl<Value *> &Roots) {
7567   // We can always demote constants.
7568   if (isa<Constant>(V)) {
7569     ToDemote.push_back(V);
7570     return true;
7571   }
7572 
7573   // If the value is not an instruction in the expression with only one use, it
7574   // cannot be demoted.
7575   auto *I = dyn_cast<Instruction>(V);
7576   if (!I || !I->hasOneUse() || !Expr.count(I))
7577     return false;
7578 
7579   switch (I->getOpcode()) {
7580 
7581   // We can always demote truncations and extensions. Since truncations can
7582   // seed additional demotion, we save the truncated value.
7583   case Instruction::Trunc:
7584     Roots.push_back(I->getOperand(0));
7585     break;
7586   case Instruction::ZExt:
7587   case Instruction::SExt:
7588     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7589         isa<InsertElementInst>(I->getOperand(0)))
7590       return false;
7591     break;
7592 
7593   // We can demote certain binary operations if we can demote both of their
7594   // operands.
7595   case Instruction::Add:
7596   case Instruction::Sub:
7597   case Instruction::Mul:
7598   case Instruction::And:
7599   case Instruction::Or:
7600   case Instruction::Xor:
7601     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7602         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7603       return false;
7604     break;
7605 
7606   // We can demote selects if we can demote their true and false values.
7607   case Instruction::Select: {
7608     SelectInst *SI = cast<SelectInst>(I);
7609     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7610         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7611       return false;
7612     break;
7613   }
7614 
7615   // We can demote phis if we can demote all their incoming operands. Note that
7616   // we don't need to worry about cycles since we ensure single use above.
7617   case Instruction::PHI: {
7618     PHINode *PN = cast<PHINode>(I);
7619     for (Value *IncValue : PN->incoming_values())
7620       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7621         return false;
7622     break;
7623   }
7624 
7625   // Otherwise, conservatively give up.
7626   default:
7627     return false;
7628   }
7629 
7630   // Record the value that we can demote.
7631   ToDemote.push_back(V);
7632   return true;
7633 }
7634 
7635 void BoUpSLP::computeMinimumValueSizes() {
7636   // If there are no external uses, the expression tree must be rooted by a
7637   // store. We can't demote in-memory values, so there is nothing to do here.
7638   if (ExternalUses.empty())
7639     return;
7640 
7641   // We only attempt to truncate integer expressions.
7642   auto &TreeRoot = VectorizableTree[0]->Scalars;
7643   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
7644   if (!TreeRootIT)
7645     return;
7646 
7647   // If the expression is not rooted by a store, these roots should have
7648   // external uses. We will rely on InstCombine to rewrite the expression in
7649   // the narrower type. However, InstCombine only rewrites single-use values.
7650   // This means that if a tree entry other than a root is used externally, it
7651   // must have multiple uses and InstCombine will not rewrite it. The code
7652   // below ensures that only the roots are used externally.
7653   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
7654   for (auto &EU : ExternalUses)
7655     if (!Expr.erase(EU.Scalar))
7656       return;
7657   if (!Expr.empty())
7658     return;
7659 
7660   // Collect the scalar values of the vectorizable expression. We will use this
7661   // context to determine which values can be demoted. If we see a truncation,
7662   // we mark it as seeding another demotion.
7663   for (auto &EntryPtr : VectorizableTree)
7664     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
7665 
7666   // Ensure the roots of the vectorizable tree don't form a cycle. They must
7667   // have a single external user that is not in the vectorizable tree.
7668   for (auto *Root : TreeRoot)
7669     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
7670       return;
7671 
7672   // Conservatively determine if we can actually truncate the roots of the
7673   // expression. Collect the values that can be demoted in ToDemote and
7674   // additional roots that require investigating in Roots.
7675   SmallVector<Value *, 32> ToDemote;
7676   SmallVector<Value *, 4> Roots;
7677   for (auto *Root : TreeRoot)
7678     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
7679       return;
7680 
7681   // The maximum bit width required to represent all the values that can be
7682   // demoted without loss of precision. It would be safe to truncate the roots
7683   // of the expression to this width.
7684   auto MaxBitWidth = 8u;
7685 
7686   // We first check if all the bits of the roots are demanded. If they're not,
7687   // we can truncate the roots to this narrower type.
7688   for (auto *Root : TreeRoot) {
7689     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
7690     MaxBitWidth = std::max<unsigned>(
7691         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
7692   }
7693 
7694   // True if the roots can be zero-extended back to their original type, rather
7695   // than sign-extended. We know that if the leading bits are not demanded, we
7696   // can safely zero-extend. So we initialize IsKnownPositive to True.
7697   bool IsKnownPositive = true;
7698 
7699   // If all the bits of the roots are demanded, we can try a little harder to
7700   // compute a narrower type. This can happen, for example, if the roots are
7701   // getelementptr indices. InstCombine promotes these indices to the pointer
7702   // width. Thus, all their bits are technically demanded even though the
7703   // address computation might be vectorized in a smaller type.
7704   //
7705   // We start by looking at each entry that can be demoted. We compute the
7706   // maximum bit width required to store the scalar by using ValueTracking to
7707   // compute the number of high-order bits we can truncate.
7708   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
7709       llvm::all_of(TreeRoot, [](Value *R) {
7710         assert(R->hasOneUse() && "Root should have only one use!");
7711         return isa<GetElementPtrInst>(R->user_back());
7712       })) {
7713     MaxBitWidth = 8u;
7714 
7715     // Determine if the sign bit of all the roots is known to be zero. If not,
7716     // IsKnownPositive is set to False.
7717     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
7718       KnownBits Known = computeKnownBits(R, *DL);
7719       return Known.isNonNegative();
7720     });
7721 
7722     // Determine the maximum number of bits required to store the scalar
7723     // values.
7724     for (auto *Scalar : ToDemote) {
7725       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
7726       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
7727       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
7728     }
7729 
7730     // If we can't prove that the sign bit is zero, we must add one to the
7731     // maximum bit width to account for the unknown sign bit. This preserves
7732     // the existing sign bit so we can safely sign-extend the root back to the
7733     // original type. Otherwise, if we know the sign bit is zero, we will
7734     // zero-extend the root instead.
7735     //
7736     // FIXME: This is somewhat suboptimal, as there will be cases where adding
7737     //        one to the maximum bit width will yield a larger-than-necessary
7738     //        type. In general, we need to add an extra bit only if we can't
7739     //        prove that the upper bit of the original type is equal to the
7740     //        upper bit of the proposed smaller type. If these two bits are the
7741     //        same (either zero or one) we know that sign-extending from the
7742     //        smaller type will result in the same value. Here, since we can't
7743     //        yet prove this, we are just making the proposed smaller type
7744     //        larger to ensure correctness.
7745     if (!IsKnownPositive)
7746       ++MaxBitWidth;
7747   }
7748 
7749   // Round MaxBitWidth up to the next power-of-two.
7750   if (!isPowerOf2_64(MaxBitWidth))
7751     MaxBitWidth = NextPowerOf2(MaxBitWidth);
7752 
7753   // If the maximum bit width we compute is less than the with of the roots'
7754   // type, we can proceed with the narrowing. Otherwise, do nothing.
7755   if (MaxBitWidth >= TreeRootIT->getBitWidth())
7756     return;
7757 
7758   // If we can truncate the root, we must collect additional values that might
7759   // be demoted as a result. That is, those seeded by truncations we will
7760   // modify.
7761   while (!Roots.empty())
7762     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
7763 
7764   // Finally, map the values we can demote to the maximum bit with we computed.
7765   for (auto *Scalar : ToDemote)
7766     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
7767 }
7768 
7769 namespace {
7770 
7771 /// The SLPVectorizer Pass.
7772 struct SLPVectorizer : public FunctionPass {
7773   SLPVectorizerPass Impl;
7774 
7775   /// Pass identification, replacement for typeid
7776   static char ID;
7777 
7778   explicit SLPVectorizer() : FunctionPass(ID) {
7779     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
7780   }
7781 
7782   bool doInitialization(Module &M) override { return false; }
7783 
7784   bool runOnFunction(Function &F) override {
7785     if (skipFunction(F))
7786       return false;
7787 
7788     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
7789     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
7790     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7791     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
7792     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
7793     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7794     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7795     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
7796     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
7797     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
7798 
7799     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7800   }
7801 
7802   void getAnalysisUsage(AnalysisUsage &AU) const override {
7803     FunctionPass::getAnalysisUsage(AU);
7804     AU.addRequired<AssumptionCacheTracker>();
7805     AU.addRequired<ScalarEvolutionWrapperPass>();
7806     AU.addRequired<AAResultsWrapperPass>();
7807     AU.addRequired<TargetTransformInfoWrapperPass>();
7808     AU.addRequired<LoopInfoWrapperPass>();
7809     AU.addRequired<DominatorTreeWrapperPass>();
7810     AU.addRequired<DemandedBitsWrapperPass>();
7811     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
7812     AU.addRequired<InjectTLIMappingsLegacy>();
7813     AU.addPreserved<LoopInfoWrapperPass>();
7814     AU.addPreserved<DominatorTreeWrapperPass>();
7815     AU.addPreserved<AAResultsWrapperPass>();
7816     AU.addPreserved<GlobalsAAWrapperPass>();
7817     AU.setPreservesCFG();
7818   }
7819 };
7820 
7821 } // end anonymous namespace
7822 
7823 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
7824   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
7825   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
7826   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
7827   auto *AA = &AM.getResult<AAManager>(F);
7828   auto *LI = &AM.getResult<LoopAnalysis>(F);
7829   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
7830   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
7831   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
7832   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
7833 
7834   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7835   if (!Changed)
7836     return PreservedAnalyses::all();
7837 
7838   PreservedAnalyses PA;
7839   PA.preserveSet<CFGAnalyses>();
7840   return PA;
7841 }
7842 
7843 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
7844                                 TargetTransformInfo *TTI_,
7845                                 TargetLibraryInfo *TLI_, AAResults *AA_,
7846                                 LoopInfo *LI_, DominatorTree *DT_,
7847                                 AssumptionCache *AC_, DemandedBits *DB_,
7848                                 OptimizationRemarkEmitter *ORE_) {
7849   if (!RunSLPVectorization)
7850     return false;
7851   SE = SE_;
7852   TTI = TTI_;
7853   TLI = TLI_;
7854   AA = AA_;
7855   LI = LI_;
7856   DT = DT_;
7857   AC = AC_;
7858   DB = DB_;
7859   DL = &F.getParent()->getDataLayout();
7860 
7861   Stores.clear();
7862   GEPs.clear();
7863   bool Changed = false;
7864 
7865   // If the target claims to have no vector registers don't attempt
7866   // vectorization.
7867   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
7868     return false;
7869 
7870   // Don't vectorize when the attribute NoImplicitFloat is used.
7871   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
7872     return false;
7873 
7874   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
7875 
7876   // Use the bottom up slp vectorizer to construct chains that start with
7877   // store instructions.
7878   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
7879 
7880   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
7881   // delete instructions.
7882 
7883   // Update DFS numbers now so that we can use them for ordering.
7884   DT->updateDFSNumbers();
7885 
7886   // Scan the blocks in the function in post order.
7887   for (auto BB : post_order(&F.getEntryBlock())) {
7888     collectSeedInstructions(BB);
7889 
7890     // Vectorize trees that end at stores.
7891     if (!Stores.empty()) {
7892       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
7893                         << " underlying objects.\n");
7894       Changed |= vectorizeStoreChains(R);
7895     }
7896 
7897     // Vectorize trees that end at reductions.
7898     Changed |= vectorizeChainsInBlock(BB, R);
7899 
7900     // Vectorize the index computations of getelementptr instructions. This
7901     // is primarily intended to catch gather-like idioms ending at
7902     // non-consecutive loads.
7903     if (!GEPs.empty()) {
7904       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
7905                         << " underlying objects.\n");
7906       Changed |= vectorizeGEPIndices(BB, R);
7907     }
7908   }
7909 
7910   if (Changed) {
7911     R.optimizeGatherSequence();
7912     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
7913   }
7914   return Changed;
7915 }
7916 
7917 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
7918                                             unsigned Idx) {
7919   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
7920                     << "\n");
7921   const unsigned Sz = R.getVectorElementSize(Chain[0]);
7922   const unsigned MinVF = R.getMinVecRegSize() / Sz;
7923   unsigned VF = Chain.size();
7924 
7925   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
7926     return false;
7927 
7928   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
7929                     << "\n");
7930 
7931   R.buildTree(Chain);
7932   if (R.isTreeTinyAndNotFullyVectorizable())
7933     return false;
7934   if (R.isLoadCombineCandidate())
7935     return false;
7936   R.reorderTopToBottom();
7937   R.reorderBottomToTop();
7938   R.buildExternalUses();
7939 
7940   R.computeMinimumValueSizes();
7941 
7942   InstructionCost Cost = R.getTreeCost();
7943 
7944   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
7945   if (Cost < -SLPCostThreshold) {
7946     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
7947 
7948     using namespace ore;
7949 
7950     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
7951                                         cast<StoreInst>(Chain[0]))
7952                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
7953                      << " and with tree size "
7954                      << NV("TreeSize", R.getTreeSize()));
7955 
7956     R.vectorizeTree();
7957     return true;
7958   }
7959 
7960   return false;
7961 }
7962 
7963 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
7964                                         BoUpSLP &R) {
7965   // We may run into multiple chains that merge into a single chain. We mark the
7966   // stores that we vectorized so that we don't visit the same store twice.
7967   BoUpSLP::ValueSet VectorizedStores;
7968   bool Changed = false;
7969 
7970   int E = Stores.size();
7971   SmallBitVector Tails(E, false);
7972   int MaxIter = MaxStoreLookup.getValue();
7973   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
7974       E, std::make_pair(E, INT_MAX));
7975   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
7976   int IterCnt;
7977   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
7978                                   &CheckedPairs,
7979                                   &ConsecutiveChain](int K, int Idx) {
7980     if (IterCnt >= MaxIter)
7981       return true;
7982     if (CheckedPairs[Idx].test(K))
7983       return ConsecutiveChain[K].second == 1 &&
7984              ConsecutiveChain[K].first == Idx;
7985     ++IterCnt;
7986     CheckedPairs[Idx].set(K);
7987     CheckedPairs[K].set(Idx);
7988     Optional<int> Diff = getPointersDiff(
7989         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
7990         Stores[Idx]->getValueOperand()->getType(),
7991         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
7992     if (!Diff || *Diff == 0)
7993       return false;
7994     int Val = *Diff;
7995     if (Val < 0) {
7996       if (ConsecutiveChain[Idx].second > -Val) {
7997         Tails.set(K);
7998         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
7999       }
8000       return false;
8001     }
8002     if (ConsecutiveChain[K].second <= Val)
8003       return false;
8004 
8005     Tails.set(Idx);
8006     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8007     return Val == 1;
8008   };
8009   // Do a quadratic search on all of the given stores in reverse order and find
8010   // all of the pairs of stores that follow each other.
8011   for (int Idx = E - 1; Idx >= 0; --Idx) {
8012     // If a store has multiple consecutive store candidates, search according
8013     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8014     // This is because usually pairing with immediate succeeding or preceding
8015     // candidate create the best chance to find slp vectorization opportunity.
8016     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8017     IterCnt = 0;
8018     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8019       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8020           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8021         break;
8022   }
8023 
8024   // Tracks if we tried to vectorize stores starting from the given tail
8025   // already.
8026   SmallBitVector TriedTails(E, false);
8027   // For stores that start but don't end a link in the chain:
8028   for (int Cnt = E; Cnt > 0; --Cnt) {
8029     int I = Cnt - 1;
8030     if (ConsecutiveChain[I].first == E || Tails.test(I))
8031       continue;
8032     // We found a store instr that starts a chain. Now follow the chain and try
8033     // to vectorize it.
8034     BoUpSLP::ValueList Operands;
8035     // Collect the chain into a list.
8036     while (I != E && !VectorizedStores.count(Stores[I])) {
8037       Operands.push_back(Stores[I]);
8038       Tails.set(I);
8039       if (ConsecutiveChain[I].second != 1) {
8040         // Mark the new end in the chain and go back, if required. It might be
8041         // required if the original stores come in reversed order, for example.
8042         if (ConsecutiveChain[I].first != E &&
8043             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8044             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8045           TriedTails.set(I);
8046           Tails.reset(ConsecutiveChain[I].first);
8047           if (Cnt < ConsecutiveChain[I].first + 2)
8048             Cnt = ConsecutiveChain[I].first + 2;
8049         }
8050         break;
8051       }
8052       // Move to the next value in the chain.
8053       I = ConsecutiveChain[I].first;
8054     }
8055     assert(!Operands.empty() && "Expected non-empty list of stores.");
8056 
8057     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8058     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8059     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8060 
8061     unsigned MinVF = R.getMinVF(EltSize);
8062     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8063                               MaxElts);
8064 
8065     // FIXME: Is division-by-2 the correct step? Should we assert that the
8066     // register size is a power-of-2?
8067     unsigned StartIdx = 0;
8068     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8069       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8070         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8071         if (!VectorizedStores.count(Slice.front()) &&
8072             !VectorizedStores.count(Slice.back()) &&
8073             vectorizeStoreChain(Slice, R, Cnt)) {
8074           // Mark the vectorized stores so that we don't vectorize them again.
8075           VectorizedStores.insert(Slice.begin(), Slice.end());
8076           Changed = true;
8077           // If we vectorized initial block, no need to try to vectorize it
8078           // again.
8079           if (Cnt == StartIdx)
8080             StartIdx += Size;
8081           Cnt += Size;
8082           continue;
8083         }
8084         ++Cnt;
8085       }
8086       // Check if the whole array was vectorized already - exit.
8087       if (StartIdx >= Operands.size())
8088         break;
8089     }
8090   }
8091 
8092   return Changed;
8093 }
8094 
8095 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8096   // Initialize the collections. We will make a single pass over the block.
8097   Stores.clear();
8098   GEPs.clear();
8099 
8100   // Visit the store and getelementptr instructions in BB and organize them in
8101   // Stores and GEPs according to the underlying objects of their pointer
8102   // operands.
8103   for (Instruction &I : *BB) {
8104     // Ignore store instructions that are volatile or have a pointer operand
8105     // that doesn't point to a scalar type.
8106     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8107       if (!SI->isSimple())
8108         continue;
8109       if (!isValidElementType(SI->getValueOperand()->getType()))
8110         continue;
8111       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8112     }
8113 
8114     // Ignore getelementptr instructions that have more than one index, a
8115     // constant index, or a pointer operand that doesn't point to a scalar
8116     // type.
8117     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8118       auto Idx = GEP->idx_begin()->get();
8119       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8120         continue;
8121       if (!isValidElementType(Idx->getType()))
8122         continue;
8123       if (GEP->getType()->isVectorTy())
8124         continue;
8125       GEPs[GEP->getPointerOperand()].push_back(GEP);
8126     }
8127   }
8128 }
8129 
8130 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8131   if (!A || !B)
8132     return false;
8133   Value *VL[] = {A, B};
8134   return tryToVectorizeList(VL, R);
8135 }
8136 
8137 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8138                                            bool LimitForRegisterSize) {
8139   if (VL.size() < 2)
8140     return false;
8141 
8142   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8143                     << VL.size() << ".\n");
8144 
8145   // Check that all of the parts are instructions of the same type,
8146   // we permit an alternate opcode via InstructionsState.
8147   InstructionsState S = getSameOpcode(VL);
8148   if (!S.getOpcode())
8149     return false;
8150 
8151   Instruction *I0 = cast<Instruction>(S.OpValue);
8152   // Make sure invalid types (including vector type) are rejected before
8153   // determining vectorization factor for scalar instructions.
8154   for (Value *V : VL) {
8155     Type *Ty = V->getType();
8156     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8157       // NOTE: the following will give user internal llvm type name, which may
8158       // not be useful.
8159       R.getORE()->emit([&]() {
8160         std::string type_str;
8161         llvm::raw_string_ostream rso(type_str);
8162         Ty->print(rso);
8163         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8164                << "Cannot SLP vectorize list: type "
8165                << rso.str() + " is unsupported by vectorizer";
8166       });
8167       return false;
8168     }
8169   }
8170 
8171   unsigned Sz = R.getVectorElementSize(I0);
8172   unsigned MinVF = R.getMinVF(Sz);
8173   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8174   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8175   if (MaxVF < 2) {
8176     R.getORE()->emit([&]() {
8177       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8178              << "Cannot SLP vectorize list: vectorization factor "
8179              << "less than 2 is not supported";
8180     });
8181     return false;
8182   }
8183 
8184   bool Changed = false;
8185   bool CandidateFound = false;
8186   InstructionCost MinCost = SLPCostThreshold.getValue();
8187   Type *ScalarTy = VL[0]->getType();
8188   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8189     ScalarTy = IE->getOperand(1)->getType();
8190 
8191   unsigned NextInst = 0, MaxInst = VL.size();
8192   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8193     // No actual vectorization should happen, if number of parts is the same as
8194     // provided vectorization factor (i.e. the scalar type is used for vector
8195     // code during codegen).
8196     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8197     if (TTI->getNumberOfParts(VecTy) == VF)
8198       continue;
8199     for (unsigned I = NextInst; I < MaxInst; ++I) {
8200       unsigned OpsWidth = 0;
8201 
8202       if (I + VF > MaxInst)
8203         OpsWidth = MaxInst - I;
8204       else
8205         OpsWidth = VF;
8206 
8207       if (!isPowerOf2_32(OpsWidth))
8208         continue;
8209 
8210       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8211           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8212         break;
8213 
8214       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8215       // Check that a previous iteration of this loop did not delete the Value.
8216       if (llvm::any_of(Ops, [&R](Value *V) {
8217             auto *I = dyn_cast<Instruction>(V);
8218             return I && R.isDeleted(I);
8219           }))
8220         continue;
8221 
8222       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8223                         << "\n");
8224 
8225       R.buildTree(Ops);
8226       if (R.isTreeTinyAndNotFullyVectorizable())
8227         continue;
8228       R.reorderTopToBottom();
8229       R.reorderBottomToTop();
8230       R.buildExternalUses();
8231 
8232       R.computeMinimumValueSizes();
8233       InstructionCost Cost = R.getTreeCost();
8234       CandidateFound = true;
8235       MinCost = std::min(MinCost, Cost);
8236 
8237       if (Cost < -SLPCostThreshold) {
8238         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8239         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8240                                                     cast<Instruction>(Ops[0]))
8241                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8242                                  << " and with tree size "
8243                                  << ore::NV("TreeSize", R.getTreeSize()));
8244 
8245         R.vectorizeTree();
8246         // Move to the next bundle.
8247         I += VF - 1;
8248         NextInst = I + 1;
8249         Changed = true;
8250       }
8251     }
8252   }
8253 
8254   if (!Changed && CandidateFound) {
8255     R.getORE()->emit([&]() {
8256       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8257              << "List vectorization was possible but not beneficial with cost "
8258              << ore::NV("Cost", MinCost) << " >= "
8259              << ore::NV("Treshold", -SLPCostThreshold);
8260     });
8261   } else if (!Changed) {
8262     R.getORE()->emit([&]() {
8263       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8264              << "Cannot SLP vectorize list: vectorization was impossible"
8265              << " with available vectorization factors";
8266     });
8267   }
8268   return Changed;
8269 }
8270 
8271 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8272   if (!I)
8273     return false;
8274 
8275   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8276     return false;
8277 
8278   Value *P = I->getParent();
8279 
8280   // Vectorize in current basic block only.
8281   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8282   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8283   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8284     return false;
8285 
8286   // Try to vectorize V.
8287   if (tryToVectorizePair(Op0, Op1, R))
8288     return true;
8289 
8290   auto *A = dyn_cast<BinaryOperator>(Op0);
8291   auto *B = dyn_cast<BinaryOperator>(Op1);
8292   // Try to skip B.
8293   if (B && B->hasOneUse()) {
8294     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8295     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8296     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8297       return true;
8298     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8299       return true;
8300   }
8301 
8302   // Try to skip A.
8303   if (A && A->hasOneUse()) {
8304     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8305     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8306     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8307       return true;
8308     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8309       return true;
8310   }
8311   return false;
8312 }
8313 
8314 namespace {
8315 
8316 /// Model horizontal reductions.
8317 ///
8318 /// A horizontal reduction is a tree of reduction instructions that has values
8319 /// that can be put into a vector as its leaves. For example:
8320 ///
8321 /// mul mul mul mul
8322 ///  \  /    \  /
8323 ///   +       +
8324 ///    \     /
8325 ///       +
8326 /// This tree has "mul" as its leaf values and "+" as its reduction
8327 /// instructions. A reduction can feed into a store or a binary operation
8328 /// feeding a phi.
8329 ///    ...
8330 ///    \  /
8331 ///     +
8332 ///     |
8333 ///  phi +=
8334 ///
8335 ///  Or:
8336 ///    ...
8337 ///    \  /
8338 ///     +
8339 ///     |
8340 ///   *p =
8341 ///
8342 class HorizontalReduction {
8343   using ReductionOpsType = SmallVector<Value *, 16>;
8344   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8345   ReductionOpsListType ReductionOps;
8346   SmallVector<Value *, 32> ReducedVals;
8347   // Use map vector to make stable output.
8348   MapVector<Instruction *, Value *> ExtraArgs;
8349   WeakTrackingVH ReductionRoot;
8350   /// The type of reduction operation.
8351   RecurKind RdxKind;
8352 
8353   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8354 
8355   static bool isCmpSelMinMax(Instruction *I) {
8356     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8357            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8358   }
8359 
8360   // And/or are potentially poison-safe logical patterns like:
8361   // select x, y, false
8362   // select x, true, y
8363   static bool isBoolLogicOp(Instruction *I) {
8364     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8365            match(I, m_LogicalOr(m_Value(), m_Value()));
8366   }
8367 
8368   /// Checks if instruction is associative and can be vectorized.
8369   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8370     if (Kind == RecurKind::None)
8371       return false;
8372 
8373     // Integer ops that map to select instructions or intrinsics are fine.
8374     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8375         isBoolLogicOp(I))
8376       return true;
8377 
8378     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8379       // FP min/max are associative except for NaN and -0.0. We do not
8380       // have to rule out -0.0 here because the intrinsic semantics do not
8381       // specify a fixed result for it.
8382       return I->getFastMathFlags().noNaNs();
8383     }
8384 
8385     return I->isAssociative();
8386   }
8387 
8388   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8389     // Poison-safe 'or' takes the form: select X, true, Y
8390     // To make that work with the normal operand processing, we skip the
8391     // true value operand.
8392     // TODO: Change the code and data structures to handle this without a hack.
8393     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8394       return I->getOperand(2);
8395     return I->getOperand(Index);
8396   }
8397 
8398   /// Checks if the ParentStackElem.first should be marked as a reduction
8399   /// operation with an extra argument or as extra argument itself.
8400   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8401                     Value *ExtraArg) {
8402     if (ExtraArgs.count(ParentStackElem.first)) {
8403       ExtraArgs[ParentStackElem.first] = nullptr;
8404       // We ran into something like:
8405       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8406       // The whole ParentStackElem.first should be considered as an extra value
8407       // in this case.
8408       // Do not perform analysis of remaining operands of ParentStackElem.first
8409       // instruction, this whole instruction is an extra argument.
8410       ParentStackElem.second = INVALID_OPERAND_INDEX;
8411     } else {
8412       // We ran into something like:
8413       // ParentStackElem.first += ... + ExtraArg + ...
8414       ExtraArgs[ParentStackElem.first] = ExtraArg;
8415     }
8416   }
8417 
8418   /// Creates reduction operation with the current opcode.
8419   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8420                          Value *RHS, const Twine &Name, bool UseSelect) {
8421     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8422     switch (Kind) {
8423     case RecurKind::Or:
8424       if (UseSelect &&
8425           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8426         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8427       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8428                                  Name);
8429     case RecurKind::And:
8430       if (UseSelect &&
8431           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8432         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8433       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8434                                  Name);
8435     case RecurKind::Add:
8436     case RecurKind::Mul:
8437     case RecurKind::Xor:
8438     case RecurKind::FAdd:
8439     case RecurKind::FMul:
8440       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8441                                  Name);
8442     case RecurKind::FMax:
8443       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8444     case RecurKind::FMin:
8445       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8446     case RecurKind::SMax:
8447       if (UseSelect) {
8448         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8449         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8450       }
8451       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8452     case RecurKind::SMin:
8453       if (UseSelect) {
8454         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8455         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8456       }
8457       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8458     case RecurKind::UMax:
8459       if (UseSelect) {
8460         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8461         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8462       }
8463       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8464     case RecurKind::UMin:
8465       if (UseSelect) {
8466         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8467         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8468       }
8469       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8470     default:
8471       llvm_unreachable("Unknown reduction operation.");
8472     }
8473   }
8474 
8475   /// Creates reduction operation with the current opcode with the IR flags
8476   /// from \p ReductionOps.
8477   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8478                          Value *RHS, const Twine &Name,
8479                          const ReductionOpsListType &ReductionOps) {
8480     bool UseSelect = ReductionOps.size() == 2 ||
8481                      // Logical or/and.
8482                      (ReductionOps.size() == 1 &&
8483                       isa<SelectInst>(ReductionOps.front().front()));
8484     assert((!UseSelect || ReductionOps.size() != 2 ||
8485             isa<SelectInst>(ReductionOps[1][0])) &&
8486            "Expected cmp + select pairs for reduction");
8487     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8488     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8489       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8490         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8491         propagateIRFlags(Op, ReductionOps[1]);
8492         return Op;
8493       }
8494     }
8495     propagateIRFlags(Op, ReductionOps[0]);
8496     return Op;
8497   }
8498 
8499   /// Creates reduction operation with the current opcode with the IR flags
8500   /// from \p I.
8501   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8502                          Value *RHS, const Twine &Name, Instruction *I) {
8503     auto *SelI = dyn_cast<SelectInst>(I);
8504     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8505     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8506       if (auto *Sel = dyn_cast<SelectInst>(Op))
8507         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8508     }
8509     propagateIRFlags(Op, I);
8510     return Op;
8511   }
8512 
8513   static RecurKind getRdxKind(Instruction *I) {
8514     assert(I && "Expected instruction for reduction matching");
8515     TargetTransformInfo::ReductionFlags RdxFlags;
8516     if (match(I, m_Add(m_Value(), m_Value())))
8517       return RecurKind::Add;
8518     if (match(I, m_Mul(m_Value(), m_Value())))
8519       return RecurKind::Mul;
8520     if (match(I, m_And(m_Value(), m_Value())) ||
8521         match(I, m_LogicalAnd(m_Value(), m_Value())))
8522       return RecurKind::And;
8523     if (match(I, m_Or(m_Value(), m_Value())) ||
8524         match(I, m_LogicalOr(m_Value(), m_Value())))
8525       return RecurKind::Or;
8526     if (match(I, m_Xor(m_Value(), m_Value())))
8527       return RecurKind::Xor;
8528     if (match(I, m_FAdd(m_Value(), m_Value())))
8529       return RecurKind::FAdd;
8530     if (match(I, m_FMul(m_Value(), m_Value())))
8531       return RecurKind::FMul;
8532 
8533     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8534       return RecurKind::FMax;
8535     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8536       return RecurKind::FMin;
8537 
8538     // This matches either cmp+select or intrinsics. SLP is expected to handle
8539     // either form.
8540     // TODO: If we are canonicalizing to intrinsics, we can remove several
8541     //       special-case paths that deal with selects.
8542     if (match(I, m_SMax(m_Value(), m_Value())))
8543       return RecurKind::SMax;
8544     if (match(I, m_SMin(m_Value(), m_Value())))
8545       return RecurKind::SMin;
8546     if (match(I, m_UMax(m_Value(), m_Value())))
8547       return RecurKind::UMax;
8548     if (match(I, m_UMin(m_Value(), m_Value())))
8549       return RecurKind::UMin;
8550 
8551     if (auto *Select = dyn_cast<SelectInst>(I)) {
8552       // Try harder: look for min/max pattern based on instructions producing
8553       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8554       // During the intermediate stages of SLP, it's very common to have
8555       // pattern like this (since optimizeGatherSequence is run only once
8556       // at the end):
8557       // %1 = extractelement <2 x i32> %a, i32 0
8558       // %2 = extractelement <2 x i32> %a, i32 1
8559       // %cond = icmp sgt i32 %1, %2
8560       // %3 = extractelement <2 x i32> %a, i32 0
8561       // %4 = extractelement <2 x i32> %a, i32 1
8562       // %select = select i1 %cond, i32 %3, i32 %4
8563       CmpInst::Predicate Pred;
8564       Instruction *L1;
8565       Instruction *L2;
8566 
8567       Value *LHS = Select->getTrueValue();
8568       Value *RHS = Select->getFalseValue();
8569       Value *Cond = Select->getCondition();
8570 
8571       // TODO: Support inverse predicates.
8572       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8573         if (!isa<ExtractElementInst>(RHS) ||
8574             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8575           return RecurKind::None;
8576       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8577         if (!isa<ExtractElementInst>(LHS) ||
8578             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8579           return RecurKind::None;
8580       } else {
8581         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8582           return RecurKind::None;
8583         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8584             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8585             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8586           return RecurKind::None;
8587       }
8588 
8589       TargetTransformInfo::ReductionFlags RdxFlags;
8590       switch (Pred) {
8591       default:
8592         return RecurKind::None;
8593       case CmpInst::ICMP_SGT:
8594       case CmpInst::ICMP_SGE:
8595         return RecurKind::SMax;
8596       case CmpInst::ICMP_SLT:
8597       case CmpInst::ICMP_SLE:
8598         return RecurKind::SMin;
8599       case CmpInst::ICMP_UGT:
8600       case CmpInst::ICMP_UGE:
8601         return RecurKind::UMax;
8602       case CmpInst::ICMP_ULT:
8603       case CmpInst::ICMP_ULE:
8604         return RecurKind::UMin;
8605       }
8606     }
8607     return RecurKind::None;
8608   }
8609 
8610   /// Get the index of the first operand.
8611   static unsigned getFirstOperandIndex(Instruction *I) {
8612     return isCmpSelMinMax(I) ? 1 : 0;
8613   }
8614 
8615   /// Total number of operands in the reduction operation.
8616   static unsigned getNumberOfOperands(Instruction *I) {
8617     return isCmpSelMinMax(I) ? 3 : 2;
8618   }
8619 
8620   /// Checks if the instruction is in basic block \p BB.
8621   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8622   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8623     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
8624       auto *Sel = cast<SelectInst>(I);
8625       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
8626       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
8627     }
8628     return I->getParent() == BB;
8629   }
8630 
8631   /// Expected number of uses for reduction operations/reduced values.
8632   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
8633     if (IsCmpSelMinMax) {
8634       // SelectInst must be used twice while the condition op must have single
8635       // use only.
8636       if (auto *Sel = dyn_cast<SelectInst>(I))
8637         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
8638       return I->hasNUses(2);
8639     }
8640 
8641     // Arithmetic reduction operation must be used once only.
8642     return I->hasOneUse();
8643   }
8644 
8645   /// Initializes the list of reduction operations.
8646   void initReductionOps(Instruction *I) {
8647     if (isCmpSelMinMax(I))
8648       ReductionOps.assign(2, ReductionOpsType());
8649     else
8650       ReductionOps.assign(1, ReductionOpsType());
8651   }
8652 
8653   /// Add all reduction operations for the reduction instruction \p I.
8654   void addReductionOps(Instruction *I) {
8655     if (isCmpSelMinMax(I)) {
8656       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
8657       ReductionOps[1].emplace_back(I);
8658     } else {
8659       ReductionOps[0].emplace_back(I);
8660     }
8661   }
8662 
8663   static Value *getLHS(RecurKind Kind, Instruction *I) {
8664     if (Kind == RecurKind::None)
8665       return nullptr;
8666     return I->getOperand(getFirstOperandIndex(I));
8667   }
8668   static Value *getRHS(RecurKind Kind, Instruction *I) {
8669     if (Kind == RecurKind::None)
8670       return nullptr;
8671     return I->getOperand(getFirstOperandIndex(I) + 1);
8672   }
8673 
8674 public:
8675   HorizontalReduction() = default;
8676 
8677   /// Try to find a reduction tree.
8678   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
8679     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
8680            "Phi needs to use the binary operator");
8681     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
8682             isa<IntrinsicInst>(Inst)) &&
8683            "Expected binop, select, or intrinsic for reduction matching");
8684     RdxKind = getRdxKind(Inst);
8685 
8686     // We could have a initial reductions that is not an add.
8687     //  r *= v1 + v2 + v3 + v4
8688     // In such a case start looking for a tree rooted in the first '+'.
8689     if (Phi) {
8690       if (getLHS(RdxKind, Inst) == Phi) {
8691         Phi = nullptr;
8692         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
8693         if (!Inst)
8694           return false;
8695         RdxKind = getRdxKind(Inst);
8696       } else if (getRHS(RdxKind, Inst) == Phi) {
8697         Phi = nullptr;
8698         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
8699         if (!Inst)
8700           return false;
8701         RdxKind = getRdxKind(Inst);
8702       }
8703     }
8704 
8705     if (!isVectorizable(RdxKind, Inst))
8706       return false;
8707 
8708     // Analyze "regular" integer/FP types for reductions - no target-specific
8709     // types or pointers.
8710     Type *Ty = Inst->getType();
8711     if (!isValidElementType(Ty) || Ty->isPointerTy())
8712       return false;
8713 
8714     // Though the ultimate reduction may have multiple uses, its condition must
8715     // have only single use.
8716     if (auto *Sel = dyn_cast<SelectInst>(Inst))
8717       if (!Sel->getCondition()->hasOneUse())
8718         return false;
8719 
8720     ReductionRoot = Inst;
8721 
8722     // The opcode for leaf values that we perform a reduction on.
8723     // For example: load(x) + load(y) + load(z) + fptoui(w)
8724     // The leaf opcode for 'w' does not match, so we don't include it as a
8725     // potential candidate for the reduction.
8726     unsigned LeafOpcode = 0;
8727 
8728     // Post-order traverse the reduction tree starting at Inst. We only handle
8729     // true trees containing binary operators or selects.
8730     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
8731     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
8732     initReductionOps(Inst);
8733     while (!Stack.empty()) {
8734       Instruction *TreeN = Stack.back().first;
8735       unsigned EdgeToVisit = Stack.back().second++;
8736       const RecurKind TreeRdxKind = getRdxKind(TreeN);
8737       bool IsReducedValue = TreeRdxKind != RdxKind;
8738 
8739       // Postorder visit.
8740       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
8741         if (IsReducedValue)
8742           ReducedVals.push_back(TreeN);
8743         else {
8744           auto ExtraArgsIter = ExtraArgs.find(TreeN);
8745           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
8746             // Check if TreeN is an extra argument of its parent operation.
8747             if (Stack.size() <= 1) {
8748               // TreeN can't be an extra argument as it is a root reduction
8749               // operation.
8750               return false;
8751             }
8752             // Yes, TreeN is an extra argument, do not add it to a list of
8753             // reduction operations.
8754             // Stack[Stack.size() - 2] always points to the parent operation.
8755             markExtraArg(Stack[Stack.size() - 2], TreeN);
8756             ExtraArgs.erase(TreeN);
8757           } else
8758             addReductionOps(TreeN);
8759         }
8760         // Retract.
8761         Stack.pop_back();
8762         continue;
8763       }
8764 
8765       // Visit operands.
8766       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
8767       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
8768       if (!EdgeInst) {
8769         // Edge value is not a reduction instruction or a leaf instruction.
8770         // (It may be a constant, function argument, or something else.)
8771         markExtraArg(Stack.back(), EdgeVal);
8772         continue;
8773       }
8774       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
8775       // Continue analysis if the next operand is a reduction operation or
8776       // (possibly) a leaf value. If the leaf value opcode is not set,
8777       // the first met operation != reduction operation is considered as the
8778       // leaf opcode.
8779       // Only handle trees in the current basic block.
8780       // Each tree node needs to have minimal number of users except for the
8781       // ultimate reduction.
8782       const bool IsRdxInst = EdgeRdxKind == RdxKind;
8783       if (EdgeInst != Phi && EdgeInst != Inst &&
8784           hasSameParent(EdgeInst, Inst->getParent()) &&
8785           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
8786           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
8787         if (IsRdxInst) {
8788           // We need to be able to reassociate the reduction operations.
8789           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
8790             // I is an extra argument for TreeN (its parent operation).
8791             markExtraArg(Stack.back(), EdgeInst);
8792             continue;
8793           }
8794         } else if (!LeafOpcode) {
8795           LeafOpcode = EdgeInst->getOpcode();
8796         }
8797         Stack.push_back(
8798             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
8799         continue;
8800       }
8801       // I is an extra argument for TreeN (its parent operation).
8802       markExtraArg(Stack.back(), EdgeInst);
8803     }
8804     return true;
8805   }
8806 
8807   /// Attempt to vectorize the tree found by matchAssociativeReduction.
8808   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
8809     // If there are a sufficient number of reduction values, reduce
8810     // to a nearby power-of-2. We can safely generate oversized
8811     // vectors and rely on the backend to split them to legal sizes.
8812     unsigned NumReducedVals = ReducedVals.size();
8813     if (NumReducedVals < 4)
8814       return nullptr;
8815 
8816     // Intersect the fast-math-flags from all reduction operations.
8817     FastMathFlags RdxFMF;
8818     RdxFMF.set();
8819     for (ReductionOpsType &RdxOp : ReductionOps) {
8820       for (Value *RdxVal : RdxOp) {
8821         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
8822           RdxFMF &= FPMO->getFastMathFlags();
8823       }
8824     }
8825 
8826     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
8827     Builder.setFastMathFlags(RdxFMF);
8828 
8829     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
8830     // The same extra argument may be used several times, so log each attempt
8831     // to use it.
8832     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
8833       assert(Pair.first && "DebugLoc must be set.");
8834       ExternallyUsedValues[Pair.second].push_back(Pair.first);
8835     }
8836 
8837     // The compare instruction of a min/max is the insertion point for new
8838     // instructions and may be replaced with a new compare instruction.
8839     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
8840       assert(isa<SelectInst>(RdxRootInst) &&
8841              "Expected min/max reduction to have select root instruction");
8842       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
8843       assert(isa<Instruction>(ScalarCond) &&
8844              "Expected min/max reduction to have compare condition");
8845       return cast<Instruction>(ScalarCond);
8846     };
8847 
8848     // The reduction root is used as the insertion point for new instructions,
8849     // so set it as externally used to prevent it from being deleted.
8850     ExternallyUsedValues[ReductionRoot];
8851     SmallVector<Value *, 16> IgnoreList;
8852     for (ReductionOpsType &RdxOp : ReductionOps)
8853       IgnoreList.append(RdxOp.begin(), RdxOp.end());
8854 
8855     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
8856     if (NumReducedVals > ReduxWidth) {
8857       // In the loop below, we are building a tree based on a window of
8858       // 'ReduxWidth' values.
8859       // If the operands of those values have common traits (compare predicate,
8860       // constant operand, etc), then we want to group those together to
8861       // minimize the cost of the reduction.
8862 
8863       // TODO: This should be extended to count common operands for
8864       //       compares and binops.
8865 
8866       // Step 1: Count the number of times each compare predicate occurs.
8867       SmallDenseMap<unsigned, unsigned> PredCountMap;
8868       for (Value *RdxVal : ReducedVals) {
8869         CmpInst::Predicate Pred;
8870         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
8871           ++PredCountMap[Pred];
8872       }
8873       // Step 2: Sort the values so the most common predicates come first.
8874       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
8875         CmpInst::Predicate PredA, PredB;
8876         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
8877             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
8878           return PredCountMap[PredA] > PredCountMap[PredB];
8879         }
8880         return false;
8881       });
8882     }
8883 
8884     Value *VectorizedTree = nullptr;
8885     unsigned i = 0;
8886     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
8887       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
8888       V.buildTree(VL, IgnoreList);
8889       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
8890         break;
8891       if (V.isLoadCombineReductionCandidate(RdxKind))
8892         break;
8893       V.reorderTopToBottom();
8894       V.reorderBottomToTop(/*IgnoreReorder=*/true);
8895       V.buildExternalUses(ExternallyUsedValues);
8896 
8897       // For a poison-safe boolean logic reduction, do not replace select
8898       // instructions with logic ops. All reduced values will be frozen (see
8899       // below) to prevent leaking poison.
8900       if (isa<SelectInst>(ReductionRoot) &&
8901           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
8902           NumReducedVals != ReduxWidth)
8903         break;
8904 
8905       V.computeMinimumValueSizes();
8906 
8907       // Estimate cost.
8908       InstructionCost TreeCost =
8909           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
8910       InstructionCost ReductionCost =
8911           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
8912       InstructionCost Cost = TreeCost + ReductionCost;
8913       if (!Cost.isValid()) {
8914         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
8915         return nullptr;
8916       }
8917       if (Cost >= -SLPCostThreshold) {
8918         V.getORE()->emit([&]() {
8919           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
8920                                           cast<Instruction>(VL[0]))
8921                  << "Vectorizing horizontal reduction is possible"
8922                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
8923                  << " and threshold "
8924                  << ore::NV("Threshold", -SLPCostThreshold);
8925         });
8926         break;
8927       }
8928 
8929       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
8930                         << Cost << ". (HorRdx)\n");
8931       V.getORE()->emit([&]() {
8932         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
8933                                   cast<Instruction>(VL[0]))
8934                << "Vectorized horizontal reduction with cost "
8935                << ore::NV("Cost", Cost) << " and with tree size "
8936                << ore::NV("TreeSize", V.getTreeSize());
8937       });
8938 
8939       // Vectorize a tree.
8940       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
8941       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
8942 
8943       // Emit a reduction. If the root is a select (min/max idiom), the insert
8944       // point is the compare condition of that select.
8945       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
8946       if (isCmpSelMinMax(RdxRootInst))
8947         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
8948       else
8949         Builder.SetInsertPoint(RdxRootInst);
8950 
8951       // To prevent poison from leaking across what used to be sequential, safe,
8952       // scalar boolean logic operations, the reduction operand must be frozen.
8953       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
8954         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
8955 
8956       Value *ReducedSubTree =
8957           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
8958 
8959       if (!VectorizedTree) {
8960         // Initialize the final value in the reduction.
8961         VectorizedTree = ReducedSubTree;
8962       } else {
8963         // Update the final value in the reduction.
8964         Builder.SetCurrentDebugLocation(Loc);
8965         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8966                                   ReducedSubTree, "op.rdx", ReductionOps);
8967       }
8968       i += ReduxWidth;
8969       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
8970     }
8971 
8972     if (VectorizedTree) {
8973       // Finish the reduction.
8974       for (; i < NumReducedVals; ++i) {
8975         auto *I = cast<Instruction>(ReducedVals[i]);
8976         Builder.SetCurrentDebugLocation(I->getDebugLoc());
8977         VectorizedTree =
8978             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
8979       }
8980       for (auto &Pair : ExternallyUsedValues) {
8981         // Add each externally used value to the final reduction.
8982         for (auto *I : Pair.second) {
8983           Builder.SetCurrentDebugLocation(I->getDebugLoc());
8984           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8985                                     Pair.first, "op.extra", I);
8986         }
8987       }
8988 
8989       ReductionRoot->replaceAllUsesWith(VectorizedTree);
8990 
8991       // Mark all scalar reduction ops for deletion, they are replaced by the
8992       // vector reductions.
8993       V.eraseInstructions(IgnoreList);
8994     }
8995     return VectorizedTree;
8996   }
8997 
8998   unsigned numReductionValues() const { return ReducedVals.size(); }
8999 
9000 private:
9001   /// Calculate the cost of a reduction.
9002   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9003                                    Value *FirstReducedVal, unsigned ReduxWidth,
9004                                    FastMathFlags FMF) {
9005     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9006     Type *ScalarTy = FirstReducedVal->getType();
9007     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9008     InstructionCost VectorCost, ScalarCost;
9009     switch (RdxKind) {
9010     case RecurKind::Add:
9011     case RecurKind::Mul:
9012     case RecurKind::Or:
9013     case RecurKind::And:
9014     case RecurKind::Xor:
9015     case RecurKind::FAdd:
9016     case RecurKind::FMul: {
9017       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9018       VectorCost =
9019           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9020       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9021       break;
9022     }
9023     case RecurKind::FMax:
9024     case RecurKind::FMin: {
9025       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9026       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9027       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9028                                                /*unsigned=*/false, CostKind);
9029       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9030       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9031                                            SclCondTy, RdxPred, CostKind) +
9032                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9033                                            SclCondTy, RdxPred, CostKind);
9034       break;
9035     }
9036     case RecurKind::SMax:
9037     case RecurKind::SMin:
9038     case RecurKind::UMax:
9039     case RecurKind::UMin: {
9040       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9041       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9042       bool IsUnsigned =
9043           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9044       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9045                                                CostKind);
9046       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9047       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9048                                            SclCondTy, RdxPred, CostKind) +
9049                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9050                                            SclCondTy, RdxPred, CostKind);
9051       break;
9052     }
9053     default:
9054       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9055     }
9056 
9057     // Scalar cost is repeated for N-1 elements.
9058     ScalarCost *= (ReduxWidth - 1);
9059     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9060                       << " for reduction that starts with " << *FirstReducedVal
9061                       << " (It is a splitting reduction)\n");
9062     return VectorCost - ScalarCost;
9063   }
9064 
9065   /// Emit a horizontal reduction of the vectorized value.
9066   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9067                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9068     assert(VectorizedValue && "Need to have a vectorized tree node");
9069     assert(isPowerOf2_32(ReduxWidth) &&
9070            "We only handle power-of-two reductions for now");
9071     assert(RdxKind != RecurKind::FMulAdd &&
9072            "A call to the llvm.fmuladd intrinsic is not handled yet");
9073 
9074     ++NumVectorInstructions;
9075     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind,
9076                                        ReductionOps.back());
9077   }
9078 };
9079 
9080 } // end anonymous namespace
9081 
9082 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9083   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9084     return cast<FixedVectorType>(IE->getType())->getNumElements();
9085 
9086   unsigned AggregateSize = 1;
9087   auto *IV = cast<InsertValueInst>(InsertInst);
9088   Type *CurrentType = IV->getType();
9089   do {
9090     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9091       for (auto *Elt : ST->elements())
9092         if (Elt != ST->getElementType(0)) // check homogeneity
9093           return None;
9094       AggregateSize *= ST->getNumElements();
9095       CurrentType = ST->getElementType(0);
9096     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9097       AggregateSize *= AT->getNumElements();
9098       CurrentType = AT->getElementType();
9099     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9100       AggregateSize *= VT->getNumElements();
9101       return AggregateSize;
9102     } else if (CurrentType->isSingleValueType()) {
9103       return AggregateSize;
9104     } else {
9105       return None;
9106     }
9107   } while (true);
9108 }
9109 
9110 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9111                                    TargetTransformInfo *TTI,
9112                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9113                                    SmallVectorImpl<Value *> &InsertElts,
9114                                    unsigned OperandOffset) {
9115   do {
9116     Value *InsertedOperand = LastInsertInst->getOperand(1);
9117     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9118     if (!OperandIndex)
9119       return false;
9120     if (isa<InsertElementInst>(InsertedOperand) ||
9121         isa<InsertValueInst>(InsertedOperand)) {
9122       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9123                                   BuildVectorOpds, InsertElts, *OperandIndex))
9124         return false;
9125     } else {
9126       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9127       InsertElts[*OperandIndex] = LastInsertInst;
9128     }
9129     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9130   } while (LastInsertInst != nullptr &&
9131            (isa<InsertValueInst>(LastInsertInst) ||
9132             isa<InsertElementInst>(LastInsertInst)) &&
9133            LastInsertInst->hasOneUse());
9134   return true;
9135 }
9136 
9137 /// Recognize construction of vectors like
9138 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9139 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9140 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9141 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9142 ///  starting from the last insertelement or insertvalue instruction.
9143 ///
9144 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9145 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9146 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9147 ///
9148 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9149 ///
9150 /// \return true if it matches.
9151 static bool findBuildAggregate(Instruction *LastInsertInst,
9152                                TargetTransformInfo *TTI,
9153                                SmallVectorImpl<Value *> &BuildVectorOpds,
9154                                SmallVectorImpl<Value *> &InsertElts) {
9155 
9156   assert((isa<InsertElementInst>(LastInsertInst) ||
9157           isa<InsertValueInst>(LastInsertInst)) &&
9158          "Expected insertelement or insertvalue instruction!");
9159 
9160   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9161          "Expected empty result vectors!");
9162 
9163   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9164   if (!AggregateSize)
9165     return false;
9166   BuildVectorOpds.resize(*AggregateSize);
9167   InsertElts.resize(*AggregateSize);
9168 
9169   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9170                              0)) {
9171     llvm::erase_value(BuildVectorOpds, nullptr);
9172     llvm::erase_value(InsertElts, nullptr);
9173     if (BuildVectorOpds.size() >= 2)
9174       return true;
9175   }
9176 
9177   return false;
9178 }
9179 
9180 /// Try and get a reduction value from a phi node.
9181 ///
9182 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9183 /// if they come from either \p ParentBB or a containing loop latch.
9184 ///
9185 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9186 /// if not possible.
9187 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9188                                 BasicBlock *ParentBB, LoopInfo *LI) {
9189   // There are situations where the reduction value is not dominated by the
9190   // reduction phi. Vectorizing such cases has been reported to cause
9191   // miscompiles. See PR25787.
9192   auto DominatedReduxValue = [&](Value *R) {
9193     return isa<Instruction>(R) &&
9194            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9195   };
9196 
9197   Value *Rdx = nullptr;
9198 
9199   // Return the incoming value if it comes from the same BB as the phi node.
9200   if (P->getIncomingBlock(0) == ParentBB) {
9201     Rdx = P->getIncomingValue(0);
9202   } else if (P->getIncomingBlock(1) == ParentBB) {
9203     Rdx = P->getIncomingValue(1);
9204   }
9205 
9206   if (Rdx && DominatedReduxValue(Rdx))
9207     return Rdx;
9208 
9209   // Otherwise, check whether we have a loop latch to look at.
9210   Loop *BBL = LI->getLoopFor(ParentBB);
9211   if (!BBL)
9212     return nullptr;
9213   BasicBlock *BBLatch = BBL->getLoopLatch();
9214   if (!BBLatch)
9215     return nullptr;
9216 
9217   // There is a loop latch, return the incoming value if it comes from
9218   // that. This reduction pattern occasionally turns up.
9219   if (P->getIncomingBlock(0) == BBLatch) {
9220     Rdx = P->getIncomingValue(0);
9221   } else if (P->getIncomingBlock(1) == BBLatch) {
9222     Rdx = P->getIncomingValue(1);
9223   }
9224 
9225   if (Rdx && DominatedReduxValue(Rdx))
9226     return Rdx;
9227 
9228   return nullptr;
9229 }
9230 
9231 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9232   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9233     return true;
9234   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9235     return true;
9236   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9237     return true;
9238   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9239     return true;
9240   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9241     return true;
9242   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9243     return true;
9244   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9245     return true;
9246   return false;
9247 }
9248 
9249 /// Attempt to reduce a horizontal reduction.
9250 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9251 /// with reduction operators \a Root (or one of its operands) in a basic block
9252 /// \a BB, then check if it can be done. If horizontal reduction is not found
9253 /// and root instruction is a binary operation, vectorization of the operands is
9254 /// attempted.
9255 /// \returns true if a horizontal reduction was matched and reduced or operands
9256 /// of one of the binary instruction were vectorized.
9257 /// \returns false if a horizontal reduction was not matched (or not possible)
9258 /// or no vectorization of any binary operation feeding \a Root instruction was
9259 /// performed.
9260 static bool tryToVectorizeHorReductionOrInstOperands(
9261     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9262     TargetTransformInfo *TTI,
9263     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9264   if (!ShouldVectorizeHor)
9265     return false;
9266 
9267   if (!Root)
9268     return false;
9269 
9270   if (Root->getParent() != BB || isa<PHINode>(Root))
9271     return false;
9272   // Start analysis starting from Root instruction. If horizontal reduction is
9273   // found, try to vectorize it. If it is not a horizontal reduction or
9274   // vectorization is not possible or not effective, and currently analyzed
9275   // instruction is a binary operation, try to vectorize the operands, using
9276   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9277   // the same procedure considering each operand as a possible root of the
9278   // horizontal reduction.
9279   // Interrupt the process if the Root instruction itself was vectorized or all
9280   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9281   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9282   // CmpInsts so we can skip extra attempts in
9283   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9284   std::queue<std::pair<Instruction *, unsigned>> Stack;
9285   Stack.emplace(Root, 0);
9286   SmallPtrSet<Value *, 8> VisitedInstrs;
9287   SmallVector<WeakTrackingVH> PostponedInsts;
9288   bool Res = false;
9289   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9290                                      Value *&B1) -> Value * {
9291     bool IsBinop = matchRdxBop(Inst, B0, B1);
9292     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9293     if (IsBinop || IsSelect) {
9294       HorizontalReduction HorRdx;
9295       if (HorRdx.matchAssociativeReduction(P, Inst))
9296         return HorRdx.tryToReduce(R, TTI);
9297     }
9298     return nullptr;
9299   };
9300   while (!Stack.empty()) {
9301     Instruction *Inst;
9302     unsigned Level;
9303     std::tie(Inst, Level) = Stack.front();
9304     Stack.pop();
9305     // Do not try to analyze instruction that has already been vectorized.
9306     // This may happen when we vectorize instruction operands on a previous
9307     // iteration while stack was populated before that happened.
9308     if (R.isDeleted(Inst))
9309       continue;
9310     Value *B0 = nullptr, *B1 = nullptr;
9311     if (Value *V = TryToReduce(Inst, B0, B1)) {
9312       Res = true;
9313       // Set P to nullptr to avoid re-analysis of phi node in
9314       // matchAssociativeReduction function unless this is the root node.
9315       P = nullptr;
9316       if (auto *I = dyn_cast<Instruction>(V)) {
9317         // Try to find another reduction.
9318         Stack.emplace(I, Level);
9319         continue;
9320       }
9321     } else {
9322       bool IsBinop = B0 && B1;
9323       if (P && IsBinop) {
9324         Inst = dyn_cast<Instruction>(B0);
9325         if (Inst == P)
9326           Inst = dyn_cast<Instruction>(B1);
9327         if (!Inst) {
9328           // Set P to nullptr to avoid re-analysis of phi node in
9329           // matchAssociativeReduction function unless this is the root node.
9330           P = nullptr;
9331           continue;
9332         }
9333       }
9334       // Set P to nullptr to avoid re-analysis of phi node in
9335       // matchAssociativeReduction function unless this is the root node.
9336       P = nullptr;
9337       // Do not try to vectorize CmpInst operands, this is done separately.
9338       // Final attempt for binop args vectorization should happen after the loop
9339       // to try to find reductions.
9340       if (!isa<CmpInst>(Inst))
9341         PostponedInsts.push_back(Inst);
9342     }
9343 
9344     // Try to vectorize operands.
9345     // Continue analysis for the instruction from the same basic block only to
9346     // save compile time.
9347     if (++Level < RecursionMaxDepth)
9348       for (auto *Op : Inst->operand_values())
9349         if (VisitedInstrs.insert(Op).second)
9350           if (auto *I = dyn_cast<Instruction>(Op))
9351             // Do not try to vectorize CmpInst operands,  this is done
9352             // separately.
9353             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9354                 I->getParent() == BB)
9355               Stack.emplace(I, Level);
9356   }
9357   // Try to vectorized binops where reductions were not found.
9358   for (Value *V : PostponedInsts)
9359     if (auto *Inst = dyn_cast<Instruction>(V))
9360       if (!R.isDeleted(Inst))
9361         Res |= Vectorize(Inst, R);
9362   return Res;
9363 }
9364 
9365 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9366                                                  BasicBlock *BB, BoUpSLP &R,
9367                                                  TargetTransformInfo *TTI) {
9368   auto *I = dyn_cast_or_null<Instruction>(V);
9369   if (!I)
9370     return false;
9371 
9372   if (!isa<BinaryOperator>(I))
9373     P = nullptr;
9374   // Try to match and vectorize a horizontal reduction.
9375   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9376     return tryToVectorize(I, R);
9377   };
9378   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9379                                                   ExtraVectorization);
9380 }
9381 
9382 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9383                                                  BasicBlock *BB, BoUpSLP &R) {
9384   const DataLayout &DL = BB->getModule()->getDataLayout();
9385   if (!R.canMapToVector(IVI->getType(), DL))
9386     return false;
9387 
9388   SmallVector<Value *, 16> BuildVectorOpds;
9389   SmallVector<Value *, 16> BuildVectorInsts;
9390   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9391     return false;
9392 
9393   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9394   // Aggregate value is unlikely to be processed in vector register, we need to
9395   // extract scalars into scalar registers, so NeedExtraction is set true.
9396   return tryToVectorizeList(BuildVectorOpds, R);
9397 }
9398 
9399 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9400                                                    BasicBlock *BB, BoUpSLP &R) {
9401   SmallVector<Value *, 16> BuildVectorInsts;
9402   SmallVector<Value *, 16> BuildVectorOpds;
9403   SmallVector<int> Mask;
9404   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9405       (llvm::all_of(
9406            BuildVectorOpds,
9407            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9408        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9409     return false;
9410 
9411   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9412   return tryToVectorizeList(BuildVectorInsts, R);
9413 }
9414 
9415 template <typename T>
9416 static bool
9417 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9418                        function_ref<unsigned(T *)> Limit,
9419                        function_ref<bool(T *, T *)> Comparator,
9420                        function_ref<bool(T *, T *)> AreCompatible,
9421                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorize,
9422                        bool LimitForRegisterSize) {
9423   bool Changed = false;
9424   // Sort by type, parent, operands.
9425   stable_sort(Incoming, Comparator);
9426 
9427   // Try to vectorize elements base on their type.
9428   SmallVector<T *> Candidates;
9429   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9430     // Look for the next elements with the same type, parent and operand
9431     // kinds.
9432     auto *SameTypeIt = IncIt;
9433     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9434       ++SameTypeIt;
9435 
9436     // Try to vectorize them.
9437     unsigned NumElts = (SameTypeIt - IncIt);
9438     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9439                       << NumElts << ")\n");
9440     // The vectorization is a 3-state attempt:
9441     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9442     // size of maximal register at first.
9443     // 2. Try to vectorize remaining instructions with the same type, if
9444     // possible. This may result in the better vectorization results rather than
9445     // if we try just to vectorize instructions with the same/alternate opcodes.
9446     // 3. Final attempt to try to vectorize all instructions with the
9447     // same/alternate ops only, this may result in some extra final
9448     // vectorization.
9449     if (NumElts > 1 &&
9450         TryToVectorize(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9451       // Success start over because instructions might have been changed.
9452       Changed = true;
9453     } else if (NumElts < Limit(*IncIt) &&
9454                (Candidates.empty() ||
9455                 Candidates.front()->getType() == (*IncIt)->getType())) {
9456       Candidates.append(IncIt, std::next(IncIt, NumElts));
9457     }
9458     // Final attempt to vectorize instructions with the same types.
9459     if (Candidates.size() > 1 &&
9460         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9461       if (TryToVectorize(Candidates, /*LimitForRegisterSize=*/false)) {
9462         // Success start over because instructions might have been changed.
9463         Changed = true;
9464       } else if (LimitForRegisterSize) {
9465         // Try to vectorize using small vectors.
9466         for (auto *It = Candidates.begin(), *End = Candidates.end();
9467              It != End;) {
9468           auto *SameTypeIt = It;
9469           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9470             ++SameTypeIt;
9471           unsigned NumElts = (SameTypeIt - It);
9472           if (NumElts > 1 && TryToVectorize(makeArrayRef(It, NumElts),
9473                                             /*LimitForRegisterSize=*/false))
9474             Changed = true;
9475           It = SameTypeIt;
9476         }
9477       }
9478       Candidates.clear();
9479     }
9480 
9481     // Start over at the next instruction of a different type (or the end).
9482     IncIt = SameTypeIt;
9483   }
9484   return Changed;
9485 }
9486 
9487 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9488     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9489     bool AtTerminator) {
9490   bool OpsChanged = false;
9491   SmallVector<Instruction *, 4> PostponedCmps;
9492   for (auto *I : reverse(Instructions)) {
9493     if (R.isDeleted(I))
9494       continue;
9495     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9496       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9497     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9498       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9499     else if (isa<CmpInst>(I))
9500       PostponedCmps.push_back(I);
9501   }
9502   if (AtTerminator) {
9503     // Try to find reductions first.
9504     for (Instruction *I : PostponedCmps) {
9505       if (R.isDeleted(I))
9506         continue;
9507       for (Value *Op : I->operands())
9508         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9509     }
9510     // Try to vectorize operands as vector bundles.
9511     for (Instruction *I : PostponedCmps) {
9512       if (R.isDeleted(I))
9513         continue;
9514       OpsChanged |= tryToVectorize(I, R);
9515     }
9516     // Try to vectorize list of compares.
9517     // Sort by type, compare predicate, etc.
9518     // TODO: Add analysis on the operand opcodes (profitable to vectorize
9519     // instructions with same/alternate opcodes/const values).
9520     auto &&CompareSorter = [&R](Value *V, Value *V2) {
9521       auto *CI1 = cast<CmpInst>(V);
9522       auto *CI2 = cast<CmpInst>(V2);
9523       if (R.isDeleted(CI2) || !isValidElementType(CI2->getType()))
9524         return false;
9525       if (CI1->getOperand(0)->getType()->getTypeID() <
9526           CI2->getOperand(0)->getType()->getTypeID())
9527         return true;
9528       if (CI1->getOperand(0)->getType()->getTypeID() >
9529           CI2->getOperand(0)->getType()->getTypeID())
9530         return false;
9531       return CI1->getPredicate() < CI2->getPredicate() ||
9532              (CI1->getPredicate() > CI2->getPredicate() &&
9533               CI1->getPredicate() <
9534                   CmpInst::getSwappedPredicate(CI2->getPredicate()));
9535     };
9536 
9537     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
9538       if (V1 == V2)
9539         return true;
9540       auto *CI1 = cast<CmpInst>(V1);
9541       auto *CI2 = cast<CmpInst>(V2);
9542       if (R.isDeleted(CI2) || !isValidElementType(CI2->getType()))
9543         return false;
9544       if (CI1->getOperand(0)->getType() != CI2->getOperand(0)->getType())
9545         return false;
9546       return CI1->getPredicate() == CI2->getPredicate() ||
9547              CI1->getPredicate() ==
9548                  CmpInst::getSwappedPredicate(CI2->getPredicate());
9549     };
9550     auto Limit = [&R](Value *V) {
9551       unsigned EltSize = R.getVectorElementSize(V);
9552       return std::max(2U, R.getMaxVecRegSize() / EltSize);
9553     };
9554 
9555     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
9556     OpsChanged |= tryToVectorizeSequence<Value>(
9557         Vals, Limit, CompareSorter, AreCompatibleCompares,
9558         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9559           // Exclude possible reductions from other blocks.
9560           bool ArePossiblyReducedInOtherBlock =
9561               any_of(Candidates, [](Value *V) {
9562                 return any_of(V->users(), [V](User *U) {
9563                   return isa<SelectInst>(U) &&
9564                          cast<SelectInst>(U)->getParent() !=
9565                              cast<Instruction>(V)->getParent();
9566                 });
9567               });
9568           if (ArePossiblyReducedInOtherBlock)
9569             return false;
9570           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9571         },
9572         /*LimitForRegisterSize=*/true);
9573     Instructions.clear();
9574   } else {
9575     // Insert in reverse order since the PostponedCmps vector was filled in
9576     // reverse order.
9577     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9578   }
9579   return OpsChanged;
9580 }
9581 
9582 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9583   bool Changed = false;
9584   SmallVector<Value *, 4> Incoming;
9585   SmallPtrSet<Value *, 16> VisitedInstrs;
9586   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9587   // node. Allows better to identify the chains that can be vectorized in the
9588   // better way.
9589   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9590   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9591     assert(isValidElementType(V1->getType()) &&
9592            isValidElementType(V2->getType()) &&
9593            "Expected vectorizable types only.");
9594     // It is fine to compare type IDs here, since we expect only vectorizable
9595     // types, like ints, floats and pointers, we don't care about other type.
9596     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9597       return true;
9598     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
9599       return false;
9600     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9601     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9602     if (Opcodes1.size() < Opcodes2.size())
9603       return true;
9604     if (Opcodes1.size() > Opcodes2.size())
9605       return false;
9606     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9607       // Undefs are compatible with any other value.
9608       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9609         continue;
9610       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9611         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9612           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
9613           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
9614           if (!NodeI1)
9615             return NodeI2 != nullptr;
9616           if (!NodeI2)
9617             return false;
9618           assert((NodeI1 == NodeI2) ==
9619                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9620                  "Different nodes should have different DFS numbers");
9621           if (NodeI1 != NodeI2)
9622             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9623           InstructionsState S = getSameOpcode({I1, I2});
9624           if (S.getOpcode())
9625             continue;
9626           return I1->getOpcode() < I2->getOpcode();
9627         }
9628       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9629         continue;
9630       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
9631         return true;
9632       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
9633         return false;
9634     }
9635     return false;
9636   };
9637   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
9638     if (V1 == V2)
9639       return true;
9640     if (V1->getType() != V2->getType())
9641       return false;
9642     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9643     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9644     if (Opcodes1.size() != Opcodes2.size())
9645       return false;
9646     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9647       // Undefs are compatible with any other value.
9648       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9649         continue;
9650       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9651         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9652           if (I1->getParent() != I2->getParent())
9653             return false;
9654           InstructionsState S = getSameOpcode({I1, I2});
9655           if (S.getOpcode())
9656             continue;
9657           return false;
9658         }
9659       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9660         continue;
9661       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
9662         return false;
9663     }
9664     return true;
9665   };
9666   auto Limit = [&R](Value *V) {
9667     unsigned EltSize = R.getVectorElementSize(V);
9668     return std::max(2U, R.getMaxVecRegSize() / EltSize);
9669   };
9670 
9671   bool HaveVectorizedPhiNodes = false;
9672   do {
9673     // Collect the incoming values from the PHIs.
9674     Incoming.clear();
9675     for (Instruction &I : *BB) {
9676       PHINode *P = dyn_cast<PHINode>(&I);
9677       if (!P)
9678         break;
9679 
9680       // No need to analyze deleted, vectorized and non-vectorizable
9681       // instructions.
9682       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
9683           isValidElementType(P->getType()))
9684         Incoming.push_back(P);
9685     }
9686 
9687     // Find the corresponding non-phi nodes for better matching when trying to
9688     // build the tree.
9689     for (Value *V : Incoming) {
9690       SmallVectorImpl<Value *> &Opcodes =
9691           PHIToOpcodes.try_emplace(V).first->getSecond();
9692       if (!Opcodes.empty())
9693         continue;
9694       SmallVector<Value *, 4> Nodes(1, V);
9695       SmallPtrSet<Value *, 4> Visited;
9696       while (!Nodes.empty()) {
9697         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
9698         if (!Visited.insert(PHI).second)
9699           continue;
9700         for (Value *V : PHI->incoming_values()) {
9701           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
9702             Nodes.push_back(PHI1);
9703             continue;
9704           }
9705           Opcodes.emplace_back(V);
9706         }
9707       }
9708     }
9709 
9710     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
9711         Incoming, Limit, PHICompare, AreCompatiblePHIs,
9712         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9713           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9714         },
9715         /*LimitForRegisterSize=*/true);
9716     Changed |= HaveVectorizedPhiNodes;
9717     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
9718   } while (HaveVectorizedPhiNodes);
9719 
9720   VisitedInstrs.clear();
9721 
9722   SmallVector<Instruction *, 8> PostProcessInstructions;
9723   SmallDenseSet<Instruction *, 4> KeyNodes;
9724   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
9725     // Skip instructions with scalable type. The num of elements is unknown at
9726     // compile-time for scalable type.
9727     if (isa<ScalableVectorType>(it->getType()))
9728       continue;
9729 
9730     // Skip instructions marked for the deletion.
9731     if (R.isDeleted(&*it))
9732       continue;
9733     // We may go through BB multiple times so skip the one we have checked.
9734     if (!VisitedInstrs.insert(&*it).second) {
9735       if (it->use_empty() && KeyNodes.contains(&*it) &&
9736           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9737                                       it->isTerminator())) {
9738         // We would like to start over since some instructions are deleted
9739         // and the iterator may become invalid value.
9740         Changed = true;
9741         it = BB->begin();
9742         e = BB->end();
9743       }
9744       continue;
9745     }
9746 
9747     if (isa<DbgInfoIntrinsic>(it))
9748       continue;
9749 
9750     // Try to vectorize reductions that use PHINodes.
9751     if (PHINode *P = dyn_cast<PHINode>(it)) {
9752       // Check that the PHI is a reduction PHI.
9753       if (P->getNumIncomingValues() == 2) {
9754         // Try to match and vectorize a horizontal reduction.
9755         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
9756                                      TTI)) {
9757           Changed = true;
9758           it = BB->begin();
9759           e = BB->end();
9760           continue;
9761         }
9762       }
9763       // Try to vectorize the incoming values of the PHI, to catch reductions
9764       // that feed into PHIs.
9765       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
9766         // Skip if the incoming block is the current BB for now. Also, bypass
9767         // unreachable IR for efficiency and to avoid crashing.
9768         // TODO: Collect the skipped incoming values and try to vectorize them
9769         // after processing BB.
9770         if (BB == P->getIncomingBlock(I) ||
9771             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
9772           continue;
9773 
9774         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
9775                                             P->getIncomingBlock(I), R, TTI);
9776       }
9777       continue;
9778     }
9779 
9780     // Ran into an instruction without users, like terminator, or function call
9781     // with ignored return value, store. Ignore unused instructions (basing on
9782     // instruction type, except for CallInst and InvokeInst).
9783     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
9784                             isa<InvokeInst>(it))) {
9785       KeyNodes.insert(&*it);
9786       bool OpsChanged = false;
9787       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
9788         for (auto *V : it->operand_values()) {
9789           // Try to match and vectorize a horizontal reduction.
9790           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
9791         }
9792       }
9793       // Start vectorization of post-process list of instructions from the
9794       // top-tree instructions to try to vectorize as many instructions as
9795       // possible.
9796       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9797                                                 it->isTerminator());
9798       if (OpsChanged) {
9799         // We would like to start over since some instructions are deleted
9800         // and the iterator may become invalid value.
9801         Changed = true;
9802         it = BB->begin();
9803         e = BB->end();
9804         continue;
9805       }
9806     }
9807 
9808     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
9809         isa<InsertValueInst>(it))
9810       PostProcessInstructions.push_back(&*it);
9811   }
9812 
9813   return Changed;
9814 }
9815 
9816 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
9817   auto Changed = false;
9818   for (auto &Entry : GEPs) {
9819     // If the getelementptr list has fewer than two elements, there's nothing
9820     // to do.
9821     if (Entry.second.size() < 2)
9822       continue;
9823 
9824     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
9825                       << Entry.second.size() << ".\n");
9826 
9827     // Process the GEP list in chunks suitable for the target's supported
9828     // vector size. If a vector register can't hold 1 element, we are done. We
9829     // are trying to vectorize the index computations, so the maximum number of
9830     // elements is based on the size of the index expression, rather than the
9831     // size of the GEP itself (the target's pointer size).
9832     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9833     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
9834     if (MaxVecRegSize < EltSize)
9835       continue;
9836 
9837     unsigned MaxElts = MaxVecRegSize / EltSize;
9838     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
9839       auto Len = std::min<unsigned>(BE - BI, MaxElts);
9840       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
9841 
9842       // Initialize a set a candidate getelementptrs. Note that we use a
9843       // SetVector here to preserve program order. If the index computations
9844       // are vectorizable and begin with loads, we want to minimize the chance
9845       // of having to reorder them later.
9846       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
9847 
9848       // Some of the candidates may have already been vectorized after we
9849       // initially collected them. If so, they are marked as deleted, so remove
9850       // them from the set of candidates.
9851       Candidates.remove_if(
9852           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
9853 
9854       // Remove from the set of candidates all pairs of getelementptrs with
9855       // constant differences. Such getelementptrs are likely not good
9856       // candidates for vectorization in a bottom-up phase since one can be
9857       // computed from the other. We also ensure all candidate getelementptr
9858       // indices are unique.
9859       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
9860         auto *GEPI = GEPList[I];
9861         if (!Candidates.count(GEPI))
9862           continue;
9863         auto *SCEVI = SE->getSCEV(GEPList[I]);
9864         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
9865           auto *GEPJ = GEPList[J];
9866           auto *SCEVJ = SE->getSCEV(GEPList[J]);
9867           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
9868             Candidates.remove(GEPI);
9869             Candidates.remove(GEPJ);
9870           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
9871             Candidates.remove(GEPJ);
9872           }
9873         }
9874       }
9875 
9876       // We break out of the above computation as soon as we know there are
9877       // fewer than two candidates remaining.
9878       if (Candidates.size() < 2)
9879         continue;
9880 
9881       // Add the single, non-constant index of each candidate to the bundle. We
9882       // ensured the indices met these constraints when we originally collected
9883       // the getelementptrs.
9884       SmallVector<Value *, 16> Bundle(Candidates.size());
9885       auto BundleIndex = 0u;
9886       for (auto *V : Candidates) {
9887         auto *GEP = cast<GetElementPtrInst>(V);
9888         auto *GEPIdx = GEP->idx_begin()->get();
9889         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
9890         Bundle[BundleIndex++] = GEPIdx;
9891       }
9892 
9893       // Try and vectorize the indices. We are currently only interested in
9894       // gather-like cases of the form:
9895       //
9896       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
9897       //
9898       // where the loads of "a", the loads of "b", and the subtractions can be
9899       // performed in parallel. It's likely that detecting this pattern in a
9900       // bottom-up phase will be simpler and less costly than building a
9901       // full-blown top-down phase beginning at the consecutive loads.
9902       Changed |= tryToVectorizeList(Bundle, R);
9903     }
9904   }
9905   return Changed;
9906 }
9907 
9908 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
9909   bool Changed = false;
9910   // Sort by type, base pointers and values operand. Value operands must be
9911   // compatible (have the same opcode, same parent), otherwise it is
9912   // definitely not profitable to try to vectorize them.
9913   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
9914     if (V->getPointerOperandType()->getTypeID() <
9915         V2->getPointerOperandType()->getTypeID())
9916       return true;
9917     if (V->getPointerOperandType()->getTypeID() >
9918         V2->getPointerOperandType()->getTypeID())
9919       return false;
9920     // UndefValues are compatible with all other values.
9921     if (isa<UndefValue>(V->getValueOperand()) ||
9922         isa<UndefValue>(V2->getValueOperand()))
9923       return false;
9924     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
9925       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9926         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
9927             DT->getNode(I1->getParent());
9928         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
9929             DT->getNode(I2->getParent());
9930         assert(NodeI1 && "Should only process reachable instructions");
9931         assert(NodeI1 && "Should only process reachable instructions");
9932         assert((NodeI1 == NodeI2) ==
9933                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9934                "Different nodes should have different DFS numbers");
9935         if (NodeI1 != NodeI2)
9936           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9937         InstructionsState S = getSameOpcode({I1, I2});
9938         if (S.getOpcode())
9939           return false;
9940         return I1->getOpcode() < I2->getOpcode();
9941       }
9942     if (isa<Constant>(V->getValueOperand()) &&
9943         isa<Constant>(V2->getValueOperand()))
9944       return false;
9945     return V->getValueOperand()->getValueID() <
9946            V2->getValueOperand()->getValueID();
9947   };
9948 
9949   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
9950     if (V1 == V2)
9951       return true;
9952     if (V1->getPointerOperandType() != V2->getPointerOperandType())
9953       return false;
9954     // Undefs are compatible with any other value.
9955     if (isa<UndefValue>(V1->getValueOperand()) ||
9956         isa<UndefValue>(V2->getValueOperand()))
9957       return true;
9958     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
9959       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9960         if (I1->getParent() != I2->getParent())
9961           return false;
9962         InstructionsState S = getSameOpcode({I1, I2});
9963         return S.getOpcode() > 0;
9964       }
9965     if (isa<Constant>(V1->getValueOperand()) &&
9966         isa<Constant>(V2->getValueOperand()))
9967       return true;
9968     return V1->getValueOperand()->getValueID() ==
9969            V2->getValueOperand()->getValueID();
9970   };
9971   auto Limit = [&R, this](StoreInst *SI) {
9972     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
9973     return R.getMinVF(EltSize);
9974   };
9975 
9976   // Attempt to sort and vectorize each of the store-groups.
9977   for (auto &Pair : Stores) {
9978     if (Pair.second.size() < 2)
9979       continue;
9980 
9981     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
9982                       << Pair.second.size() << ".\n");
9983 
9984     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
9985       continue;
9986 
9987     Changed |= tryToVectorizeSequence<StoreInst>(
9988         Pair.second, Limit, StoreSorter, AreCompatibleStores,
9989         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
9990           return vectorizeStores(Candidates, R);
9991         },
9992         /*LimitForRegisterSize=*/false);
9993   }
9994   return Changed;
9995 }
9996 
9997 char SLPVectorizer::ID = 0;
9998 
9999 static const char lv_name[] = "SLP Vectorizer";
10000 
10001 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10002 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10003 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10004 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10005 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10006 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10007 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10008 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10009 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10010 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10011 
10012 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10013