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     // Reached the start of a new vector registers.
4352     if (Idx % EltsPerVector == 0) {
4353       AllConsecutive = true;
4354       continue;
4355     }
4356 
4357     // Check all extracts for a vector register on the target directly
4358     // extract values in order.
4359     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4360     unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4361     AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4362                       CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4363 
4364     if (AllConsecutive)
4365       continue;
4366 
4367     // Skip all indices, except for the last index per vector block.
4368     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4369       continue;
4370 
4371     // If we have a series of extracts which are not consecutive and hence
4372     // cannot re-use the source vector register directly, compute the shuffle
4373     // cost to extract the a vector with EltsPerVector elements.
4374     Cost += TTI.getShuffleCost(
4375         TargetTransformInfo::SK_PermuteSingleSrc,
4376         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4377   }
4378   return Cost;
4379 }
4380 
4381 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4382 /// operations operands.
4383 static void
4384 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4385                      ArrayRef<int> ReusesIndices,
4386                      const function_ref<bool(Instruction *)> IsAltOp,
4387                      SmallVectorImpl<int> &Mask,
4388                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4389                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4390   unsigned Sz = VL.size();
4391   Mask.assign(Sz, UndefMaskElem);
4392   SmallVector<int> OrderMask;
4393   if (!ReorderIndices.empty())
4394     inversePermutation(ReorderIndices, OrderMask);
4395   for (unsigned I = 0; I < Sz; ++I) {
4396     unsigned Idx = I;
4397     if (!ReorderIndices.empty())
4398       Idx = OrderMask[I];
4399     auto *OpInst = cast<Instruction>(VL[Idx]);
4400     if (IsAltOp(OpInst)) {
4401       Mask[I] = Sz + Idx;
4402       if (AltScalars)
4403         AltScalars->push_back(OpInst);
4404     } else {
4405       Mask[I] = Idx;
4406       if (OpScalars)
4407         OpScalars->push_back(OpInst);
4408     }
4409   }
4410   if (!ReusesIndices.empty()) {
4411     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4412     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4413       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4414     });
4415     Mask.swap(NewMask);
4416   }
4417 }
4418 
4419 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4420                                       ArrayRef<Value *> VectorizedVals) {
4421   ArrayRef<Value*> VL = E->Scalars;
4422 
4423   Type *ScalarTy = VL[0]->getType();
4424   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4425     ScalarTy = SI->getValueOperand()->getType();
4426   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4427     ScalarTy = CI->getOperand(0)->getType();
4428   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4429     ScalarTy = IE->getOperand(1)->getType();
4430   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4431   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4432 
4433   // If we have computed a smaller type for the expression, update VecTy so
4434   // that the costs will be accurate.
4435   if (MinBWs.count(VL[0]))
4436     VecTy = FixedVectorType::get(
4437         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4438   unsigned EntryVF = E->getVectorFactor();
4439   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4440 
4441   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4442   // FIXME: it tries to fix a problem with MSVC buildbots.
4443   TargetTransformInfo &TTIRef = *TTI;
4444   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4445                                VectorizedVals, E](InstructionCost &Cost) {
4446     DenseMap<Value *, int> ExtractVectorsTys;
4447     SmallPtrSet<Value *, 4> CheckedExtracts;
4448     for (auto *V : VL) {
4449       if (isa<UndefValue>(V))
4450         continue;
4451       // If all users of instruction are going to be vectorized and this
4452       // instruction itself is not going to be vectorized, consider this
4453       // instruction as dead and remove its cost from the final cost of the
4454       // vectorized tree.
4455       // Also, avoid adjusting the cost for extractelements with multiple uses
4456       // in different graph entries.
4457       const TreeEntry *VE = getTreeEntry(V);
4458       if (!CheckedExtracts.insert(V).second ||
4459           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4460           (VE && VE != E))
4461         continue;
4462       auto *EE = cast<ExtractElementInst>(V);
4463       Optional<unsigned> EEIdx = getExtractIndex(EE);
4464       if (!EEIdx)
4465         continue;
4466       unsigned Idx = *EEIdx;
4467       if (TTIRef.getNumberOfParts(VecTy) !=
4468           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4469         auto It =
4470             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4471         It->getSecond() = std::min<int>(It->second, Idx);
4472       }
4473       // Take credit for instruction that will become dead.
4474       if (EE->hasOneUse()) {
4475         Instruction *Ext = EE->user_back();
4476         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4477             all_of(Ext->users(),
4478                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4479           // Use getExtractWithExtendCost() to calculate the cost of
4480           // extractelement/ext pair.
4481           Cost -=
4482               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4483                                               EE->getVectorOperandType(), Idx);
4484           // Add back the cost of s|zext which is subtracted separately.
4485           Cost += TTIRef.getCastInstrCost(
4486               Ext->getOpcode(), Ext->getType(), EE->getType(),
4487               TTI::getCastContextHint(Ext), CostKind, Ext);
4488           continue;
4489         }
4490       }
4491       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4492                                         EE->getVectorOperandType(), Idx);
4493     }
4494     // Add a cost for subvector extracts/inserts if required.
4495     for (const auto &Data : ExtractVectorsTys) {
4496       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4497       unsigned NumElts = VecTy->getNumElements();
4498       if (Data.second % NumElts == 0)
4499         continue;
4500       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4501         unsigned Idx = (Data.second / NumElts) * NumElts;
4502         unsigned EENumElts = EEVTy->getNumElements();
4503         if (Idx + NumElts <= EENumElts) {
4504           Cost +=
4505               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4506                                     EEVTy, None, Idx, VecTy);
4507         } else {
4508           // Need to round up the subvector type vectorization factor to avoid a
4509           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4510           // <= EENumElts.
4511           auto *SubVT =
4512               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4513           Cost +=
4514               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4515                                     EEVTy, None, Idx, SubVT);
4516         }
4517       } else {
4518         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4519                                       VecTy, None, 0, EEVTy);
4520       }
4521     }
4522   };
4523   if (E->State == TreeEntry::NeedToGather) {
4524     if (allConstant(VL))
4525       return 0;
4526     if (isa<InsertElementInst>(VL[0]))
4527       return InstructionCost::getInvalid();
4528     SmallVector<int> Mask;
4529     SmallVector<const TreeEntry *> Entries;
4530     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4531         isGatherShuffledEntry(E, Mask, Entries);
4532     if (Shuffle.hasValue()) {
4533       InstructionCost GatherCost = 0;
4534       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4535         // Perfect match in the graph, will reuse the previously vectorized
4536         // node. Cost is 0.
4537         LLVM_DEBUG(
4538             dbgs()
4539             << "SLP: perfect diamond match for gather bundle that starts with "
4540             << *VL.front() << ".\n");
4541         if (NeedToShuffleReuses)
4542           GatherCost =
4543               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4544                                   FinalVecTy, E->ReuseShuffleIndices);
4545       } else {
4546         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4547                           << " entries for bundle that starts with "
4548                           << *VL.front() << ".\n");
4549         // Detected that instead of gather we can emit a shuffle of single/two
4550         // previously vectorized nodes. Add the cost of the permutation rather
4551         // than gather.
4552         ::addMask(Mask, E->ReuseShuffleIndices);
4553         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4554       }
4555       return GatherCost;
4556     }
4557     if ((E->getOpcode() == Instruction::ExtractElement ||
4558          all_of(E->Scalars,
4559                 [](Value *V) {
4560                   return isa<ExtractElementInst, UndefValue>(V);
4561                 })) &&
4562         allSameType(VL)) {
4563       // Check that gather of extractelements can be represented as just a
4564       // shuffle of a single/two vectors the scalars are extracted from.
4565       SmallVector<int> Mask;
4566       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4567           isFixedVectorShuffle(VL, Mask);
4568       if (ShuffleKind.hasValue()) {
4569         // Found the bunch of extractelement instructions that must be gathered
4570         // into a vector and can be represented as a permutation elements in a
4571         // single input vector or of 2 input vectors.
4572         InstructionCost Cost =
4573             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4574         AdjustExtractsCost(Cost);
4575         if (NeedToShuffleReuses)
4576           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4577                                       FinalVecTy, E->ReuseShuffleIndices);
4578         return Cost;
4579       }
4580     }
4581     if (isSplat(VL)) {
4582       // Found the broadcasting of the single scalar, calculate the cost as the
4583       // broadcast.
4584       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4585     }
4586     InstructionCost ReuseShuffleCost = 0;
4587     if (NeedToShuffleReuses)
4588       ReuseShuffleCost = TTI->getShuffleCost(
4589           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4590     // Improve gather cost for gather of loads, if we can group some of the
4591     // loads into vector loads.
4592     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4593         !E->isAltShuffle()) {
4594       BoUpSLP::ValueSet VectorizedLoads;
4595       unsigned StartIdx = 0;
4596       unsigned VF = VL.size() / 2;
4597       unsigned VectorizedCnt = 0;
4598       unsigned ScatterVectorizeCnt = 0;
4599       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4600       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4601         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4602              Cnt += VF) {
4603           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4604           if (!VectorizedLoads.count(Slice.front()) &&
4605               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4606             SmallVector<Value *> PointerOps;
4607             OrdersType CurrentOrder;
4608             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4609                                               *SE, CurrentOrder, PointerOps);
4610             switch (LS) {
4611             case LoadsState::Vectorize:
4612             case LoadsState::ScatterVectorize:
4613               // Mark the vectorized loads so that we don't vectorize them
4614               // again.
4615               if (LS == LoadsState::Vectorize)
4616                 ++VectorizedCnt;
4617               else
4618                 ++ScatterVectorizeCnt;
4619               VectorizedLoads.insert(Slice.begin(), Slice.end());
4620               // If we vectorized initial block, no need to try to vectorize it
4621               // again.
4622               if (Cnt == StartIdx)
4623                 StartIdx += VF;
4624               break;
4625             case LoadsState::Gather:
4626               break;
4627             }
4628           }
4629         }
4630         // Check if the whole array was vectorized already - exit.
4631         if (StartIdx >= VL.size())
4632           break;
4633         // Found vectorizable parts - exit.
4634         if (!VectorizedLoads.empty())
4635           break;
4636       }
4637       if (!VectorizedLoads.empty()) {
4638         InstructionCost GatherCost = 0;
4639         unsigned NumParts = TTI->getNumberOfParts(VecTy);
4640         bool NeedInsertSubvectorAnalysis =
4641             !NumParts || (VL.size() / VF) > NumParts;
4642         // Get the cost for gathered loads.
4643         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4644           if (VectorizedLoads.contains(VL[I]))
4645             continue;
4646           GatherCost += getGatherCost(VL.slice(I, VF));
4647         }
4648         // The cost for vectorized loads.
4649         InstructionCost ScalarsCost = 0;
4650         for (Value *V : VectorizedLoads) {
4651           auto *LI = cast<LoadInst>(V);
4652           ScalarsCost += TTI->getMemoryOpCost(
4653               Instruction::Load, LI->getType(), LI->getAlign(),
4654               LI->getPointerAddressSpace(), CostKind, LI);
4655         }
4656         auto *LI = cast<LoadInst>(E->getMainOp());
4657         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4658         Align Alignment = LI->getAlign();
4659         GatherCost +=
4660             VectorizedCnt *
4661             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4662                                  LI->getPointerAddressSpace(), CostKind, LI);
4663         GatherCost += ScatterVectorizeCnt *
4664                       TTI->getGatherScatterOpCost(
4665                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4666                           /*VariableMask=*/false, Alignment, CostKind, LI);
4667         if (NeedInsertSubvectorAnalysis) {
4668           // Add the cost for the subvectors insert.
4669           for (int I = VF, E = VL.size(); I < E; I += VF)
4670             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
4671                                               None, I, LoadTy);
4672         }
4673         return ReuseShuffleCost + GatherCost - ScalarsCost;
4674       }
4675     }
4676     return ReuseShuffleCost + getGatherCost(VL);
4677   }
4678   InstructionCost CommonCost = 0;
4679   SmallVector<int> Mask;
4680   if (!E->ReorderIndices.empty()) {
4681     SmallVector<int> NewMask;
4682     if (E->getOpcode() == Instruction::Store) {
4683       // For stores the order is actually a mask.
4684       NewMask.resize(E->ReorderIndices.size());
4685       copy(E->ReorderIndices, NewMask.begin());
4686     } else {
4687       inversePermutation(E->ReorderIndices, NewMask);
4688     }
4689     ::addMask(Mask, NewMask);
4690   }
4691   if (NeedToShuffleReuses)
4692     ::addMask(Mask, E->ReuseShuffleIndices);
4693   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
4694     CommonCost =
4695         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
4696   assert((E->State == TreeEntry::Vectorize ||
4697           E->State == TreeEntry::ScatterVectorize) &&
4698          "Unhandled state");
4699   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
4700   Instruction *VL0 = E->getMainOp();
4701   unsigned ShuffleOrOp =
4702       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4703   switch (ShuffleOrOp) {
4704     case Instruction::PHI:
4705       return 0;
4706 
4707     case Instruction::ExtractValue:
4708     case Instruction::ExtractElement: {
4709       // The common cost of removal ExtractElement/ExtractValue instructions +
4710       // the cost of shuffles, if required to resuffle the original vector.
4711       if (NeedToShuffleReuses) {
4712         unsigned Idx = 0;
4713         for (unsigned I : E->ReuseShuffleIndices) {
4714           if (ShuffleOrOp == Instruction::ExtractElement) {
4715             auto *EE = cast<ExtractElementInst>(VL[I]);
4716             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4717                                                   EE->getVectorOperandType(),
4718                                                   *getExtractIndex(EE));
4719           } else {
4720             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4721                                                   VecTy, Idx);
4722             ++Idx;
4723           }
4724         }
4725         Idx = EntryVF;
4726         for (Value *V : VL) {
4727           if (ShuffleOrOp == Instruction::ExtractElement) {
4728             auto *EE = cast<ExtractElementInst>(V);
4729             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4730                                                   EE->getVectorOperandType(),
4731                                                   *getExtractIndex(EE));
4732           } else {
4733             --Idx;
4734             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4735                                                   VecTy, Idx);
4736           }
4737         }
4738       }
4739       if (ShuffleOrOp == Instruction::ExtractValue) {
4740         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
4741           auto *EI = cast<Instruction>(VL[I]);
4742           // Take credit for instruction that will become dead.
4743           if (EI->hasOneUse()) {
4744             Instruction *Ext = EI->user_back();
4745             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4746                 all_of(Ext->users(),
4747                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
4748               // Use getExtractWithExtendCost() to calculate the cost of
4749               // extractelement/ext pair.
4750               CommonCost -= TTI->getExtractWithExtendCost(
4751                   Ext->getOpcode(), Ext->getType(), VecTy, I);
4752               // Add back the cost of s|zext which is subtracted separately.
4753               CommonCost += TTI->getCastInstrCost(
4754                   Ext->getOpcode(), Ext->getType(), EI->getType(),
4755                   TTI::getCastContextHint(Ext), CostKind, Ext);
4756               continue;
4757             }
4758           }
4759           CommonCost -=
4760               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
4761         }
4762       } else {
4763         AdjustExtractsCost(CommonCost);
4764       }
4765       return CommonCost;
4766     }
4767     case Instruction::InsertElement: {
4768       assert(E->ReuseShuffleIndices.empty() &&
4769              "Unique insertelements only are expected.");
4770       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
4771 
4772       unsigned const NumElts = SrcVecTy->getNumElements();
4773       unsigned const NumScalars = VL.size();
4774       APInt DemandedElts = APInt::getZero(NumElts);
4775       // TODO: Add support for Instruction::InsertValue.
4776       SmallVector<int> Mask;
4777       if (!E->ReorderIndices.empty()) {
4778         inversePermutation(E->ReorderIndices, Mask);
4779         Mask.append(NumElts - NumScalars, UndefMaskElem);
4780       } else {
4781         Mask.assign(NumElts, UndefMaskElem);
4782         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
4783       }
4784       unsigned Offset = *getInsertIndex(VL0, 0);
4785       bool IsIdentity = true;
4786       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
4787       Mask.swap(PrevMask);
4788       for (unsigned I = 0; I < NumScalars; ++I) {
4789         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
4790         if (!InsertIdx || *InsertIdx == UndefMaskElem)
4791           continue;
4792         DemandedElts.setBit(*InsertIdx);
4793         IsIdentity &= *InsertIdx - Offset == I;
4794         Mask[*InsertIdx - Offset] = I;
4795       }
4796       assert(Offset < NumElts && "Failed to find vector index offset");
4797 
4798       InstructionCost Cost = 0;
4799       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
4800                                             /*Insert*/ true, /*Extract*/ false);
4801 
4802       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
4803         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
4804         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
4805         Cost += TTI->getShuffleCost(
4806             TargetTransformInfo::SK_PermuteSingleSrc,
4807             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
4808       } else if (!IsIdentity) {
4809         auto *FirstInsert =
4810             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
4811               return !is_contained(E->Scalars,
4812                                    cast<Instruction>(V)->getOperand(0));
4813             }));
4814         if (isUndefVector(FirstInsert->getOperand(0))) {
4815           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
4816         } else {
4817           SmallVector<int> InsertMask(NumElts);
4818           std::iota(InsertMask.begin(), InsertMask.end(), 0);
4819           for (unsigned I = 0; I < NumElts; I++) {
4820             if (Mask[I] != UndefMaskElem)
4821               InsertMask[Offset + I] = NumElts + I;
4822           }
4823           Cost +=
4824               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
4825         }
4826       }
4827 
4828       return Cost;
4829     }
4830     case Instruction::ZExt:
4831     case Instruction::SExt:
4832     case Instruction::FPToUI:
4833     case Instruction::FPToSI:
4834     case Instruction::FPExt:
4835     case Instruction::PtrToInt:
4836     case Instruction::IntToPtr:
4837     case Instruction::SIToFP:
4838     case Instruction::UIToFP:
4839     case Instruction::Trunc:
4840     case Instruction::FPTrunc:
4841     case Instruction::BitCast: {
4842       Type *SrcTy = VL0->getOperand(0)->getType();
4843       InstructionCost ScalarEltCost =
4844           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
4845                                 TTI::getCastContextHint(VL0), CostKind, VL0);
4846       if (NeedToShuffleReuses) {
4847         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
4848       }
4849 
4850       // Calculate the cost of this instruction.
4851       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
4852 
4853       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
4854       InstructionCost VecCost = 0;
4855       // Check if the values are candidates to demote.
4856       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
4857         VecCost = CommonCost + TTI->getCastInstrCost(
4858                                    E->getOpcode(), VecTy, SrcVecTy,
4859                                    TTI::getCastContextHint(VL0), CostKind, VL0);
4860       }
4861       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4862       return VecCost - ScalarCost;
4863     }
4864     case Instruction::FCmp:
4865     case Instruction::ICmp:
4866     case Instruction::Select: {
4867       // Calculate the cost of this instruction.
4868       InstructionCost ScalarEltCost =
4869           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
4870                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
4871       if (NeedToShuffleReuses) {
4872         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
4873       }
4874       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
4875       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4876 
4877       // Check if all entries in VL are either compares or selects with compares
4878       // as condition that have the same predicates.
4879       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
4880       bool First = true;
4881       for (auto *V : VL) {
4882         CmpInst::Predicate CurrentPred;
4883         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
4884         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
4885              !match(V, MatchCmp)) ||
4886             (!First && VecPred != CurrentPred)) {
4887           VecPred = CmpInst::BAD_ICMP_PREDICATE;
4888           break;
4889         }
4890         First = false;
4891         VecPred = CurrentPred;
4892       }
4893 
4894       InstructionCost VecCost = TTI->getCmpSelInstrCost(
4895           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
4896       // Check if it is possible and profitable to use min/max for selects in
4897       // VL.
4898       //
4899       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
4900       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
4901         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
4902                                           {VecTy, VecTy});
4903         InstructionCost IntrinsicCost =
4904             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4905         // If the selects are the only uses of the compares, they will be dead
4906         // and we can adjust the cost by removing their cost.
4907         if (IntrinsicAndUse.second)
4908           IntrinsicCost -=
4909               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
4910                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
4911         VecCost = std::min(VecCost, IntrinsicCost);
4912       }
4913       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4914       return CommonCost + VecCost - ScalarCost;
4915     }
4916     case Instruction::FNeg:
4917     case Instruction::Add:
4918     case Instruction::FAdd:
4919     case Instruction::Sub:
4920     case Instruction::FSub:
4921     case Instruction::Mul:
4922     case Instruction::FMul:
4923     case Instruction::UDiv:
4924     case Instruction::SDiv:
4925     case Instruction::FDiv:
4926     case Instruction::URem:
4927     case Instruction::SRem:
4928     case Instruction::FRem:
4929     case Instruction::Shl:
4930     case Instruction::LShr:
4931     case Instruction::AShr:
4932     case Instruction::And:
4933     case Instruction::Or:
4934     case Instruction::Xor: {
4935       // Certain instructions can be cheaper to vectorize if they have a
4936       // constant second vector operand.
4937       TargetTransformInfo::OperandValueKind Op1VK =
4938           TargetTransformInfo::OK_AnyValue;
4939       TargetTransformInfo::OperandValueKind Op2VK =
4940           TargetTransformInfo::OK_UniformConstantValue;
4941       TargetTransformInfo::OperandValueProperties Op1VP =
4942           TargetTransformInfo::OP_None;
4943       TargetTransformInfo::OperandValueProperties Op2VP =
4944           TargetTransformInfo::OP_PowerOf2;
4945 
4946       // If all operands are exactly the same ConstantInt then set the
4947       // operand kind to OK_UniformConstantValue.
4948       // If instead not all operands are constants, then set the operand kind
4949       // to OK_AnyValue. If all operands are constants but not the same,
4950       // then set the operand kind to OK_NonUniformConstantValue.
4951       ConstantInt *CInt0 = nullptr;
4952       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
4953         const Instruction *I = cast<Instruction>(VL[i]);
4954         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
4955         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
4956         if (!CInt) {
4957           Op2VK = TargetTransformInfo::OK_AnyValue;
4958           Op2VP = TargetTransformInfo::OP_None;
4959           break;
4960         }
4961         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
4962             !CInt->getValue().isPowerOf2())
4963           Op2VP = TargetTransformInfo::OP_None;
4964         if (i == 0) {
4965           CInt0 = CInt;
4966           continue;
4967         }
4968         if (CInt0 != CInt)
4969           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4970       }
4971 
4972       SmallVector<const Value *, 4> Operands(VL0->operand_values());
4973       InstructionCost ScalarEltCost =
4974           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
4975                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4976       if (NeedToShuffleReuses) {
4977         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
4978       }
4979       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4980       InstructionCost VecCost =
4981           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
4982                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4983       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4984       return CommonCost + VecCost - ScalarCost;
4985     }
4986     case Instruction::GetElementPtr: {
4987       TargetTransformInfo::OperandValueKind Op1VK =
4988           TargetTransformInfo::OK_AnyValue;
4989       TargetTransformInfo::OperandValueKind Op2VK =
4990           TargetTransformInfo::OK_UniformConstantValue;
4991 
4992       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
4993           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
4994       if (NeedToShuffleReuses) {
4995         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
4996       }
4997       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4998       InstructionCost VecCost = TTI->getArithmeticInstrCost(
4999           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5000       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5001       return CommonCost + VecCost - ScalarCost;
5002     }
5003     case Instruction::Load: {
5004       // Cost of wide load - cost of scalar loads.
5005       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5006       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5007           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5008       if (NeedToShuffleReuses) {
5009         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5010       }
5011       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5012       InstructionCost VecLdCost;
5013       if (E->State == TreeEntry::Vectorize) {
5014         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5015                                          CostKind, VL0);
5016       } else {
5017         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5018         Align CommonAlignment = Alignment;
5019         for (Value *V : VL)
5020           CommonAlignment =
5021               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5022         VecLdCost = TTI->getGatherScatterOpCost(
5023             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5024             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5025       }
5026       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5027       return CommonCost + VecLdCost - ScalarLdCost;
5028     }
5029     case Instruction::Store: {
5030       // We know that we can merge the stores. Calculate the cost.
5031       bool IsReorder = !E->ReorderIndices.empty();
5032       auto *SI =
5033           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5034       Align Alignment = SI->getAlign();
5035       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5036           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5037       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5038       InstructionCost VecStCost = TTI->getMemoryOpCost(
5039           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5040       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5041       return CommonCost + VecStCost - ScalarStCost;
5042     }
5043     case Instruction::Call: {
5044       CallInst *CI = cast<CallInst>(VL0);
5045       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5046 
5047       // Calculate the cost of the scalar and vector calls.
5048       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5049       InstructionCost ScalarEltCost =
5050           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5051       if (NeedToShuffleReuses) {
5052         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5053       }
5054       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5055 
5056       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5057       InstructionCost VecCallCost =
5058           std::min(VecCallCosts.first, VecCallCosts.second);
5059 
5060       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5061                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5062                         << " for " << *CI << "\n");
5063 
5064       return CommonCost + VecCallCost - ScalarCallCost;
5065     }
5066     case Instruction::ShuffleVector: {
5067       assert(E->isAltShuffle() &&
5068              ((Instruction::isBinaryOp(E->getOpcode()) &&
5069                Instruction::isBinaryOp(E->getAltOpcode())) ||
5070               (Instruction::isCast(E->getOpcode()) &&
5071                Instruction::isCast(E->getAltOpcode()))) &&
5072              "Invalid Shuffle Vector Operand");
5073       InstructionCost ScalarCost = 0;
5074       if (NeedToShuffleReuses) {
5075         for (unsigned Idx : E->ReuseShuffleIndices) {
5076           Instruction *I = cast<Instruction>(VL[Idx]);
5077           CommonCost -= TTI->getInstructionCost(I, CostKind);
5078         }
5079         for (Value *V : VL) {
5080           Instruction *I = cast<Instruction>(V);
5081           CommonCost += TTI->getInstructionCost(I, CostKind);
5082         }
5083       }
5084       for (Value *V : VL) {
5085         Instruction *I = cast<Instruction>(V);
5086         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5087         ScalarCost += TTI->getInstructionCost(I, CostKind);
5088       }
5089       // VecCost is equal to sum of the cost of creating 2 vectors
5090       // and the cost of creating shuffle.
5091       InstructionCost VecCost = 0;
5092       // Try to find the previous shuffle node with the same operands and same
5093       // main/alternate ops.
5094       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5095         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5096           if (TE.get() == E)
5097             break;
5098           if (TE->isAltShuffle() &&
5099               ((TE->getOpcode() == E->getOpcode() &&
5100                 TE->getAltOpcode() == E->getAltOpcode()) ||
5101                (TE->getOpcode() == E->getAltOpcode() &&
5102                 TE->getAltOpcode() == E->getOpcode())) &&
5103               TE->hasEqualOperands(*E))
5104             return true;
5105         }
5106         return false;
5107       };
5108       if (TryFindNodeWithEqualOperands()) {
5109         LLVM_DEBUG({
5110           dbgs() << "SLP: diamond match for alternate node found.\n";
5111           E->dump();
5112         });
5113         // No need to add new vector costs here since we're going to reuse
5114         // same main/alternate vector ops, just do different shuffling.
5115       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5116         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5117         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5118                                                CostKind);
5119       } else {
5120         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5121         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5122         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5123         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5124         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5125                                         TTI::CastContextHint::None, CostKind);
5126         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5127                                          TTI::CastContextHint::None, CostKind);
5128       }
5129 
5130       SmallVector<int> Mask;
5131       buildSuffleEntryMask(
5132           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5133           [E](Instruction *I) {
5134             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5135             return I->getOpcode() == E->getAltOpcode();
5136           },
5137           Mask);
5138       CommonCost =
5139           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5140       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5141       return CommonCost + VecCost - ScalarCost;
5142     }
5143     default:
5144       llvm_unreachable("Unknown instruction");
5145   }
5146 }
5147 
5148 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5149   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5150                     << VectorizableTree.size() << " is fully vectorizable .\n");
5151 
5152   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5153     SmallVector<int> Mask;
5154     return TE->State == TreeEntry::NeedToGather &&
5155            !any_of(TE->Scalars,
5156                    [this](Value *V) { return EphValues.contains(V); }) &&
5157            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5158             TE->Scalars.size() < Limit ||
5159             ((TE->getOpcode() == Instruction::ExtractElement ||
5160               all_of(TE->Scalars,
5161                      [](Value *V) {
5162                        return isa<ExtractElementInst, UndefValue>(V);
5163                      })) &&
5164              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5165             (TE->State == TreeEntry::NeedToGather &&
5166              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5167   };
5168 
5169   // We only handle trees of heights 1 and 2.
5170   if (VectorizableTree.size() == 1 &&
5171       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5172        (ForReduction &&
5173         AreVectorizableGathers(VectorizableTree[0].get(),
5174                                VectorizableTree[0]->Scalars.size()) &&
5175         VectorizableTree[0]->getVectorFactor() > 2)))
5176     return true;
5177 
5178   if (VectorizableTree.size() != 2)
5179     return false;
5180 
5181   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5182   // with the second gather nodes if they have less scalar operands rather than
5183   // the initial tree element (may be profitable to shuffle the second gather)
5184   // or they are extractelements, which form shuffle.
5185   SmallVector<int> Mask;
5186   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5187       AreVectorizableGathers(VectorizableTree[1].get(),
5188                              VectorizableTree[0]->Scalars.size()))
5189     return true;
5190 
5191   // Gathering cost would be too much for tiny trees.
5192   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5193       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5194        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5195     return false;
5196 
5197   return true;
5198 }
5199 
5200 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5201                                        TargetTransformInfo *TTI,
5202                                        bool MustMatchOrInst) {
5203   // Look past the root to find a source value. Arbitrarily follow the
5204   // path through operand 0 of any 'or'. Also, peek through optional
5205   // shift-left-by-multiple-of-8-bits.
5206   Value *ZextLoad = Root;
5207   const APInt *ShAmtC;
5208   bool FoundOr = false;
5209   while (!isa<ConstantExpr>(ZextLoad) &&
5210          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5211           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5212            ShAmtC->urem(8) == 0))) {
5213     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5214     ZextLoad = BinOp->getOperand(0);
5215     if (BinOp->getOpcode() == Instruction::Or)
5216       FoundOr = true;
5217   }
5218   // Check if the input is an extended load of the required or/shift expression.
5219   Value *LoadPtr;
5220   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5221       !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
5222     return false;
5223 
5224   // Require that the total load bit width is a legal integer type.
5225   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5226   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5227   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
5228   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5229   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5230     return false;
5231 
5232   // Everything matched - assume that we can fold the whole sequence using
5233   // load combining.
5234   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5235              << *(cast<Instruction>(Root)) << "\n");
5236 
5237   return true;
5238 }
5239 
5240 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5241   if (RdxKind != RecurKind::Or)
5242     return false;
5243 
5244   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5245   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5246   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5247                                     /* MatchOr */ false);
5248 }
5249 
5250 bool BoUpSLP::isLoadCombineCandidate() const {
5251   // Peek through a final sequence of stores and check if all operations are
5252   // likely to be load-combined.
5253   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5254   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5255     Value *X;
5256     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5257         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5258       return false;
5259   }
5260   return true;
5261 }
5262 
5263 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5264   // No need to vectorize inserts of gathered values.
5265   if (VectorizableTree.size() == 2 &&
5266       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5267       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5268     return true;
5269 
5270   // We can vectorize the tree if its size is greater than or equal to the
5271   // minimum size specified by the MinTreeSize command line option.
5272   if (VectorizableTree.size() >= MinTreeSize)
5273     return false;
5274 
5275   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5276   // can vectorize it if we can prove it fully vectorizable.
5277   if (isFullyVectorizableTinyTree(ForReduction))
5278     return false;
5279 
5280   assert(VectorizableTree.empty()
5281              ? ExternalUses.empty()
5282              : true && "We shouldn't have any external users");
5283 
5284   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5285   // vectorizable.
5286   return true;
5287 }
5288 
5289 InstructionCost BoUpSLP::getSpillCost() const {
5290   // Walk from the bottom of the tree to the top, tracking which values are
5291   // live. When we see a call instruction that is not part of our tree,
5292   // query TTI to see if there is a cost to keeping values live over it
5293   // (for example, if spills and fills are required).
5294   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5295   InstructionCost Cost = 0;
5296 
5297   SmallPtrSet<Instruction*, 4> LiveValues;
5298   Instruction *PrevInst = nullptr;
5299 
5300   // The entries in VectorizableTree are not necessarily ordered by their
5301   // position in basic blocks. Collect them and order them by dominance so later
5302   // instructions are guaranteed to be visited first. For instructions in
5303   // different basic blocks, we only scan to the beginning of the block, so
5304   // their order does not matter, as long as all instructions in a basic block
5305   // are grouped together. Using dominance ensures a deterministic order.
5306   SmallVector<Instruction *, 16> OrderedScalars;
5307   for (const auto &TEPtr : VectorizableTree) {
5308     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5309     if (!Inst)
5310       continue;
5311     OrderedScalars.push_back(Inst);
5312   }
5313   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5314     auto *NodeA = DT->getNode(A->getParent());
5315     auto *NodeB = DT->getNode(B->getParent());
5316     assert(NodeA && "Should only process reachable instructions");
5317     assert(NodeB && "Should only process reachable instructions");
5318     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5319            "Different nodes should have different DFS numbers");
5320     if (NodeA != NodeB)
5321       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5322     return B->comesBefore(A);
5323   });
5324 
5325   for (Instruction *Inst : OrderedScalars) {
5326     if (!PrevInst) {
5327       PrevInst = Inst;
5328       continue;
5329     }
5330 
5331     // Update LiveValues.
5332     LiveValues.erase(PrevInst);
5333     for (auto &J : PrevInst->operands()) {
5334       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5335         LiveValues.insert(cast<Instruction>(&*J));
5336     }
5337 
5338     LLVM_DEBUG({
5339       dbgs() << "SLP: #LV: " << LiveValues.size();
5340       for (auto *X : LiveValues)
5341         dbgs() << " " << X->getName();
5342       dbgs() << ", Looking at ";
5343       Inst->dump();
5344     });
5345 
5346     // Now find the sequence of instructions between PrevInst and Inst.
5347     unsigned NumCalls = 0;
5348     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5349                                  PrevInstIt =
5350                                      PrevInst->getIterator().getReverse();
5351     while (InstIt != PrevInstIt) {
5352       if (PrevInstIt == PrevInst->getParent()->rend()) {
5353         PrevInstIt = Inst->getParent()->rbegin();
5354         continue;
5355       }
5356 
5357       // Debug information does not impact spill cost.
5358       if ((isa<CallInst>(&*PrevInstIt) &&
5359            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5360           &*PrevInstIt != PrevInst)
5361         NumCalls++;
5362 
5363       ++PrevInstIt;
5364     }
5365 
5366     if (NumCalls) {
5367       SmallVector<Type*, 4> V;
5368       for (auto *II : LiveValues) {
5369         auto *ScalarTy = II->getType();
5370         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5371           ScalarTy = VectorTy->getElementType();
5372         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5373       }
5374       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5375     }
5376 
5377     PrevInst = Inst;
5378   }
5379 
5380   return Cost;
5381 }
5382 
5383 /// Check if two insertelement instructions are from the same buildvector.
5384 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5385                                             InsertElementInst *V) {
5386   // Instructions must be from the same basic blocks.
5387   if (VU->getParent() != V->getParent())
5388     return false;
5389   // Checks if 2 insertelements are from the same buildvector.
5390   if (VU->getType() != V->getType())
5391     return false;
5392   // Multiple used inserts are separate nodes.
5393   if (!VU->hasOneUse() && !V->hasOneUse())
5394     return false;
5395   auto *IE1 = VU;
5396   auto *IE2 = V;
5397   // Go through the vector operand of insertelement instructions trying to find
5398   // either VU as the original vector for IE2 or V as the original vector for
5399   // IE1.
5400   do {
5401     if (IE2 == VU || IE1 == V)
5402       return true;
5403     if (IE1) {
5404       if (IE1 != VU && !IE1->hasOneUse())
5405         IE1 = nullptr;
5406       else
5407         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5408     }
5409     if (IE2) {
5410       if (IE2 != V && !IE2->hasOneUse())
5411         IE2 = nullptr;
5412       else
5413         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5414     }
5415   } while (IE1 || IE2);
5416   return false;
5417 }
5418 
5419 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5420   InstructionCost Cost = 0;
5421   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5422                     << VectorizableTree.size() << ".\n");
5423 
5424   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5425 
5426   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5427     TreeEntry &TE = *VectorizableTree[I].get();
5428 
5429     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5430     Cost += C;
5431     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5432                       << " for bundle that starts with " << *TE.Scalars[0]
5433                       << ".\n"
5434                       << "SLP: Current total cost = " << Cost << "\n");
5435   }
5436 
5437   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5438   InstructionCost ExtractCost = 0;
5439   SmallVector<unsigned> VF;
5440   SmallVector<SmallVector<int>> ShuffleMask;
5441   SmallVector<Value *> FirstUsers;
5442   SmallVector<APInt> DemandedElts;
5443   for (ExternalUser &EU : ExternalUses) {
5444     // We only add extract cost once for the same scalar.
5445     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5446         !ExtractCostCalculated.insert(EU.Scalar).second)
5447       continue;
5448 
5449     // Uses by ephemeral values are free (because the ephemeral value will be
5450     // removed prior to code generation, and so the extraction will be
5451     // removed as well).
5452     if (EphValues.count(EU.User))
5453       continue;
5454 
5455     // No extract cost for vector "scalar"
5456     if (isa<FixedVectorType>(EU.Scalar->getType()))
5457       continue;
5458 
5459     // Already counted the cost for external uses when tried to adjust the cost
5460     // for extractelements, no need to add it again.
5461     if (isa<ExtractElementInst>(EU.Scalar))
5462       continue;
5463 
5464     // If found user is an insertelement, do not calculate extract cost but try
5465     // to detect it as a final shuffled/identity match.
5466     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5467       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5468         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5469         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5470           continue;
5471         auto *It = find_if(FirstUsers, [VU](Value *V) {
5472           return areTwoInsertFromSameBuildVector(VU,
5473                                                  cast<InsertElementInst>(V));
5474         });
5475         int VecId = -1;
5476         if (It == FirstUsers.end()) {
5477           VF.push_back(FTy->getNumElements());
5478           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5479           // Find the insertvector, vectorized in tree, if any.
5480           Value *Base = VU;
5481           while (isa<InsertElementInst>(Base)) {
5482             // Build the mask for the vectorized insertelement instructions.
5483             if (const TreeEntry *E = getTreeEntry(Base)) {
5484               VU = cast<InsertElementInst>(Base);
5485               do {
5486                 int Idx = E->findLaneForValue(Base);
5487                 ShuffleMask.back()[Idx] = Idx;
5488                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5489               } while (E == getTreeEntry(Base));
5490               break;
5491             }
5492             Base = cast<InsertElementInst>(Base)->getOperand(0);
5493           }
5494           FirstUsers.push_back(VU);
5495           DemandedElts.push_back(APInt::getZero(VF.back()));
5496           VecId = FirstUsers.size() - 1;
5497         } else {
5498           VecId = std::distance(FirstUsers.begin(), It);
5499         }
5500         int Idx = *InsertIdx;
5501         ShuffleMask[VecId][Idx] = EU.Lane;
5502         DemandedElts[VecId].setBit(Idx);
5503         continue;
5504       }
5505     }
5506 
5507     // If we plan to rewrite the tree in a smaller type, we will need to sign
5508     // extend the extracted value back to the original type. Here, we account
5509     // for the extract and the added cost of the sign extend if needed.
5510     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5511     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5512     if (MinBWs.count(ScalarRoot)) {
5513       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5514       auto Extend =
5515           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5516       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5517       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5518                                                    VecTy, EU.Lane);
5519     } else {
5520       ExtractCost +=
5521           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5522     }
5523   }
5524 
5525   InstructionCost SpillCost = getSpillCost();
5526   Cost += SpillCost + ExtractCost;
5527   if (FirstUsers.size() == 1) {
5528     int Limit = ShuffleMask.front().size() * 2;
5529     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5530         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5531       InstructionCost C = TTI->getShuffleCost(
5532           TTI::SK_PermuteSingleSrc,
5533           cast<FixedVectorType>(FirstUsers.front()->getType()),
5534           ShuffleMask.front());
5535       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5536                         << " for final shuffle of insertelement external users "
5537                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5538                         << "SLP: Current total cost = " << Cost << "\n");
5539       Cost += C;
5540     }
5541     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5542         cast<FixedVectorType>(FirstUsers.front()->getType()),
5543         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5544     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5545                       << " for insertelements gather.\n"
5546                       << "SLP: Current total cost = " << Cost << "\n");
5547     Cost -= InsertCost;
5548   } else if (FirstUsers.size() >= 2) {
5549     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5550     // Combined masks of the first 2 vectors.
5551     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5552     copy(ShuffleMask.front(), CombinedMask.begin());
5553     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5554     auto *VecTy = FixedVectorType::get(
5555         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5556         MaxVF);
5557     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5558       if (ShuffleMask[1][I] != UndefMaskElem) {
5559         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5560         CombinedDemandedElts.setBit(I);
5561       }
5562     }
5563     InstructionCost C =
5564         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5565     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5566                       << " for final shuffle of vector node and external "
5567                          "insertelement users "
5568                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5569                       << "SLP: Current total cost = " << Cost << "\n");
5570     Cost += C;
5571     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5572         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5573     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5574                       << " for insertelements gather.\n"
5575                       << "SLP: Current total cost = " << Cost << "\n");
5576     Cost -= InsertCost;
5577     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5578       // Other elements - permutation of 2 vectors (the initial one and the
5579       // next Ith incoming vector).
5580       unsigned VF = ShuffleMask[I].size();
5581       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5582         int Mask = ShuffleMask[I][Idx];
5583         if (Mask != UndefMaskElem)
5584           CombinedMask[Idx] = MaxVF + Mask;
5585         else if (CombinedMask[Idx] != UndefMaskElem)
5586           CombinedMask[Idx] = Idx;
5587       }
5588       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5589         if (CombinedMask[Idx] != UndefMaskElem)
5590           CombinedMask[Idx] = Idx;
5591       InstructionCost C =
5592           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5593       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5594                         << " for final shuffle of vector node and external "
5595                            "insertelement users "
5596                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5597                         << "SLP: Current total cost = " << Cost << "\n");
5598       Cost += C;
5599       InstructionCost InsertCost = TTI->getScalarizationOverhead(
5600           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5601           /*Insert*/ true, /*Extract*/ false);
5602       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5603                         << " for insertelements gather.\n"
5604                         << "SLP: Current total cost = " << Cost << "\n");
5605       Cost -= InsertCost;
5606     }
5607   }
5608 
5609 #ifndef NDEBUG
5610   SmallString<256> Str;
5611   {
5612     raw_svector_ostream OS(Str);
5613     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5614        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5615        << "SLP: Total Cost = " << Cost << ".\n";
5616   }
5617   LLVM_DEBUG(dbgs() << Str);
5618   if (ViewSLPTree)
5619     ViewGraph(this, "SLP" + F->getName(), false, Str);
5620 #endif
5621 
5622   return Cost;
5623 }
5624 
5625 Optional<TargetTransformInfo::ShuffleKind>
5626 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5627                                SmallVectorImpl<const TreeEntry *> &Entries) {
5628   // TODO: currently checking only for Scalars in the tree entry, need to count
5629   // reused elements too for better cost estimation.
5630   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5631   Entries.clear();
5632   // Build a lists of values to tree entries.
5633   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5634   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5635     if (EntryPtr.get() == TE)
5636       break;
5637     if (EntryPtr->State != TreeEntry::NeedToGather)
5638       continue;
5639     for (Value *V : EntryPtr->Scalars)
5640       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5641   }
5642   // Find all tree entries used by the gathered values. If no common entries
5643   // found - not a shuffle.
5644   // Here we build a set of tree nodes for each gathered value and trying to
5645   // find the intersection between these sets. If we have at least one common
5646   // tree node for each gathered value - we have just a permutation of the
5647   // single vector. If we have 2 different sets, we're in situation where we
5648   // have a permutation of 2 input vectors.
5649   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5650   DenseMap<Value *, int> UsedValuesEntry;
5651   for (Value *V : TE->Scalars) {
5652     if (isa<UndefValue>(V))
5653       continue;
5654     // Build a list of tree entries where V is used.
5655     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5656     auto It = ValueToTEs.find(V);
5657     if (It != ValueToTEs.end())
5658       VToTEs = It->second;
5659     if (const TreeEntry *VTE = getTreeEntry(V))
5660       VToTEs.insert(VTE);
5661     if (VToTEs.empty())
5662       return None;
5663     if (UsedTEs.empty()) {
5664       // The first iteration, just insert the list of nodes to vector.
5665       UsedTEs.push_back(VToTEs);
5666     } else {
5667       // Need to check if there are any previously used tree nodes which use V.
5668       // If there are no such nodes, consider that we have another one input
5669       // vector.
5670       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
5671       unsigned Idx = 0;
5672       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
5673         // Do we have a non-empty intersection of previously listed tree entries
5674         // and tree entries using current V?
5675         set_intersect(VToTEs, Set);
5676         if (!VToTEs.empty()) {
5677           // Yes, write the new subset and continue analysis for the next
5678           // scalar.
5679           Set.swap(VToTEs);
5680           break;
5681         }
5682         VToTEs = SavedVToTEs;
5683         ++Idx;
5684       }
5685       // No non-empty intersection found - need to add a second set of possible
5686       // source vectors.
5687       if (Idx == UsedTEs.size()) {
5688         // If the number of input vectors is greater than 2 - not a permutation,
5689         // fallback to the regular gather.
5690         if (UsedTEs.size() == 2)
5691           return None;
5692         UsedTEs.push_back(SavedVToTEs);
5693         Idx = UsedTEs.size() - 1;
5694       }
5695       UsedValuesEntry.try_emplace(V, Idx);
5696     }
5697   }
5698 
5699   unsigned VF = 0;
5700   if (UsedTEs.size() == 1) {
5701     // Try to find the perfect match in another gather node at first.
5702     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
5703       return EntryPtr->isSame(TE->Scalars);
5704     });
5705     if (It != UsedTEs.front().end()) {
5706       Entries.push_back(*It);
5707       std::iota(Mask.begin(), Mask.end(), 0);
5708       return TargetTransformInfo::SK_PermuteSingleSrc;
5709     }
5710     // No perfect match, just shuffle, so choose the first tree node.
5711     Entries.push_back(*UsedTEs.front().begin());
5712   } else {
5713     // Try to find nodes with the same vector factor.
5714     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
5715     DenseMap<int, const TreeEntry *> VFToTE;
5716     for (const TreeEntry *TE : UsedTEs.front())
5717       VFToTE.try_emplace(TE->getVectorFactor(), TE);
5718     for (const TreeEntry *TE : UsedTEs.back()) {
5719       auto It = VFToTE.find(TE->getVectorFactor());
5720       if (It != VFToTE.end()) {
5721         VF = It->first;
5722         Entries.push_back(It->second);
5723         Entries.push_back(TE);
5724         break;
5725       }
5726     }
5727     // No 2 source vectors with the same vector factor - give up and do regular
5728     // gather.
5729     if (Entries.empty())
5730       return None;
5731   }
5732 
5733   // Build a shuffle mask for better cost estimation and vector emission.
5734   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
5735     Value *V = TE->Scalars[I];
5736     if (isa<UndefValue>(V))
5737       continue;
5738     unsigned Idx = UsedValuesEntry.lookup(V);
5739     const TreeEntry *VTE = Entries[Idx];
5740     int FoundLane = VTE->findLaneForValue(V);
5741     Mask[I] = Idx * VF + FoundLane;
5742     // Extra check required by isSingleSourceMaskImpl function (called by
5743     // ShuffleVectorInst::isSingleSourceMask).
5744     if (Mask[I] >= 2 * E)
5745       return None;
5746   }
5747   switch (Entries.size()) {
5748   case 1:
5749     return TargetTransformInfo::SK_PermuteSingleSrc;
5750   case 2:
5751     return TargetTransformInfo::SK_PermuteTwoSrc;
5752   default:
5753     break;
5754   }
5755   return None;
5756 }
5757 
5758 InstructionCost
5759 BoUpSLP::getGatherCost(FixedVectorType *Ty,
5760                        const DenseSet<unsigned> &ShuffledIndices,
5761                        bool NeedToShuffle) const {
5762   unsigned NumElts = Ty->getNumElements();
5763   APInt DemandedElts = APInt::getZero(NumElts);
5764   for (unsigned I = 0; I < NumElts; ++I)
5765     if (!ShuffledIndices.count(I))
5766       DemandedElts.setBit(I);
5767   InstructionCost Cost =
5768       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
5769                                     /*Extract*/ false);
5770   if (NeedToShuffle)
5771     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
5772   return Cost;
5773 }
5774 
5775 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
5776   // Find the type of the operands in VL.
5777   Type *ScalarTy = VL[0]->getType();
5778   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5779     ScalarTy = SI->getValueOperand()->getType();
5780   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5781   bool DuplicateNonConst = false;
5782   // Find the cost of inserting/extracting values from the vector.
5783   // Check if the same elements are inserted several times and count them as
5784   // shuffle candidates.
5785   DenseSet<unsigned> ShuffledElements;
5786   DenseSet<Value *> UniqueElements;
5787   // Iterate in reverse order to consider insert elements with the high cost.
5788   for (unsigned I = VL.size(); I > 0; --I) {
5789     unsigned Idx = I - 1;
5790     // No need to shuffle duplicates for constants.
5791     if (isConstant(VL[Idx])) {
5792       ShuffledElements.insert(Idx);
5793       continue;
5794     }
5795     if (!UniqueElements.insert(VL[Idx]).second) {
5796       DuplicateNonConst = true;
5797       ShuffledElements.insert(Idx);
5798     }
5799   }
5800   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
5801 }
5802 
5803 // Perform operand reordering on the instructions in VL and return the reordered
5804 // operands in Left and Right.
5805 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
5806                                              SmallVectorImpl<Value *> &Left,
5807                                              SmallVectorImpl<Value *> &Right,
5808                                              const DataLayout &DL,
5809                                              ScalarEvolution &SE,
5810                                              const BoUpSLP &R) {
5811   if (VL.empty())
5812     return;
5813   VLOperands Ops(VL, DL, SE, R);
5814   // Reorder the operands in place.
5815   Ops.reorder();
5816   Left = Ops.getVL(0);
5817   Right = Ops.getVL(1);
5818 }
5819 
5820 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
5821   // Get the basic block this bundle is in. All instructions in the bundle
5822   // should be in this block.
5823   auto *Front = E->getMainOp();
5824   auto *BB = Front->getParent();
5825   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
5826     auto *I = cast<Instruction>(V);
5827     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
5828   }));
5829 
5830   // The last instruction in the bundle in program order.
5831   Instruction *LastInst = nullptr;
5832 
5833   // Find the last instruction. The common case should be that BB has been
5834   // scheduled, and the last instruction is VL.back(). So we start with
5835   // VL.back() and iterate over schedule data until we reach the end of the
5836   // bundle. The end of the bundle is marked by null ScheduleData.
5837   if (BlocksSchedules.count(BB)) {
5838     auto *Bundle =
5839         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
5840     if (Bundle && Bundle->isPartOfBundle())
5841       for (; Bundle; Bundle = Bundle->NextInBundle)
5842         if (Bundle->OpValue == Bundle->Inst)
5843           LastInst = Bundle->Inst;
5844   }
5845 
5846   // LastInst can still be null at this point if there's either not an entry
5847   // for BB in BlocksSchedules or there's no ScheduleData available for
5848   // VL.back(). This can be the case if buildTree_rec aborts for various
5849   // reasons (e.g., the maximum recursion depth is reached, the maximum region
5850   // size is reached, etc.). ScheduleData is initialized in the scheduling
5851   // "dry-run".
5852   //
5853   // If this happens, we can still find the last instruction by brute force. We
5854   // iterate forwards from Front (inclusive) until we either see all
5855   // instructions in the bundle or reach the end of the block. If Front is the
5856   // last instruction in program order, LastInst will be set to Front, and we
5857   // will visit all the remaining instructions in the block.
5858   //
5859   // One of the reasons we exit early from buildTree_rec is to place an upper
5860   // bound on compile-time. Thus, taking an additional compile-time hit here is
5861   // not ideal. However, this should be exceedingly rare since it requires that
5862   // we both exit early from buildTree_rec and that the bundle be out-of-order
5863   // (causing us to iterate all the way to the end of the block).
5864   if (!LastInst) {
5865     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
5866     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
5867       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
5868         LastInst = &I;
5869       if (Bundle.empty())
5870         break;
5871     }
5872   }
5873   assert(LastInst && "Failed to find last instruction in bundle");
5874 
5875   // Set the insertion point after the last instruction in the bundle. Set the
5876   // debug location to Front.
5877   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
5878   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
5879 }
5880 
5881 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
5882   // List of instructions/lanes from current block and/or the blocks which are
5883   // part of the current loop. These instructions will be inserted at the end to
5884   // make it possible to optimize loops and hoist invariant instructions out of
5885   // the loops body with better chances for success.
5886   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
5887   SmallSet<int, 4> PostponedIndices;
5888   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
5889   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
5890     SmallPtrSet<BasicBlock *, 4> Visited;
5891     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
5892       InsertBB = InsertBB->getSinglePredecessor();
5893     return InsertBB && InsertBB == InstBB;
5894   };
5895   for (int I = 0, E = VL.size(); I < E; ++I) {
5896     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
5897       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
5898            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
5899           PostponedIndices.insert(I).second)
5900         PostponedInsts.emplace_back(Inst, I);
5901   }
5902 
5903   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
5904     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
5905     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
5906     if (!InsElt)
5907       return Vec;
5908     GatherShuffleSeq.insert(InsElt);
5909     CSEBlocks.insert(InsElt->getParent());
5910     // Add to our 'need-to-extract' list.
5911     if (TreeEntry *Entry = getTreeEntry(V)) {
5912       // Find which lane we need to extract.
5913       unsigned FoundLane = Entry->findLaneForValue(V);
5914       ExternalUses.emplace_back(V, InsElt, FoundLane);
5915     }
5916     return Vec;
5917   };
5918   Value *Val0 =
5919       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
5920   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
5921   Value *Vec = PoisonValue::get(VecTy);
5922   SmallVector<int> NonConsts;
5923   // Insert constant values at first.
5924   for (int I = 0, E = VL.size(); I < E; ++I) {
5925     if (PostponedIndices.contains(I))
5926       continue;
5927     if (!isConstant(VL[I])) {
5928       NonConsts.push_back(I);
5929       continue;
5930     }
5931     Vec = CreateInsertElement(Vec, VL[I], I);
5932   }
5933   // Insert non-constant values.
5934   for (int I : NonConsts)
5935     Vec = CreateInsertElement(Vec, VL[I], I);
5936   // Append instructions, which are/may be part of the loop, in the end to make
5937   // it possible to hoist non-loop-based instructions.
5938   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
5939     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
5940 
5941   return Vec;
5942 }
5943 
5944 namespace {
5945 /// Merges shuffle masks and emits final shuffle instruction, if required.
5946 class ShuffleInstructionBuilder {
5947   IRBuilderBase &Builder;
5948   const unsigned VF = 0;
5949   bool IsFinalized = false;
5950   SmallVector<int, 4> Mask;
5951   /// Holds all of the instructions that we gathered.
5952   SetVector<Instruction *> &GatherShuffleSeq;
5953   /// A list of blocks that we are going to CSE.
5954   SetVector<BasicBlock *> &CSEBlocks;
5955 
5956 public:
5957   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
5958                             SetVector<Instruction *> &GatherShuffleSeq,
5959                             SetVector<BasicBlock *> &CSEBlocks)
5960       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
5961         CSEBlocks(CSEBlocks) {}
5962 
5963   /// Adds a mask, inverting it before applying.
5964   void addInversedMask(ArrayRef<unsigned> SubMask) {
5965     if (SubMask.empty())
5966       return;
5967     SmallVector<int, 4> NewMask;
5968     inversePermutation(SubMask, NewMask);
5969     addMask(NewMask);
5970   }
5971 
5972   /// Functions adds masks, merging them into  single one.
5973   void addMask(ArrayRef<unsigned> SubMask) {
5974     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
5975     addMask(NewMask);
5976   }
5977 
5978   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
5979 
5980   Value *finalize(Value *V) {
5981     IsFinalized = true;
5982     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
5983     if (VF == ValueVF && Mask.empty())
5984       return V;
5985     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
5986     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
5987     addMask(NormalizedMask);
5988 
5989     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
5990       return V;
5991     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
5992     if (auto *I = dyn_cast<Instruction>(Vec)) {
5993       GatherShuffleSeq.insert(I);
5994       CSEBlocks.insert(I->getParent());
5995     }
5996     return Vec;
5997   }
5998 
5999   ~ShuffleInstructionBuilder() {
6000     assert((IsFinalized || Mask.empty()) &&
6001            "Shuffle construction must be finalized.");
6002   }
6003 };
6004 } // namespace
6005 
6006 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6007   unsigned VF = VL.size();
6008   InstructionsState S = getSameOpcode(VL);
6009   if (S.getOpcode()) {
6010     if (TreeEntry *E = getTreeEntry(S.OpValue))
6011       if (E->isSame(VL)) {
6012         Value *V = vectorizeTree(E);
6013         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6014           if (!E->ReuseShuffleIndices.empty()) {
6015             // Reshuffle to get only unique values.
6016             // If some of the scalars are duplicated in the vectorization tree
6017             // entry, we do not vectorize them but instead generate a mask for
6018             // the reuses. But if there are several users of the same entry,
6019             // they may have different vectorization factors. This is especially
6020             // important for PHI nodes. In this case, we need to adapt the
6021             // resulting instruction for the user vectorization factor and have
6022             // to reshuffle it again to take only unique elements of the vector.
6023             // Without this code the function incorrectly returns reduced vector
6024             // instruction with the same elements, not with the unique ones.
6025 
6026             // block:
6027             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6028             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6029             // ... (use %2)
6030             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6031             // br %block
6032             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6033             SmallSet<int, 4> UsedIdxs;
6034             int Pos = 0;
6035             int Sz = VL.size();
6036             for (int Idx : E->ReuseShuffleIndices) {
6037               if (Idx != Sz && Idx != UndefMaskElem &&
6038                   UsedIdxs.insert(Idx).second)
6039                 UniqueIdxs[Idx] = Pos;
6040               ++Pos;
6041             }
6042             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6043                                             "less than original vector size.");
6044             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6045             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6046           } else {
6047             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6048                    "Expected vectorization factor less "
6049                    "than original vector size.");
6050             SmallVector<int> UniformMask(VF, 0);
6051             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6052             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6053           }
6054           if (auto *I = dyn_cast<Instruction>(V)) {
6055             GatherShuffleSeq.insert(I);
6056             CSEBlocks.insert(I->getParent());
6057           }
6058         }
6059         return V;
6060       }
6061   }
6062 
6063   // Check that every instruction appears once in this bundle.
6064   SmallVector<int> ReuseShuffleIndicies;
6065   SmallVector<Value *> UniqueValues;
6066   if (VL.size() > 2) {
6067     DenseMap<Value *, unsigned> UniquePositions;
6068     unsigned NumValues =
6069         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6070                                     return !isa<UndefValue>(V);
6071                                   }).base());
6072     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6073     int UniqueVals = 0;
6074     for (Value *V : VL.drop_back(VL.size() - VF)) {
6075       if (isa<UndefValue>(V)) {
6076         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6077         continue;
6078       }
6079       if (isConstant(V)) {
6080         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6081         UniqueValues.emplace_back(V);
6082         continue;
6083       }
6084       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6085       ReuseShuffleIndicies.emplace_back(Res.first->second);
6086       if (Res.second) {
6087         UniqueValues.emplace_back(V);
6088         ++UniqueVals;
6089       }
6090     }
6091     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6092       // Emit pure splat vector.
6093       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6094                                   UndefMaskElem);
6095     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6096       ReuseShuffleIndicies.clear();
6097       UniqueValues.clear();
6098       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6099     }
6100     UniqueValues.append(VF - UniqueValues.size(),
6101                         PoisonValue::get(VL[0]->getType()));
6102     VL = UniqueValues;
6103   }
6104 
6105   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6106                                            CSEBlocks);
6107   Value *Vec = gather(VL);
6108   if (!ReuseShuffleIndicies.empty()) {
6109     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6110     Vec = ShuffleBuilder.finalize(Vec);
6111   }
6112   return Vec;
6113 }
6114 
6115 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6116   IRBuilder<>::InsertPointGuard Guard(Builder);
6117 
6118   if (E->VectorizedValue) {
6119     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6120     return E->VectorizedValue;
6121   }
6122 
6123   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6124   unsigned VF = E->getVectorFactor();
6125   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6126                                            CSEBlocks);
6127   if (E->State == TreeEntry::NeedToGather) {
6128     if (E->getMainOp())
6129       setInsertPointAfterBundle(E);
6130     Value *Vec;
6131     SmallVector<int> Mask;
6132     SmallVector<const TreeEntry *> Entries;
6133     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6134         isGatherShuffledEntry(E, Mask, Entries);
6135     if (Shuffle.hasValue()) {
6136       assert((Entries.size() == 1 || Entries.size() == 2) &&
6137              "Expected shuffle of 1 or 2 entries.");
6138       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6139                                         Entries.back()->VectorizedValue, Mask);
6140       if (auto *I = dyn_cast<Instruction>(Vec)) {
6141         GatherShuffleSeq.insert(I);
6142         CSEBlocks.insert(I->getParent());
6143       }
6144     } else {
6145       Vec = gather(E->Scalars);
6146     }
6147     if (NeedToShuffleReuses) {
6148       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6149       Vec = ShuffleBuilder.finalize(Vec);
6150     }
6151     E->VectorizedValue = Vec;
6152     return Vec;
6153   }
6154 
6155   assert((E->State == TreeEntry::Vectorize ||
6156           E->State == TreeEntry::ScatterVectorize) &&
6157          "Unhandled state");
6158   unsigned ShuffleOrOp =
6159       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6160   Instruction *VL0 = E->getMainOp();
6161   Type *ScalarTy = VL0->getType();
6162   if (auto *Store = dyn_cast<StoreInst>(VL0))
6163     ScalarTy = Store->getValueOperand()->getType();
6164   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6165     ScalarTy = IE->getOperand(1)->getType();
6166   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6167   switch (ShuffleOrOp) {
6168     case Instruction::PHI: {
6169       assert(
6170           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6171           "PHI reordering is free.");
6172       auto *PH = cast<PHINode>(VL0);
6173       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6174       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6175       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6176       Value *V = NewPhi;
6177       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6178       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6179       V = ShuffleBuilder.finalize(V);
6180 
6181       E->VectorizedValue = V;
6182 
6183       // PHINodes may have multiple entries from the same block. We want to
6184       // visit every block once.
6185       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6186 
6187       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6188         ValueList Operands;
6189         BasicBlock *IBB = PH->getIncomingBlock(i);
6190 
6191         if (!VisitedBBs.insert(IBB).second) {
6192           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6193           continue;
6194         }
6195 
6196         Builder.SetInsertPoint(IBB->getTerminator());
6197         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6198         Value *Vec = vectorizeTree(E->getOperand(i));
6199         NewPhi->addIncoming(Vec, IBB);
6200       }
6201 
6202       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6203              "Invalid number of incoming values");
6204       return V;
6205     }
6206 
6207     case Instruction::ExtractElement: {
6208       Value *V = E->getSingleOperand(0);
6209       Builder.SetInsertPoint(VL0);
6210       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6211       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6212       V = ShuffleBuilder.finalize(V);
6213       E->VectorizedValue = V;
6214       return V;
6215     }
6216     case Instruction::ExtractValue: {
6217       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6218       Builder.SetInsertPoint(LI);
6219       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6220       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6221       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6222       Value *NewV = propagateMetadata(V, E->Scalars);
6223       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6224       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6225       NewV = ShuffleBuilder.finalize(NewV);
6226       E->VectorizedValue = NewV;
6227       return NewV;
6228     }
6229     case Instruction::InsertElement: {
6230       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6231       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6232       Value *V = vectorizeTree(E->getOperand(1));
6233 
6234       // Create InsertVector shuffle if necessary
6235       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6236         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6237       }));
6238       const unsigned NumElts =
6239           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6240       const unsigned NumScalars = E->Scalars.size();
6241 
6242       unsigned Offset = *getInsertIndex(VL0, 0);
6243       assert(Offset < NumElts && "Failed to find vector index offset");
6244 
6245       // Create shuffle to resize vector
6246       SmallVector<int> Mask;
6247       if (!E->ReorderIndices.empty()) {
6248         inversePermutation(E->ReorderIndices, Mask);
6249         Mask.append(NumElts - NumScalars, UndefMaskElem);
6250       } else {
6251         Mask.assign(NumElts, UndefMaskElem);
6252         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6253       }
6254       // Create InsertVector shuffle if necessary
6255       bool IsIdentity = true;
6256       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6257       Mask.swap(PrevMask);
6258       for (unsigned I = 0; I < NumScalars; ++I) {
6259         Value *Scalar = E->Scalars[PrevMask[I]];
6260         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6261         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6262           continue;
6263         IsIdentity &= *InsertIdx - Offset == I;
6264         Mask[*InsertIdx - Offset] = I;
6265       }
6266       if (!IsIdentity || NumElts != NumScalars) {
6267         V = Builder.CreateShuffleVector(V, Mask);
6268         if (auto *I = dyn_cast<Instruction>(V)) {
6269           GatherShuffleSeq.insert(I);
6270           CSEBlocks.insert(I->getParent());
6271         }
6272       }
6273 
6274       if ((!IsIdentity || Offset != 0 ||
6275            !isUndefVector(FirstInsert->getOperand(0))) &&
6276           NumElts != NumScalars) {
6277         SmallVector<int> InsertMask(NumElts);
6278         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6279         for (unsigned I = 0; I < NumElts; I++) {
6280           if (Mask[I] != UndefMaskElem)
6281             InsertMask[Offset + I] = NumElts + I;
6282         }
6283 
6284         V = Builder.CreateShuffleVector(
6285             FirstInsert->getOperand(0), V, InsertMask,
6286             cast<Instruction>(E->Scalars.back())->getName());
6287         if (auto *I = dyn_cast<Instruction>(V)) {
6288           GatherShuffleSeq.insert(I);
6289           CSEBlocks.insert(I->getParent());
6290         }
6291       }
6292 
6293       ++NumVectorInstructions;
6294       E->VectorizedValue = V;
6295       return V;
6296     }
6297     case Instruction::ZExt:
6298     case Instruction::SExt:
6299     case Instruction::FPToUI:
6300     case Instruction::FPToSI:
6301     case Instruction::FPExt:
6302     case Instruction::PtrToInt:
6303     case Instruction::IntToPtr:
6304     case Instruction::SIToFP:
6305     case Instruction::UIToFP:
6306     case Instruction::Trunc:
6307     case Instruction::FPTrunc:
6308     case Instruction::BitCast: {
6309       setInsertPointAfterBundle(E);
6310 
6311       Value *InVec = vectorizeTree(E->getOperand(0));
6312 
6313       if (E->VectorizedValue) {
6314         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6315         return E->VectorizedValue;
6316       }
6317 
6318       auto *CI = cast<CastInst>(VL0);
6319       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6320       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6321       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6322       V = ShuffleBuilder.finalize(V);
6323 
6324       E->VectorizedValue = V;
6325       ++NumVectorInstructions;
6326       return V;
6327     }
6328     case Instruction::FCmp:
6329     case Instruction::ICmp: {
6330       setInsertPointAfterBundle(E);
6331 
6332       Value *L = vectorizeTree(E->getOperand(0));
6333       Value *R = vectorizeTree(E->getOperand(1));
6334 
6335       if (E->VectorizedValue) {
6336         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6337         return E->VectorizedValue;
6338       }
6339 
6340       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6341       Value *V = Builder.CreateCmp(P0, L, R);
6342       propagateIRFlags(V, E->Scalars, VL0);
6343       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6344       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6345       V = ShuffleBuilder.finalize(V);
6346 
6347       E->VectorizedValue = V;
6348       ++NumVectorInstructions;
6349       return V;
6350     }
6351     case Instruction::Select: {
6352       setInsertPointAfterBundle(E);
6353 
6354       Value *Cond = vectorizeTree(E->getOperand(0));
6355       Value *True = vectorizeTree(E->getOperand(1));
6356       Value *False = vectorizeTree(E->getOperand(2));
6357 
6358       if (E->VectorizedValue) {
6359         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6360         return E->VectorizedValue;
6361       }
6362 
6363       Value *V = Builder.CreateSelect(Cond, True, False);
6364       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6365       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6366       V = ShuffleBuilder.finalize(V);
6367 
6368       E->VectorizedValue = V;
6369       ++NumVectorInstructions;
6370       return V;
6371     }
6372     case Instruction::FNeg: {
6373       setInsertPointAfterBundle(E);
6374 
6375       Value *Op = vectorizeTree(E->getOperand(0));
6376 
6377       if (E->VectorizedValue) {
6378         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6379         return E->VectorizedValue;
6380       }
6381 
6382       Value *V = Builder.CreateUnOp(
6383           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6384       propagateIRFlags(V, E->Scalars, VL0);
6385       if (auto *I = dyn_cast<Instruction>(V))
6386         V = propagateMetadata(I, E->Scalars);
6387 
6388       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6389       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6390       V = ShuffleBuilder.finalize(V);
6391 
6392       E->VectorizedValue = V;
6393       ++NumVectorInstructions;
6394 
6395       return V;
6396     }
6397     case Instruction::Add:
6398     case Instruction::FAdd:
6399     case Instruction::Sub:
6400     case Instruction::FSub:
6401     case Instruction::Mul:
6402     case Instruction::FMul:
6403     case Instruction::UDiv:
6404     case Instruction::SDiv:
6405     case Instruction::FDiv:
6406     case Instruction::URem:
6407     case Instruction::SRem:
6408     case Instruction::FRem:
6409     case Instruction::Shl:
6410     case Instruction::LShr:
6411     case Instruction::AShr:
6412     case Instruction::And:
6413     case Instruction::Or:
6414     case Instruction::Xor: {
6415       setInsertPointAfterBundle(E);
6416 
6417       Value *LHS = vectorizeTree(E->getOperand(0));
6418       Value *RHS = vectorizeTree(E->getOperand(1));
6419 
6420       if (E->VectorizedValue) {
6421         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6422         return E->VectorizedValue;
6423       }
6424 
6425       Value *V = Builder.CreateBinOp(
6426           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6427           RHS);
6428       propagateIRFlags(V, E->Scalars, VL0);
6429       if (auto *I = dyn_cast<Instruction>(V))
6430         V = propagateMetadata(I, E->Scalars);
6431 
6432       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6433       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6434       V = ShuffleBuilder.finalize(V);
6435 
6436       E->VectorizedValue = V;
6437       ++NumVectorInstructions;
6438 
6439       return V;
6440     }
6441     case Instruction::Load: {
6442       // Loads are inserted at the head of the tree because we don't want to
6443       // sink them all the way down past store instructions.
6444       setInsertPointAfterBundle(E);
6445 
6446       LoadInst *LI = cast<LoadInst>(VL0);
6447       Instruction *NewLI;
6448       unsigned AS = LI->getPointerAddressSpace();
6449       Value *PO = LI->getPointerOperand();
6450       if (E->State == TreeEntry::Vectorize) {
6451 
6452         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6453 
6454         // The pointer operand uses an in-tree scalar so we add the new BitCast
6455         // to ExternalUses list to make sure that an extract will be generated
6456         // in the future.
6457         if (TreeEntry *Entry = getTreeEntry(PO)) {
6458           // Find which lane we need to extract.
6459           unsigned FoundLane = Entry->findLaneForValue(PO);
6460           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6461         }
6462 
6463         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6464       } else {
6465         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6466         Value *VecPtr = vectorizeTree(E->getOperand(0));
6467         // Use the minimum alignment of the gathered loads.
6468         Align CommonAlignment = LI->getAlign();
6469         for (Value *V : E->Scalars)
6470           CommonAlignment =
6471               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6472         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6473       }
6474       Value *V = propagateMetadata(NewLI, E->Scalars);
6475 
6476       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6477       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6478       V = ShuffleBuilder.finalize(V);
6479       E->VectorizedValue = V;
6480       ++NumVectorInstructions;
6481       return V;
6482     }
6483     case Instruction::Store: {
6484       auto *SI = cast<StoreInst>(VL0);
6485       unsigned AS = SI->getPointerAddressSpace();
6486 
6487       setInsertPointAfterBundle(E);
6488 
6489       Value *VecValue = vectorizeTree(E->getOperand(0));
6490       ShuffleBuilder.addMask(E->ReorderIndices);
6491       VecValue = ShuffleBuilder.finalize(VecValue);
6492 
6493       Value *ScalarPtr = SI->getPointerOperand();
6494       Value *VecPtr = Builder.CreateBitCast(
6495           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6496       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6497                                                  SI->getAlign());
6498 
6499       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6500       // ExternalUses to make sure that an extract will be generated in the
6501       // future.
6502       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6503         // Find which lane we need to extract.
6504         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6505         ExternalUses.push_back(
6506             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6507       }
6508 
6509       Value *V = propagateMetadata(ST, E->Scalars);
6510 
6511       E->VectorizedValue = V;
6512       ++NumVectorInstructions;
6513       return V;
6514     }
6515     case Instruction::GetElementPtr: {
6516       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6517       setInsertPointAfterBundle(E);
6518 
6519       Value *Op0 = vectorizeTree(E->getOperand(0));
6520 
6521       SmallVector<Value *> OpVecs;
6522       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6523         Value *OpVec = vectorizeTree(E->getOperand(J));
6524         OpVecs.push_back(OpVec);
6525       }
6526 
6527       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6528       if (Instruction *I = dyn_cast<Instruction>(V))
6529         V = propagateMetadata(I, E->Scalars);
6530 
6531       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6532       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6533       V = ShuffleBuilder.finalize(V);
6534 
6535       E->VectorizedValue = V;
6536       ++NumVectorInstructions;
6537 
6538       return V;
6539     }
6540     case Instruction::Call: {
6541       CallInst *CI = cast<CallInst>(VL0);
6542       setInsertPointAfterBundle(E);
6543 
6544       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6545       if (Function *FI = CI->getCalledFunction())
6546         IID = FI->getIntrinsicID();
6547 
6548       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6549 
6550       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6551       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6552                           VecCallCosts.first <= VecCallCosts.second;
6553 
6554       Value *ScalarArg = nullptr;
6555       std::vector<Value *> OpVecs;
6556       SmallVector<Type *, 2> TysForDecl =
6557           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6558       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6559         ValueList OpVL;
6560         // Some intrinsics have scalar arguments. This argument should not be
6561         // vectorized.
6562         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6563           CallInst *CEI = cast<CallInst>(VL0);
6564           ScalarArg = CEI->getArgOperand(j);
6565           OpVecs.push_back(CEI->getArgOperand(j));
6566           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6567             TysForDecl.push_back(ScalarArg->getType());
6568           continue;
6569         }
6570 
6571         Value *OpVec = vectorizeTree(E->getOperand(j));
6572         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6573         OpVecs.push_back(OpVec);
6574       }
6575 
6576       Function *CF;
6577       if (!UseIntrinsic) {
6578         VFShape Shape =
6579             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6580                                   VecTy->getNumElements())),
6581                          false /*HasGlobalPred*/);
6582         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6583       } else {
6584         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6585       }
6586 
6587       SmallVector<OperandBundleDef, 1> OpBundles;
6588       CI->getOperandBundlesAsDefs(OpBundles);
6589       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6590 
6591       // The scalar argument uses an in-tree scalar so we add the new vectorized
6592       // call to ExternalUses list to make sure that an extract will be
6593       // generated in the future.
6594       if (ScalarArg) {
6595         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6596           // Find which lane we need to extract.
6597           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6598           ExternalUses.push_back(
6599               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6600         }
6601       }
6602 
6603       propagateIRFlags(V, E->Scalars, VL0);
6604       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6605       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6606       V = ShuffleBuilder.finalize(V);
6607 
6608       E->VectorizedValue = V;
6609       ++NumVectorInstructions;
6610       return V;
6611     }
6612     case Instruction::ShuffleVector: {
6613       assert(E->isAltShuffle() &&
6614              ((Instruction::isBinaryOp(E->getOpcode()) &&
6615                Instruction::isBinaryOp(E->getAltOpcode())) ||
6616               (Instruction::isCast(E->getOpcode()) &&
6617                Instruction::isCast(E->getAltOpcode()))) &&
6618              "Invalid Shuffle Vector Operand");
6619 
6620       Value *LHS = nullptr, *RHS = nullptr;
6621       if (Instruction::isBinaryOp(E->getOpcode())) {
6622         setInsertPointAfterBundle(E);
6623         LHS = vectorizeTree(E->getOperand(0));
6624         RHS = vectorizeTree(E->getOperand(1));
6625       } else {
6626         setInsertPointAfterBundle(E);
6627         LHS = vectorizeTree(E->getOperand(0));
6628       }
6629 
6630       if (E->VectorizedValue) {
6631         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6632         return E->VectorizedValue;
6633       }
6634 
6635       Value *V0, *V1;
6636       if (Instruction::isBinaryOp(E->getOpcode())) {
6637         V0 = Builder.CreateBinOp(
6638             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6639         V1 = Builder.CreateBinOp(
6640             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6641       } else {
6642         V0 = Builder.CreateCast(
6643             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6644         V1 = Builder.CreateCast(
6645             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6646       }
6647       // Add V0 and V1 to later analysis to try to find and remove matching
6648       // instruction, if any.
6649       for (Value *V : {V0, V1}) {
6650         if (auto *I = dyn_cast<Instruction>(V)) {
6651           GatherShuffleSeq.insert(I);
6652           CSEBlocks.insert(I->getParent());
6653         }
6654       }
6655 
6656       // Create shuffle to take alternate operations from the vector.
6657       // Also, gather up main and alt scalar ops to propagate IR flags to
6658       // each vector operation.
6659       ValueList OpScalars, AltScalars;
6660       SmallVector<int> Mask;
6661       buildSuffleEntryMask(
6662           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6663           [E](Instruction *I) {
6664             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6665             return I->getOpcode() == E->getAltOpcode();
6666           },
6667           Mask, &OpScalars, &AltScalars);
6668 
6669       propagateIRFlags(V0, OpScalars);
6670       propagateIRFlags(V1, AltScalars);
6671 
6672       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
6673       if (auto *I = dyn_cast<Instruction>(V)) {
6674         V = propagateMetadata(I, E->Scalars);
6675         GatherShuffleSeq.insert(I);
6676         CSEBlocks.insert(I->getParent());
6677       }
6678       V = ShuffleBuilder.finalize(V);
6679 
6680       E->VectorizedValue = V;
6681       ++NumVectorInstructions;
6682 
6683       return V;
6684     }
6685     default:
6686     llvm_unreachable("unknown inst");
6687   }
6688   return nullptr;
6689 }
6690 
6691 Value *BoUpSLP::vectorizeTree() {
6692   ExtraValueToDebugLocsMap ExternallyUsedValues;
6693   return vectorizeTree(ExternallyUsedValues);
6694 }
6695 
6696 Value *
6697 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
6698   // All blocks must be scheduled before any instructions are inserted.
6699   for (auto &BSIter : BlocksSchedules) {
6700     scheduleBlock(BSIter.second.get());
6701   }
6702 
6703   Builder.SetInsertPoint(&F->getEntryBlock().front());
6704   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
6705 
6706   // If the vectorized tree can be rewritten in a smaller type, we truncate the
6707   // vectorized root. InstCombine will then rewrite the entire expression. We
6708   // sign extend the extracted values below.
6709   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6710   if (MinBWs.count(ScalarRoot)) {
6711     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
6712       // If current instr is a phi and not the last phi, insert it after the
6713       // last phi node.
6714       if (isa<PHINode>(I))
6715         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
6716       else
6717         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
6718     }
6719     auto BundleWidth = VectorizableTree[0]->Scalars.size();
6720     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6721     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
6722     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
6723     VectorizableTree[0]->VectorizedValue = Trunc;
6724   }
6725 
6726   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
6727                     << " values .\n");
6728 
6729   // Extract all of the elements with the external uses.
6730   for (const auto &ExternalUse : ExternalUses) {
6731     Value *Scalar = ExternalUse.Scalar;
6732     llvm::User *User = ExternalUse.User;
6733 
6734     // Skip users that we already RAUW. This happens when one instruction
6735     // has multiple uses of the same value.
6736     if (User && !is_contained(Scalar->users(), User))
6737       continue;
6738     TreeEntry *E = getTreeEntry(Scalar);
6739     assert(E && "Invalid scalar");
6740     assert(E->State != TreeEntry::NeedToGather &&
6741            "Extracting from a gather list");
6742 
6743     Value *Vec = E->VectorizedValue;
6744     assert(Vec && "Can't find vectorizable value");
6745 
6746     Value *Lane = Builder.getInt32(ExternalUse.Lane);
6747     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
6748       if (Scalar->getType() != Vec->getType()) {
6749         Value *Ex;
6750         // "Reuse" the existing extract to improve final codegen.
6751         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
6752           Ex = Builder.CreateExtractElement(ES->getOperand(0),
6753                                             ES->getOperand(1));
6754         } else {
6755           Ex = Builder.CreateExtractElement(Vec, Lane);
6756         }
6757         // If necessary, sign-extend or zero-extend ScalarRoot
6758         // to the larger type.
6759         if (!MinBWs.count(ScalarRoot))
6760           return Ex;
6761         if (MinBWs[ScalarRoot].second)
6762           return Builder.CreateSExt(Ex, Scalar->getType());
6763         return Builder.CreateZExt(Ex, Scalar->getType());
6764       }
6765       assert(isa<FixedVectorType>(Scalar->getType()) &&
6766              isa<InsertElementInst>(Scalar) &&
6767              "In-tree scalar of vector type is not insertelement?");
6768       return Vec;
6769     };
6770     // If User == nullptr, the Scalar is used as extra arg. Generate
6771     // ExtractElement instruction and update the record for this scalar in
6772     // ExternallyUsedValues.
6773     if (!User) {
6774       assert(ExternallyUsedValues.count(Scalar) &&
6775              "Scalar with nullptr as an external user must be registered in "
6776              "ExternallyUsedValues map");
6777       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6778         Builder.SetInsertPoint(VecI->getParent(),
6779                                std::next(VecI->getIterator()));
6780       } else {
6781         Builder.SetInsertPoint(&F->getEntryBlock().front());
6782       }
6783       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6784       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
6785       auto &NewInstLocs = ExternallyUsedValues[NewInst];
6786       auto It = ExternallyUsedValues.find(Scalar);
6787       assert(It != ExternallyUsedValues.end() &&
6788              "Externally used scalar is not found in ExternallyUsedValues");
6789       NewInstLocs.append(It->second);
6790       ExternallyUsedValues.erase(Scalar);
6791       // Required to update internally referenced instructions.
6792       Scalar->replaceAllUsesWith(NewInst);
6793       continue;
6794     }
6795 
6796     // Generate extracts for out-of-tree users.
6797     // Find the insertion point for the extractelement lane.
6798     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6799       if (PHINode *PH = dyn_cast<PHINode>(User)) {
6800         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
6801           if (PH->getIncomingValue(i) == Scalar) {
6802             Instruction *IncomingTerminator =
6803                 PH->getIncomingBlock(i)->getTerminator();
6804             if (isa<CatchSwitchInst>(IncomingTerminator)) {
6805               Builder.SetInsertPoint(VecI->getParent(),
6806                                      std::next(VecI->getIterator()));
6807             } else {
6808               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
6809             }
6810             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6811             CSEBlocks.insert(PH->getIncomingBlock(i));
6812             PH->setOperand(i, NewInst);
6813           }
6814         }
6815       } else {
6816         Builder.SetInsertPoint(cast<Instruction>(User));
6817         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6818         CSEBlocks.insert(cast<Instruction>(User)->getParent());
6819         User->replaceUsesOfWith(Scalar, NewInst);
6820       }
6821     } else {
6822       Builder.SetInsertPoint(&F->getEntryBlock().front());
6823       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6824       CSEBlocks.insert(&F->getEntryBlock());
6825       User->replaceUsesOfWith(Scalar, NewInst);
6826     }
6827 
6828     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
6829   }
6830 
6831   // For each vectorized value:
6832   for (auto &TEPtr : VectorizableTree) {
6833     TreeEntry *Entry = TEPtr.get();
6834 
6835     // No need to handle users of gathered values.
6836     if (Entry->State == TreeEntry::NeedToGather)
6837       continue;
6838 
6839     assert(Entry->VectorizedValue && "Can't find vectorizable value");
6840 
6841     // For each lane:
6842     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
6843       Value *Scalar = Entry->Scalars[Lane];
6844 
6845 #ifndef NDEBUG
6846       Type *Ty = Scalar->getType();
6847       if (!Ty->isVoidTy()) {
6848         for (User *U : Scalar->users()) {
6849           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
6850 
6851           // It is legal to delete users in the ignorelist.
6852           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
6853                   (isa_and_nonnull<Instruction>(U) &&
6854                    isDeleted(cast<Instruction>(U)))) &&
6855                  "Deleting out-of-tree value");
6856         }
6857       }
6858 #endif
6859       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
6860       eraseInstruction(cast<Instruction>(Scalar));
6861     }
6862   }
6863 
6864   Builder.ClearInsertionPoint();
6865   InstrElementSize.clear();
6866 
6867   return VectorizableTree[0]->VectorizedValue;
6868 }
6869 
6870 void BoUpSLP::optimizeGatherSequence() {
6871   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
6872                     << " gather sequences instructions.\n");
6873   // LICM InsertElementInst sequences.
6874   for (Instruction *I : GatherShuffleSeq) {
6875     if (isDeleted(I))
6876       continue;
6877 
6878     // Check if this block is inside a loop.
6879     Loop *L = LI->getLoopFor(I->getParent());
6880     if (!L)
6881       continue;
6882 
6883     // Check if it has a preheader.
6884     BasicBlock *PreHeader = L->getLoopPreheader();
6885     if (!PreHeader)
6886       continue;
6887 
6888     // If the vector or the element that we insert into it are
6889     // instructions that are defined in this basic block then we can't
6890     // hoist this instruction.
6891     if (any_of(I->operands(), [L](Value *V) {
6892           auto *OpI = dyn_cast<Instruction>(V);
6893           return OpI && L->contains(OpI);
6894         }))
6895       continue;
6896 
6897     // We can hoist this instruction. Move it to the pre-header.
6898     I->moveBefore(PreHeader->getTerminator());
6899   }
6900 
6901   // Make a list of all reachable blocks in our CSE queue.
6902   SmallVector<const DomTreeNode *, 8> CSEWorkList;
6903   CSEWorkList.reserve(CSEBlocks.size());
6904   for (BasicBlock *BB : CSEBlocks)
6905     if (DomTreeNode *N = DT->getNode(BB)) {
6906       assert(DT->isReachableFromEntry(N));
6907       CSEWorkList.push_back(N);
6908     }
6909 
6910   // Sort blocks by domination. This ensures we visit a block after all blocks
6911   // dominating it are visited.
6912   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
6913     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
6914            "Different nodes should have different DFS numbers");
6915     return A->getDFSNumIn() < B->getDFSNumIn();
6916   });
6917 
6918   // Less defined shuffles can be replaced by the more defined copies.
6919   // Between two shuffles one is less defined if it has the same vector operands
6920   // and its mask indeces are the same as in the first one or undefs. E.g.
6921   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
6922   // poison, <0, 0, 0, 0>.
6923   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
6924                                            SmallVectorImpl<int> &NewMask) {
6925     if (I1->getType() != I2->getType())
6926       return false;
6927     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
6928     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
6929     if (!SI1 || !SI2)
6930       return I1->isIdenticalTo(I2);
6931     if (SI1->isIdenticalTo(SI2))
6932       return true;
6933     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
6934       if (SI1->getOperand(I) != SI2->getOperand(I))
6935         return false;
6936     // Check if the second instruction is more defined than the first one.
6937     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
6938     ArrayRef<int> SM1 = SI1->getShuffleMask();
6939     // Count trailing undefs in the mask to check the final number of used
6940     // registers.
6941     unsigned LastUndefsCnt = 0;
6942     for (int I = 0, E = NewMask.size(); I < E; ++I) {
6943       if (SM1[I] == UndefMaskElem)
6944         ++LastUndefsCnt;
6945       else
6946         LastUndefsCnt = 0;
6947       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
6948           NewMask[I] != SM1[I])
6949         return false;
6950       if (NewMask[I] == UndefMaskElem)
6951         NewMask[I] = SM1[I];
6952     }
6953     // Check if the last undefs actually change the final number of used vector
6954     // registers.
6955     return SM1.size() - LastUndefsCnt > 1 &&
6956            TTI->getNumberOfParts(SI1->getType()) ==
6957                TTI->getNumberOfParts(
6958                    FixedVectorType::get(SI1->getType()->getElementType(),
6959                                         SM1.size() - LastUndefsCnt));
6960   };
6961   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
6962   // instructions. TODO: We can further optimize this scan if we split the
6963   // instructions into different buckets based on the insert lane.
6964   SmallVector<Instruction *, 16> Visited;
6965   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
6966     assert(*I &&
6967            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
6968            "Worklist not sorted properly!");
6969     BasicBlock *BB = (*I)->getBlock();
6970     // For all instructions in blocks containing gather sequences:
6971     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
6972       if (isDeleted(&In))
6973         continue;
6974       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
6975           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
6976         continue;
6977 
6978       // Check if we can replace this instruction with any of the
6979       // visited instructions.
6980       bool Replaced = false;
6981       for (Instruction *&V : Visited) {
6982         SmallVector<int> NewMask;
6983         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
6984             DT->dominates(V->getParent(), In.getParent())) {
6985           In.replaceAllUsesWith(V);
6986           eraseInstruction(&In);
6987           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
6988             if (!NewMask.empty())
6989               SI->setShuffleMask(NewMask);
6990           Replaced = true;
6991           break;
6992         }
6993         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
6994             GatherShuffleSeq.contains(V) &&
6995             IsIdenticalOrLessDefined(V, &In, NewMask) &&
6996             DT->dominates(In.getParent(), V->getParent())) {
6997           In.moveAfter(V);
6998           V->replaceAllUsesWith(&In);
6999           eraseInstruction(V);
7000           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7001             if (!NewMask.empty())
7002               SI->setShuffleMask(NewMask);
7003           V = &In;
7004           Replaced = true;
7005           break;
7006         }
7007       }
7008       if (!Replaced) {
7009         assert(!is_contained(Visited, &In));
7010         Visited.push_back(&In);
7011       }
7012     }
7013   }
7014   CSEBlocks.clear();
7015   GatherShuffleSeq.clear();
7016 }
7017 
7018 // Groups the instructions to a bundle (which is then a single scheduling entity)
7019 // and schedules instructions until the bundle gets ready.
7020 Optional<BoUpSLP::ScheduleData *>
7021 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7022                                             const InstructionsState &S) {
7023   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7024   // instructions.
7025   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7026     return nullptr;
7027 
7028   // Initialize the instruction bundle.
7029   Instruction *OldScheduleEnd = ScheduleEnd;
7030   ScheduleData *PrevInBundle = nullptr;
7031   ScheduleData *Bundle = nullptr;
7032   bool ReSchedule = false;
7033   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7034 
7035   auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule,
7036                                                          ScheduleData *Bundle) {
7037     // The scheduling region got new instructions at the lower end (or it is a
7038     // new region for the first bundle). This makes it necessary to
7039     // recalculate all dependencies.
7040     // It is seldom that this needs to be done a second time after adding the
7041     // initial bundle to the region.
7042     if (ScheduleEnd != OldScheduleEnd) {
7043       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7044         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7045       ReSchedule = true;
7046     }
7047     if (ReSchedule) {
7048       resetSchedule();
7049       initialFillReadyList(ReadyInsts);
7050     }
7051     if (Bundle) {
7052       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7053                         << " in block " << BB->getName() << "\n");
7054       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7055     }
7056 
7057     // Now try to schedule the new bundle or (if no bundle) just calculate
7058     // dependencies. As soon as the bundle is "ready" it means that there are no
7059     // cyclic dependencies and we can schedule it. Note that's important that we
7060     // don't "schedule" the bundle yet (see cancelScheduling).
7061     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7062            !ReadyInsts.empty()) {
7063       ScheduleData *Picked = ReadyInsts.pop_back_val();
7064       if (Picked->isSchedulingEntity() && Picked->isReady())
7065         schedule(Picked, ReadyInsts);
7066     }
7067   };
7068 
7069   // Make sure that the scheduling region contains all
7070   // instructions of the bundle.
7071   for (Value *V : VL) {
7072     if (!extendSchedulingRegion(V, S)) {
7073       // If the scheduling region got new instructions at the lower end (or it
7074       // is a new region for the first bundle). This makes it necessary to
7075       // recalculate all dependencies.
7076       // Otherwise the compiler may crash trying to incorrectly calculate
7077       // dependencies and emit instruction in the wrong order at the actual
7078       // scheduling.
7079       TryScheduleBundle(/*ReSchedule=*/false, nullptr);
7080       return None;
7081     }
7082   }
7083 
7084   for (Value *V : VL) {
7085     ScheduleData *BundleMember = getScheduleData(V);
7086     assert(BundleMember &&
7087            "no ScheduleData for bundle member (maybe not in same basic block)");
7088     if (BundleMember->IsScheduled) {
7089       // A bundle member was scheduled as single instruction before and now
7090       // needs to be scheduled as part of the bundle. We just get rid of the
7091       // existing schedule.
7092       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7093                         << " was already scheduled\n");
7094       ReSchedule = true;
7095     }
7096     assert(BundleMember->isSchedulingEntity() &&
7097            "bundle member already part of other bundle");
7098     if (PrevInBundle) {
7099       PrevInBundle->NextInBundle = BundleMember;
7100     } else {
7101       Bundle = BundleMember;
7102     }
7103     BundleMember->UnscheduledDepsInBundle = 0;
7104     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7105 
7106     // Group the instructions to a bundle.
7107     BundleMember->FirstInBundle = Bundle;
7108     PrevInBundle = BundleMember;
7109   }
7110   assert(Bundle && "Failed to find schedule bundle");
7111   TryScheduleBundle(ReSchedule, Bundle);
7112   if (!Bundle->isReady()) {
7113     cancelScheduling(VL, S.OpValue);
7114     return None;
7115   }
7116   return Bundle;
7117 }
7118 
7119 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7120                                                 Value *OpValue) {
7121   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7122     return;
7123 
7124   ScheduleData *Bundle = getScheduleData(OpValue);
7125   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7126   assert(!Bundle->IsScheduled &&
7127          "Can't cancel bundle which is already scheduled");
7128   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7129          "tried to unbundle something which is not a bundle");
7130 
7131   // Un-bundle: make single instructions out of the bundle.
7132   ScheduleData *BundleMember = Bundle;
7133   while (BundleMember) {
7134     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7135     BundleMember->FirstInBundle = BundleMember;
7136     ScheduleData *Next = BundleMember->NextInBundle;
7137     BundleMember->NextInBundle = nullptr;
7138     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7139     if (BundleMember->UnscheduledDepsInBundle == 0) {
7140       ReadyInsts.insert(BundleMember);
7141     }
7142     BundleMember = Next;
7143   }
7144 }
7145 
7146 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7147   // Allocate a new ScheduleData for the instruction.
7148   if (ChunkPos >= ChunkSize) {
7149     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7150     ChunkPos = 0;
7151   }
7152   return &(ScheduleDataChunks.back()[ChunkPos++]);
7153 }
7154 
7155 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7156                                                       const InstructionsState &S) {
7157   if (getScheduleData(V, isOneOf(S, V)))
7158     return true;
7159   Instruction *I = dyn_cast<Instruction>(V);
7160   assert(I && "bundle member must be an instruction");
7161   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7162          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7163          "be scheduled");
7164   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7165     ScheduleData *ISD = getScheduleData(I);
7166     if (!ISD)
7167       return false;
7168     assert(isInSchedulingRegion(ISD) &&
7169            "ScheduleData not in scheduling region");
7170     ScheduleData *SD = allocateScheduleDataChunks();
7171     SD->Inst = I;
7172     SD->init(SchedulingRegionID, S.OpValue);
7173     ExtraScheduleDataMap[I][S.OpValue] = SD;
7174     return true;
7175   };
7176   if (CheckSheduleForI(I))
7177     return true;
7178   if (!ScheduleStart) {
7179     // It's the first instruction in the new region.
7180     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7181     ScheduleStart = I;
7182     ScheduleEnd = I->getNextNode();
7183     if (isOneOf(S, I) != I)
7184       CheckSheduleForI(I);
7185     assert(ScheduleEnd && "tried to vectorize a terminator?");
7186     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7187     return true;
7188   }
7189   // Search up and down at the same time, because we don't know if the new
7190   // instruction is above or below the existing scheduling region.
7191   BasicBlock::reverse_iterator UpIter =
7192       ++ScheduleStart->getIterator().getReverse();
7193   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7194   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7195   BasicBlock::iterator LowerEnd = BB->end();
7196   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7197          &*DownIter != I) {
7198     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7199       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7200       return false;
7201     }
7202 
7203     ++UpIter;
7204     ++DownIter;
7205   }
7206   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7207     assert(I->getParent() == ScheduleStart->getParent() &&
7208            "Instruction is in wrong basic block.");
7209     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7210     ScheduleStart = I;
7211     if (isOneOf(S, I) != I)
7212       CheckSheduleForI(I);
7213     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7214                       << "\n");
7215     return true;
7216   }
7217   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7218          "Expected to reach top of the basic block or instruction down the "
7219          "lower end.");
7220   assert(I->getParent() == ScheduleEnd->getParent() &&
7221          "Instruction is in wrong basic block.");
7222   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7223                    nullptr);
7224   ScheduleEnd = I->getNextNode();
7225   if (isOneOf(S, I) != I)
7226     CheckSheduleForI(I);
7227   assert(ScheduleEnd && "tried to vectorize a terminator?");
7228   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7229   return true;
7230 }
7231 
7232 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7233                                                 Instruction *ToI,
7234                                                 ScheduleData *PrevLoadStore,
7235                                                 ScheduleData *NextLoadStore) {
7236   ScheduleData *CurrentLoadStore = PrevLoadStore;
7237   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7238     ScheduleData *SD = ScheduleDataMap[I];
7239     if (!SD) {
7240       SD = allocateScheduleDataChunks();
7241       ScheduleDataMap[I] = SD;
7242       SD->Inst = I;
7243     }
7244     assert(!isInSchedulingRegion(SD) &&
7245            "new ScheduleData already in scheduling region");
7246     SD->init(SchedulingRegionID, I);
7247 
7248     if (I->mayReadOrWriteMemory() &&
7249         (!isa<IntrinsicInst>(I) ||
7250          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7251           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7252               Intrinsic::pseudoprobe))) {
7253       // Update the linked list of memory accessing instructions.
7254       if (CurrentLoadStore) {
7255         CurrentLoadStore->NextLoadStore = SD;
7256       } else {
7257         FirstLoadStoreInRegion = SD;
7258       }
7259       CurrentLoadStore = SD;
7260     }
7261   }
7262   if (NextLoadStore) {
7263     if (CurrentLoadStore)
7264       CurrentLoadStore->NextLoadStore = NextLoadStore;
7265   } else {
7266     LastLoadStoreInRegion = CurrentLoadStore;
7267   }
7268 }
7269 
7270 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7271                                                      bool InsertInReadyList,
7272                                                      BoUpSLP *SLP) {
7273   assert(SD->isSchedulingEntity());
7274 
7275   SmallVector<ScheduleData *, 10> WorkList;
7276   WorkList.push_back(SD);
7277 
7278   while (!WorkList.empty()) {
7279     ScheduleData *SD = WorkList.pop_back_val();
7280 
7281     ScheduleData *BundleMember = SD;
7282     while (BundleMember) {
7283       assert(isInSchedulingRegion(BundleMember));
7284       if (!BundleMember->hasValidDependencies()) {
7285 
7286         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7287                           << "\n");
7288         BundleMember->Dependencies = 0;
7289         BundleMember->resetUnscheduledDeps();
7290 
7291         // Handle def-use chain dependencies.
7292         if (BundleMember->OpValue != BundleMember->Inst) {
7293           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7294           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7295             BundleMember->Dependencies++;
7296             ScheduleData *DestBundle = UseSD->FirstInBundle;
7297             if (!DestBundle->IsScheduled)
7298               BundleMember->incrementUnscheduledDeps(1);
7299             if (!DestBundle->hasValidDependencies())
7300               WorkList.push_back(DestBundle);
7301           }
7302         } else {
7303           for (User *U : BundleMember->Inst->users()) {
7304             if (isa<Instruction>(U)) {
7305               ScheduleData *UseSD = getScheduleData(U);
7306               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7307                 BundleMember->Dependencies++;
7308                 ScheduleData *DestBundle = UseSD->FirstInBundle;
7309                 if (!DestBundle->IsScheduled)
7310                   BundleMember->incrementUnscheduledDeps(1);
7311                 if (!DestBundle->hasValidDependencies())
7312                   WorkList.push_back(DestBundle);
7313               }
7314             } else {
7315               // I'm not sure if this can ever happen. But we need to be safe.
7316               // This lets the instruction/bundle never be scheduled and
7317               // eventually disable vectorization.
7318               BundleMember->Dependencies++;
7319               BundleMember->incrementUnscheduledDeps(1);
7320             }
7321           }
7322         }
7323 
7324         // Handle the memory dependencies.
7325         ScheduleData *DepDest = BundleMember->NextLoadStore;
7326         if (DepDest) {
7327           Instruction *SrcInst = BundleMember->Inst;
7328           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
7329           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7330           unsigned numAliased = 0;
7331           unsigned DistToSrc = 1;
7332 
7333           while (DepDest) {
7334             assert(isInSchedulingRegion(DepDest));
7335 
7336             // We have two limits to reduce the complexity:
7337             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7338             //    SLP->isAliased (which is the expensive part in this loop).
7339             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7340             //    the whole loop (even if the loop is fast, it's quadratic).
7341             //    It's important for the loop break condition (see below) to
7342             //    check this limit even between two read-only instructions.
7343             if (DistToSrc >= MaxMemDepDistance ||
7344                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7345                      (numAliased >= AliasedCheckLimit ||
7346                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7347 
7348               // We increment the counter only if the locations are aliased
7349               // (instead of counting all alias checks). This gives a better
7350               // balance between reduced runtime and accurate dependencies.
7351               numAliased++;
7352 
7353               DepDest->MemoryDependencies.push_back(BundleMember);
7354               BundleMember->Dependencies++;
7355               ScheduleData *DestBundle = DepDest->FirstInBundle;
7356               if (!DestBundle->IsScheduled) {
7357                 BundleMember->incrementUnscheduledDeps(1);
7358               }
7359               if (!DestBundle->hasValidDependencies()) {
7360                 WorkList.push_back(DestBundle);
7361               }
7362             }
7363             DepDest = DepDest->NextLoadStore;
7364 
7365             // Example, explaining the loop break condition: Let's assume our
7366             // starting instruction is i0 and MaxMemDepDistance = 3.
7367             //
7368             //                      +--------v--v--v
7369             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7370             //             +--------^--^--^
7371             //
7372             // MaxMemDepDistance let us stop alias-checking at i3 and we add
7373             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7374             // Previously we already added dependencies from i3 to i6,i7,i8
7375             // (because of MaxMemDepDistance). As we added a dependency from
7376             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7377             // and we can abort this loop at i6.
7378             if (DistToSrc >= 2 * MaxMemDepDistance)
7379               break;
7380             DistToSrc++;
7381           }
7382         }
7383       }
7384       BundleMember = BundleMember->NextInBundle;
7385     }
7386     if (InsertInReadyList && SD->isReady()) {
7387       ReadyInsts.push_back(SD);
7388       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7389                         << "\n");
7390     }
7391   }
7392 }
7393 
7394 void BoUpSLP::BlockScheduling::resetSchedule() {
7395   assert(ScheduleStart &&
7396          "tried to reset schedule on block which has not been scheduled");
7397   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7398     doForAllOpcodes(I, [&](ScheduleData *SD) {
7399       assert(isInSchedulingRegion(SD) &&
7400              "ScheduleData not in scheduling region");
7401       SD->IsScheduled = false;
7402       SD->resetUnscheduledDeps();
7403     });
7404   }
7405   ReadyInsts.clear();
7406 }
7407 
7408 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7409   if (!BS->ScheduleStart)
7410     return;
7411 
7412   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7413 
7414   BS->resetSchedule();
7415 
7416   // For the real scheduling we use a more sophisticated ready-list: it is
7417   // sorted by the original instruction location. This lets the final schedule
7418   // be as  close as possible to the original instruction order.
7419   struct ScheduleDataCompare {
7420     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7421       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7422     }
7423   };
7424   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7425 
7426   // Ensure that all dependency data is updated and fill the ready-list with
7427   // initial instructions.
7428   int Idx = 0;
7429   int NumToSchedule = 0;
7430   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7431        I = I->getNextNode()) {
7432     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7433       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7434               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7435              "scheduler and vectorizer bundle mismatch");
7436       SD->FirstInBundle->SchedulingPriority = Idx++;
7437       if (SD->isSchedulingEntity()) {
7438         BS->calculateDependencies(SD, false, this);
7439         NumToSchedule++;
7440       }
7441     });
7442   }
7443   BS->initialFillReadyList(ReadyInsts);
7444 
7445   Instruction *LastScheduledInst = BS->ScheduleEnd;
7446 
7447   // Do the "real" scheduling.
7448   while (!ReadyInsts.empty()) {
7449     ScheduleData *picked = *ReadyInsts.begin();
7450     ReadyInsts.erase(ReadyInsts.begin());
7451 
7452     // Move the scheduled instruction(s) to their dedicated places, if not
7453     // there yet.
7454     ScheduleData *BundleMember = picked;
7455     while (BundleMember) {
7456       Instruction *pickedInst = BundleMember->Inst;
7457       if (pickedInst->getNextNode() != LastScheduledInst) {
7458         BS->BB->getInstList().remove(pickedInst);
7459         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
7460                                      pickedInst);
7461       }
7462       LastScheduledInst = pickedInst;
7463       BundleMember = BundleMember->NextInBundle;
7464     }
7465 
7466     BS->schedule(picked, ReadyInsts);
7467     NumToSchedule--;
7468   }
7469   assert(NumToSchedule == 0 && "could not schedule all instructions");
7470 
7471   // Avoid duplicate scheduling of the block.
7472   BS->ScheduleStart = nullptr;
7473 }
7474 
7475 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7476   // If V is a store, just return the width of the stored value (or value
7477   // truncated just before storing) without traversing the expression tree.
7478   // This is the common case.
7479   if (auto *Store = dyn_cast<StoreInst>(V)) {
7480     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7481       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7482     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7483   }
7484 
7485   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7486     return getVectorElementSize(IEI->getOperand(1));
7487 
7488   auto E = InstrElementSize.find(V);
7489   if (E != InstrElementSize.end())
7490     return E->second;
7491 
7492   // If V is not a store, we can traverse the expression tree to find loads
7493   // that feed it. The type of the loaded value may indicate a more suitable
7494   // width than V's type. We want to base the vector element size on the width
7495   // of memory operations where possible.
7496   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7497   SmallPtrSet<Instruction *, 16> Visited;
7498   if (auto *I = dyn_cast<Instruction>(V)) {
7499     Worklist.emplace_back(I, I->getParent());
7500     Visited.insert(I);
7501   }
7502 
7503   // Traverse the expression tree in bottom-up order looking for loads. If we
7504   // encounter an instruction we don't yet handle, we give up.
7505   auto Width = 0u;
7506   while (!Worklist.empty()) {
7507     Instruction *I;
7508     BasicBlock *Parent;
7509     std::tie(I, Parent) = Worklist.pop_back_val();
7510 
7511     // We should only be looking at scalar instructions here. If the current
7512     // instruction has a vector type, skip.
7513     auto *Ty = I->getType();
7514     if (isa<VectorType>(Ty))
7515       continue;
7516 
7517     // If the current instruction is a load, update MaxWidth to reflect the
7518     // width of the loaded value.
7519     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7520         isa<ExtractValueInst>(I))
7521       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7522 
7523     // Otherwise, we need to visit the operands of the instruction. We only
7524     // handle the interesting cases from buildTree here. If an operand is an
7525     // instruction we haven't yet visited and from the same basic block as the
7526     // user or the use is a PHI node, we add it to the worklist.
7527     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7528              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7529              isa<UnaryOperator>(I)) {
7530       for (Use &U : I->operands())
7531         if (auto *J = dyn_cast<Instruction>(U.get()))
7532           if (Visited.insert(J).second &&
7533               (isa<PHINode>(I) || J->getParent() == Parent))
7534             Worklist.emplace_back(J, J->getParent());
7535     } else {
7536       break;
7537     }
7538   }
7539 
7540   // If we didn't encounter a memory access in the expression tree, or if we
7541   // gave up for some reason, just return the width of V. Otherwise, return the
7542   // maximum width we found.
7543   if (!Width) {
7544     if (auto *CI = dyn_cast<CmpInst>(V))
7545       V = CI->getOperand(0);
7546     Width = DL->getTypeSizeInBits(V->getType());
7547   }
7548 
7549   for (Instruction *I : Visited)
7550     InstrElementSize[I] = Width;
7551 
7552   return Width;
7553 }
7554 
7555 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7556 // smaller type with a truncation. We collect the values that will be demoted
7557 // in ToDemote and additional roots that require investigating in Roots.
7558 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7559                                   SmallVectorImpl<Value *> &ToDemote,
7560                                   SmallVectorImpl<Value *> &Roots) {
7561   // We can always demote constants.
7562   if (isa<Constant>(V)) {
7563     ToDemote.push_back(V);
7564     return true;
7565   }
7566 
7567   // If the value is not an instruction in the expression with only one use, it
7568   // cannot be demoted.
7569   auto *I = dyn_cast<Instruction>(V);
7570   if (!I || !I->hasOneUse() || !Expr.count(I))
7571     return false;
7572 
7573   switch (I->getOpcode()) {
7574 
7575   // We can always demote truncations and extensions. Since truncations can
7576   // seed additional demotion, we save the truncated value.
7577   case Instruction::Trunc:
7578     Roots.push_back(I->getOperand(0));
7579     break;
7580   case Instruction::ZExt:
7581   case Instruction::SExt:
7582     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7583         isa<InsertElementInst>(I->getOperand(0)))
7584       return false;
7585     break;
7586 
7587   // We can demote certain binary operations if we can demote both of their
7588   // operands.
7589   case Instruction::Add:
7590   case Instruction::Sub:
7591   case Instruction::Mul:
7592   case Instruction::And:
7593   case Instruction::Or:
7594   case Instruction::Xor:
7595     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7596         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7597       return false;
7598     break;
7599 
7600   // We can demote selects if we can demote their true and false values.
7601   case Instruction::Select: {
7602     SelectInst *SI = cast<SelectInst>(I);
7603     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7604         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7605       return false;
7606     break;
7607   }
7608 
7609   // We can demote phis if we can demote all their incoming operands. Note that
7610   // we don't need to worry about cycles since we ensure single use above.
7611   case Instruction::PHI: {
7612     PHINode *PN = cast<PHINode>(I);
7613     for (Value *IncValue : PN->incoming_values())
7614       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7615         return false;
7616     break;
7617   }
7618 
7619   // Otherwise, conservatively give up.
7620   default:
7621     return false;
7622   }
7623 
7624   // Record the value that we can demote.
7625   ToDemote.push_back(V);
7626   return true;
7627 }
7628 
7629 void BoUpSLP::computeMinimumValueSizes() {
7630   // If there are no external uses, the expression tree must be rooted by a
7631   // store. We can't demote in-memory values, so there is nothing to do here.
7632   if (ExternalUses.empty())
7633     return;
7634 
7635   // We only attempt to truncate integer expressions.
7636   auto &TreeRoot = VectorizableTree[0]->Scalars;
7637   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
7638   if (!TreeRootIT)
7639     return;
7640 
7641   // If the expression is not rooted by a store, these roots should have
7642   // external uses. We will rely on InstCombine to rewrite the expression in
7643   // the narrower type. However, InstCombine only rewrites single-use values.
7644   // This means that if a tree entry other than a root is used externally, it
7645   // must have multiple uses and InstCombine will not rewrite it. The code
7646   // below ensures that only the roots are used externally.
7647   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
7648   for (auto &EU : ExternalUses)
7649     if (!Expr.erase(EU.Scalar))
7650       return;
7651   if (!Expr.empty())
7652     return;
7653 
7654   // Collect the scalar values of the vectorizable expression. We will use this
7655   // context to determine which values can be demoted. If we see a truncation,
7656   // we mark it as seeding another demotion.
7657   for (auto &EntryPtr : VectorizableTree)
7658     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
7659 
7660   // Ensure the roots of the vectorizable tree don't form a cycle. They must
7661   // have a single external user that is not in the vectorizable tree.
7662   for (auto *Root : TreeRoot)
7663     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
7664       return;
7665 
7666   // Conservatively determine if we can actually truncate the roots of the
7667   // expression. Collect the values that can be demoted in ToDemote and
7668   // additional roots that require investigating in Roots.
7669   SmallVector<Value *, 32> ToDemote;
7670   SmallVector<Value *, 4> Roots;
7671   for (auto *Root : TreeRoot)
7672     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
7673       return;
7674 
7675   // The maximum bit width required to represent all the values that can be
7676   // demoted without loss of precision. It would be safe to truncate the roots
7677   // of the expression to this width.
7678   auto MaxBitWidth = 8u;
7679 
7680   // We first check if all the bits of the roots are demanded. If they're not,
7681   // we can truncate the roots to this narrower type.
7682   for (auto *Root : TreeRoot) {
7683     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
7684     MaxBitWidth = std::max<unsigned>(
7685         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
7686   }
7687 
7688   // True if the roots can be zero-extended back to their original type, rather
7689   // than sign-extended. We know that if the leading bits are not demanded, we
7690   // can safely zero-extend. So we initialize IsKnownPositive to True.
7691   bool IsKnownPositive = true;
7692 
7693   // If all the bits of the roots are demanded, we can try a little harder to
7694   // compute a narrower type. This can happen, for example, if the roots are
7695   // getelementptr indices. InstCombine promotes these indices to the pointer
7696   // width. Thus, all their bits are technically demanded even though the
7697   // address computation might be vectorized in a smaller type.
7698   //
7699   // We start by looking at each entry that can be demoted. We compute the
7700   // maximum bit width required to store the scalar by using ValueTracking to
7701   // compute the number of high-order bits we can truncate.
7702   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
7703       llvm::all_of(TreeRoot, [](Value *R) {
7704         assert(R->hasOneUse() && "Root should have only one use!");
7705         return isa<GetElementPtrInst>(R->user_back());
7706       })) {
7707     MaxBitWidth = 8u;
7708 
7709     // Determine if the sign bit of all the roots is known to be zero. If not,
7710     // IsKnownPositive is set to False.
7711     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
7712       KnownBits Known = computeKnownBits(R, *DL);
7713       return Known.isNonNegative();
7714     });
7715 
7716     // Determine the maximum number of bits required to store the scalar
7717     // values.
7718     for (auto *Scalar : ToDemote) {
7719       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
7720       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
7721       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
7722     }
7723 
7724     // If we can't prove that the sign bit is zero, we must add one to the
7725     // maximum bit width to account for the unknown sign bit. This preserves
7726     // the existing sign bit so we can safely sign-extend the root back to the
7727     // original type. Otherwise, if we know the sign bit is zero, we will
7728     // zero-extend the root instead.
7729     //
7730     // FIXME: This is somewhat suboptimal, as there will be cases where adding
7731     //        one to the maximum bit width will yield a larger-than-necessary
7732     //        type. In general, we need to add an extra bit only if we can't
7733     //        prove that the upper bit of the original type is equal to the
7734     //        upper bit of the proposed smaller type. If these two bits are the
7735     //        same (either zero or one) we know that sign-extending from the
7736     //        smaller type will result in the same value. Here, since we can't
7737     //        yet prove this, we are just making the proposed smaller type
7738     //        larger to ensure correctness.
7739     if (!IsKnownPositive)
7740       ++MaxBitWidth;
7741   }
7742 
7743   // Round MaxBitWidth up to the next power-of-two.
7744   if (!isPowerOf2_64(MaxBitWidth))
7745     MaxBitWidth = NextPowerOf2(MaxBitWidth);
7746 
7747   // If the maximum bit width we compute is less than the with of the roots'
7748   // type, we can proceed with the narrowing. Otherwise, do nothing.
7749   if (MaxBitWidth >= TreeRootIT->getBitWidth())
7750     return;
7751 
7752   // If we can truncate the root, we must collect additional values that might
7753   // be demoted as a result. That is, those seeded by truncations we will
7754   // modify.
7755   while (!Roots.empty())
7756     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
7757 
7758   // Finally, map the values we can demote to the maximum bit with we computed.
7759   for (auto *Scalar : ToDemote)
7760     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
7761 }
7762 
7763 namespace {
7764 
7765 /// The SLPVectorizer Pass.
7766 struct SLPVectorizer : public FunctionPass {
7767   SLPVectorizerPass Impl;
7768 
7769   /// Pass identification, replacement for typeid
7770   static char ID;
7771 
7772   explicit SLPVectorizer() : FunctionPass(ID) {
7773     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
7774   }
7775 
7776   bool doInitialization(Module &M) override { return false; }
7777 
7778   bool runOnFunction(Function &F) override {
7779     if (skipFunction(F))
7780       return false;
7781 
7782     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
7783     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
7784     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7785     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
7786     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
7787     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7788     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7789     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
7790     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
7791     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
7792 
7793     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7794   }
7795 
7796   void getAnalysisUsage(AnalysisUsage &AU) const override {
7797     FunctionPass::getAnalysisUsage(AU);
7798     AU.addRequired<AssumptionCacheTracker>();
7799     AU.addRequired<ScalarEvolutionWrapperPass>();
7800     AU.addRequired<AAResultsWrapperPass>();
7801     AU.addRequired<TargetTransformInfoWrapperPass>();
7802     AU.addRequired<LoopInfoWrapperPass>();
7803     AU.addRequired<DominatorTreeWrapperPass>();
7804     AU.addRequired<DemandedBitsWrapperPass>();
7805     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
7806     AU.addRequired<InjectTLIMappingsLegacy>();
7807     AU.addPreserved<LoopInfoWrapperPass>();
7808     AU.addPreserved<DominatorTreeWrapperPass>();
7809     AU.addPreserved<AAResultsWrapperPass>();
7810     AU.addPreserved<GlobalsAAWrapperPass>();
7811     AU.setPreservesCFG();
7812   }
7813 };
7814 
7815 } // end anonymous namespace
7816 
7817 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
7818   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
7819   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
7820   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
7821   auto *AA = &AM.getResult<AAManager>(F);
7822   auto *LI = &AM.getResult<LoopAnalysis>(F);
7823   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
7824   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
7825   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
7826   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
7827 
7828   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7829   if (!Changed)
7830     return PreservedAnalyses::all();
7831 
7832   PreservedAnalyses PA;
7833   PA.preserveSet<CFGAnalyses>();
7834   return PA;
7835 }
7836 
7837 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
7838                                 TargetTransformInfo *TTI_,
7839                                 TargetLibraryInfo *TLI_, AAResults *AA_,
7840                                 LoopInfo *LI_, DominatorTree *DT_,
7841                                 AssumptionCache *AC_, DemandedBits *DB_,
7842                                 OptimizationRemarkEmitter *ORE_) {
7843   if (!RunSLPVectorization)
7844     return false;
7845   SE = SE_;
7846   TTI = TTI_;
7847   TLI = TLI_;
7848   AA = AA_;
7849   LI = LI_;
7850   DT = DT_;
7851   AC = AC_;
7852   DB = DB_;
7853   DL = &F.getParent()->getDataLayout();
7854 
7855   Stores.clear();
7856   GEPs.clear();
7857   bool Changed = false;
7858 
7859   // If the target claims to have no vector registers don't attempt
7860   // vectorization.
7861   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
7862     return false;
7863 
7864   // Don't vectorize when the attribute NoImplicitFloat is used.
7865   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
7866     return false;
7867 
7868   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
7869 
7870   // Use the bottom up slp vectorizer to construct chains that start with
7871   // store instructions.
7872   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
7873 
7874   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
7875   // delete instructions.
7876 
7877   // Update DFS numbers now so that we can use them for ordering.
7878   DT->updateDFSNumbers();
7879 
7880   // Scan the blocks in the function in post order.
7881   for (auto BB : post_order(&F.getEntryBlock())) {
7882     collectSeedInstructions(BB);
7883 
7884     // Vectorize trees that end at stores.
7885     if (!Stores.empty()) {
7886       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
7887                         << " underlying objects.\n");
7888       Changed |= vectorizeStoreChains(R);
7889     }
7890 
7891     // Vectorize trees that end at reductions.
7892     Changed |= vectorizeChainsInBlock(BB, R);
7893 
7894     // Vectorize the index computations of getelementptr instructions. This
7895     // is primarily intended to catch gather-like idioms ending at
7896     // non-consecutive loads.
7897     if (!GEPs.empty()) {
7898       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
7899                         << " underlying objects.\n");
7900       Changed |= vectorizeGEPIndices(BB, R);
7901     }
7902   }
7903 
7904   if (Changed) {
7905     R.optimizeGatherSequence();
7906     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
7907   }
7908   return Changed;
7909 }
7910 
7911 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
7912                                             unsigned Idx) {
7913   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
7914                     << "\n");
7915   const unsigned Sz = R.getVectorElementSize(Chain[0]);
7916   const unsigned MinVF = R.getMinVecRegSize() / Sz;
7917   unsigned VF = Chain.size();
7918 
7919   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
7920     return false;
7921 
7922   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
7923                     << "\n");
7924 
7925   R.buildTree(Chain);
7926   if (R.isTreeTinyAndNotFullyVectorizable())
7927     return false;
7928   if (R.isLoadCombineCandidate())
7929     return false;
7930   R.reorderTopToBottom();
7931   R.reorderBottomToTop();
7932   R.buildExternalUses();
7933 
7934   R.computeMinimumValueSizes();
7935 
7936   InstructionCost Cost = R.getTreeCost();
7937 
7938   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
7939   if (Cost < -SLPCostThreshold) {
7940     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
7941 
7942     using namespace ore;
7943 
7944     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
7945                                         cast<StoreInst>(Chain[0]))
7946                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
7947                      << " and with tree size "
7948                      << NV("TreeSize", R.getTreeSize()));
7949 
7950     R.vectorizeTree();
7951     return true;
7952   }
7953 
7954   return false;
7955 }
7956 
7957 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
7958                                         BoUpSLP &R) {
7959   // We may run into multiple chains that merge into a single chain. We mark the
7960   // stores that we vectorized so that we don't visit the same store twice.
7961   BoUpSLP::ValueSet VectorizedStores;
7962   bool Changed = false;
7963 
7964   int E = Stores.size();
7965   SmallBitVector Tails(E, false);
7966   int MaxIter = MaxStoreLookup.getValue();
7967   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
7968       E, std::make_pair(E, INT_MAX));
7969   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
7970   int IterCnt;
7971   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
7972                                   &CheckedPairs,
7973                                   &ConsecutiveChain](int K, int Idx) {
7974     if (IterCnt >= MaxIter)
7975       return true;
7976     if (CheckedPairs[Idx].test(K))
7977       return ConsecutiveChain[K].second == 1 &&
7978              ConsecutiveChain[K].first == Idx;
7979     ++IterCnt;
7980     CheckedPairs[Idx].set(K);
7981     CheckedPairs[K].set(Idx);
7982     Optional<int> Diff = getPointersDiff(
7983         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
7984         Stores[Idx]->getValueOperand()->getType(),
7985         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
7986     if (!Diff || *Diff == 0)
7987       return false;
7988     int Val = *Diff;
7989     if (Val < 0) {
7990       if (ConsecutiveChain[Idx].second > -Val) {
7991         Tails.set(K);
7992         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
7993       }
7994       return false;
7995     }
7996     if (ConsecutiveChain[K].second <= Val)
7997       return false;
7998 
7999     Tails.set(Idx);
8000     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8001     return Val == 1;
8002   };
8003   // Do a quadratic search on all of the given stores in reverse order and find
8004   // all of the pairs of stores that follow each other.
8005   for (int Idx = E - 1; Idx >= 0; --Idx) {
8006     // If a store has multiple consecutive store candidates, search according
8007     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8008     // This is because usually pairing with immediate succeeding or preceding
8009     // candidate create the best chance to find slp vectorization opportunity.
8010     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8011     IterCnt = 0;
8012     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8013       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8014           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8015         break;
8016   }
8017 
8018   // Tracks if we tried to vectorize stores starting from the given tail
8019   // already.
8020   SmallBitVector TriedTails(E, false);
8021   // For stores that start but don't end a link in the chain:
8022   for (int Cnt = E; Cnt > 0; --Cnt) {
8023     int I = Cnt - 1;
8024     if (ConsecutiveChain[I].first == E || Tails.test(I))
8025       continue;
8026     // We found a store instr that starts a chain. Now follow the chain and try
8027     // to vectorize it.
8028     BoUpSLP::ValueList Operands;
8029     // Collect the chain into a list.
8030     while (I != E && !VectorizedStores.count(Stores[I])) {
8031       Operands.push_back(Stores[I]);
8032       Tails.set(I);
8033       if (ConsecutiveChain[I].second != 1) {
8034         // Mark the new end in the chain and go back, if required. It might be
8035         // required if the original stores come in reversed order, for example.
8036         if (ConsecutiveChain[I].first != E &&
8037             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8038             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8039           TriedTails.set(I);
8040           Tails.reset(ConsecutiveChain[I].first);
8041           if (Cnt < ConsecutiveChain[I].first + 2)
8042             Cnt = ConsecutiveChain[I].first + 2;
8043         }
8044         break;
8045       }
8046       // Move to the next value in the chain.
8047       I = ConsecutiveChain[I].first;
8048     }
8049     assert(!Operands.empty() && "Expected non-empty list of stores.");
8050 
8051     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8052     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8053     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8054 
8055     unsigned MinVF = R.getMinVF(EltSize);
8056     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8057                               MaxElts);
8058 
8059     // FIXME: Is division-by-2 the correct step? Should we assert that the
8060     // register size is a power-of-2?
8061     unsigned StartIdx = 0;
8062     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8063       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8064         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8065         if (!VectorizedStores.count(Slice.front()) &&
8066             !VectorizedStores.count(Slice.back()) &&
8067             vectorizeStoreChain(Slice, R, Cnt)) {
8068           // Mark the vectorized stores so that we don't vectorize them again.
8069           VectorizedStores.insert(Slice.begin(), Slice.end());
8070           Changed = true;
8071           // If we vectorized initial block, no need to try to vectorize it
8072           // again.
8073           if (Cnt == StartIdx)
8074             StartIdx += Size;
8075           Cnt += Size;
8076           continue;
8077         }
8078         ++Cnt;
8079       }
8080       // Check if the whole array was vectorized already - exit.
8081       if (StartIdx >= Operands.size())
8082         break;
8083     }
8084   }
8085 
8086   return Changed;
8087 }
8088 
8089 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8090   // Initialize the collections. We will make a single pass over the block.
8091   Stores.clear();
8092   GEPs.clear();
8093 
8094   // Visit the store and getelementptr instructions in BB and organize them in
8095   // Stores and GEPs according to the underlying objects of their pointer
8096   // operands.
8097   for (Instruction &I : *BB) {
8098     // Ignore store instructions that are volatile or have a pointer operand
8099     // that doesn't point to a scalar type.
8100     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8101       if (!SI->isSimple())
8102         continue;
8103       if (!isValidElementType(SI->getValueOperand()->getType()))
8104         continue;
8105       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8106     }
8107 
8108     // Ignore getelementptr instructions that have more than one index, a
8109     // constant index, or a pointer operand that doesn't point to a scalar
8110     // type.
8111     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8112       auto Idx = GEP->idx_begin()->get();
8113       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8114         continue;
8115       if (!isValidElementType(Idx->getType()))
8116         continue;
8117       if (GEP->getType()->isVectorTy())
8118         continue;
8119       GEPs[GEP->getPointerOperand()].push_back(GEP);
8120     }
8121   }
8122 }
8123 
8124 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8125   if (!A || !B)
8126     return false;
8127   Value *VL[] = {A, B};
8128   return tryToVectorizeList(VL, R);
8129 }
8130 
8131 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8132                                            bool LimitForRegisterSize) {
8133   if (VL.size() < 2)
8134     return false;
8135 
8136   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8137                     << VL.size() << ".\n");
8138 
8139   // Check that all of the parts are instructions of the same type,
8140   // we permit an alternate opcode via InstructionsState.
8141   InstructionsState S = getSameOpcode(VL);
8142   if (!S.getOpcode())
8143     return false;
8144 
8145   Instruction *I0 = cast<Instruction>(S.OpValue);
8146   // Make sure invalid types (including vector type) are rejected before
8147   // determining vectorization factor for scalar instructions.
8148   for (Value *V : VL) {
8149     Type *Ty = V->getType();
8150     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8151       // NOTE: the following will give user internal llvm type name, which may
8152       // not be useful.
8153       R.getORE()->emit([&]() {
8154         std::string type_str;
8155         llvm::raw_string_ostream rso(type_str);
8156         Ty->print(rso);
8157         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8158                << "Cannot SLP vectorize list: type "
8159                << rso.str() + " is unsupported by vectorizer";
8160       });
8161       return false;
8162     }
8163   }
8164 
8165   unsigned Sz = R.getVectorElementSize(I0);
8166   unsigned MinVF = R.getMinVF(Sz);
8167   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8168   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8169   if (MaxVF < 2) {
8170     R.getORE()->emit([&]() {
8171       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8172              << "Cannot SLP vectorize list: vectorization factor "
8173              << "less than 2 is not supported";
8174     });
8175     return false;
8176   }
8177 
8178   bool Changed = false;
8179   bool CandidateFound = false;
8180   InstructionCost MinCost = SLPCostThreshold.getValue();
8181   Type *ScalarTy = VL[0]->getType();
8182   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8183     ScalarTy = IE->getOperand(1)->getType();
8184 
8185   unsigned NextInst = 0, MaxInst = VL.size();
8186   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8187     // No actual vectorization should happen, if number of parts is the same as
8188     // provided vectorization factor (i.e. the scalar type is used for vector
8189     // code during codegen).
8190     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8191     if (TTI->getNumberOfParts(VecTy) == VF)
8192       continue;
8193     for (unsigned I = NextInst; I < MaxInst; ++I) {
8194       unsigned OpsWidth = 0;
8195 
8196       if (I + VF > MaxInst)
8197         OpsWidth = MaxInst - I;
8198       else
8199         OpsWidth = VF;
8200 
8201       if (!isPowerOf2_32(OpsWidth))
8202         continue;
8203 
8204       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8205           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8206         break;
8207 
8208       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8209       // Check that a previous iteration of this loop did not delete the Value.
8210       if (llvm::any_of(Ops, [&R](Value *V) {
8211             auto *I = dyn_cast<Instruction>(V);
8212             return I && R.isDeleted(I);
8213           }))
8214         continue;
8215 
8216       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8217                         << "\n");
8218 
8219       R.buildTree(Ops);
8220       if (R.isTreeTinyAndNotFullyVectorizable())
8221         continue;
8222       R.reorderTopToBottom();
8223       R.reorderBottomToTop();
8224       R.buildExternalUses();
8225 
8226       R.computeMinimumValueSizes();
8227       InstructionCost Cost = R.getTreeCost();
8228       CandidateFound = true;
8229       MinCost = std::min(MinCost, Cost);
8230 
8231       if (Cost < -SLPCostThreshold) {
8232         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8233         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8234                                                     cast<Instruction>(Ops[0]))
8235                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8236                                  << " and with tree size "
8237                                  << ore::NV("TreeSize", R.getTreeSize()));
8238 
8239         R.vectorizeTree();
8240         // Move to the next bundle.
8241         I += VF - 1;
8242         NextInst = I + 1;
8243         Changed = true;
8244       }
8245     }
8246   }
8247 
8248   if (!Changed && CandidateFound) {
8249     R.getORE()->emit([&]() {
8250       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8251              << "List vectorization was possible but not beneficial with cost "
8252              << ore::NV("Cost", MinCost) << " >= "
8253              << ore::NV("Treshold", -SLPCostThreshold);
8254     });
8255   } else if (!Changed) {
8256     R.getORE()->emit([&]() {
8257       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8258              << "Cannot SLP vectorize list: vectorization was impossible"
8259              << " with available vectorization factors";
8260     });
8261   }
8262   return Changed;
8263 }
8264 
8265 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8266   if (!I)
8267     return false;
8268 
8269   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8270     return false;
8271 
8272   Value *P = I->getParent();
8273 
8274   // Vectorize in current basic block only.
8275   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8276   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8277   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8278     return false;
8279 
8280   // Try to vectorize V.
8281   if (tryToVectorizePair(Op0, Op1, R))
8282     return true;
8283 
8284   auto *A = dyn_cast<BinaryOperator>(Op0);
8285   auto *B = dyn_cast<BinaryOperator>(Op1);
8286   // Try to skip B.
8287   if (B && B->hasOneUse()) {
8288     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8289     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8290     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8291       return true;
8292     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8293       return true;
8294   }
8295 
8296   // Try to skip A.
8297   if (A && A->hasOneUse()) {
8298     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8299     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8300     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8301       return true;
8302     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8303       return true;
8304   }
8305   return false;
8306 }
8307 
8308 namespace {
8309 
8310 /// Model horizontal reductions.
8311 ///
8312 /// A horizontal reduction is a tree of reduction instructions that has values
8313 /// that can be put into a vector as its leaves. For example:
8314 ///
8315 /// mul mul mul mul
8316 ///  \  /    \  /
8317 ///   +       +
8318 ///    \     /
8319 ///       +
8320 /// This tree has "mul" as its leaf values and "+" as its reduction
8321 /// instructions. A reduction can feed into a store or a binary operation
8322 /// feeding a phi.
8323 ///    ...
8324 ///    \  /
8325 ///     +
8326 ///     |
8327 ///  phi +=
8328 ///
8329 ///  Or:
8330 ///    ...
8331 ///    \  /
8332 ///     +
8333 ///     |
8334 ///   *p =
8335 ///
8336 class HorizontalReduction {
8337   using ReductionOpsType = SmallVector<Value *, 16>;
8338   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8339   ReductionOpsListType ReductionOps;
8340   SmallVector<Value *, 32> ReducedVals;
8341   // Use map vector to make stable output.
8342   MapVector<Instruction *, Value *> ExtraArgs;
8343   WeakTrackingVH ReductionRoot;
8344   /// The type of reduction operation.
8345   RecurKind RdxKind;
8346 
8347   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8348 
8349   static bool isCmpSelMinMax(Instruction *I) {
8350     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8351            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8352   }
8353 
8354   // And/or are potentially poison-safe logical patterns like:
8355   // select x, y, false
8356   // select x, true, y
8357   static bool isBoolLogicOp(Instruction *I) {
8358     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8359            match(I, m_LogicalOr(m_Value(), m_Value()));
8360   }
8361 
8362   /// Checks if instruction is associative and can be vectorized.
8363   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8364     if (Kind == RecurKind::None)
8365       return false;
8366 
8367     // Integer ops that map to select instructions or intrinsics are fine.
8368     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8369         isBoolLogicOp(I))
8370       return true;
8371 
8372     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8373       // FP min/max are associative except for NaN and -0.0. We do not
8374       // have to rule out -0.0 here because the intrinsic semantics do not
8375       // specify a fixed result for it.
8376       return I->getFastMathFlags().noNaNs();
8377     }
8378 
8379     return I->isAssociative();
8380   }
8381 
8382   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8383     // Poison-safe 'or' takes the form: select X, true, Y
8384     // To make that work with the normal operand processing, we skip the
8385     // true value operand.
8386     // TODO: Change the code and data structures to handle this without a hack.
8387     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8388       return I->getOperand(2);
8389     return I->getOperand(Index);
8390   }
8391 
8392   /// Checks if the ParentStackElem.first should be marked as a reduction
8393   /// operation with an extra argument or as extra argument itself.
8394   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8395                     Value *ExtraArg) {
8396     if (ExtraArgs.count(ParentStackElem.first)) {
8397       ExtraArgs[ParentStackElem.first] = nullptr;
8398       // We ran into something like:
8399       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8400       // The whole ParentStackElem.first should be considered as an extra value
8401       // in this case.
8402       // Do not perform analysis of remaining operands of ParentStackElem.first
8403       // instruction, this whole instruction is an extra argument.
8404       ParentStackElem.second = INVALID_OPERAND_INDEX;
8405     } else {
8406       // We ran into something like:
8407       // ParentStackElem.first += ... + ExtraArg + ...
8408       ExtraArgs[ParentStackElem.first] = ExtraArg;
8409     }
8410   }
8411 
8412   /// Creates reduction operation with the current opcode.
8413   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8414                          Value *RHS, const Twine &Name, bool UseSelect) {
8415     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8416     switch (Kind) {
8417     case RecurKind::Or:
8418       if (UseSelect &&
8419           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8420         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8421       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8422                                  Name);
8423     case RecurKind::And:
8424       if (UseSelect &&
8425           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8426         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8427       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8428                                  Name);
8429     case RecurKind::Add:
8430     case RecurKind::Mul:
8431     case RecurKind::Xor:
8432     case RecurKind::FAdd:
8433     case RecurKind::FMul:
8434       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8435                                  Name);
8436     case RecurKind::FMax:
8437       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8438     case RecurKind::FMin:
8439       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8440     case RecurKind::SMax:
8441       if (UseSelect) {
8442         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8443         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8444       }
8445       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8446     case RecurKind::SMin:
8447       if (UseSelect) {
8448         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8449         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8450       }
8451       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8452     case RecurKind::UMax:
8453       if (UseSelect) {
8454         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8455         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8456       }
8457       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8458     case RecurKind::UMin:
8459       if (UseSelect) {
8460         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8461         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8462       }
8463       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8464     default:
8465       llvm_unreachable("Unknown reduction operation.");
8466     }
8467   }
8468 
8469   /// Creates reduction operation with the current opcode with the IR flags
8470   /// from \p ReductionOps.
8471   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8472                          Value *RHS, const Twine &Name,
8473                          const ReductionOpsListType &ReductionOps) {
8474     bool UseSelect = ReductionOps.size() == 2 ||
8475                      // Logical or/and.
8476                      (ReductionOps.size() == 1 &&
8477                       isa<SelectInst>(ReductionOps.front().front()));
8478     assert((!UseSelect || ReductionOps.size() != 2 ||
8479             isa<SelectInst>(ReductionOps[1][0])) &&
8480            "Expected cmp + select pairs for reduction");
8481     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8482     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8483       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8484         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8485         propagateIRFlags(Op, ReductionOps[1]);
8486         return Op;
8487       }
8488     }
8489     propagateIRFlags(Op, ReductionOps[0]);
8490     return Op;
8491   }
8492 
8493   /// Creates reduction operation with the current opcode with the IR flags
8494   /// from \p I.
8495   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8496                          Value *RHS, const Twine &Name, Instruction *I) {
8497     auto *SelI = dyn_cast<SelectInst>(I);
8498     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8499     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8500       if (auto *Sel = dyn_cast<SelectInst>(Op))
8501         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8502     }
8503     propagateIRFlags(Op, I);
8504     return Op;
8505   }
8506 
8507   static RecurKind getRdxKind(Instruction *I) {
8508     assert(I && "Expected instruction for reduction matching");
8509     TargetTransformInfo::ReductionFlags RdxFlags;
8510     if (match(I, m_Add(m_Value(), m_Value())))
8511       return RecurKind::Add;
8512     if (match(I, m_Mul(m_Value(), m_Value())))
8513       return RecurKind::Mul;
8514     if (match(I, m_And(m_Value(), m_Value())) ||
8515         match(I, m_LogicalAnd(m_Value(), m_Value())))
8516       return RecurKind::And;
8517     if (match(I, m_Or(m_Value(), m_Value())) ||
8518         match(I, m_LogicalOr(m_Value(), m_Value())))
8519       return RecurKind::Or;
8520     if (match(I, m_Xor(m_Value(), m_Value())))
8521       return RecurKind::Xor;
8522     if (match(I, m_FAdd(m_Value(), m_Value())))
8523       return RecurKind::FAdd;
8524     if (match(I, m_FMul(m_Value(), m_Value())))
8525       return RecurKind::FMul;
8526 
8527     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8528       return RecurKind::FMax;
8529     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8530       return RecurKind::FMin;
8531 
8532     // This matches either cmp+select or intrinsics. SLP is expected to handle
8533     // either form.
8534     // TODO: If we are canonicalizing to intrinsics, we can remove several
8535     //       special-case paths that deal with selects.
8536     if (match(I, m_SMax(m_Value(), m_Value())))
8537       return RecurKind::SMax;
8538     if (match(I, m_SMin(m_Value(), m_Value())))
8539       return RecurKind::SMin;
8540     if (match(I, m_UMax(m_Value(), m_Value())))
8541       return RecurKind::UMax;
8542     if (match(I, m_UMin(m_Value(), m_Value())))
8543       return RecurKind::UMin;
8544 
8545     if (auto *Select = dyn_cast<SelectInst>(I)) {
8546       // Try harder: look for min/max pattern based on instructions producing
8547       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8548       // During the intermediate stages of SLP, it's very common to have
8549       // pattern like this (since optimizeGatherSequence is run only once
8550       // at the end):
8551       // %1 = extractelement <2 x i32> %a, i32 0
8552       // %2 = extractelement <2 x i32> %a, i32 1
8553       // %cond = icmp sgt i32 %1, %2
8554       // %3 = extractelement <2 x i32> %a, i32 0
8555       // %4 = extractelement <2 x i32> %a, i32 1
8556       // %select = select i1 %cond, i32 %3, i32 %4
8557       CmpInst::Predicate Pred;
8558       Instruction *L1;
8559       Instruction *L2;
8560 
8561       Value *LHS = Select->getTrueValue();
8562       Value *RHS = Select->getFalseValue();
8563       Value *Cond = Select->getCondition();
8564 
8565       // TODO: Support inverse predicates.
8566       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8567         if (!isa<ExtractElementInst>(RHS) ||
8568             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8569           return RecurKind::None;
8570       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8571         if (!isa<ExtractElementInst>(LHS) ||
8572             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8573           return RecurKind::None;
8574       } else {
8575         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8576           return RecurKind::None;
8577         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8578             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8579             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8580           return RecurKind::None;
8581       }
8582 
8583       TargetTransformInfo::ReductionFlags RdxFlags;
8584       switch (Pred) {
8585       default:
8586         return RecurKind::None;
8587       case CmpInst::ICMP_SGT:
8588       case CmpInst::ICMP_SGE:
8589         return RecurKind::SMax;
8590       case CmpInst::ICMP_SLT:
8591       case CmpInst::ICMP_SLE:
8592         return RecurKind::SMin;
8593       case CmpInst::ICMP_UGT:
8594       case CmpInst::ICMP_UGE:
8595         return RecurKind::UMax;
8596       case CmpInst::ICMP_ULT:
8597       case CmpInst::ICMP_ULE:
8598         return RecurKind::UMin;
8599       }
8600     }
8601     return RecurKind::None;
8602   }
8603 
8604   /// Get the index of the first operand.
8605   static unsigned getFirstOperandIndex(Instruction *I) {
8606     return isCmpSelMinMax(I) ? 1 : 0;
8607   }
8608 
8609   /// Total number of operands in the reduction operation.
8610   static unsigned getNumberOfOperands(Instruction *I) {
8611     return isCmpSelMinMax(I) ? 3 : 2;
8612   }
8613 
8614   /// Checks if the instruction is in basic block \p BB.
8615   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8616   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8617     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
8618       auto *Sel = cast<SelectInst>(I);
8619       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
8620       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
8621     }
8622     return I->getParent() == BB;
8623   }
8624 
8625   /// Expected number of uses for reduction operations/reduced values.
8626   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
8627     if (IsCmpSelMinMax) {
8628       // SelectInst must be used twice while the condition op must have single
8629       // use only.
8630       if (auto *Sel = dyn_cast<SelectInst>(I))
8631         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
8632       return I->hasNUses(2);
8633     }
8634 
8635     // Arithmetic reduction operation must be used once only.
8636     return I->hasOneUse();
8637   }
8638 
8639   /// Initializes the list of reduction operations.
8640   void initReductionOps(Instruction *I) {
8641     if (isCmpSelMinMax(I))
8642       ReductionOps.assign(2, ReductionOpsType());
8643     else
8644       ReductionOps.assign(1, ReductionOpsType());
8645   }
8646 
8647   /// Add all reduction operations for the reduction instruction \p I.
8648   void addReductionOps(Instruction *I) {
8649     if (isCmpSelMinMax(I)) {
8650       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
8651       ReductionOps[1].emplace_back(I);
8652     } else {
8653       ReductionOps[0].emplace_back(I);
8654     }
8655   }
8656 
8657   static Value *getLHS(RecurKind Kind, Instruction *I) {
8658     if (Kind == RecurKind::None)
8659       return nullptr;
8660     return I->getOperand(getFirstOperandIndex(I));
8661   }
8662   static Value *getRHS(RecurKind Kind, Instruction *I) {
8663     if (Kind == RecurKind::None)
8664       return nullptr;
8665     return I->getOperand(getFirstOperandIndex(I) + 1);
8666   }
8667 
8668 public:
8669   HorizontalReduction() = default;
8670 
8671   /// Try to find a reduction tree.
8672   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
8673     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
8674            "Phi needs to use the binary operator");
8675     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
8676             isa<IntrinsicInst>(Inst)) &&
8677            "Expected binop, select, or intrinsic for reduction matching");
8678     RdxKind = getRdxKind(Inst);
8679 
8680     // We could have a initial reductions that is not an add.
8681     //  r *= v1 + v2 + v3 + v4
8682     // In such a case start looking for a tree rooted in the first '+'.
8683     if (Phi) {
8684       if (getLHS(RdxKind, Inst) == Phi) {
8685         Phi = nullptr;
8686         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
8687         if (!Inst)
8688           return false;
8689         RdxKind = getRdxKind(Inst);
8690       } else if (getRHS(RdxKind, Inst) == Phi) {
8691         Phi = nullptr;
8692         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
8693         if (!Inst)
8694           return false;
8695         RdxKind = getRdxKind(Inst);
8696       }
8697     }
8698 
8699     if (!isVectorizable(RdxKind, Inst))
8700       return false;
8701 
8702     // Analyze "regular" integer/FP types for reductions - no target-specific
8703     // types or pointers.
8704     Type *Ty = Inst->getType();
8705     if (!isValidElementType(Ty) || Ty->isPointerTy())
8706       return false;
8707 
8708     // Though the ultimate reduction may have multiple uses, its condition must
8709     // have only single use.
8710     if (auto *Sel = dyn_cast<SelectInst>(Inst))
8711       if (!Sel->getCondition()->hasOneUse())
8712         return false;
8713 
8714     ReductionRoot = Inst;
8715 
8716     // The opcode for leaf values that we perform a reduction on.
8717     // For example: load(x) + load(y) + load(z) + fptoui(w)
8718     // The leaf opcode for 'w' does not match, so we don't include it as a
8719     // potential candidate for the reduction.
8720     unsigned LeafOpcode = 0;
8721 
8722     // Post-order traverse the reduction tree starting at Inst. We only handle
8723     // true trees containing binary operators or selects.
8724     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
8725     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
8726     initReductionOps(Inst);
8727     while (!Stack.empty()) {
8728       Instruction *TreeN = Stack.back().first;
8729       unsigned EdgeToVisit = Stack.back().second++;
8730       const RecurKind TreeRdxKind = getRdxKind(TreeN);
8731       bool IsReducedValue = TreeRdxKind != RdxKind;
8732 
8733       // Postorder visit.
8734       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
8735         if (IsReducedValue)
8736           ReducedVals.push_back(TreeN);
8737         else {
8738           auto ExtraArgsIter = ExtraArgs.find(TreeN);
8739           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
8740             // Check if TreeN is an extra argument of its parent operation.
8741             if (Stack.size() <= 1) {
8742               // TreeN can't be an extra argument as it is a root reduction
8743               // operation.
8744               return false;
8745             }
8746             // Yes, TreeN is an extra argument, do not add it to a list of
8747             // reduction operations.
8748             // Stack[Stack.size() - 2] always points to the parent operation.
8749             markExtraArg(Stack[Stack.size() - 2], TreeN);
8750             ExtraArgs.erase(TreeN);
8751           } else
8752             addReductionOps(TreeN);
8753         }
8754         // Retract.
8755         Stack.pop_back();
8756         continue;
8757       }
8758 
8759       // Visit operands.
8760       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
8761       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
8762       if (!EdgeInst) {
8763         // Edge value is not a reduction instruction or a leaf instruction.
8764         // (It may be a constant, function argument, or something else.)
8765         markExtraArg(Stack.back(), EdgeVal);
8766         continue;
8767       }
8768       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
8769       // Continue analysis if the next operand is a reduction operation or
8770       // (possibly) a leaf value. If the leaf value opcode is not set,
8771       // the first met operation != reduction operation is considered as the
8772       // leaf opcode.
8773       // Only handle trees in the current basic block.
8774       // Each tree node needs to have minimal number of users except for the
8775       // ultimate reduction.
8776       const bool IsRdxInst = EdgeRdxKind == RdxKind;
8777       if (EdgeInst != Phi && EdgeInst != Inst &&
8778           hasSameParent(EdgeInst, Inst->getParent()) &&
8779           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
8780           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
8781         if (IsRdxInst) {
8782           // We need to be able to reassociate the reduction operations.
8783           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
8784             // I is an extra argument for TreeN (its parent operation).
8785             markExtraArg(Stack.back(), EdgeInst);
8786             continue;
8787           }
8788         } else if (!LeafOpcode) {
8789           LeafOpcode = EdgeInst->getOpcode();
8790         }
8791         Stack.push_back(
8792             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
8793         continue;
8794       }
8795       // I is an extra argument for TreeN (its parent operation).
8796       markExtraArg(Stack.back(), EdgeInst);
8797     }
8798     return true;
8799   }
8800 
8801   /// Attempt to vectorize the tree found by matchAssociativeReduction.
8802   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
8803     // If there are a sufficient number of reduction values, reduce
8804     // to a nearby power-of-2. We can safely generate oversized
8805     // vectors and rely on the backend to split them to legal sizes.
8806     unsigned NumReducedVals = ReducedVals.size();
8807     if (NumReducedVals < 4)
8808       return nullptr;
8809 
8810     // Intersect the fast-math-flags from all reduction operations.
8811     FastMathFlags RdxFMF;
8812     RdxFMF.set();
8813     for (ReductionOpsType &RdxOp : ReductionOps) {
8814       for (Value *RdxVal : RdxOp) {
8815         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
8816           RdxFMF &= FPMO->getFastMathFlags();
8817       }
8818     }
8819 
8820     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
8821     Builder.setFastMathFlags(RdxFMF);
8822 
8823     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
8824     // The same extra argument may be used several times, so log each attempt
8825     // to use it.
8826     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
8827       assert(Pair.first && "DebugLoc must be set.");
8828       ExternallyUsedValues[Pair.second].push_back(Pair.first);
8829     }
8830 
8831     // The compare instruction of a min/max is the insertion point for new
8832     // instructions and may be replaced with a new compare instruction.
8833     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
8834       assert(isa<SelectInst>(RdxRootInst) &&
8835              "Expected min/max reduction to have select root instruction");
8836       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
8837       assert(isa<Instruction>(ScalarCond) &&
8838              "Expected min/max reduction to have compare condition");
8839       return cast<Instruction>(ScalarCond);
8840     };
8841 
8842     // The reduction root is used as the insertion point for new instructions,
8843     // so set it as externally used to prevent it from being deleted.
8844     ExternallyUsedValues[ReductionRoot];
8845     SmallVector<Value *, 16> IgnoreList;
8846     for (ReductionOpsType &RdxOp : ReductionOps)
8847       IgnoreList.append(RdxOp.begin(), RdxOp.end());
8848 
8849     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
8850     if (NumReducedVals > ReduxWidth) {
8851       // In the loop below, we are building a tree based on a window of
8852       // 'ReduxWidth' values.
8853       // If the operands of those values have common traits (compare predicate,
8854       // constant operand, etc), then we want to group those together to
8855       // minimize the cost of the reduction.
8856 
8857       // TODO: This should be extended to count common operands for
8858       //       compares and binops.
8859 
8860       // Step 1: Count the number of times each compare predicate occurs.
8861       SmallDenseMap<unsigned, unsigned> PredCountMap;
8862       for (Value *RdxVal : ReducedVals) {
8863         CmpInst::Predicate Pred;
8864         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
8865           ++PredCountMap[Pred];
8866       }
8867       // Step 2: Sort the values so the most common predicates come first.
8868       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
8869         CmpInst::Predicate PredA, PredB;
8870         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
8871             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
8872           return PredCountMap[PredA] > PredCountMap[PredB];
8873         }
8874         return false;
8875       });
8876     }
8877 
8878     Value *VectorizedTree = nullptr;
8879     unsigned i = 0;
8880     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
8881       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
8882       V.buildTree(VL, IgnoreList);
8883       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
8884         break;
8885       if (V.isLoadCombineReductionCandidate(RdxKind))
8886         break;
8887       V.reorderTopToBottom();
8888       V.reorderBottomToTop(/*IgnoreReorder=*/true);
8889       V.buildExternalUses(ExternallyUsedValues);
8890 
8891       // For a poison-safe boolean logic reduction, do not replace select
8892       // instructions with logic ops. All reduced values will be frozen (see
8893       // below) to prevent leaking poison.
8894       if (isa<SelectInst>(ReductionRoot) &&
8895           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
8896           NumReducedVals != ReduxWidth)
8897         break;
8898 
8899       V.computeMinimumValueSizes();
8900 
8901       // Estimate cost.
8902       InstructionCost TreeCost =
8903           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
8904       InstructionCost ReductionCost =
8905           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
8906       InstructionCost Cost = TreeCost + ReductionCost;
8907       if (!Cost.isValid()) {
8908         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
8909         return nullptr;
8910       }
8911       if (Cost >= -SLPCostThreshold) {
8912         V.getORE()->emit([&]() {
8913           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
8914                                           cast<Instruction>(VL[0]))
8915                  << "Vectorizing horizontal reduction is possible"
8916                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
8917                  << " and threshold "
8918                  << ore::NV("Threshold", -SLPCostThreshold);
8919         });
8920         break;
8921       }
8922 
8923       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
8924                         << Cost << ". (HorRdx)\n");
8925       V.getORE()->emit([&]() {
8926         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
8927                                   cast<Instruction>(VL[0]))
8928                << "Vectorized horizontal reduction with cost "
8929                << ore::NV("Cost", Cost) << " and with tree size "
8930                << ore::NV("TreeSize", V.getTreeSize());
8931       });
8932 
8933       // Vectorize a tree.
8934       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
8935       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
8936 
8937       // Emit a reduction. If the root is a select (min/max idiom), the insert
8938       // point is the compare condition of that select.
8939       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
8940       if (isCmpSelMinMax(RdxRootInst))
8941         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
8942       else
8943         Builder.SetInsertPoint(RdxRootInst);
8944 
8945       // To prevent poison from leaking across what used to be sequential, safe,
8946       // scalar boolean logic operations, the reduction operand must be frozen.
8947       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
8948         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
8949 
8950       Value *ReducedSubTree =
8951           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
8952 
8953       if (!VectorizedTree) {
8954         // Initialize the final value in the reduction.
8955         VectorizedTree = ReducedSubTree;
8956       } else {
8957         // Update the final value in the reduction.
8958         Builder.SetCurrentDebugLocation(Loc);
8959         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8960                                   ReducedSubTree, "op.rdx", ReductionOps);
8961       }
8962       i += ReduxWidth;
8963       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
8964     }
8965 
8966     if (VectorizedTree) {
8967       // Finish the reduction.
8968       for (; i < NumReducedVals; ++i) {
8969         auto *I = cast<Instruction>(ReducedVals[i]);
8970         Builder.SetCurrentDebugLocation(I->getDebugLoc());
8971         VectorizedTree =
8972             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
8973       }
8974       for (auto &Pair : ExternallyUsedValues) {
8975         // Add each externally used value to the final reduction.
8976         for (auto *I : Pair.second) {
8977           Builder.SetCurrentDebugLocation(I->getDebugLoc());
8978           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8979                                     Pair.first, "op.extra", I);
8980         }
8981       }
8982 
8983       ReductionRoot->replaceAllUsesWith(VectorizedTree);
8984 
8985       // Mark all scalar reduction ops for deletion, they are replaced by the
8986       // vector reductions.
8987       V.eraseInstructions(IgnoreList);
8988     }
8989     return VectorizedTree;
8990   }
8991 
8992   unsigned numReductionValues() const { return ReducedVals.size(); }
8993 
8994 private:
8995   /// Calculate the cost of a reduction.
8996   InstructionCost getReductionCost(TargetTransformInfo *TTI,
8997                                    Value *FirstReducedVal, unsigned ReduxWidth,
8998                                    FastMathFlags FMF) {
8999     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9000     Type *ScalarTy = FirstReducedVal->getType();
9001     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9002     InstructionCost VectorCost, ScalarCost;
9003     switch (RdxKind) {
9004     case RecurKind::Add:
9005     case RecurKind::Mul:
9006     case RecurKind::Or:
9007     case RecurKind::And:
9008     case RecurKind::Xor:
9009     case RecurKind::FAdd:
9010     case RecurKind::FMul: {
9011       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9012       VectorCost =
9013           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9014       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9015       break;
9016     }
9017     case RecurKind::FMax:
9018     case RecurKind::FMin: {
9019       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9020       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9021       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9022                                                /*unsigned=*/false, CostKind);
9023       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9024       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9025                                            SclCondTy, RdxPred, CostKind) +
9026                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9027                                            SclCondTy, RdxPred, CostKind);
9028       break;
9029     }
9030     case RecurKind::SMax:
9031     case RecurKind::SMin:
9032     case RecurKind::UMax:
9033     case RecurKind::UMin: {
9034       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9035       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9036       bool IsUnsigned =
9037           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9038       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9039                                                CostKind);
9040       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9041       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9042                                            SclCondTy, RdxPred, CostKind) +
9043                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9044                                            SclCondTy, RdxPred, CostKind);
9045       break;
9046     }
9047     default:
9048       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9049     }
9050 
9051     // Scalar cost is repeated for N-1 elements.
9052     ScalarCost *= (ReduxWidth - 1);
9053     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9054                       << " for reduction that starts with " << *FirstReducedVal
9055                       << " (It is a splitting reduction)\n");
9056     return VectorCost - ScalarCost;
9057   }
9058 
9059   /// Emit a horizontal reduction of the vectorized value.
9060   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9061                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9062     assert(VectorizedValue && "Need to have a vectorized tree node");
9063     assert(isPowerOf2_32(ReduxWidth) &&
9064            "We only handle power-of-two reductions for now");
9065     assert(RdxKind != RecurKind::FMulAdd &&
9066            "A call to the llvm.fmuladd intrinsic is not handled yet");
9067 
9068     ++NumVectorInstructions;
9069     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind,
9070                                        ReductionOps.back());
9071   }
9072 };
9073 
9074 } // end anonymous namespace
9075 
9076 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9077   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9078     return cast<FixedVectorType>(IE->getType())->getNumElements();
9079 
9080   unsigned AggregateSize = 1;
9081   auto *IV = cast<InsertValueInst>(InsertInst);
9082   Type *CurrentType = IV->getType();
9083   do {
9084     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9085       for (auto *Elt : ST->elements())
9086         if (Elt != ST->getElementType(0)) // check homogeneity
9087           return None;
9088       AggregateSize *= ST->getNumElements();
9089       CurrentType = ST->getElementType(0);
9090     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9091       AggregateSize *= AT->getNumElements();
9092       CurrentType = AT->getElementType();
9093     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9094       AggregateSize *= VT->getNumElements();
9095       return AggregateSize;
9096     } else if (CurrentType->isSingleValueType()) {
9097       return AggregateSize;
9098     } else {
9099       return None;
9100     }
9101   } while (true);
9102 }
9103 
9104 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9105                                    TargetTransformInfo *TTI,
9106                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9107                                    SmallVectorImpl<Value *> &InsertElts,
9108                                    unsigned OperandOffset) {
9109   do {
9110     Value *InsertedOperand = LastInsertInst->getOperand(1);
9111     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9112     if (!OperandIndex)
9113       return false;
9114     if (isa<InsertElementInst>(InsertedOperand) ||
9115         isa<InsertValueInst>(InsertedOperand)) {
9116       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9117                                   BuildVectorOpds, InsertElts, *OperandIndex))
9118         return false;
9119     } else {
9120       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9121       InsertElts[*OperandIndex] = LastInsertInst;
9122     }
9123     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9124   } while (LastInsertInst != nullptr &&
9125            (isa<InsertValueInst>(LastInsertInst) ||
9126             isa<InsertElementInst>(LastInsertInst)) &&
9127            LastInsertInst->hasOneUse());
9128   return true;
9129 }
9130 
9131 /// Recognize construction of vectors like
9132 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9133 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9134 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9135 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9136 ///  starting from the last insertelement or insertvalue instruction.
9137 ///
9138 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9139 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9140 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9141 ///
9142 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9143 ///
9144 /// \return true if it matches.
9145 static bool findBuildAggregate(Instruction *LastInsertInst,
9146                                TargetTransformInfo *TTI,
9147                                SmallVectorImpl<Value *> &BuildVectorOpds,
9148                                SmallVectorImpl<Value *> &InsertElts) {
9149 
9150   assert((isa<InsertElementInst>(LastInsertInst) ||
9151           isa<InsertValueInst>(LastInsertInst)) &&
9152          "Expected insertelement or insertvalue instruction!");
9153 
9154   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9155          "Expected empty result vectors!");
9156 
9157   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9158   if (!AggregateSize)
9159     return false;
9160   BuildVectorOpds.resize(*AggregateSize);
9161   InsertElts.resize(*AggregateSize);
9162 
9163   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9164                              0)) {
9165     llvm::erase_value(BuildVectorOpds, nullptr);
9166     llvm::erase_value(InsertElts, nullptr);
9167     if (BuildVectorOpds.size() >= 2)
9168       return true;
9169   }
9170 
9171   return false;
9172 }
9173 
9174 /// Try and get a reduction value from a phi node.
9175 ///
9176 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9177 /// if they come from either \p ParentBB or a containing loop latch.
9178 ///
9179 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9180 /// if not possible.
9181 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9182                                 BasicBlock *ParentBB, LoopInfo *LI) {
9183   // There are situations where the reduction value is not dominated by the
9184   // reduction phi. Vectorizing such cases has been reported to cause
9185   // miscompiles. See PR25787.
9186   auto DominatedReduxValue = [&](Value *R) {
9187     return isa<Instruction>(R) &&
9188            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9189   };
9190 
9191   Value *Rdx = nullptr;
9192 
9193   // Return the incoming value if it comes from the same BB as the phi node.
9194   if (P->getIncomingBlock(0) == ParentBB) {
9195     Rdx = P->getIncomingValue(0);
9196   } else if (P->getIncomingBlock(1) == ParentBB) {
9197     Rdx = P->getIncomingValue(1);
9198   }
9199 
9200   if (Rdx && DominatedReduxValue(Rdx))
9201     return Rdx;
9202 
9203   // Otherwise, check whether we have a loop latch to look at.
9204   Loop *BBL = LI->getLoopFor(ParentBB);
9205   if (!BBL)
9206     return nullptr;
9207   BasicBlock *BBLatch = BBL->getLoopLatch();
9208   if (!BBLatch)
9209     return nullptr;
9210 
9211   // There is a loop latch, return the incoming value if it comes from
9212   // that. This reduction pattern occasionally turns up.
9213   if (P->getIncomingBlock(0) == BBLatch) {
9214     Rdx = P->getIncomingValue(0);
9215   } else if (P->getIncomingBlock(1) == BBLatch) {
9216     Rdx = P->getIncomingValue(1);
9217   }
9218 
9219   if (Rdx && DominatedReduxValue(Rdx))
9220     return Rdx;
9221 
9222   return nullptr;
9223 }
9224 
9225 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9226   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9227     return true;
9228   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9229     return true;
9230   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9231     return true;
9232   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9233     return true;
9234   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9235     return true;
9236   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9237     return true;
9238   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9239     return true;
9240   return false;
9241 }
9242 
9243 /// Attempt to reduce a horizontal reduction.
9244 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9245 /// with reduction operators \a Root (or one of its operands) in a basic block
9246 /// \a BB, then check if it can be done. If horizontal reduction is not found
9247 /// and root instruction is a binary operation, vectorization of the operands is
9248 /// attempted.
9249 /// \returns true if a horizontal reduction was matched and reduced or operands
9250 /// of one of the binary instruction were vectorized.
9251 /// \returns false if a horizontal reduction was not matched (or not possible)
9252 /// or no vectorization of any binary operation feeding \a Root instruction was
9253 /// performed.
9254 static bool tryToVectorizeHorReductionOrInstOperands(
9255     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9256     TargetTransformInfo *TTI,
9257     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9258   if (!ShouldVectorizeHor)
9259     return false;
9260 
9261   if (!Root)
9262     return false;
9263 
9264   if (Root->getParent() != BB || isa<PHINode>(Root))
9265     return false;
9266   // Start analysis starting from Root instruction. If horizontal reduction is
9267   // found, try to vectorize it. If it is not a horizontal reduction or
9268   // vectorization is not possible or not effective, and currently analyzed
9269   // instruction is a binary operation, try to vectorize the operands, using
9270   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9271   // the same procedure considering each operand as a possible root of the
9272   // horizontal reduction.
9273   // Interrupt the process if the Root instruction itself was vectorized or all
9274   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9275   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9276   // CmpInsts so we can skip extra attempts in
9277   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9278   std::queue<std::pair<Instruction *, unsigned>> Stack;
9279   Stack.emplace(Root, 0);
9280   SmallPtrSet<Value *, 8> VisitedInstrs;
9281   SmallVector<WeakTrackingVH> PostponedInsts;
9282   bool Res = false;
9283   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9284                                      Value *&B1) -> Value * {
9285     bool IsBinop = matchRdxBop(Inst, B0, B1);
9286     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9287     if (IsBinop || IsSelect) {
9288       HorizontalReduction HorRdx;
9289       if (HorRdx.matchAssociativeReduction(P, Inst))
9290         return HorRdx.tryToReduce(R, TTI);
9291     }
9292     return nullptr;
9293   };
9294   while (!Stack.empty()) {
9295     Instruction *Inst;
9296     unsigned Level;
9297     std::tie(Inst, Level) = Stack.front();
9298     Stack.pop();
9299     // Do not try to analyze instruction that has already been vectorized.
9300     // This may happen when we vectorize instruction operands on a previous
9301     // iteration while stack was populated before that happened.
9302     if (R.isDeleted(Inst))
9303       continue;
9304     Value *B0 = nullptr, *B1 = nullptr;
9305     if (Value *V = TryToReduce(Inst, B0, B1)) {
9306       Res = true;
9307       // Set P to nullptr to avoid re-analysis of phi node in
9308       // matchAssociativeReduction function unless this is the root node.
9309       P = nullptr;
9310       if (auto *I = dyn_cast<Instruction>(V)) {
9311         // Try to find another reduction.
9312         Stack.emplace(I, Level);
9313         continue;
9314       }
9315     } else {
9316       bool IsBinop = B0 && B1;
9317       if (P && IsBinop) {
9318         Inst = dyn_cast<Instruction>(B0);
9319         if (Inst == P)
9320           Inst = dyn_cast<Instruction>(B1);
9321         if (!Inst) {
9322           // Set P to nullptr to avoid re-analysis of phi node in
9323           // matchAssociativeReduction function unless this is the root node.
9324           P = nullptr;
9325           continue;
9326         }
9327       }
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       // Do not try to vectorize CmpInst operands, this is done separately.
9332       // Final attempt for binop args vectorization should happen after the loop
9333       // to try to find reductions.
9334       if (!isa<CmpInst>(Inst))
9335         PostponedInsts.push_back(Inst);
9336     }
9337 
9338     // Try to vectorize operands.
9339     // Continue analysis for the instruction from the same basic block only to
9340     // save compile time.
9341     if (++Level < RecursionMaxDepth)
9342       for (auto *Op : Inst->operand_values())
9343         if (VisitedInstrs.insert(Op).second)
9344           if (auto *I = dyn_cast<Instruction>(Op))
9345             // Do not try to vectorize CmpInst operands,  this is done
9346             // separately.
9347             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9348                 I->getParent() == BB)
9349               Stack.emplace(I, Level);
9350   }
9351   // Try to vectorized binops where reductions were not found.
9352   for (Value *V : PostponedInsts)
9353     if (auto *Inst = dyn_cast<Instruction>(V))
9354       if (!R.isDeleted(Inst))
9355         Res |= Vectorize(Inst, R);
9356   return Res;
9357 }
9358 
9359 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9360                                                  BasicBlock *BB, BoUpSLP &R,
9361                                                  TargetTransformInfo *TTI) {
9362   auto *I = dyn_cast_or_null<Instruction>(V);
9363   if (!I)
9364     return false;
9365 
9366   if (!isa<BinaryOperator>(I))
9367     P = nullptr;
9368   // Try to match and vectorize a horizontal reduction.
9369   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9370     return tryToVectorize(I, R);
9371   };
9372   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9373                                                   ExtraVectorization);
9374 }
9375 
9376 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9377                                                  BasicBlock *BB, BoUpSLP &R) {
9378   const DataLayout &DL = BB->getModule()->getDataLayout();
9379   if (!R.canMapToVector(IVI->getType(), DL))
9380     return false;
9381 
9382   SmallVector<Value *, 16> BuildVectorOpds;
9383   SmallVector<Value *, 16> BuildVectorInsts;
9384   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9385     return false;
9386 
9387   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9388   // Aggregate value is unlikely to be processed in vector register, we need to
9389   // extract scalars into scalar registers, so NeedExtraction is set true.
9390   return tryToVectorizeList(BuildVectorOpds, R);
9391 }
9392 
9393 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9394                                                    BasicBlock *BB, BoUpSLP &R) {
9395   SmallVector<Value *, 16> BuildVectorInsts;
9396   SmallVector<Value *, 16> BuildVectorOpds;
9397   SmallVector<int> Mask;
9398   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9399       (llvm::all_of(
9400            BuildVectorOpds,
9401            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9402        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9403     return false;
9404 
9405   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9406   return tryToVectorizeList(BuildVectorInsts, R);
9407 }
9408 
9409 template <typename T>
9410 static bool
9411 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9412                        function_ref<unsigned(T *)> Limit,
9413                        function_ref<bool(T *, T *)> Comparator,
9414                        function_ref<bool(T *, T *)> AreCompatible,
9415                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorize,
9416                        bool LimitForRegisterSize) {
9417   bool Changed = false;
9418   // Sort by type, parent, operands.
9419   stable_sort(Incoming, Comparator);
9420 
9421   // Try to vectorize elements base on their type.
9422   SmallVector<T *> Candidates;
9423   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9424     // Look for the next elements with the same type, parent and operand
9425     // kinds.
9426     auto *SameTypeIt = IncIt;
9427     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9428       ++SameTypeIt;
9429 
9430     // Try to vectorize them.
9431     unsigned NumElts = (SameTypeIt - IncIt);
9432     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9433                       << NumElts << ")\n");
9434     // The vectorization is a 3-state attempt:
9435     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9436     // size of maximal register at first.
9437     // 2. Try to vectorize remaining instructions with the same type, if
9438     // possible. This may result in the better vectorization results rather than
9439     // if we try just to vectorize instructions with the same/alternate opcodes.
9440     // 3. Final attempt to try to vectorize all instructions with the
9441     // same/alternate ops only, this may result in some extra final
9442     // vectorization.
9443     if (NumElts > 1 &&
9444         TryToVectorize(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9445       // Success start over because instructions might have been changed.
9446       Changed = true;
9447     } else if (NumElts < Limit(*IncIt) &&
9448                (Candidates.empty() ||
9449                 Candidates.front()->getType() == (*IncIt)->getType())) {
9450       Candidates.append(IncIt, std::next(IncIt, NumElts));
9451     }
9452     // Final attempt to vectorize instructions with the same types.
9453     if (Candidates.size() > 1 &&
9454         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9455       if (TryToVectorize(Candidates, /*LimitForRegisterSize=*/false)) {
9456         // Success start over because instructions might have been changed.
9457         Changed = true;
9458       } else if (LimitForRegisterSize) {
9459         // Try to vectorize using small vectors.
9460         for (auto *It = Candidates.begin(), *End = Candidates.end();
9461              It != End;) {
9462           auto *SameTypeIt = It;
9463           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9464             ++SameTypeIt;
9465           unsigned NumElts = (SameTypeIt - It);
9466           if (NumElts > 1 && TryToVectorize(makeArrayRef(It, NumElts),
9467                                             /*LimitForRegisterSize=*/false))
9468             Changed = true;
9469           It = SameTypeIt;
9470         }
9471       }
9472       Candidates.clear();
9473     }
9474 
9475     // Start over at the next instruction of a different type (or the end).
9476     IncIt = SameTypeIt;
9477   }
9478   return Changed;
9479 }
9480 
9481 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9482     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9483     bool AtTerminator) {
9484   bool OpsChanged = false;
9485   SmallVector<Instruction *, 4> PostponedCmps;
9486   for (auto *I : reverse(Instructions)) {
9487     if (R.isDeleted(I))
9488       continue;
9489     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9490       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9491     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9492       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9493     else if (isa<CmpInst>(I))
9494       PostponedCmps.push_back(I);
9495   }
9496   if (AtTerminator) {
9497     // Try to find reductions first.
9498     for (Instruction *I : PostponedCmps) {
9499       if (R.isDeleted(I))
9500         continue;
9501       for (Value *Op : I->operands())
9502         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9503     }
9504     // Try to vectorize operands as vector bundles.
9505     for (Instruction *I : PostponedCmps) {
9506       if (R.isDeleted(I))
9507         continue;
9508       OpsChanged |= tryToVectorize(I, R);
9509     }
9510     // Try to vectorize list of compares.
9511     // Sort by type, compare predicate, etc.
9512     // TODO: Add analysis on the operand opcodes (profitable to vectorize
9513     // instructions with same/alternate opcodes/const values).
9514     auto &&CompareSorter = [&R](Value *V, Value *V2) {
9515       auto *CI1 = cast<CmpInst>(V);
9516       auto *CI2 = cast<CmpInst>(V2);
9517       if (R.isDeleted(CI2) || !isValidElementType(CI2->getType()))
9518         return false;
9519       if (CI1->getOperand(0)->getType()->getTypeID() <
9520           CI2->getOperand(0)->getType()->getTypeID())
9521         return true;
9522       if (CI1->getOperand(0)->getType()->getTypeID() >
9523           CI2->getOperand(0)->getType()->getTypeID())
9524         return false;
9525       return CI1->getPredicate() < CI2->getPredicate() ||
9526              (CI1->getPredicate() > CI2->getPredicate() &&
9527               CI1->getPredicate() <
9528                   CmpInst::getSwappedPredicate(CI2->getPredicate()));
9529     };
9530 
9531     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
9532       if (V1 == V2)
9533         return true;
9534       auto *CI1 = cast<CmpInst>(V1);
9535       auto *CI2 = cast<CmpInst>(V2);
9536       if (R.isDeleted(CI2) || !isValidElementType(CI2->getType()))
9537         return false;
9538       if (CI1->getOperand(0)->getType() != CI2->getOperand(0)->getType())
9539         return false;
9540       return CI1->getPredicate() == CI2->getPredicate() ||
9541              CI1->getPredicate() ==
9542                  CmpInst::getSwappedPredicate(CI2->getPredicate());
9543     };
9544     auto Limit = [&R](Value *V) {
9545       unsigned EltSize = R.getVectorElementSize(V);
9546       return std::max(2U, R.getMaxVecRegSize() / EltSize);
9547     };
9548 
9549     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
9550     OpsChanged |= tryToVectorizeSequence<Value>(
9551         Vals, Limit, CompareSorter, AreCompatibleCompares,
9552         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9553           // Exclude possible reductions from other blocks.
9554           bool ArePossiblyReducedInOtherBlock =
9555               any_of(Candidates, [](Value *V) {
9556                 return any_of(V->users(), [V](User *U) {
9557                   return isa<SelectInst>(U) &&
9558                          cast<SelectInst>(U)->getParent() !=
9559                              cast<Instruction>(V)->getParent();
9560                 });
9561               });
9562           if (ArePossiblyReducedInOtherBlock)
9563             return false;
9564           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9565         },
9566         /*LimitForRegisterSize=*/true);
9567     Instructions.clear();
9568   } else {
9569     // Insert in reverse order since the PostponedCmps vector was filled in
9570     // reverse order.
9571     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9572   }
9573   return OpsChanged;
9574 }
9575 
9576 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9577   bool Changed = false;
9578   SmallVector<Value *, 4> Incoming;
9579   SmallPtrSet<Value *, 16> VisitedInstrs;
9580   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9581   // node. Allows better to identify the chains that can be vectorized in the
9582   // better way.
9583   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9584   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9585     assert(isValidElementType(V1->getType()) &&
9586            isValidElementType(V2->getType()) &&
9587            "Expected vectorizable types only.");
9588     // It is fine to compare type IDs here, since we expect only vectorizable
9589     // types, like ints, floats and pointers, we don't care about other type.
9590     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9591       return true;
9592     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
9593       return false;
9594     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9595     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9596     if (Opcodes1.size() < Opcodes2.size())
9597       return true;
9598     if (Opcodes1.size() > Opcodes2.size())
9599       return false;
9600     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9601       // Undefs are compatible with any other value.
9602       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9603         continue;
9604       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9605         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9606           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
9607           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
9608           if (!NodeI1)
9609             return NodeI2 != nullptr;
9610           if (!NodeI2)
9611             return false;
9612           assert((NodeI1 == NodeI2) ==
9613                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9614                  "Different nodes should have different DFS numbers");
9615           if (NodeI1 != NodeI2)
9616             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9617           InstructionsState S = getSameOpcode({I1, I2});
9618           if (S.getOpcode())
9619             continue;
9620           return I1->getOpcode() < I2->getOpcode();
9621         }
9622       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9623         continue;
9624       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
9625         return true;
9626       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
9627         return false;
9628     }
9629     return false;
9630   };
9631   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
9632     if (V1 == V2)
9633       return true;
9634     if (V1->getType() != V2->getType())
9635       return false;
9636     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9637     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9638     if (Opcodes1.size() != Opcodes2.size())
9639       return false;
9640     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9641       // Undefs are compatible with any other value.
9642       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9643         continue;
9644       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9645         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9646           if (I1->getParent() != I2->getParent())
9647             return false;
9648           InstructionsState S = getSameOpcode({I1, I2});
9649           if (S.getOpcode())
9650             continue;
9651           return false;
9652         }
9653       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9654         continue;
9655       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
9656         return false;
9657     }
9658     return true;
9659   };
9660   auto Limit = [&R](Value *V) {
9661     unsigned EltSize = R.getVectorElementSize(V);
9662     return std::max(2U, R.getMaxVecRegSize() / EltSize);
9663   };
9664 
9665   bool HaveVectorizedPhiNodes = false;
9666   do {
9667     // Collect the incoming values from the PHIs.
9668     Incoming.clear();
9669     for (Instruction &I : *BB) {
9670       PHINode *P = dyn_cast<PHINode>(&I);
9671       if (!P)
9672         break;
9673 
9674       // No need to analyze deleted, vectorized and non-vectorizable
9675       // instructions.
9676       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
9677           isValidElementType(P->getType()))
9678         Incoming.push_back(P);
9679     }
9680 
9681     // Find the corresponding non-phi nodes for better matching when trying to
9682     // build the tree.
9683     for (Value *V : Incoming) {
9684       SmallVectorImpl<Value *> &Opcodes =
9685           PHIToOpcodes.try_emplace(V).first->getSecond();
9686       if (!Opcodes.empty())
9687         continue;
9688       SmallVector<Value *, 4> Nodes(1, V);
9689       SmallPtrSet<Value *, 4> Visited;
9690       while (!Nodes.empty()) {
9691         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
9692         if (!Visited.insert(PHI).second)
9693           continue;
9694         for (Value *V : PHI->incoming_values()) {
9695           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
9696             Nodes.push_back(PHI1);
9697             continue;
9698           }
9699           Opcodes.emplace_back(V);
9700         }
9701       }
9702     }
9703 
9704     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
9705         Incoming, Limit, PHICompare, AreCompatiblePHIs,
9706         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9707           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9708         },
9709         /*LimitForRegisterSize=*/true);
9710     Changed |= HaveVectorizedPhiNodes;
9711     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
9712   } while (HaveVectorizedPhiNodes);
9713 
9714   VisitedInstrs.clear();
9715 
9716   SmallVector<Instruction *, 8> PostProcessInstructions;
9717   SmallDenseSet<Instruction *, 4> KeyNodes;
9718   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
9719     // Skip instructions with scalable type. The num of elements is unknown at
9720     // compile-time for scalable type.
9721     if (isa<ScalableVectorType>(it->getType()))
9722       continue;
9723 
9724     // Skip instructions marked for the deletion.
9725     if (R.isDeleted(&*it))
9726       continue;
9727     // We may go through BB multiple times so skip the one we have checked.
9728     if (!VisitedInstrs.insert(&*it).second) {
9729       if (it->use_empty() && KeyNodes.contains(&*it) &&
9730           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9731                                       it->isTerminator())) {
9732         // We would like to start over since some instructions are deleted
9733         // and the iterator may become invalid value.
9734         Changed = true;
9735         it = BB->begin();
9736         e = BB->end();
9737       }
9738       continue;
9739     }
9740 
9741     if (isa<DbgInfoIntrinsic>(it))
9742       continue;
9743 
9744     // Try to vectorize reductions that use PHINodes.
9745     if (PHINode *P = dyn_cast<PHINode>(it)) {
9746       // Check that the PHI is a reduction PHI.
9747       if (P->getNumIncomingValues() == 2) {
9748         // Try to match and vectorize a horizontal reduction.
9749         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
9750                                      TTI)) {
9751           Changed = true;
9752           it = BB->begin();
9753           e = BB->end();
9754           continue;
9755         }
9756       }
9757       // Try to vectorize the incoming values of the PHI, to catch reductions
9758       // that feed into PHIs.
9759       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
9760         // Skip if the incoming block is the current BB for now. Also, bypass
9761         // unreachable IR for efficiency and to avoid crashing.
9762         // TODO: Collect the skipped incoming values and try to vectorize them
9763         // after processing BB.
9764         if (BB == P->getIncomingBlock(I) ||
9765             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
9766           continue;
9767 
9768         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
9769                                             P->getIncomingBlock(I), R, TTI);
9770       }
9771       continue;
9772     }
9773 
9774     // Ran into an instruction without users, like terminator, or function call
9775     // with ignored return value, store. Ignore unused instructions (basing on
9776     // instruction type, except for CallInst and InvokeInst).
9777     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
9778                             isa<InvokeInst>(it))) {
9779       KeyNodes.insert(&*it);
9780       bool OpsChanged = false;
9781       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
9782         for (auto *V : it->operand_values()) {
9783           // Try to match and vectorize a horizontal reduction.
9784           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
9785         }
9786       }
9787       // Start vectorization of post-process list of instructions from the
9788       // top-tree instructions to try to vectorize as many instructions as
9789       // possible.
9790       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9791                                                 it->isTerminator());
9792       if (OpsChanged) {
9793         // We would like to start over since some instructions are deleted
9794         // and the iterator may become invalid value.
9795         Changed = true;
9796         it = BB->begin();
9797         e = BB->end();
9798         continue;
9799       }
9800     }
9801 
9802     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
9803         isa<InsertValueInst>(it))
9804       PostProcessInstructions.push_back(&*it);
9805   }
9806 
9807   return Changed;
9808 }
9809 
9810 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
9811   auto Changed = false;
9812   for (auto &Entry : GEPs) {
9813     // If the getelementptr list has fewer than two elements, there's nothing
9814     // to do.
9815     if (Entry.second.size() < 2)
9816       continue;
9817 
9818     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
9819                       << Entry.second.size() << ".\n");
9820 
9821     // Process the GEP list in chunks suitable for the target's supported
9822     // vector size. If a vector register can't hold 1 element, we are done. We
9823     // are trying to vectorize the index computations, so the maximum number of
9824     // elements is based on the size of the index expression, rather than the
9825     // size of the GEP itself (the target's pointer size).
9826     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9827     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
9828     if (MaxVecRegSize < EltSize)
9829       continue;
9830 
9831     unsigned MaxElts = MaxVecRegSize / EltSize;
9832     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
9833       auto Len = std::min<unsigned>(BE - BI, MaxElts);
9834       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
9835 
9836       // Initialize a set a candidate getelementptrs. Note that we use a
9837       // SetVector here to preserve program order. If the index computations
9838       // are vectorizable and begin with loads, we want to minimize the chance
9839       // of having to reorder them later.
9840       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
9841 
9842       // Some of the candidates may have already been vectorized after we
9843       // initially collected them. If so, they are marked as deleted, so remove
9844       // them from the set of candidates.
9845       Candidates.remove_if(
9846           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
9847 
9848       // Remove from the set of candidates all pairs of getelementptrs with
9849       // constant differences. Such getelementptrs are likely not good
9850       // candidates for vectorization in a bottom-up phase since one can be
9851       // computed from the other. We also ensure all candidate getelementptr
9852       // indices are unique.
9853       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
9854         auto *GEPI = GEPList[I];
9855         if (!Candidates.count(GEPI))
9856           continue;
9857         auto *SCEVI = SE->getSCEV(GEPList[I]);
9858         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
9859           auto *GEPJ = GEPList[J];
9860           auto *SCEVJ = SE->getSCEV(GEPList[J]);
9861           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
9862             Candidates.remove(GEPI);
9863             Candidates.remove(GEPJ);
9864           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
9865             Candidates.remove(GEPJ);
9866           }
9867         }
9868       }
9869 
9870       // We break out of the above computation as soon as we know there are
9871       // fewer than two candidates remaining.
9872       if (Candidates.size() < 2)
9873         continue;
9874 
9875       // Add the single, non-constant index of each candidate to the bundle. We
9876       // ensured the indices met these constraints when we originally collected
9877       // the getelementptrs.
9878       SmallVector<Value *, 16> Bundle(Candidates.size());
9879       auto BundleIndex = 0u;
9880       for (auto *V : Candidates) {
9881         auto *GEP = cast<GetElementPtrInst>(V);
9882         auto *GEPIdx = GEP->idx_begin()->get();
9883         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
9884         Bundle[BundleIndex++] = GEPIdx;
9885       }
9886 
9887       // Try and vectorize the indices. We are currently only interested in
9888       // gather-like cases of the form:
9889       //
9890       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
9891       //
9892       // where the loads of "a", the loads of "b", and the subtractions can be
9893       // performed in parallel. It's likely that detecting this pattern in a
9894       // bottom-up phase will be simpler and less costly than building a
9895       // full-blown top-down phase beginning at the consecutive loads.
9896       Changed |= tryToVectorizeList(Bundle, R);
9897     }
9898   }
9899   return Changed;
9900 }
9901 
9902 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
9903   bool Changed = false;
9904   // Sort by type, base pointers and values operand. Value operands must be
9905   // compatible (have the same opcode, same parent), otherwise it is
9906   // definitely not profitable to try to vectorize them.
9907   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
9908     if (V->getPointerOperandType()->getTypeID() <
9909         V2->getPointerOperandType()->getTypeID())
9910       return true;
9911     if (V->getPointerOperandType()->getTypeID() >
9912         V2->getPointerOperandType()->getTypeID())
9913       return false;
9914     // UndefValues are compatible with all other values.
9915     if (isa<UndefValue>(V->getValueOperand()) ||
9916         isa<UndefValue>(V2->getValueOperand()))
9917       return false;
9918     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
9919       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9920         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
9921             DT->getNode(I1->getParent());
9922         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
9923             DT->getNode(I2->getParent());
9924         assert(NodeI1 && "Should only process reachable instructions");
9925         assert(NodeI1 && "Should only process reachable instructions");
9926         assert((NodeI1 == NodeI2) ==
9927                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9928                "Different nodes should have different DFS numbers");
9929         if (NodeI1 != NodeI2)
9930           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9931         InstructionsState S = getSameOpcode({I1, I2});
9932         if (S.getOpcode())
9933           return false;
9934         return I1->getOpcode() < I2->getOpcode();
9935       }
9936     if (isa<Constant>(V->getValueOperand()) &&
9937         isa<Constant>(V2->getValueOperand()))
9938       return false;
9939     return V->getValueOperand()->getValueID() <
9940            V2->getValueOperand()->getValueID();
9941   };
9942 
9943   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
9944     if (V1 == V2)
9945       return true;
9946     if (V1->getPointerOperandType() != V2->getPointerOperandType())
9947       return false;
9948     // Undefs are compatible with any other value.
9949     if (isa<UndefValue>(V1->getValueOperand()) ||
9950         isa<UndefValue>(V2->getValueOperand()))
9951       return true;
9952     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
9953       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9954         if (I1->getParent() != I2->getParent())
9955           return false;
9956         InstructionsState S = getSameOpcode({I1, I2});
9957         return S.getOpcode() > 0;
9958       }
9959     if (isa<Constant>(V1->getValueOperand()) &&
9960         isa<Constant>(V2->getValueOperand()))
9961       return true;
9962     return V1->getValueOperand()->getValueID() ==
9963            V2->getValueOperand()->getValueID();
9964   };
9965   auto Limit = [&R, this](StoreInst *SI) {
9966     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
9967     return R.getMinVF(EltSize);
9968   };
9969 
9970   // Attempt to sort and vectorize each of the store-groups.
9971   for (auto &Pair : Stores) {
9972     if (Pair.second.size() < 2)
9973       continue;
9974 
9975     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
9976                       << Pair.second.size() << ".\n");
9977 
9978     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
9979       continue;
9980 
9981     Changed |= tryToVectorizeSequence<StoreInst>(
9982         Pair.second, Limit, StoreSorter, AreCompatibleStores,
9983         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
9984           return vectorizeStores(Candidates, R);
9985         },
9986         /*LimitForRegisterSize=*/false);
9987   }
9988   return Changed;
9989 }
9990 
9991 char SLPVectorizer::ID = 0;
9992 
9993 static const char lv_name[] = "SLP Vectorizer";
9994 
9995 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
9996 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
9997 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
9998 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9999 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10000 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10001 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10002 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10003 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10004 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10005 
10006 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10007