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