xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp (revision 1fd87a682ad7442327078e1eeb63edc4258f9815)
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 AltOp != MainOp; }
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 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
475                                        unsigned BaseIndex = 0);
476 
477 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
478 /// compatible instructions or constants, or just some other regular values.
479 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
480                                 Value *Op1) {
481   return (isConstant(BaseOp0) && isConstant(Op0)) ||
482          (isConstant(BaseOp1) && isConstant(Op1)) ||
483          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
484           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
485          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
486          getSameOpcode({BaseOp1, Op1}).getOpcode();
487 }
488 
489 /// \returns analysis of the Instructions in \p VL described in
490 /// InstructionsState, the Opcode that we suppose the whole list
491 /// could be vectorized even if its structure is diverse.
492 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
493                                        unsigned BaseIndex) {
494   // Make sure these are all Instructions.
495   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
496     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
497 
498   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
499   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
500   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
501   CmpInst::Predicate BasePred =
502       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
503               : CmpInst::BAD_ICMP_PREDICATE;
504   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
505   unsigned AltOpcode = Opcode;
506   unsigned AltIndex = BaseIndex;
507 
508   // Check for one alternate opcode from another BinaryOperator.
509   // TODO - generalize to support all operators (types, calls etc.).
510   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
511     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
512     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
513       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
514         continue;
515       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
516           isValidForAlternation(Opcode)) {
517         AltOpcode = InstOpcode;
518         AltIndex = Cnt;
519         continue;
520       }
521     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
522       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
523       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
524       if (Ty0 == Ty1) {
525         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
526           continue;
527         if (Opcode == AltOpcode) {
528           assert(isValidForAlternation(Opcode) &&
529                  isValidForAlternation(InstOpcode) &&
530                  "Cast isn't safe for alternation, logic needs to be updated!");
531           AltOpcode = InstOpcode;
532           AltIndex = Cnt;
533           continue;
534         }
535       }
536     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
537       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
538       auto *Inst = cast<Instruction>(VL[Cnt]);
539       Type *Ty0 = BaseInst->getOperand(0)->getType();
540       Type *Ty1 = Inst->getOperand(0)->getType();
541       if (Ty0 == Ty1) {
542         Value *BaseOp0 = BaseInst->getOperand(0);
543         Value *BaseOp1 = BaseInst->getOperand(1);
544         Value *Op0 = Inst->getOperand(0);
545         Value *Op1 = Inst->getOperand(1);
546         CmpInst::Predicate CurrentPred =
547             cast<CmpInst>(VL[Cnt])->getPredicate();
548         CmpInst::Predicate SwappedCurrentPred =
549             CmpInst::getSwappedPredicate(CurrentPred);
550         // Check for compatible operands. If the corresponding operands are not
551         // compatible - need to perform alternate vectorization.
552         if (InstOpcode == Opcode) {
553           if (BasePred == CurrentPred &&
554               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
555             continue;
556           if (BasePred == SwappedCurrentPred &&
557               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
558             continue;
559           if (E == 2 &&
560               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
561             continue;
562           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
563           CmpInst::Predicate AltPred = AltInst->getPredicate();
564           Value *AltOp0 = AltInst->getOperand(0);
565           Value *AltOp1 = AltInst->getOperand(1);
566           // Check if operands are compatible with alternate operands.
567           if (AltPred == CurrentPred &&
568               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
569             continue;
570           if (AltPred == SwappedCurrentPred &&
571               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
572             continue;
573         }
574         if (BaseIndex == AltIndex) {
575           assert(isValidForAlternation(Opcode) &&
576                  isValidForAlternation(InstOpcode) &&
577                  "Cast isn't safe for alternation, logic needs to be updated!");
578           AltIndex = Cnt;
579           continue;
580         }
581         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
582         CmpInst::Predicate AltPred = AltInst->getPredicate();
583         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
584             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
585           continue;
586       }
587     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
588       continue;
589     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
590   }
591 
592   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
593                            cast<Instruction>(VL[AltIndex]));
594 }
595 
596 /// \returns true if all of the values in \p VL have the same type or false
597 /// otherwise.
598 static bool allSameType(ArrayRef<Value *> VL) {
599   Type *Ty = VL[0]->getType();
600   for (int i = 1, e = VL.size(); i < e; i++)
601     if (VL[i]->getType() != Ty)
602       return false;
603 
604   return true;
605 }
606 
607 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
608 static Optional<unsigned> getExtractIndex(Instruction *E) {
609   unsigned Opcode = E->getOpcode();
610   assert((Opcode == Instruction::ExtractElement ||
611           Opcode == Instruction::ExtractValue) &&
612          "Expected extractelement or extractvalue instruction.");
613   if (Opcode == Instruction::ExtractElement) {
614     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
615     if (!CI)
616       return None;
617     return CI->getZExtValue();
618   }
619   ExtractValueInst *EI = cast<ExtractValueInst>(E);
620   if (EI->getNumIndices() != 1)
621     return None;
622   return *EI->idx_begin();
623 }
624 
625 /// \returns True if in-tree use also needs extract. This refers to
626 /// possible scalar operand in vectorized instruction.
627 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
628                                     TargetLibraryInfo *TLI) {
629   unsigned Opcode = UserInst->getOpcode();
630   switch (Opcode) {
631   case Instruction::Load: {
632     LoadInst *LI = cast<LoadInst>(UserInst);
633     return (LI->getPointerOperand() == Scalar);
634   }
635   case Instruction::Store: {
636     StoreInst *SI = cast<StoreInst>(UserInst);
637     return (SI->getPointerOperand() == Scalar);
638   }
639   case Instruction::Call: {
640     CallInst *CI = cast<CallInst>(UserInst);
641     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
642     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
643       if (hasVectorInstrinsicScalarOpd(ID, i))
644         return (CI->getArgOperand(i) == Scalar);
645     }
646     LLVM_FALLTHROUGH;
647   }
648   default:
649     return false;
650   }
651 }
652 
653 /// \returns the AA location that is being access by the instruction.
654 static MemoryLocation getLocation(Instruction *I) {
655   if (StoreInst *SI = dyn_cast<StoreInst>(I))
656     return MemoryLocation::get(SI);
657   if (LoadInst *LI = dyn_cast<LoadInst>(I))
658     return MemoryLocation::get(LI);
659   return MemoryLocation();
660 }
661 
662 /// \returns True if the instruction is not a volatile or atomic load/store.
663 static bool isSimple(Instruction *I) {
664   if (LoadInst *LI = dyn_cast<LoadInst>(I))
665     return LI->isSimple();
666   if (StoreInst *SI = dyn_cast<StoreInst>(I))
667     return SI->isSimple();
668   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
669     return !MI->isVolatile();
670   return true;
671 }
672 
673 /// Shuffles \p Mask in accordance with the given \p SubMask.
674 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
675   if (SubMask.empty())
676     return;
677   if (Mask.empty()) {
678     Mask.append(SubMask.begin(), SubMask.end());
679     return;
680   }
681   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
682   int TermValue = std::min(Mask.size(), SubMask.size());
683   for (int I = 0, E = SubMask.size(); I < E; ++I) {
684     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
685         Mask[SubMask[I]] >= TermValue)
686       continue;
687     NewMask[I] = Mask[SubMask[I]];
688   }
689   Mask.swap(NewMask);
690 }
691 
692 /// Order may have elements assigned special value (size) which is out of
693 /// bounds. Such indices only appear on places which correspond to undef values
694 /// (see canReuseExtract for details) and used in order to avoid undef values
695 /// have effect on operands ordering.
696 /// The first loop below simply finds all unused indices and then the next loop
697 /// nest assigns these indices for undef values positions.
698 /// As an example below Order has two undef positions and they have assigned
699 /// values 3 and 7 respectively:
700 /// before:  6 9 5 4 9 2 1 0
701 /// after:   6 3 5 4 7 2 1 0
702 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
703   const unsigned Sz = Order.size();
704   SmallBitVector UnusedIndices(Sz, /*t=*/true);
705   SmallBitVector MaskedIndices(Sz);
706   for (unsigned I = 0; I < Sz; ++I) {
707     if (Order[I] < Sz)
708       UnusedIndices.reset(Order[I]);
709     else
710       MaskedIndices.set(I);
711   }
712   if (MaskedIndices.none())
713     return;
714   assert(UnusedIndices.count() == MaskedIndices.count() &&
715          "Non-synced masked/available indices.");
716   int Idx = UnusedIndices.find_first();
717   int MIdx = MaskedIndices.find_first();
718   while (MIdx >= 0) {
719     assert(Idx >= 0 && "Indices must be synced.");
720     Order[MIdx] = Idx;
721     Idx = UnusedIndices.find_next(Idx);
722     MIdx = MaskedIndices.find_next(MIdx);
723   }
724 }
725 
726 namespace llvm {
727 
728 static void inversePermutation(ArrayRef<unsigned> Indices,
729                                SmallVectorImpl<int> &Mask) {
730   Mask.clear();
731   const unsigned E = Indices.size();
732   Mask.resize(E, UndefMaskElem);
733   for (unsigned I = 0; I < E; ++I)
734     Mask[Indices[I]] = I;
735 }
736 
737 /// \returns inserting index of InsertElement or InsertValue instruction,
738 /// using Offset as base offset for index.
739 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
740   int Index = Offset;
741   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
742     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
743       auto *VT = cast<FixedVectorType>(IE->getType());
744       if (CI->getValue().uge(VT->getNumElements()))
745         return UndefMaskElem;
746       Index *= VT->getNumElements();
747       Index += CI->getZExtValue();
748       return Index;
749     }
750     if (isa<UndefValue>(IE->getOperand(2)))
751       return UndefMaskElem;
752     return None;
753   }
754 
755   auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Order and then
773 /// the \p Mask. \p Order - is the original order of the scalars, need to
774 /// reorder scalars into an unordered state at first according to the given
775 /// order. Then the ordered scalars are shuffled once again in accordance with
776 /// the provided mask.
777 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
778                            ArrayRef<int> Mask) {
779   assert(!Mask.empty() && "Expected non-empty mask.");
780   SmallVector<Value *> Prev(Scalars.size(),
781                             UndefValue::get(Scalars.front()->getType()));
782   Prev.swap(Scalars);
783   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
784     if (Mask[I] != UndefMaskElem)
785       Scalars[Mask[I]] = Prev[I];
786 }
787 
788 namespace slpvectorizer {
789 
790 /// Bottom Up SLP Vectorizer.
791 class BoUpSLP {
792   struct TreeEntry;
793   struct ScheduleData;
794 
795 public:
796   using ValueList = SmallVector<Value *, 8>;
797   using InstrList = SmallVector<Instruction *, 16>;
798   using ValueSet = SmallPtrSet<Value *, 16>;
799   using StoreList = SmallVector<StoreInst *, 8>;
800   using ExtraValueToDebugLocsMap =
801       MapVector<Value *, SmallVector<Instruction *, 2>>;
802   using OrdersType = SmallVector<unsigned, 4>;
803 
804   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
805           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
806           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
807           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
808       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
809         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
810     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
811     // Use the vector register size specified by the target unless overridden
812     // by a command-line option.
813     // TODO: It would be better to limit the vectorization factor based on
814     //       data type rather than just register size. For example, x86 AVX has
815     //       256-bit registers, but it does not support integer operations
816     //       at that width (that requires AVX2).
817     if (MaxVectorRegSizeOption.getNumOccurrences())
818       MaxVecRegSize = MaxVectorRegSizeOption;
819     else
820       MaxVecRegSize =
821           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
822               .getFixedSize();
823 
824     if (MinVectorRegSizeOption.getNumOccurrences())
825       MinVecRegSize = MinVectorRegSizeOption;
826     else
827       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
828   }
829 
830   /// Vectorize the tree that starts with the elements in \p VL.
831   /// Returns the vectorized root.
832   Value *vectorizeTree();
833 
834   /// Vectorize the tree but with the list of externally used values \p
835   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
836   /// generated extractvalue instructions.
837   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
838 
839   /// \returns the cost incurred by unwanted spills and fills, caused by
840   /// holding live values over call sites.
841   InstructionCost getSpillCost() const;
842 
843   /// \returns the vectorization cost of the subtree that starts at \p VL.
844   /// A negative number means that this is profitable.
845   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
846 
847   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
848   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
849   void buildTree(ArrayRef<Value *> Roots,
850                  ArrayRef<Value *> UserIgnoreLst = None);
851 
852   /// Builds external uses of the vectorized scalars, i.e. the list of
853   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
854   /// ExternallyUsedValues contains additional list of external uses to handle
855   /// vectorization of reductions.
856   void
857   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
858 
859   /// Clear the internal data structures that are created by 'buildTree'.
860   void deleteTree() {
861     VectorizableTree.clear();
862     ScalarToTreeEntry.clear();
863     MustGather.clear();
864     ExternalUses.clear();
865     for (auto &Iter : BlocksSchedules) {
866       BlockScheduling *BS = Iter.second.get();
867       BS->clear();
868     }
869     MinBWs.clear();
870     InstrElementSize.clear();
871   }
872 
873   unsigned getTreeSize() const { return VectorizableTree.size(); }
874 
875   /// Perform LICM and CSE on the newly generated gather sequences.
876   void optimizeGatherSequence();
877 
878   /// Checks if the specified gather tree entry \p TE can be represented as a
879   /// shuffled vector entry + (possibly) permutation with other gathers. It
880   /// implements the checks only for possibly ordered scalars (Loads,
881   /// ExtractElement, ExtractValue), which can be part of the graph.
882   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
883 
884   /// Gets reordering data for the given tree entry. If the entry is vectorized
885   /// - just return ReorderIndices, otherwise check if the scalars can be
886   /// reordered and return the most optimal order.
887   /// \param TopToBottom If true, include the order of vectorized stores and
888   /// insertelement nodes, otherwise skip them.
889   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
890 
891   /// Reorders the current graph to the most profitable order starting from the
892   /// root node to the leaf nodes. The best order is chosen only from the nodes
893   /// of the same size (vectorization factor). Smaller nodes are considered
894   /// parts of subgraph with smaller VF and they are reordered independently. We
895   /// can make it because we still need to extend smaller nodes to the wider VF
896   /// and we can merge reordering shuffles with the widening shuffles.
897   void reorderTopToBottom();
898 
899   /// Reorders the current graph to the most profitable order starting from
900   /// leaves to the root. It allows to rotate small subgraphs and reduce the
901   /// number of reshuffles if the leaf nodes use the same order. In this case we
902   /// can merge the orders and just shuffle user node instead of shuffling its
903   /// operands. Plus, even the leaf nodes have different orders, it allows to
904   /// sink reordering in the graph closer to the root node and merge it later
905   /// during analysis.
906   void reorderBottomToTop(bool IgnoreReorder = false);
907 
908   /// \return The vector element size in bits to use when vectorizing the
909   /// expression tree ending at \p V. If V is a store, the size is the width of
910   /// the stored value. Otherwise, the size is the width of the largest loaded
911   /// value reaching V. This method is used by the vectorizer to calculate
912   /// vectorization factors.
913   unsigned getVectorElementSize(Value *V);
914 
915   /// Compute the minimum type sizes required to represent the entries in a
916   /// vectorizable tree.
917   void computeMinimumValueSizes();
918 
919   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
920   unsigned getMaxVecRegSize() const {
921     return MaxVecRegSize;
922   }
923 
924   // \returns minimum vector register size as set by cl::opt.
925   unsigned getMinVecRegSize() const {
926     return MinVecRegSize;
927   }
928 
929   unsigned getMinVF(unsigned Sz) const {
930     return std::max(2U, getMinVecRegSize() / Sz);
931   }
932 
933   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
934     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
935       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
936     return MaxVF ? MaxVF : UINT_MAX;
937   }
938 
939   /// Check if homogeneous aggregate is isomorphic to some VectorType.
940   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
941   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
942   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
943   ///
944   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
945   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
946 
947   /// \returns True if the VectorizableTree is both tiny and not fully
948   /// vectorizable. We do not vectorize such trees.
949   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
950 
951   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
952   /// can be load combined in the backend. Load combining may not be allowed in
953   /// the IR optimizer, so we do not want to alter the pattern. For example,
954   /// partially transforming a scalar bswap() pattern into vector code is
955   /// effectively impossible for the backend to undo.
956   /// TODO: If load combining is allowed in the IR optimizer, this analysis
957   ///       may not be necessary.
958   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
959 
960   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
961   /// can be load combined in the backend. Load combining may not be allowed in
962   /// the IR optimizer, so we do not want to alter the pattern. For example,
963   /// partially transforming a scalar bswap() pattern into vector code is
964   /// effectively impossible for the backend to undo.
965   /// TODO: If load combining is allowed in the IR optimizer, this analysis
966   ///       may not be necessary.
967   bool isLoadCombineCandidate() const;
968 
969   OptimizationRemarkEmitter *getORE() { return ORE; }
970 
971   /// This structure holds any data we need about the edges being traversed
972   /// during buildTree_rec(). We keep track of:
973   /// (i) the user TreeEntry index, and
974   /// (ii) the index of the edge.
975   struct EdgeInfo {
976     EdgeInfo() = default;
977     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
978         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
979     /// The user TreeEntry.
980     TreeEntry *UserTE = nullptr;
981     /// The operand index of the use.
982     unsigned EdgeIdx = UINT_MAX;
983 #ifndef NDEBUG
984     friend inline raw_ostream &operator<<(raw_ostream &OS,
985                                           const BoUpSLP::EdgeInfo &EI) {
986       EI.dump(OS);
987       return OS;
988     }
989     /// Debug print.
990     void dump(raw_ostream &OS) const {
991       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
992          << " EdgeIdx:" << EdgeIdx << "}";
993     }
994     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
995 #endif
996   };
997 
998   /// A helper data structure to hold the operands of a vector of instructions.
999   /// This supports a fixed vector length for all operand vectors.
1000   class VLOperands {
1001     /// For each operand we need (i) the value, and (ii) the opcode that it
1002     /// would be attached to if the expression was in a left-linearized form.
1003     /// This is required to avoid illegal operand reordering.
1004     /// For example:
1005     /// \verbatim
1006     ///                         0 Op1
1007     ///                         |/
1008     /// Op1 Op2   Linearized    + Op2
1009     ///   \ /     ---------->   |/
1010     ///    -                    -
1011     ///
1012     /// Op1 - Op2            (0 + Op1) - Op2
1013     /// \endverbatim
1014     ///
1015     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1016     ///
1017     /// Another way to think of this is to track all the operations across the
1018     /// path from the operand all the way to the root of the tree and to
1019     /// calculate the operation that corresponds to this path. For example, the
1020     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1021     /// corresponding operation is a '-' (which matches the one in the
1022     /// linearized tree, as shown above).
1023     ///
1024     /// For lack of a better term, we refer to this operation as Accumulated
1025     /// Path Operation (APO).
1026     struct OperandData {
1027       OperandData() = default;
1028       OperandData(Value *V, bool APO, bool IsUsed)
1029           : V(V), APO(APO), IsUsed(IsUsed) {}
1030       /// The operand value.
1031       Value *V = nullptr;
1032       /// TreeEntries only allow a single opcode, or an alternate sequence of
1033       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1034       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1035       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1036       /// (e.g., Add/Mul)
1037       bool APO = false;
1038       /// Helper data for the reordering function.
1039       bool IsUsed = false;
1040     };
1041 
1042     /// During operand reordering, we are trying to select the operand at lane
1043     /// that matches best with the operand at the neighboring lane. Our
1044     /// selection is based on the type of value we are looking for. For example,
1045     /// if the neighboring lane has a load, we need to look for a load that is
1046     /// accessing a consecutive address. These strategies are summarized in the
1047     /// 'ReorderingMode' enumerator.
1048     enum class ReorderingMode {
1049       Load,     ///< Matching loads to consecutive memory addresses
1050       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1051       Constant, ///< Matching constants
1052       Splat,    ///< Matching the same instruction multiple times (broadcast)
1053       Failed,   ///< We failed to create a vectorizable group
1054     };
1055 
1056     using OperandDataVec = SmallVector<OperandData, 2>;
1057 
1058     /// A vector of operand vectors.
1059     SmallVector<OperandDataVec, 4> OpsVec;
1060 
1061     const DataLayout &DL;
1062     ScalarEvolution &SE;
1063     const BoUpSLP &R;
1064 
1065     /// \returns the operand data at \p OpIdx and \p Lane.
1066     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1067       return OpsVec[OpIdx][Lane];
1068     }
1069 
1070     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1071     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1072       return OpsVec[OpIdx][Lane];
1073     }
1074 
1075     /// Clears the used flag for all entries.
1076     void clearUsed() {
1077       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1078            OpIdx != NumOperands; ++OpIdx)
1079         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1080              ++Lane)
1081           OpsVec[OpIdx][Lane].IsUsed = false;
1082     }
1083 
1084     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1085     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1086       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1087     }
1088 
1089     // The hard-coded scores listed here are not very important, though it shall
1090     // be higher for better matches to improve the resulting cost. When
1091     // computing the scores of matching one sub-tree with another, we are
1092     // basically counting the number of values that are matching. So even if all
1093     // scores are set to 1, we would still get a decent matching result.
1094     // However, sometimes we have to break ties. For example we may have to
1095     // choose between matching loads vs matching opcodes. This is what these
1096     // scores are helping us with: they provide the order of preference. Also,
1097     // this is important if the scalar is externally used or used in another
1098     // tree entry node in the different lane.
1099 
1100     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1101     static const int ScoreConsecutiveLoads = 4;
1102     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1103     static const int ScoreReversedLoads = 3;
1104     /// ExtractElementInst from same vector and consecutive indexes.
1105     static const int ScoreConsecutiveExtracts = 4;
1106     /// ExtractElementInst from same vector and reversed indices.
1107     static const int ScoreReversedExtracts = 3;
1108     /// Constants.
1109     static const int ScoreConstants = 2;
1110     /// Instructions with the same opcode.
1111     static const int ScoreSameOpcode = 2;
1112     /// Instructions with alt opcodes (e.g, add + sub).
1113     static const int ScoreAltOpcodes = 1;
1114     /// Identical instructions (a.k.a. splat or broadcast).
1115     static const int ScoreSplat = 1;
1116     /// Matching with an undef is preferable to failing.
1117     static const int ScoreUndef = 1;
1118     /// Score for failing to find a decent match.
1119     static const int ScoreFail = 0;
1120     /// User exteranl to the vectorized code.
1121     static const int ExternalUseCost = 1;
1122     /// The user is internal but in a different lane.
1123     static const int UserInDiffLaneCost = ExternalUseCost;
1124 
1125     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1126     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1127                                ScalarEvolution &SE, int NumLanes) {
1128       if (V1 == V2)
1129         return VLOperands::ScoreSplat;
1130 
1131       auto *LI1 = dyn_cast<LoadInst>(V1);
1132       auto *LI2 = dyn_cast<LoadInst>(V2);
1133       if (LI1 && LI2) {
1134         if (LI1->getParent() != LI2->getParent())
1135           return VLOperands::ScoreFail;
1136 
1137         Optional<int> Dist = getPointersDiff(
1138             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1139             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1140         if (!Dist)
1141           return VLOperands::ScoreFail;
1142         // The distance is too large - still may be profitable to use masked
1143         // loads/gathers.
1144         if (std::abs(*Dist) > NumLanes / 2)
1145           return VLOperands::ScoreAltOpcodes;
1146         // This still will detect consecutive loads, but we might have "holes"
1147         // in some cases. It is ok for non-power-2 vectorization and may produce
1148         // better results. It should not affect current vectorization.
1149         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1150                            : VLOperands::ScoreReversedLoads;
1151       }
1152 
1153       auto *C1 = dyn_cast<Constant>(V1);
1154       auto *C2 = dyn_cast<Constant>(V2);
1155       if (C1 && C2)
1156         return VLOperands::ScoreConstants;
1157 
1158       // Extracts from consecutive indexes of the same vector better score as
1159       // the extracts could be optimized away.
1160       Value *EV1;
1161       ConstantInt *Ex1Idx;
1162       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1163         // Undefs are always profitable for extractelements.
1164         if (isa<UndefValue>(V2))
1165           return VLOperands::ScoreConsecutiveExtracts;
1166         Value *EV2 = nullptr;
1167         ConstantInt *Ex2Idx = nullptr;
1168         if (match(V2,
1169                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1170                                                          m_Undef())))) {
1171           // Undefs are always profitable for extractelements.
1172           if (!Ex2Idx)
1173             return VLOperands::ScoreConsecutiveExtracts;
1174           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1175             return VLOperands::ScoreConsecutiveExtracts;
1176           if (EV2 == EV1) {
1177             int Idx1 = Ex1Idx->getZExtValue();
1178             int Idx2 = Ex2Idx->getZExtValue();
1179             int Dist = Idx2 - Idx1;
1180             // The distance is too large - still may be profitable to use
1181             // shuffles.
1182             if (std::abs(Dist) > NumLanes / 2)
1183               return VLOperands::ScoreAltOpcodes;
1184             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1185                               : VLOperands::ScoreReversedExtracts;
1186           }
1187         }
1188       }
1189 
1190       auto *I1 = dyn_cast<Instruction>(V1);
1191       auto *I2 = dyn_cast<Instruction>(V2);
1192       if (I1 && I2) {
1193         if (I1->getParent() != I2->getParent())
1194           return VLOperands::ScoreFail;
1195         InstructionsState S = getSameOpcode({I1, I2});
1196         // Note: Only consider instructions with <= 2 operands to avoid
1197         // complexity explosion.
1198         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1199           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1200                                   : VLOperands::ScoreSameOpcode;
1201       }
1202 
1203       if (isa<UndefValue>(V2))
1204         return VLOperands::ScoreUndef;
1205 
1206       return VLOperands::ScoreFail;
1207     }
1208 
1209     /// Holds the values and their lanes that are taking part in the look-ahead
1210     /// score calculation. This is used in the external uses cost calculation.
1211     /// Need to hold all the lanes in case of splat/broadcast at least to
1212     /// correctly check for the use in the different lane.
1213     SmallDenseMap<Value *, SmallSet<int, 4>> InLookAheadValues;
1214 
1215     /// \returns the additional cost due to uses of \p LHS and \p RHS that are
1216     /// either external to the vectorized code, or require shuffling.
1217     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1218                             const std::pair<Value *, int> &RHS) {
1219       int Cost = 0;
1220       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1221       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1222         Value *V = Values[Idx].first;
1223         if (isa<Constant>(V)) {
1224           // Since this is a function pass, it doesn't make semantic sense to
1225           // walk the users of a subclass of Constant. The users could be in
1226           // another function, or even another module that happens to be in
1227           // the same LLVMContext.
1228           continue;
1229         }
1230 
1231         // Calculate the absolute lane, using the minimum relative lane of LHS
1232         // and RHS as base and Idx as the offset.
1233         int Ln = std::min(LHS.second, RHS.second) + Idx;
1234         assert(Ln >= 0 && "Bad lane calculation");
1235         unsigned UsersBudget = LookAheadUsersBudget;
1236         for (User *U : V->users()) {
1237           if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1238             // The user is in the VectorizableTree. Check if we need to insert.
1239             int UserLn = UserTE->findLaneForValue(U);
1240             assert(UserLn >= 0 && "Bad lane");
1241             // If the values are different, check just the line of the current
1242             // value. If the values are the same, need to add UserInDiffLaneCost
1243             // only if UserLn does not match both line numbers.
1244             if ((LHS.first != RHS.first && UserLn != Ln) ||
1245                 (LHS.first == RHS.first && UserLn != LHS.second &&
1246                  UserLn != RHS.second)) {
1247               Cost += UserInDiffLaneCost;
1248               break;
1249             }
1250           } else {
1251             // Check if the user is in the look-ahead code.
1252             auto It2 = InLookAheadValues.find(U);
1253             if (It2 != InLookAheadValues.end()) {
1254               // The user is in the look-ahead code. Check the lane.
1255               if (!It2->getSecond().contains(Ln)) {
1256                 Cost += UserInDiffLaneCost;
1257                 break;
1258               }
1259             } else {
1260               // The user is neither in SLP tree nor in the look-ahead code.
1261               Cost += ExternalUseCost;
1262               break;
1263             }
1264           }
1265           // Limit the number of visited uses to cap compilation time.
1266           if (--UsersBudget == 0)
1267             break;
1268         }
1269       }
1270       return Cost;
1271     }
1272 
1273     /// Go through the operands of \p LHS and \p RHS recursively until \p
1274     /// MaxLevel, and return the cummulative score. For example:
1275     /// \verbatim
1276     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1277     ///     \ /         \ /         \ /        \ /
1278     ///      +           +           +          +
1279     ///     G1          G2          G3         G4
1280     /// \endverbatim
1281     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1282     /// each level recursively, accumulating the score. It starts from matching
1283     /// the additions at level 0, then moves on to the loads (level 1). The
1284     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1285     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1286     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1287     /// Please note that the order of the operands does not matter, as we
1288     /// evaluate the score of all profitable combinations of operands. In
1289     /// other words the score of G1 and G4 is the same as G1 and G2. This
1290     /// heuristic is based on ideas described in:
1291     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1292     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1293     ///   Luís F. W. Góes
1294     int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1295                            const std::pair<Value *, int> &RHS, int CurrLevel,
1296                            int MaxLevel) {
1297 
1298       Value *V1 = LHS.first;
1299       Value *V2 = RHS.first;
1300       // Get the shallow score of V1 and V2.
1301       int ShallowScoreAtThisLevel = std::max(
1302           (int)ScoreFail, getShallowScore(V1, V2, DL, SE, getNumLanes()) -
1303                               getExternalUsesCost(LHS, RHS));
1304       int Lane1 = LHS.second;
1305       int Lane2 = RHS.second;
1306 
1307       // If reached MaxLevel,
1308       //  or if V1 and V2 are not instructions,
1309       //  or if they are SPLAT,
1310       //  or if they are not consecutive,
1311       //  or if profitable to vectorize loads or extractelements, early return
1312       //  the current cost.
1313       auto *I1 = dyn_cast<Instruction>(V1);
1314       auto *I2 = dyn_cast<Instruction>(V2);
1315       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1316           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1317           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1318             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1319            ShallowScoreAtThisLevel))
1320         return ShallowScoreAtThisLevel;
1321       assert(I1 && I2 && "Should have early exited.");
1322 
1323       // Keep track of in-tree values for determining the external-use cost.
1324       InLookAheadValues[V1].insert(Lane1);
1325       InLookAheadValues[V2].insert(Lane2);
1326 
1327       // Contains the I2 operand indexes that got matched with I1 operands.
1328       SmallSet<unsigned, 4> Op2Used;
1329 
1330       // Recursion towards the operands of I1 and I2. We are trying all possible
1331       // operand pairs, and keeping track of the best score.
1332       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1333            OpIdx1 != NumOperands1; ++OpIdx1) {
1334         // Try to pair op1I with the best operand of I2.
1335         int MaxTmpScore = 0;
1336         unsigned MaxOpIdx2 = 0;
1337         bool FoundBest = false;
1338         // If I2 is commutative try all combinations.
1339         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1340         unsigned ToIdx = isCommutative(I2)
1341                              ? I2->getNumOperands()
1342                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1343         assert(FromIdx <= ToIdx && "Bad index");
1344         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1345           // Skip operands already paired with OpIdx1.
1346           if (Op2Used.count(OpIdx2))
1347             continue;
1348           // Recursively calculate the cost at each level
1349           int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1350                                             {I2->getOperand(OpIdx2), Lane2},
1351                                             CurrLevel + 1, MaxLevel);
1352           // Look for the best score.
1353           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1354             MaxTmpScore = TmpScore;
1355             MaxOpIdx2 = OpIdx2;
1356             FoundBest = true;
1357           }
1358         }
1359         if (FoundBest) {
1360           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1361           Op2Used.insert(MaxOpIdx2);
1362           ShallowScoreAtThisLevel += MaxTmpScore;
1363         }
1364       }
1365       return ShallowScoreAtThisLevel;
1366     }
1367 
1368     /// \Returns the look-ahead score, which tells us how much the sub-trees
1369     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1370     /// score. This helps break ties in an informed way when we cannot decide on
1371     /// the order of the operands by just considering the immediate
1372     /// predecessors.
1373     int getLookAheadScore(const std::pair<Value *, int> &LHS,
1374                           const std::pair<Value *, int> &RHS) {
1375       InLookAheadValues.clear();
1376       return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1377     }
1378 
1379     // Search all operands in Ops[*][Lane] for the one that matches best
1380     // Ops[OpIdx][LastLane] and return its opreand index.
1381     // If no good match can be found, return None.
1382     Optional<unsigned>
1383     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1384                    ArrayRef<ReorderingMode> ReorderingModes) {
1385       unsigned NumOperands = getNumOperands();
1386 
1387       // The operand of the previous lane at OpIdx.
1388       Value *OpLastLane = getData(OpIdx, LastLane).V;
1389 
1390       // Our strategy mode for OpIdx.
1391       ReorderingMode RMode = ReorderingModes[OpIdx];
1392 
1393       // The linearized opcode of the operand at OpIdx, Lane.
1394       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1395 
1396       // The best operand index and its score.
1397       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1398       // are using the score to differentiate between the two.
1399       struct BestOpData {
1400         Optional<unsigned> Idx = None;
1401         unsigned Score = 0;
1402       } BestOp;
1403 
1404       // Iterate through all unused operands and look for the best.
1405       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1406         // Get the operand at Idx and Lane.
1407         OperandData &OpData = getData(Idx, Lane);
1408         Value *Op = OpData.V;
1409         bool OpAPO = OpData.APO;
1410 
1411         // Skip already selected operands.
1412         if (OpData.IsUsed)
1413           continue;
1414 
1415         // Skip if we are trying to move the operand to a position with a
1416         // different opcode in the linearized tree form. This would break the
1417         // semantics.
1418         if (OpAPO != OpIdxAPO)
1419           continue;
1420 
1421         // Look for an operand that matches the current mode.
1422         switch (RMode) {
1423         case ReorderingMode::Load:
1424         case ReorderingMode::Constant:
1425         case ReorderingMode::Opcode: {
1426           bool LeftToRight = Lane > LastLane;
1427           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1428           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1429           unsigned Score =
1430               getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1431           if (Score > BestOp.Score) {
1432             BestOp.Idx = Idx;
1433             BestOp.Score = Score;
1434           }
1435           break;
1436         }
1437         case ReorderingMode::Splat:
1438           if (Op == OpLastLane)
1439             BestOp.Idx = Idx;
1440           break;
1441         case ReorderingMode::Failed:
1442           return None;
1443         }
1444       }
1445 
1446       if (BestOp.Idx) {
1447         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1448         return BestOp.Idx;
1449       }
1450       // If we could not find a good match return None.
1451       return None;
1452     }
1453 
1454     /// Helper for reorderOperandVecs.
1455     /// \returns the lane that we should start reordering from. This is the one
1456     /// which has the least number of operands that can freely move about or
1457     /// less profitable because it already has the most optimal set of operands.
1458     unsigned getBestLaneToStartReordering() const {
1459       unsigned Min = UINT_MAX;
1460       unsigned SameOpNumber = 0;
1461       // std::pair<unsigned, unsigned> is used to implement a simple voting
1462       // algorithm and choose the lane with the least number of operands that
1463       // can freely move about or less profitable because it already has the
1464       // most optimal set of operands. The first unsigned is a counter for
1465       // voting, the second unsigned is the counter of lanes with instructions
1466       // with same/alternate opcodes and same parent basic block.
1467       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1468       // Try to be closer to the original results, if we have multiple lanes
1469       // with same cost. If 2 lanes have the same cost, use the one with the
1470       // lowest index.
1471       for (int I = getNumLanes(); I > 0; --I) {
1472         unsigned Lane = I - 1;
1473         OperandsOrderData NumFreeOpsHash =
1474             getMaxNumOperandsThatCanBeReordered(Lane);
1475         // Compare the number of operands that can move and choose the one with
1476         // the least number.
1477         if (NumFreeOpsHash.NumOfAPOs < Min) {
1478           Min = NumFreeOpsHash.NumOfAPOs;
1479           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1480           HashMap.clear();
1481           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1482         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1483                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1484           // Select the most optimal lane in terms of number of operands that
1485           // should be moved around.
1486           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1487           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1488         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1489                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1490           auto It = HashMap.find(NumFreeOpsHash.Hash);
1491           if (It == HashMap.end())
1492             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1493           else
1494             ++It->second.first;
1495         }
1496       }
1497       // Select the lane with the minimum counter.
1498       unsigned BestLane = 0;
1499       unsigned CntMin = UINT_MAX;
1500       for (const auto &Data : reverse(HashMap)) {
1501         if (Data.second.first < CntMin) {
1502           CntMin = Data.second.first;
1503           BestLane = Data.second.second;
1504         }
1505       }
1506       return BestLane;
1507     }
1508 
1509     /// Data structure that helps to reorder operands.
1510     struct OperandsOrderData {
1511       /// The best number of operands with the same APOs, which can be
1512       /// reordered.
1513       unsigned NumOfAPOs = UINT_MAX;
1514       /// Number of operands with the same/alternate instruction opcode and
1515       /// parent.
1516       unsigned NumOpsWithSameOpcodeParent = 0;
1517       /// Hash for the actual operands ordering.
1518       /// Used to count operands, actually their position id and opcode
1519       /// value. It is used in the voting mechanism to find the lane with the
1520       /// least number of operands that can freely move about or less profitable
1521       /// because it already has the most optimal set of operands. Can be
1522       /// replaced with SmallVector<unsigned> instead but hash code is faster
1523       /// and requires less memory.
1524       unsigned Hash = 0;
1525     };
1526     /// \returns the maximum number of operands that are allowed to be reordered
1527     /// for \p Lane and the number of compatible instructions(with the same
1528     /// parent/opcode). This is used as a heuristic for selecting the first lane
1529     /// to start operand reordering.
1530     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1531       unsigned CntTrue = 0;
1532       unsigned NumOperands = getNumOperands();
1533       // Operands with the same APO can be reordered. We therefore need to count
1534       // how many of them we have for each APO, like this: Cnt[APO] = x.
1535       // Since we only have two APOs, namely true and false, we can avoid using
1536       // a map. Instead we can simply count the number of operands that
1537       // correspond to one of them (in this case the 'true' APO), and calculate
1538       // the other by subtracting it from the total number of operands.
1539       // Operands with the same instruction opcode and parent are more
1540       // profitable since we don't need to move them in many cases, with a high
1541       // probability such lane already can be vectorized effectively.
1542       bool AllUndefs = true;
1543       unsigned NumOpsWithSameOpcodeParent = 0;
1544       Instruction *OpcodeI = nullptr;
1545       BasicBlock *Parent = nullptr;
1546       unsigned Hash = 0;
1547       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1548         const OperandData &OpData = getData(OpIdx, Lane);
1549         if (OpData.APO)
1550           ++CntTrue;
1551         // Use Boyer-Moore majority voting for finding the majority opcode and
1552         // the number of times it occurs.
1553         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1554           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1555               I->getParent() != Parent) {
1556             if (NumOpsWithSameOpcodeParent == 0) {
1557               NumOpsWithSameOpcodeParent = 1;
1558               OpcodeI = I;
1559               Parent = I->getParent();
1560             } else {
1561               --NumOpsWithSameOpcodeParent;
1562             }
1563           } else {
1564             ++NumOpsWithSameOpcodeParent;
1565           }
1566         }
1567         Hash = hash_combine(
1568             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1569         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1570       }
1571       if (AllUndefs)
1572         return {};
1573       OperandsOrderData Data;
1574       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1575       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1576       Data.Hash = Hash;
1577       return Data;
1578     }
1579 
1580     /// Go through the instructions in VL and append their operands.
1581     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1582       assert(!VL.empty() && "Bad VL");
1583       assert((empty() || VL.size() == getNumLanes()) &&
1584              "Expected same number of lanes");
1585       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1586       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1587       OpsVec.resize(NumOperands);
1588       unsigned NumLanes = VL.size();
1589       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1590         OpsVec[OpIdx].resize(NumLanes);
1591         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1592           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1593           // Our tree has just 3 nodes: the root and two operands.
1594           // It is therefore trivial to get the APO. We only need to check the
1595           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1596           // RHS operand. The LHS operand of both add and sub is never attached
1597           // to an inversese operation in the linearized form, therefore its APO
1598           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1599 
1600           // Since operand reordering is performed on groups of commutative
1601           // operations or alternating sequences (e.g., +, -), we can safely
1602           // tell the inverse operations by checking commutativity.
1603           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1604           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1605           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1606                                  APO, false};
1607         }
1608       }
1609     }
1610 
1611     /// \returns the number of operands.
1612     unsigned getNumOperands() const { return OpsVec.size(); }
1613 
1614     /// \returns the number of lanes.
1615     unsigned getNumLanes() const { return OpsVec[0].size(); }
1616 
1617     /// \returns the operand value at \p OpIdx and \p Lane.
1618     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1619       return getData(OpIdx, Lane).V;
1620     }
1621 
1622     /// \returns true if the data structure is empty.
1623     bool empty() const { return OpsVec.empty(); }
1624 
1625     /// Clears the data.
1626     void clear() { OpsVec.clear(); }
1627 
1628     /// \Returns true if there are enough operands identical to \p Op to fill
1629     /// the whole vector.
1630     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1631     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1632       bool OpAPO = getData(OpIdx, Lane).APO;
1633       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1634         if (Ln == Lane)
1635           continue;
1636         // This is set to true if we found a candidate for broadcast at Lane.
1637         bool FoundCandidate = false;
1638         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1639           OperandData &Data = getData(OpI, Ln);
1640           if (Data.APO != OpAPO || Data.IsUsed)
1641             continue;
1642           if (Data.V == Op) {
1643             FoundCandidate = true;
1644             Data.IsUsed = true;
1645             break;
1646           }
1647         }
1648         if (!FoundCandidate)
1649           return false;
1650       }
1651       return true;
1652     }
1653 
1654   public:
1655     /// Initialize with all the operands of the instruction vector \p RootVL.
1656     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1657                ScalarEvolution &SE, const BoUpSLP &R)
1658         : DL(DL), SE(SE), R(R) {
1659       // Append all the operands of RootVL.
1660       appendOperandsOfVL(RootVL);
1661     }
1662 
1663     /// \Returns a value vector with the operands across all lanes for the
1664     /// opearnd at \p OpIdx.
1665     ValueList getVL(unsigned OpIdx) const {
1666       ValueList OpVL(OpsVec[OpIdx].size());
1667       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1668              "Expected same num of lanes across all operands");
1669       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1670         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1671       return OpVL;
1672     }
1673 
1674     // Performs operand reordering for 2 or more operands.
1675     // The original operands are in OrigOps[OpIdx][Lane].
1676     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1677     void reorder() {
1678       unsigned NumOperands = getNumOperands();
1679       unsigned NumLanes = getNumLanes();
1680       // Each operand has its own mode. We are using this mode to help us select
1681       // the instructions for each lane, so that they match best with the ones
1682       // we have selected so far.
1683       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1684 
1685       // This is a greedy single-pass algorithm. We are going over each lane
1686       // once and deciding on the best order right away with no back-tracking.
1687       // However, in order to increase its effectiveness, we start with the lane
1688       // that has operands that can move the least. For example, given the
1689       // following lanes:
1690       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1691       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1692       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1693       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1694       // we will start at Lane 1, since the operands of the subtraction cannot
1695       // be reordered. Then we will visit the rest of the lanes in a circular
1696       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1697 
1698       // Find the first lane that we will start our search from.
1699       unsigned FirstLane = getBestLaneToStartReordering();
1700 
1701       // Initialize the modes.
1702       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1703         Value *OpLane0 = getValue(OpIdx, FirstLane);
1704         // Keep track if we have instructions with all the same opcode on one
1705         // side.
1706         if (isa<LoadInst>(OpLane0))
1707           ReorderingModes[OpIdx] = ReorderingMode::Load;
1708         else if (isa<Instruction>(OpLane0)) {
1709           // Check if OpLane0 should be broadcast.
1710           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1711             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1712           else
1713             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1714         }
1715         else if (isa<Constant>(OpLane0))
1716           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1717         else if (isa<Argument>(OpLane0))
1718           // Our best hope is a Splat. It may save some cost in some cases.
1719           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1720         else
1721           // NOTE: This should be unreachable.
1722           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1723       }
1724 
1725       // Check that we don't have same operands. No need to reorder if operands
1726       // are just perfect diamond or shuffled diamond match. Do not do it only
1727       // for possible broadcasts or non-power of 2 number of scalars (just for
1728       // now).
1729       auto &&SkipReordering = [this]() {
1730         SmallPtrSet<Value *, 4> UniqueValues;
1731         ArrayRef<OperandData> Op0 = OpsVec.front();
1732         for (const OperandData &Data : Op0)
1733           UniqueValues.insert(Data.V);
1734         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1735           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1736                 return !UniqueValues.contains(Data.V);
1737               }))
1738             return false;
1739         }
1740         // TODO: Check if we can remove a check for non-power-2 number of
1741         // scalars after full support of non-power-2 vectorization.
1742         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1743       };
1744 
1745       // If the initial strategy fails for any of the operand indexes, then we
1746       // perform reordering again in a second pass. This helps avoid assigning
1747       // high priority to the failed strategy, and should improve reordering for
1748       // the non-failed operand indexes.
1749       for (int Pass = 0; Pass != 2; ++Pass) {
1750         // Check if no need to reorder operands since they're are perfect or
1751         // shuffled diamond match.
1752         // Need to to do it to avoid extra external use cost counting for
1753         // shuffled matches, which may cause regressions.
1754         if (SkipReordering())
1755           break;
1756         // Skip the second pass if the first pass did not fail.
1757         bool StrategyFailed = false;
1758         // Mark all operand data as free to use.
1759         clearUsed();
1760         // We keep the original operand order for the FirstLane, so reorder the
1761         // rest of the lanes. We are visiting the nodes in a circular fashion,
1762         // using FirstLane as the center point and increasing the radius
1763         // distance.
1764         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1765           // Visit the lane on the right and then the lane on the left.
1766           for (int Direction : {+1, -1}) {
1767             int Lane = FirstLane + Direction * Distance;
1768             if (Lane < 0 || Lane >= (int)NumLanes)
1769               continue;
1770             int LastLane = Lane - Direction;
1771             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1772                    "Out of bounds");
1773             // Look for a good match for each operand.
1774             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1775               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1776               Optional<unsigned> BestIdx =
1777                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1778               // By not selecting a value, we allow the operands that follow to
1779               // select a better matching value. We will get a non-null value in
1780               // the next run of getBestOperand().
1781               if (BestIdx) {
1782                 // Swap the current operand with the one returned by
1783                 // getBestOperand().
1784                 swap(OpIdx, BestIdx.getValue(), Lane);
1785               } else {
1786                 // We failed to find a best operand, set mode to 'Failed'.
1787                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1788                 // Enable the second pass.
1789                 StrategyFailed = true;
1790               }
1791             }
1792           }
1793         }
1794         // Skip second pass if the strategy did not fail.
1795         if (!StrategyFailed)
1796           break;
1797       }
1798     }
1799 
1800 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1801     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1802       switch (RMode) {
1803       case ReorderingMode::Load:
1804         return "Load";
1805       case ReorderingMode::Opcode:
1806         return "Opcode";
1807       case ReorderingMode::Constant:
1808         return "Constant";
1809       case ReorderingMode::Splat:
1810         return "Splat";
1811       case ReorderingMode::Failed:
1812         return "Failed";
1813       }
1814       llvm_unreachable("Unimplemented Reordering Type");
1815     }
1816 
1817     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1818                                                    raw_ostream &OS) {
1819       return OS << getModeStr(RMode);
1820     }
1821 
1822     /// Debug print.
1823     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1824       printMode(RMode, dbgs());
1825     }
1826 
1827     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1828       return printMode(RMode, OS);
1829     }
1830 
1831     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1832       const unsigned Indent = 2;
1833       unsigned Cnt = 0;
1834       for (const OperandDataVec &OpDataVec : OpsVec) {
1835         OS << "Operand " << Cnt++ << "\n";
1836         for (const OperandData &OpData : OpDataVec) {
1837           OS.indent(Indent) << "{";
1838           if (Value *V = OpData.V)
1839             OS << *V;
1840           else
1841             OS << "null";
1842           OS << ", APO:" << OpData.APO << "}\n";
1843         }
1844         OS << "\n";
1845       }
1846       return OS;
1847     }
1848 
1849     /// Debug print.
1850     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1851 #endif
1852   };
1853 
1854   /// Checks if the instruction is marked for deletion.
1855   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1856 
1857   /// Marks values operands for later deletion by replacing them with Undefs.
1858   void eraseInstructions(ArrayRef<Value *> AV);
1859 
1860   ~BoUpSLP();
1861 
1862 private:
1863   /// Checks if all users of \p I are the part of the vectorization tree.
1864   bool areAllUsersVectorized(Instruction *I,
1865                              ArrayRef<Value *> VectorizedVals) const;
1866 
1867   /// \returns the cost of the vectorizable entry.
1868   InstructionCost getEntryCost(const TreeEntry *E,
1869                                ArrayRef<Value *> VectorizedVals);
1870 
1871   /// This is the recursive part of buildTree.
1872   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1873                      const EdgeInfo &EI);
1874 
1875   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1876   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1877   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1878   /// returns false, setting \p CurrentOrder to either an empty vector or a
1879   /// non-identity permutation that allows to reuse extract instructions.
1880   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1881                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1882 
1883   /// Vectorize a single entry in the tree.
1884   Value *vectorizeTree(TreeEntry *E);
1885 
1886   /// Vectorize a single entry in the tree, starting in \p VL.
1887   Value *vectorizeTree(ArrayRef<Value *> VL);
1888 
1889   /// \returns the scalarization cost for this type. Scalarization in this
1890   /// context means the creation of vectors from a group of scalars. If \p
1891   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1892   /// vector elements.
1893   InstructionCost getGatherCost(FixedVectorType *Ty,
1894                                 const DenseSet<unsigned> &ShuffledIndices,
1895                                 bool NeedToShuffle) const;
1896 
1897   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1898   /// tree entries.
1899   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1900   /// previous tree entries. \p Mask is filled with the shuffle mask.
1901   Optional<TargetTransformInfo::ShuffleKind>
1902   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1903                         SmallVectorImpl<const TreeEntry *> &Entries);
1904 
1905   /// \returns the scalarization cost for this list of values. Assuming that
1906   /// this subtree gets vectorized, we may need to extract the values from the
1907   /// roots. This method calculates the cost of extracting the values.
1908   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1909 
1910   /// Set the Builder insert point to one after the last instruction in
1911   /// the bundle
1912   void setInsertPointAfterBundle(const TreeEntry *E);
1913 
1914   /// \returns a vector from a collection of scalars in \p VL.
1915   Value *gather(ArrayRef<Value *> VL);
1916 
1917   /// \returns whether the VectorizableTree is fully vectorizable and will
1918   /// be beneficial even the tree height is tiny.
1919   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1920 
1921   /// Reorder commutative or alt operands to get better probability of
1922   /// generating vectorized code.
1923   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1924                                              SmallVectorImpl<Value *> &Left,
1925                                              SmallVectorImpl<Value *> &Right,
1926                                              const DataLayout &DL,
1927                                              ScalarEvolution &SE,
1928                                              const BoUpSLP &R);
1929   struct TreeEntry {
1930     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1931     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1932 
1933     /// \returns true if the scalars in VL are equal to this entry.
1934     bool isSame(ArrayRef<Value *> VL) const {
1935       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1936         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1937           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1938         return VL.size() == Mask.size() &&
1939                std::equal(VL.begin(), VL.end(), Mask.begin(),
1940                           [Scalars](Value *V, int Idx) {
1941                             return (isa<UndefValue>(V) &&
1942                                     Idx == UndefMaskElem) ||
1943                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1944                           });
1945       };
1946       if (!ReorderIndices.empty()) {
1947         // TODO: implement matching if the nodes are just reordered, still can
1948         // treat the vector as the same if the list of scalars matches VL
1949         // directly, without reordering.
1950         SmallVector<int> Mask;
1951         inversePermutation(ReorderIndices, Mask);
1952         if (VL.size() == Scalars.size())
1953           return IsSame(Scalars, Mask);
1954         if (VL.size() == ReuseShuffleIndices.size()) {
1955           ::addMask(Mask, ReuseShuffleIndices);
1956           return IsSame(Scalars, Mask);
1957         }
1958         return false;
1959       }
1960       return IsSame(Scalars, ReuseShuffleIndices);
1961     }
1962 
1963     /// \returns true if current entry has same operands as \p TE.
1964     bool hasEqualOperands(const TreeEntry &TE) const {
1965       if (TE.getNumOperands() != getNumOperands())
1966         return false;
1967       SmallBitVector Used(getNumOperands());
1968       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1969         unsigned PrevCount = Used.count();
1970         for (unsigned K = 0; K < E; ++K) {
1971           if (Used.test(K))
1972             continue;
1973           if (getOperand(K) == TE.getOperand(I)) {
1974             Used.set(K);
1975             break;
1976           }
1977         }
1978         // Check if we actually found the matching operand.
1979         if (PrevCount == Used.count())
1980           return false;
1981       }
1982       return true;
1983     }
1984 
1985     /// \return Final vectorization factor for the node. Defined by the total
1986     /// number of vectorized scalars, including those, used several times in the
1987     /// entry and counted in the \a ReuseShuffleIndices, if any.
1988     unsigned getVectorFactor() const {
1989       if (!ReuseShuffleIndices.empty())
1990         return ReuseShuffleIndices.size();
1991       return Scalars.size();
1992     };
1993 
1994     /// A vector of scalars.
1995     ValueList Scalars;
1996 
1997     /// The Scalars are vectorized into this value. It is initialized to Null.
1998     Value *VectorizedValue = nullptr;
1999 
2000     /// Do we need to gather this sequence or vectorize it
2001     /// (either with vector instruction or with scatter/gather
2002     /// intrinsics for store/load)?
2003     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2004     EntryState State;
2005 
2006     /// Does this sequence require some shuffling?
2007     SmallVector<int, 4> ReuseShuffleIndices;
2008 
2009     /// Does this entry require reordering?
2010     SmallVector<unsigned, 4> ReorderIndices;
2011 
2012     /// Points back to the VectorizableTree.
2013     ///
2014     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2015     /// to be a pointer and needs to be able to initialize the child iterator.
2016     /// Thus we need a reference back to the container to translate the indices
2017     /// to entries.
2018     VecTreeTy &Container;
2019 
2020     /// The TreeEntry index containing the user of this entry.  We can actually
2021     /// have multiple users so the data structure is not truly a tree.
2022     SmallVector<EdgeInfo, 1> UserTreeIndices;
2023 
2024     /// The index of this treeEntry in VectorizableTree.
2025     int Idx = -1;
2026 
2027   private:
2028     /// The operands of each instruction in each lane Operands[op_index][lane].
2029     /// Note: This helps avoid the replication of the code that performs the
2030     /// reordering of operands during buildTree_rec() and vectorizeTree().
2031     SmallVector<ValueList, 2> Operands;
2032 
2033     /// The main/alternate instruction.
2034     Instruction *MainOp = nullptr;
2035     Instruction *AltOp = nullptr;
2036 
2037   public:
2038     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2039     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2040       if (Operands.size() < OpIdx + 1)
2041         Operands.resize(OpIdx + 1);
2042       assert(Operands[OpIdx].empty() && "Already resized?");
2043       assert(OpVL.size() <= Scalars.size() &&
2044              "Number of operands is greater than the number of scalars.");
2045       Operands[OpIdx].resize(OpVL.size());
2046       copy(OpVL, Operands[OpIdx].begin());
2047     }
2048 
2049     /// Set the operands of this bundle in their original order.
2050     void setOperandsInOrder() {
2051       assert(Operands.empty() && "Already initialized?");
2052       auto *I0 = cast<Instruction>(Scalars[0]);
2053       Operands.resize(I0->getNumOperands());
2054       unsigned NumLanes = Scalars.size();
2055       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2056            OpIdx != NumOperands; ++OpIdx) {
2057         Operands[OpIdx].resize(NumLanes);
2058         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2059           auto *I = cast<Instruction>(Scalars[Lane]);
2060           assert(I->getNumOperands() == NumOperands &&
2061                  "Expected same number of operands");
2062           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2063         }
2064       }
2065     }
2066 
2067     /// Reorders operands of the node to the given mask \p Mask.
2068     void reorderOperands(ArrayRef<int> Mask) {
2069       for (ValueList &Operand : Operands)
2070         reorderScalars(Operand, Mask);
2071     }
2072 
2073     /// \returns the \p OpIdx operand of this TreeEntry.
2074     ValueList &getOperand(unsigned OpIdx) {
2075       assert(OpIdx < Operands.size() && "Off bounds");
2076       return Operands[OpIdx];
2077     }
2078 
2079     /// \returns the \p OpIdx operand of this TreeEntry.
2080     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2081       assert(OpIdx < Operands.size() && "Off bounds");
2082       return Operands[OpIdx];
2083     }
2084 
2085     /// \returns the number of operands.
2086     unsigned getNumOperands() const { return Operands.size(); }
2087 
2088     /// \return the single \p OpIdx operand.
2089     Value *getSingleOperand(unsigned OpIdx) const {
2090       assert(OpIdx < Operands.size() && "Off bounds");
2091       assert(!Operands[OpIdx].empty() && "No operand available");
2092       return Operands[OpIdx][0];
2093     }
2094 
2095     /// Some of the instructions in the list have alternate opcodes.
2096     bool isAltShuffle() const { return MainOp != AltOp; }
2097 
2098     bool isOpcodeOrAlt(Instruction *I) const {
2099       unsigned CheckedOpcode = I->getOpcode();
2100       return (getOpcode() == CheckedOpcode ||
2101               getAltOpcode() == CheckedOpcode);
2102     }
2103 
2104     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2105     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2106     /// \p OpValue.
2107     Value *isOneOf(Value *Op) const {
2108       auto *I = dyn_cast<Instruction>(Op);
2109       if (I && isOpcodeOrAlt(I))
2110         return Op;
2111       return MainOp;
2112     }
2113 
2114     void setOperations(const InstructionsState &S) {
2115       MainOp = S.MainOp;
2116       AltOp = S.AltOp;
2117     }
2118 
2119     Instruction *getMainOp() const {
2120       return MainOp;
2121     }
2122 
2123     Instruction *getAltOp() const {
2124       return AltOp;
2125     }
2126 
2127     /// The main/alternate opcodes for the list of instructions.
2128     unsigned getOpcode() const {
2129       return MainOp ? MainOp->getOpcode() : 0;
2130     }
2131 
2132     unsigned getAltOpcode() const {
2133       return AltOp ? AltOp->getOpcode() : 0;
2134     }
2135 
2136     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2137     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2138     int findLaneForValue(Value *V) const {
2139       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2140       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2141       if (!ReorderIndices.empty())
2142         FoundLane = ReorderIndices[FoundLane];
2143       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2144       if (!ReuseShuffleIndices.empty()) {
2145         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2146                                   find(ReuseShuffleIndices, FoundLane));
2147       }
2148       return FoundLane;
2149     }
2150 
2151 #ifndef NDEBUG
2152     /// Debug printer.
2153     LLVM_DUMP_METHOD void dump() const {
2154       dbgs() << Idx << ".\n";
2155       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2156         dbgs() << "Operand " << OpI << ":\n";
2157         for (const Value *V : Operands[OpI])
2158           dbgs().indent(2) << *V << "\n";
2159       }
2160       dbgs() << "Scalars: \n";
2161       for (Value *V : Scalars)
2162         dbgs().indent(2) << *V << "\n";
2163       dbgs() << "State: ";
2164       switch (State) {
2165       case Vectorize:
2166         dbgs() << "Vectorize\n";
2167         break;
2168       case ScatterVectorize:
2169         dbgs() << "ScatterVectorize\n";
2170         break;
2171       case NeedToGather:
2172         dbgs() << "NeedToGather\n";
2173         break;
2174       }
2175       dbgs() << "MainOp: ";
2176       if (MainOp)
2177         dbgs() << *MainOp << "\n";
2178       else
2179         dbgs() << "NULL\n";
2180       dbgs() << "AltOp: ";
2181       if (AltOp)
2182         dbgs() << *AltOp << "\n";
2183       else
2184         dbgs() << "NULL\n";
2185       dbgs() << "VectorizedValue: ";
2186       if (VectorizedValue)
2187         dbgs() << *VectorizedValue << "\n";
2188       else
2189         dbgs() << "NULL\n";
2190       dbgs() << "ReuseShuffleIndices: ";
2191       if (ReuseShuffleIndices.empty())
2192         dbgs() << "Empty";
2193       else
2194         for (int ReuseIdx : ReuseShuffleIndices)
2195           dbgs() << ReuseIdx << ", ";
2196       dbgs() << "\n";
2197       dbgs() << "ReorderIndices: ";
2198       for (unsigned ReorderIdx : ReorderIndices)
2199         dbgs() << ReorderIdx << ", ";
2200       dbgs() << "\n";
2201       dbgs() << "UserTreeIndices: ";
2202       for (const auto &EInfo : UserTreeIndices)
2203         dbgs() << EInfo << ", ";
2204       dbgs() << "\n";
2205     }
2206 #endif
2207   };
2208 
2209 #ifndef NDEBUG
2210   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2211                      InstructionCost VecCost,
2212                      InstructionCost ScalarCost) const {
2213     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2214     dbgs() << "SLP: Costs:\n";
2215     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2216     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2217     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2218     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2219                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2220   }
2221 #endif
2222 
2223   /// Create a new VectorizableTree entry.
2224   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2225                           const InstructionsState &S,
2226                           const EdgeInfo &UserTreeIdx,
2227                           ArrayRef<int> ReuseShuffleIndices = None,
2228                           ArrayRef<unsigned> ReorderIndices = None) {
2229     TreeEntry::EntryState EntryState =
2230         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2231     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2232                         ReuseShuffleIndices, ReorderIndices);
2233   }
2234 
2235   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2236                           TreeEntry::EntryState EntryState,
2237                           Optional<ScheduleData *> Bundle,
2238                           const InstructionsState &S,
2239                           const EdgeInfo &UserTreeIdx,
2240                           ArrayRef<int> ReuseShuffleIndices = None,
2241                           ArrayRef<unsigned> ReorderIndices = None) {
2242     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2243             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2244            "Need to vectorize gather entry?");
2245     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2246     TreeEntry *Last = VectorizableTree.back().get();
2247     Last->Idx = VectorizableTree.size() - 1;
2248     Last->State = EntryState;
2249     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2250                                      ReuseShuffleIndices.end());
2251     if (ReorderIndices.empty()) {
2252       Last->Scalars.assign(VL.begin(), VL.end());
2253       Last->setOperations(S);
2254     } else {
2255       // Reorder scalars and build final mask.
2256       Last->Scalars.assign(VL.size(), nullptr);
2257       transform(ReorderIndices, Last->Scalars.begin(),
2258                 [VL](unsigned Idx) -> Value * {
2259                   if (Idx >= VL.size())
2260                     return UndefValue::get(VL.front()->getType());
2261                   return VL[Idx];
2262                 });
2263       InstructionsState S = getSameOpcode(Last->Scalars);
2264       Last->setOperations(S);
2265       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2266     }
2267     if (Last->State != TreeEntry::NeedToGather) {
2268       for (Value *V : VL) {
2269         assert(!getTreeEntry(V) && "Scalar already in tree!");
2270         ScalarToTreeEntry[V] = Last;
2271       }
2272       // Update the scheduler bundle to point to this TreeEntry.
2273       unsigned Lane = 0;
2274       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2275            BundleMember = BundleMember->NextInBundle) {
2276         BundleMember->TE = Last;
2277         BundleMember->Lane = Lane;
2278         ++Lane;
2279       }
2280       assert((!Bundle.getValue() || Lane == VL.size()) &&
2281              "Bundle and VL out of sync");
2282     } else {
2283       MustGather.insert(VL.begin(), VL.end());
2284     }
2285 
2286     if (UserTreeIdx.UserTE)
2287       Last->UserTreeIndices.push_back(UserTreeIdx);
2288 
2289     return Last;
2290   }
2291 
2292   /// -- Vectorization State --
2293   /// Holds all of the tree entries.
2294   TreeEntry::VecTreeTy VectorizableTree;
2295 
2296 #ifndef NDEBUG
2297   /// Debug printer.
2298   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2299     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2300       VectorizableTree[Id]->dump();
2301       dbgs() << "\n";
2302     }
2303   }
2304 #endif
2305 
2306   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2307 
2308   const TreeEntry *getTreeEntry(Value *V) const {
2309     return ScalarToTreeEntry.lookup(V);
2310   }
2311 
2312   /// Maps a specific scalar to its tree entry.
2313   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2314 
2315   /// Maps a value to the proposed vectorizable size.
2316   SmallDenseMap<Value *, unsigned> InstrElementSize;
2317 
2318   /// A list of scalars that we found that we need to keep as scalars.
2319   ValueSet MustGather;
2320 
2321   /// This POD struct describes one external user in the vectorized tree.
2322   struct ExternalUser {
2323     ExternalUser(Value *S, llvm::User *U, int L)
2324         : Scalar(S), User(U), Lane(L) {}
2325 
2326     // Which scalar in our function.
2327     Value *Scalar;
2328 
2329     // Which user that uses the scalar.
2330     llvm::User *User;
2331 
2332     // Which lane does the scalar belong to.
2333     int Lane;
2334   };
2335   using UserList = SmallVector<ExternalUser, 16>;
2336 
2337   /// Checks if two instructions may access the same memory.
2338   ///
2339   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2340   /// is invariant in the calling loop.
2341   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2342                  Instruction *Inst2) {
2343     // First check if the result is already in the cache.
2344     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2345     Optional<bool> &result = AliasCache[key];
2346     if (result.hasValue()) {
2347       return result.getValue();
2348     }
2349     bool aliased = true;
2350     if (Loc1.Ptr && isSimple(Inst1))
2351       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2352     // Store the result in the cache.
2353     result = aliased;
2354     return aliased;
2355   }
2356 
2357   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2358 
2359   /// Cache for alias results.
2360   /// TODO: consider moving this to the AliasAnalysis itself.
2361   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2362 
2363   /// Removes an instruction from its block and eventually deletes it.
2364   /// It's like Instruction::eraseFromParent() except that the actual deletion
2365   /// is delayed until BoUpSLP is destructed.
2366   /// This is required to ensure that there are no incorrect collisions in the
2367   /// AliasCache, which can happen if a new instruction is allocated at the
2368   /// same address as a previously deleted instruction.
2369   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2370     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2371     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2372   }
2373 
2374   /// Temporary store for deleted instructions. Instructions will be deleted
2375   /// eventually when the BoUpSLP is destructed.
2376   DenseMap<Instruction *, bool> DeletedInstructions;
2377 
2378   /// A list of values that need to extracted out of the tree.
2379   /// This list holds pairs of (Internal Scalar : External User). External User
2380   /// can be nullptr, it means that this Internal Scalar will be used later,
2381   /// after vectorization.
2382   UserList ExternalUses;
2383 
2384   /// Values used only by @llvm.assume calls.
2385   SmallPtrSet<const Value *, 32> EphValues;
2386 
2387   /// Holds all of the instructions that we gathered.
2388   SetVector<Instruction *> GatherShuffleSeq;
2389 
2390   /// A list of blocks that we are going to CSE.
2391   SetVector<BasicBlock *> CSEBlocks;
2392 
2393   /// Contains all scheduling relevant data for an instruction.
2394   /// A ScheduleData either represents a single instruction or a member of an
2395   /// instruction bundle (= a group of instructions which is combined into a
2396   /// vector instruction).
2397   struct ScheduleData {
2398     // The initial value for the dependency counters. It means that the
2399     // dependencies are not calculated yet.
2400     enum { InvalidDeps = -1 };
2401 
2402     ScheduleData() = default;
2403 
2404     void init(int BlockSchedulingRegionID, Value *OpVal) {
2405       FirstInBundle = this;
2406       NextInBundle = nullptr;
2407       NextLoadStore = nullptr;
2408       IsScheduled = false;
2409       SchedulingRegionID = BlockSchedulingRegionID;
2410       UnscheduledDepsInBundle = UnscheduledDeps;
2411       clearDependencies();
2412       OpValue = OpVal;
2413       TE = nullptr;
2414       Lane = -1;
2415     }
2416 
2417     /// Returns true if the dependency information has been calculated.
2418     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2419 
2420     /// Returns true for single instructions and for bundle representatives
2421     /// (= the head of a bundle).
2422     bool isSchedulingEntity() const { return FirstInBundle == this; }
2423 
2424     /// Returns true if it represents an instruction bundle and not only a
2425     /// single instruction.
2426     bool isPartOfBundle() const {
2427       return NextInBundle != nullptr || FirstInBundle != this;
2428     }
2429 
2430     /// Returns true if it is ready for scheduling, i.e. it has no more
2431     /// unscheduled depending instructions/bundles.
2432     bool isReady() const {
2433       assert(isSchedulingEntity() &&
2434              "can't consider non-scheduling entity for ready list");
2435       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2436     }
2437 
2438     /// Modifies the number of unscheduled dependencies, also updating it for
2439     /// the whole bundle.
2440     int incrementUnscheduledDeps(int Incr) {
2441       UnscheduledDeps += Incr;
2442       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2443     }
2444 
2445     /// Sets the number of unscheduled dependencies to the number of
2446     /// dependencies.
2447     void resetUnscheduledDeps() {
2448       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2449     }
2450 
2451     /// Clears all dependency information.
2452     void clearDependencies() {
2453       Dependencies = InvalidDeps;
2454       resetUnscheduledDeps();
2455       MemoryDependencies.clear();
2456     }
2457 
2458     void dump(raw_ostream &os) const {
2459       if (!isSchedulingEntity()) {
2460         os << "/ " << *Inst;
2461       } else if (NextInBundle) {
2462         os << '[' << *Inst;
2463         ScheduleData *SD = NextInBundle;
2464         while (SD) {
2465           os << ';' << *SD->Inst;
2466           SD = SD->NextInBundle;
2467         }
2468         os << ']';
2469       } else {
2470         os << *Inst;
2471       }
2472     }
2473 
2474     Instruction *Inst = nullptr;
2475 
2476     /// Points to the head in an instruction bundle (and always to this for
2477     /// single instructions).
2478     ScheduleData *FirstInBundle = nullptr;
2479 
2480     /// Single linked list of all instructions in a bundle. Null if it is a
2481     /// single instruction.
2482     ScheduleData *NextInBundle = nullptr;
2483 
2484     /// Single linked list of all memory instructions (e.g. load, store, call)
2485     /// in the block - until the end of the scheduling region.
2486     ScheduleData *NextLoadStore = nullptr;
2487 
2488     /// The dependent memory instructions.
2489     /// This list is derived on demand in calculateDependencies().
2490     SmallVector<ScheduleData *, 4> MemoryDependencies;
2491 
2492     /// This ScheduleData is in the current scheduling region if this matches
2493     /// the current SchedulingRegionID of BlockScheduling.
2494     int SchedulingRegionID = 0;
2495 
2496     /// Used for getting a "good" final ordering of instructions.
2497     int SchedulingPriority = 0;
2498 
2499     /// The number of dependencies. Constitutes of the number of users of the
2500     /// instruction plus the number of dependent memory instructions (if any).
2501     /// This value is calculated on demand.
2502     /// If InvalidDeps, the number of dependencies is not calculated yet.
2503     int Dependencies = InvalidDeps;
2504 
2505     /// The number of dependencies minus the number of dependencies of scheduled
2506     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2507     /// for scheduling.
2508     /// Note that this is negative as long as Dependencies is not calculated.
2509     int UnscheduledDeps = InvalidDeps;
2510 
2511     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2512     /// single instructions.
2513     int UnscheduledDepsInBundle = InvalidDeps;
2514 
2515     /// True if this instruction is scheduled (or considered as scheduled in the
2516     /// dry-run).
2517     bool IsScheduled = false;
2518 
2519     /// Opcode of the current instruction in the schedule data.
2520     Value *OpValue = nullptr;
2521 
2522     /// The TreeEntry that this instruction corresponds to.
2523     TreeEntry *TE = nullptr;
2524 
2525     /// The lane of this node in the TreeEntry.
2526     int Lane = -1;
2527   };
2528 
2529 #ifndef NDEBUG
2530   friend inline raw_ostream &operator<<(raw_ostream &os,
2531                                         const BoUpSLP::ScheduleData &SD) {
2532     SD.dump(os);
2533     return os;
2534   }
2535 #endif
2536 
2537   friend struct GraphTraits<BoUpSLP *>;
2538   friend struct DOTGraphTraits<BoUpSLP *>;
2539 
2540   /// Contains all scheduling data for a basic block.
2541   struct BlockScheduling {
2542     BlockScheduling(BasicBlock *BB)
2543         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2544 
2545     void clear() {
2546       ReadyInsts.clear();
2547       ScheduleStart = nullptr;
2548       ScheduleEnd = nullptr;
2549       FirstLoadStoreInRegion = nullptr;
2550       LastLoadStoreInRegion = nullptr;
2551 
2552       // Reduce the maximum schedule region size by the size of the
2553       // previous scheduling run.
2554       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2555       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2556         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2557       ScheduleRegionSize = 0;
2558 
2559       // Make a new scheduling region, i.e. all existing ScheduleData is not
2560       // in the new region yet.
2561       ++SchedulingRegionID;
2562     }
2563 
2564     ScheduleData *getScheduleData(Value *V) {
2565       ScheduleData *SD = ScheduleDataMap[V];
2566       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2567         return SD;
2568       return nullptr;
2569     }
2570 
2571     ScheduleData *getScheduleData(Value *V, Value *Key) {
2572       if (V == Key)
2573         return getScheduleData(V);
2574       auto I = ExtraScheduleDataMap.find(V);
2575       if (I != ExtraScheduleDataMap.end()) {
2576         ScheduleData *SD = I->second[Key];
2577         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2578           return SD;
2579       }
2580       return nullptr;
2581     }
2582 
2583     bool isInSchedulingRegion(ScheduleData *SD) const {
2584       return SD->SchedulingRegionID == SchedulingRegionID;
2585     }
2586 
2587     /// Marks an instruction as scheduled and puts all dependent ready
2588     /// instructions into the ready-list.
2589     template <typename ReadyListType>
2590     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2591       SD->IsScheduled = true;
2592       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2593 
2594       for (ScheduleData *BundleMember = SD; BundleMember;
2595            BundleMember = BundleMember->NextInBundle) {
2596         if (BundleMember->Inst != BundleMember->OpValue)
2597           continue;
2598 
2599         // Handle the def-use chain dependencies.
2600 
2601         // Decrement the unscheduled counter and insert to ready list if ready.
2602         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2603           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2604             if (OpDef && OpDef->hasValidDependencies() &&
2605                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2606               // There are no more unscheduled dependencies after
2607               // decrementing, so we can put the dependent instruction
2608               // into the ready list.
2609               ScheduleData *DepBundle = OpDef->FirstInBundle;
2610               assert(!DepBundle->IsScheduled &&
2611                      "already scheduled bundle gets ready");
2612               ReadyList.insert(DepBundle);
2613               LLVM_DEBUG(dbgs()
2614                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2615             }
2616           });
2617         };
2618 
2619         // If BundleMember is a vector bundle, its operands may have been
2620         // reordered duiring buildTree(). We therefore need to get its operands
2621         // through the TreeEntry.
2622         if (TreeEntry *TE = BundleMember->TE) {
2623           int Lane = BundleMember->Lane;
2624           assert(Lane >= 0 && "Lane not set");
2625 
2626           // Since vectorization tree is being built recursively this assertion
2627           // ensures that the tree entry has all operands set before reaching
2628           // this code. Couple of exceptions known at the moment are extracts
2629           // where their second (immediate) operand is not added. Since
2630           // immediates do not affect scheduler behavior this is considered
2631           // okay.
2632           auto *In = TE->getMainOp();
2633           assert(In &&
2634                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2635                   In->getNumOperands() == TE->getNumOperands()) &&
2636                  "Missed TreeEntry operands?");
2637           (void)In; // fake use to avoid build failure when assertions disabled
2638 
2639           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2640                OpIdx != NumOperands; ++OpIdx)
2641             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2642               DecrUnsched(I);
2643         } else {
2644           // If BundleMember is a stand-alone instruction, no operand reordering
2645           // has taken place, so we directly access its operands.
2646           for (Use &U : BundleMember->Inst->operands())
2647             if (auto *I = dyn_cast<Instruction>(U.get()))
2648               DecrUnsched(I);
2649         }
2650         // Handle the memory dependencies.
2651         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2652           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2653             // There are no more unscheduled dependencies after decrementing,
2654             // so we can put the dependent instruction into the ready list.
2655             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2656             assert(!DepBundle->IsScheduled &&
2657                    "already scheduled bundle gets ready");
2658             ReadyList.insert(DepBundle);
2659             LLVM_DEBUG(dbgs()
2660                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2661           }
2662         }
2663       }
2664     }
2665 
2666     void doForAllOpcodes(Value *V,
2667                          function_ref<void(ScheduleData *SD)> Action) {
2668       if (ScheduleData *SD = getScheduleData(V))
2669         Action(SD);
2670       auto I = ExtraScheduleDataMap.find(V);
2671       if (I != ExtraScheduleDataMap.end())
2672         for (auto &P : I->second)
2673           if (P.second->SchedulingRegionID == SchedulingRegionID)
2674             Action(P.second);
2675     }
2676 
2677     /// Put all instructions into the ReadyList which are ready for scheduling.
2678     template <typename ReadyListType>
2679     void initialFillReadyList(ReadyListType &ReadyList) {
2680       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2681         doForAllOpcodes(I, [&](ScheduleData *SD) {
2682           if (SD->isSchedulingEntity() && SD->isReady()) {
2683             ReadyList.insert(SD);
2684             LLVM_DEBUG(dbgs()
2685                        << "SLP:    initially in ready list: " << *I << "\n");
2686           }
2687         });
2688       }
2689     }
2690 
2691     /// Build a bundle from the ScheduleData nodes corresponding to the
2692     /// scalar instruction for each lane.
2693     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2694 
2695     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2696     /// cyclic dependencies. This is only a dry-run, no instructions are
2697     /// actually moved at this stage.
2698     /// \returns the scheduling bundle. The returned Optional value is non-None
2699     /// if \p VL is allowed to be scheduled.
2700     Optional<ScheduleData *>
2701     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2702                       const InstructionsState &S);
2703 
2704     /// Un-bundles a group of instructions.
2705     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2706 
2707     /// Allocates schedule data chunk.
2708     ScheduleData *allocateScheduleDataChunks();
2709 
2710     /// Extends the scheduling region so that V is inside the region.
2711     /// \returns true if the region size is within the limit.
2712     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2713 
2714     /// Initialize the ScheduleData structures for new instructions in the
2715     /// scheduling region.
2716     void initScheduleData(Instruction *FromI, Instruction *ToI,
2717                           ScheduleData *PrevLoadStore,
2718                           ScheduleData *NextLoadStore);
2719 
2720     /// Updates the dependency information of a bundle and of all instructions/
2721     /// bundles which depend on the original bundle.
2722     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2723                                BoUpSLP *SLP);
2724 
2725     /// Sets all instruction in the scheduling region to un-scheduled.
2726     void resetSchedule();
2727 
2728     BasicBlock *BB;
2729 
2730     /// Simple memory allocation for ScheduleData.
2731     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2732 
2733     /// The size of a ScheduleData array in ScheduleDataChunks.
2734     int ChunkSize;
2735 
2736     /// The allocator position in the current chunk, which is the last entry
2737     /// of ScheduleDataChunks.
2738     int ChunkPos;
2739 
2740     /// Attaches ScheduleData to Instruction.
2741     /// Note that the mapping survives during all vectorization iterations, i.e.
2742     /// ScheduleData structures are recycled.
2743     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2744 
2745     /// Attaches ScheduleData to Instruction with the leading key.
2746     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2747         ExtraScheduleDataMap;
2748 
2749     struct ReadyList : SmallVector<ScheduleData *, 8> {
2750       void insert(ScheduleData *SD) { push_back(SD); }
2751     };
2752 
2753     /// The ready-list for scheduling (only used for the dry-run).
2754     ReadyList ReadyInsts;
2755 
2756     /// The first instruction of the scheduling region.
2757     Instruction *ScheduleStart = nullptr;
2758 
2759     /// The first instruction _after_ the scheduling region.
2760     Instruction *ScheduleEnd = nullptr;
2761 
2762     /// The first memory accessing instruction in the scheduling region
2763     /// (can be null).
2764     ScheduleData *FirstLoadStoreInRegion = nullptr;
2765 
2766     /// The last memory accessing instruction in the scheduling region
2767     /// (can be null).
2768     ScheduleData *LastLoadStoreInRegion = nullptr;
2769 
2770     /// The current size of the scheduling region.
2771     int ScheduleRegionSize = 0;
2772 
2773     /// The maximum size allowed for the scheduling region.
2774     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2775 
2776     /// The ID of the scheduling region. For a new vectorization iteration this
2777     /// is incremented which "removes" all ScheduleData from the region.
2778     // Make sure that the initial SchedulingRegionID is greater than the
2779     // initial SchedulingRegionID in ScheduleData (which is 0).
2780     int SchedulingRegionID = 1;
2781   };
2782 
2783   /// Attaches the BlockScheduling structures to basic blocks.
2784   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2785 
2786   /// Performs the "real" scheduling. Done before vectorization is actually
2787   /// performed in a basic block.
2788   void scheduleBlock(BlockScheduling *BS);
2789 
2790   /// List of users to ignore during scheduling and that don't need extracting.
2791   ArrayRef<Value *> UserIgnoreList;
2792 
2793   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2794   /// sorted SmallVectors of unsigned.
2795   struct OrdersTypeDenseMapInfo {
2796     static OrdersType getEmptyKey() {
2797       OrdersType V;
2798       V.push_back(~1U);
2799       return V;
2800     }
2801 
2802     static OrdersType getTombstoneKey() {
2803       OrdersType V;
2804       V.push_back(~2U);
2805       return V;
2806     }
2807 
2808     static unsigned getHashValue(const OrdersType &V) {
2809       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2810     }
2811 
2812     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2813       return LHS == RHS;
2814     }
2815   };
2816 
2817   // Analysis and block reference.
2818   Function *F;
2819   ScalarEvolution *SE;
2820   TargetTransformInfo *TTI;
2821   TargetLibraryInfo *TLI;
2822   AAResults *AA;
2823   LoopInfo *LI;
2824   DominatorTree *DT;
2825   AssumptionCache *AC;
2826   DemandedBits *DB;
2827   const DataLayout *DL;
2828   OptimizationRemarkEmitter *ORE;
2829 
2830   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2831   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2832 
2833   /// Instruction builder to construct the vectorized tree.
2834   IRBuilder<> Builder;
2835 
2836   /// A map of scalar integer values to the smallest bit width with which they
2837   /// can legally be represented. The values map to (width, signed) pairs,
2838   /// where "width" indicates the minimum bit width and "signed" is True if the
2839   /// value must be signed-extended, rather than zero-extended, back to its
2840   /// original width.
2841   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2842 };
2843 
2844 } // end namespace slpvectorizer
2845 
2846 template <> struct GraphTraits<BoUpSLP *> {
2847   using TreeEntry = BoUpSLP::TreeEntry;
2848 
2849   /// NodeRef has to be a pointer per the GraphWriter.
2850   using NodeRef = TreeEntry *;
2851 
2852   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2853 
2854   /// Add the VectorizableTree to the index iterator to be able to return
2855   /// TreeEntry pointers.
2856   struct ChildIteratorType
2857       : public iterator_adaptor_base<
2858             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2859     ContainerTy &VectorizableTree;
2860 
2861     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2862                       ContainerTy &VT)
2863         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2864 
2865     NodeRef operator*() { return I->UserTE; }
2866   };
2867 
2868   static NodeRef getEntryNode(BoUpSLP &R) {
2869     return R.VectorizableTree[0].get();
2870   }
2871 
2872   static ChildIteratorType child_begin(NodeRef N) {
2873     return {N->UserTreeIndices.begin(), N->Container};
2874   }
2875 
2876   static ChildIteratorType child_end(NodeRef N) {
2877     return {N->UserTreeIndices.end(), N->Container};
2878   }
2879 
2880   /// For the node iterator we just need to turn the TreeEntry iterator into a
2881   /// TreeEntry* iterator so that it dereferences to NodeRef.
2882   class nodes_iterator {
2883     using ItTy = ContainerTy::iterator;
2884     ItTy It;
2885 
2886   public:
2887     nodes_iterator(const ItTy &It2) : It(It2) {}
2888     NodeRef operator*() { return It->get(); }
2889     nodes_iterator operator++() {
2890       ++It;
2891       return *this;
2892     }
2893     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2894   };
2895 
2896   static nodes_iterator nodes_begin(BoUpSLP *R) {
2897     return nodes_iterator(R->VectorizableTree.begin());
2898   }
2899 
2900   static nodes_iterator nodes_end(BoUpSLP *R) {
2901     return nodes_iterator(R->VectorizableTree.end());
2902   }
2903 
2904   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2905 };
2906 
2907 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2908   using TreeEntry = BoUpSLP::TreeEntry;
2909 
2910   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2911 
2912   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2913     std::string Str;
2914     raw_string_ostream OS(Str);
2915     if (isSplat(Entry->Scalars))
2916       OS << "<splat> ";
2917     for (auto V : Entry->Scalars) {
2918       OS << *V;
2919       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2920             return EU.Scalar == V;
2921           }))
2922         OS << " <extract>";
2923       OS << "\n";
2924     }
2925     return Str;
2926   }
2927 
2928   static std::string getNodeAttributes(const TreeEntry *Entry,
2929                                        const BoUpSLP *) {
2930     if (Entry->State == TreeEntry::NeedToGather)
2931       return "color=red";
2932     return "";
2933   }
2934 };
2935 
2936 } // end namespace llvm
2937 
2938 BoUpSLP::~BoUpSLP() {
2939   for (const auto &Pair : DeletedInstructions) {
2940     // Replace operands of ignored instructions with Undefs in case if they were
2941     // marked for deletion.
2942     if (Pair.getSecond()) {
2943       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2944       Pair.getFirst()->replaceAllUsesWith(Undef);
2945     }
2946     Pair.getFirst()->dropAllReferences();
2947   }
2948   for (const auto &Pair : DeletedInstructions) {
2949     assert(Pair.getFirst()->use_empty() &&
2950            "trying to erase instruction with users.");
2951     Pair.getFirst()->eraseFromParent();
2952   }
2953 #ifdef EXPENSIVE_CHECKS
2954   // If we could guarantee that this call is not extremely slow, we could
2955   // remove the ifdef limitation (see PR47712).
2956   assert(!verifyFunction(*F, &dbgs()));
2957 #endif
2958 }
2959 
2960 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2961   for (auto *V : AV) {
2962     if (auto *I = dyn_cast<Instruction>(V))
2963       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2964   };
2965 }
2966 
2967 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
2968 /// contains original mask for the scalars reused in the node. Procedure
2969 /// transform this mask in accordance with the given \p Mask.
2970 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
2971   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
2972          "Expected non-empty mask.");
2973   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
2974   Prev.swap(Reuses);
2975   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
2976     if (Mask[I] != UndefMaskElem)
2977       Reuses[Mask[I]] = Prev[I];
2978 }
2979 
2980 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
2981 /// the original order of the scalars. Procedure transforms the provided order
2982 /// in accordance with the given \p Mask. If the resulting \p Order is just an
2983 /// identity order, \p Order is cleared.
2984 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
2985   assert(!Mask.empty() && "Expected non-empty mask.");
2986   SmallVector<int> MaskOrder;
2987   if (Order.empty()) {
2988     MaskOrder.resize(Mask.size());
2989     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
2990   } else {
2991     inversePermutation(Order, MaskOrder);
2992   }
2993   reorderReuses(MaskOrder, Mask);
2994   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
2995     Order.clear();
2996     return;
2997   }
2998   Order.assign(Mask.size(), Mask.size());
2999   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3000     if (MaskOrder[I] != UndefMaskElem)
3001       Order[MaskOrder[I]] = I;
3002   fixupOrderingIndices(Order);
3003 }
3004 
3005 Optional<BoUpSLP::OrdersType>
3006 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3007   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3008   unsigned NumScalars = TE.Scalars.size();
3009   OrdersType CurrentOrder(NumScalars, NumScalars);
3010   SmallVector<int> Positions;
3011   SmallBitVector UsedPositions(NumScalars);
3012   const TreeEntry *STE = nullptr;
3013   // Try to find all gathered scalars that are gets vectorized in other
3014   // vectorize node. Here we can have only one single tree vector node to
3015   // correctly identify order of the gathered scalars.
3016   for (unsigned I = 0; I < NumScalars; ++I) {
3017     Value *V = TE.Scalars[I];
3018     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3019       continue;
3020     if (const auto *LocalSTE = getTreeEntry(V)) {
3021       if (!STE)
3022         STE = LocalSTE;
3023       else if (STE != LocalSTE)
3024         // Take the order only from the single vector node.
3025         return None;
3026       unsigned Lane =
3027           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3028       if (Lane >= NumScalars)
3029         return None;
3030       if (CurrentOrder[Lane] != NumScalars) {
3031         if (Lane != I)
3032           continue;
3033         UsedPositions.reset(CurrentOrder[Lane]);
3034       }
3035       // The partial identity (where only some elements of the gather node are
3036       // in the identity order) is good.
3037       CurrentOrder[Lane] = I;
3038       UsedPositions.set(I);
3039     }
3040   }
3041   // Need to keep the order if we have a vector entry and at least 2 scalars or
3042   // the vectorized entry has just 2 scalars.
3043   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3044     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3045       for (unsigned I = 0; I < NumScalars; ++I)
3046         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3047           return false;
3048       return true;
3049     };
3050     if (IsIdentityOrder(CurrentOrder)) {
3051       CurrentOrder.clear();
3052       return CurrentOrder;
3053     }
3054     auto *It = CurrentOrder.begin();
3055     for (unsigned I = 0; I < NumScalars;) {
3056       if (UsedPositions.test(I)) {
3057         ++I;
3058         continue;
3059       }
3060       if (*It == NumScalars) {
3061         *It = I;
3062         ++I;
3063       }
3064       ++It;
3065     }
3066     return CurrentOrder;
3067   }
3068   return None;
3069 }
3070 
3071 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3072                                                          bool TopToBottom) {
3073   // No need to reorder if need to shuffle reuses, still need to shuffle the
3074   // node.
3075   if (!TE.ReuseShuffleIndices.empty())
3076     return None;
3077   if (TE.State == TreeEntry::Vectorize &&
3078       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3079        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3080       !TE.isAltShuffle())
3081     return TE.ReorderIndices;
3082   if (TE.State == TreeEntry::NeedToGather) {
3083     // TODO: add analysis of other gather nodes with extractelement
3084     // instructions and other values/instructions, not only undefs.
3085     if (((TE.getOpcode() == Instruction::ExtractElement &&
3086           !TE.isAltShuffle()) ||
3087          (all_of(TE.Scalars,
3088                  [](Value *V) {
3089                    return isa<UndefValue, ExtractElementInst>(V);
3090                  }) &&
3091           any_of(TE.Scalars,
3092                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3093         all_of(TE.Scalars,
3094                [](Value *V) {
3095                  auto *EE = dyn_cast<ExtractElementInst>(V);
3096                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3097                }) &&
3098         allSameType(TE.Scalars)) {
3099       // Check that gather of extractelements can be represented as
3100       // just a shuffle of a single vector.
3101       OrdersType CurrentOrder;
3102       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3103       if (Reuse || !CurrentOrder.empty()) {
3104         if (!CurrentOrder.empty())
3105           fixupOrderingIndices(CurrentOrder);
3106         return CurrentOrder;
3107       }
3108     }
3109     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3110       return CurrentOrder;
3111   }
3112   return None;
3113 }
3114 
3115 void BoUpSLP::reorderTopToBottom() {
3116   // Maps VF to the graph nodes.
3117   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3118   // ExtractElement gather nodes which can be vectorized and need to handle
3119   // their ordering.
3120   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3121   // Find all reorderable nodes with the given VF.
3122   // Currently the are vectorized stores,loads,extracts + some gathering of
3123   // extracts.
3124   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3125                                  const std::unique_ptr<TreeEntry> &TE) {
3126     if (Optional<OrdersType> CurrentOrder =
3127             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3128       // Do not include ordering for nodes used in the alt opcode vectorization,
3129       // better to reorder them during bottom-to-top stage. If follow the order
3130       // here, it causes reordering of the whole graph though actually it is
3131       // profitable just to reorder the subgraph that starts from the alternate
3132       // opcode vectorization node. Such nodes already end-up with the shuffle
3133       // instruction and it is just enough to change this shuffle rather than
3134       // rotate the scalars for the whole graph.
3135       unsigned Cnt = 0;
3136       const TreeEntry *UserTE = TE.get();
3137       while (UserTE && Cnt < RecursionMaxDepth) {
3138         if (UserTE->UserTreeIndices.size() != 1)
3139           break;
3140         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3141               return EI.UserTE->State == TreeEntry::Vectorize &&
3142                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3143             }))
3144           return;
3145         if (UserTE->UserTreeIndices.empty())
3146           UserTE = nullptr;
3147         else
3148           UserTE = UserTE->UserTreeIndices.back().UserTE;
3149         ++Cnt;
3150       }
3151       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3152       if (TE->State != TreeEntry::Vectorize)
3153         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3154     }
3155   });
3156 
3157   // Reorder the graph nodes according to their vectorization factor.
3158   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3159        VF /= 2) {
3160     auto It = VFToOrderedEntries.find(VF);
3161     if (It == VFToOrderedEntries.end())
3162       continue;
3163     // Try to find the most profitable order. We just are looking for the most
3164     // used order and reorder scalar elements in the nodes according to this
3165     // mostly used order.
3166     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3167     // All operands are reordered and used only in this node - propagate the
3168     // most used order to the user node.
3169     MapVector<OrdersType, unsigned,
3170               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3171         OrdersUses;
3172     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3173     for (const TreeEntry *OpTE : OrderedEntries) {
3174       // No need to reorder this nodes, still need to extend and to use shuffle,
3175       // just need to merge reordering shuffle and the reuse shuffle.
3176       if (!OpTE->ReuseShuffleIndices.empty())
3177         continue;
3178       // Count number of orders uses.
3179       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3180         if (OpTE->State == TreeEntry::NeedToGather)
3181           return GathersToOrders.find(OpTE)->second;
3182         return OpTE->ReorderIndices;
3183       }();
3184       // Stores actually store the mask, not the order, need to invert.
3185       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3186           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3187         SmallVector<int> Mask;
3188         inversePermutation(Order, Mask);
3189         unsigned E = Order.size();
3190         OrdersType CurrentOrder(E, E);
3191         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3192           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3193         });
3194         fixupOrderingIndices(CurrentOrder);
3195         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3196       } else {
3197         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3198       }
3199     }
3200     // Set order of the user node.
3201     if (OrdersUses.empty())
3202       continue;
3203     // Choose the most used order.
3204     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3205     unsigned Cnt = OrdersUses.front().second;
3206     for (const auto &Pair : drop_begin(OrdersUses)) {
3207       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3208         BestOrder = Pair.first;
3209         Cnt = Pair.second;
3210       }
3211     }
3212     // Set order of the user node.
3213     if (BestOrder.empty())
3214       continue;
3215     SmallVector<int> Mask;
3216     inversePermutation(BestOrder, Mask);
3217     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3218     unsigned E = BestOrder.size();
3219     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3220       return I < E ? static_cast<int>(I) : UndefMaskElem;
3221     });
3222     // Do an actual reordering, if profitable.
3223     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3224       // Just do the reordering for the nodes with the given VF.
3225       if (TE->Scalars.size() != VF) {
3226         if (TE->ReuseShuffleIndices.size() == VF) {
3227           // Need to reorder the reuses masks of the operands with smaller VF to
3228           // be able to find the match between the graph nodes and scalar
3229           // operands of the given node during vectorization/cost estimation.
3230           assert(all_of(TE->UserTreeIndices,
3231                         [VF, &TE](const EdgeInfo &EI) {
3232                           return EI.UserTE->Scalars.size() == VF ||
3233                                  EI.UserTE->Scalars.size() ==
3234                                      TE->Scalars.size();
3235                         }) &&
3236                  "All users must be of VF size.");
3237           // Update ordering of the operands with the smaller VF than the given
3238           // one.
3239           reorderReuses(TE->ReuseShuffleIndices, Mask);
3240         }
3241         continue;
3242       }
3243       if (TE->State == TreeEntry::Vectorize &&
3244           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3245               InsertElementInst>(TE->getMainOp()) &&
3246           !TE->isAltShuffle()) {
3247         // Build correct orders for extract{element,value}, loads and
3248         // stores.
3249         reorderOrder(TE->ReorderIndices, Mask);
3250         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3251           TE->reorderOperands(Mask);
3252       } else {
3253         // Reorder the node and its operands.
3254         TE->reorderOperands(Mask);
3255         assert(TE->ReorderIndices.empty() &&
3256                "Expected empty reorder sequence.");
3257         reorderScalars(TE->Scalars, Mask);
3258       }
3259       if (!TE->ReuseShuffleIndices.empty()) {
3260         // Apply reversed order to keep the original ordering of the reused
3261         // elements to avoid extra reorder indices shuffling.
3262         OrdersType CurrentOrder;
3263         reorderOrder(CurrentOrder, MaskOrder);
3264         SmallVector<int> NewReuses;
3265         inversePermutation(CurrentOrder, NewReuses);
3266         addMask(NewReuses, TE->ReuseShuffleIndices);
3267         TE->ReuseShuffleIndices.swap(NewReuses);
3268       }
3269     }
3270   }
3271 }
3272 
3273 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3274   SetVector<TreeEntry *> OrderedEntries;
3275   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3276   // Find all reorderable leaf nodes with the given VF.
3277   // Currently the are vectorized loads,extracts without alternate operands +
3278   // some gathering of extracts.
3279   SmallVector<TreeEntry *> NonVectorized;
3280   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3281                               &NonVectorized](
3282                                  const std::unique_ptr<TreeEntry> &TE) {
3283     if (TE->State != TreeEntry::Vectorize)
3284       NonVectorized.push_back(TE.get());
3285     if (Optional<OrdersType> CurrentOrder =
3286             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3287       OrderedEntries.insert(TE.get());
3288       if (TE->State != TreeEntry::Vectorize)
3289         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3290     }
3291   });
3292 
3293   // Checks if the operands of the users are reordarable and have only single
3294   // use.
3295   auto &&CheckOperands =
3296       [this, &NonVectorized](const auto &Data,
3297                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3298         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3299           if (any_of(Data.second,
3300                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3301                        return OpData.first == I &&
3302                               OpData.second->State == TreeEntry::Vectorize;
3303                      }))
3304             continue;
3305           ArrayRef<Value *> VL = Data.first->getOperand(I);
3306           const TreeEntry *TE = nullptr;
3307           const auto *It = find_if(VL, [this, &TE](Value *V) {
3308             TE = getTreeEntry(V);
3309             return TE;
3310           });
3311           if (It != VL.end() && TE->isSame(VL))
3312             return false;
3313           TreeEntry *Gather = nullptr;
3314           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3315                 assert(TE->State != TreeEntry::Vectorize &&
3316                        "Only non-vectorized nodes are expected.");
3317                 if (TE->isSame(VL)) {
3318                   Gather = TE;
3319                   return true;
3320                 }
3321                 return false;
3322               }) > 1)
3323             return false;
3324           if (Gather)
3325             GatherOps.push_back(Gather);
3326         }
3327         return true;
3328       };
3329   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3330   // I.e., if the node has operands, that are reordered, try to make at least
3331   // one operand order in the natural order and reorder others + reorder the
3332   // user node itself.
3333   SmallPtrSet<const TreeEntry *, 4> Visited;
3334   while (!OrderedEntries.empty()) {
3335     // 1. Filter out only reordered nodes.
3336     // 2. If the entry has multiple uses - skip it and jump to the next node.
3337     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3338     SmallVector<TreeEntry *> Filtered;
3339     for (TreeEntry *TE : OrderedEntries) {
3340       if (!(TE->State == TreeEntry::Vectorize ||
3341             (TE->State == TreeEntry::NeedToGather &&
3342              GathersToOrders.count(TE))) ||
3343           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3344           !all_of(drop_begin(TE->UserTreeIndices),
3345                   [TE](const EdgeInfo &EI) {
3346                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3347                   }) ||
3348           !Visited.insert(TE).second) {
3349         Filtered.push_back(TE);
3350         continue;
3351       }
3352       // Build a map between user nodes and their operands order to speedup
3353       // search. The graph currently does not provide this dependency directly.
3354       for (EdgeInfo &EI : TE->UserTreeIndices) {
3355         TreeEntry *UserTE = EI.UserTE;
3356         auto It = Users.find(UserTE);
3357         if (It == Users.end())
3358           It = Users.insert({UserTE, {}}).first;
3359         It->second.emplace_back(EI.EdgeIdx, TE);
3360       }
3361     }
3362     // Erase filtered entries.
3363     for_each(Filtered,
3364              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3365     for (const auto &Data : Users) {
3366       // Check that operands are used only in the User node.
3367       SmallVector<TreeEntry *> GatherOps;
3368       if (!CheckOperands(Data, GatherOps)) {
3369         for_each(Data.second,
3370                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3371                    OrderedEntries.remove(Op.second);
3372                  });
3373         continue;
3374       }
3375       // All operands are reordered and used only in this node - propagate the
3376       // most used order to the user node.
3377       MapVector<OrdersType, unsigned,
3378                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3379           OrdersUses;
3380       // Do the analysis for each tree entry only once, otherwise the order of
3381       // the same node my be considered several times, though might be not
3382       // profitable.
3383       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3384       for (const auto &Op : Data.second) {
3385         TreeEntry *OpTE = Op.second;
3386         if (!VisitedOps.insert(OpTE).second)
3387           continue;
3388         if (!OpTE->ReuseShuffleIndices.empty() ||
3389             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3390           continue;
3391         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3392           if (OpTE->State == TreeEntry::NeedToGather)
3393             return GathersToOrders.find(OpTE)->second;
3394           return OpTE->ReorderIndices;
3395         }();
3396         // Stores actually store the mask, not the order, need to invert.
3397         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3398             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3399           SmallVector<int> Mask;
3400           inversePermutation(Order, Mask);
3401           unsigned E = Order.size();
3402           OrdersType CurrentOrder(E, E);
3403           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3404             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3405           });
3406           fixupOrderingIndices(CurrentOrder);
3407           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3408         } else {
3409           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3410         }
3411         OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3412             OpTE->UserTreeIndices.size();
3413         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3414         --OrdersUses[{}];
3415       }
3416       // If no orders - skip current nodes and jump to the next one, if any.
3417       if (OrdersUses.empty()) {
3418         for_each(Data.second,
3419                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3420                    OrderedEntries.remove(Op.second);
3421                  });
3422         continue;
3423       }
3424       // Choose the best order.
3425       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3426       unsigned Cnt = OrdersUses.front().second;
3427       for (const auto &Pair : drop_begin(OrdersUses)) {
3428         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3429           BestOrder = Pair.first;
3430           Cnt = Pair.second;
3431         }
3432       }
3433       // Set order of the user node (reordering of operands and user nodes).
3434       if (BestOrder.empty()) {
3435         for_each(Data.second,
3436                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3437                    OrderedEntries.remove(Op.second);
3438                  });
3439         continue;
3440       }
3441       // Erase operands from OrderedEntries list and adjust their orders.
3442       VisitedOps.clear();
3443       SmallVector<int> Mask;
3444       inversePermutation(BestOrder, Mask);
3445       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3446       unsigned E = BestOrder.size();
3447       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3448         return I < E ? static_cast<int>(I) : UndefMaskElem;
3449       });
3450       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3451         TreeEntry *TE = Op.second;
3452         OrderedEntries.remove(TE);
3453         if (!VisitedOps.insert(TE).second)
3454           continue;
3455         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3456           // Just reorder reuses indices.
3457           reorderReuses(TE->ReuseShuffleIndices, Mask);
3458           continue;
3459         }
3460         // Gathers are processed separately.
3461         if (TE->State != TreeEntry::Vectorize)
3462           continue;
3463         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3464                 TE->ReorderIndices.empty()) &&
3465                "Non-matching sizes of user/operand entries.");
3466         reorderOrder(TE->ReorderIndices, Mask);
3467       }
3468       // For gathers just need to reorder its scalars.
3469       for (TreeEntry *Gather : GatherOps) {
3470         assert(Gather->ReorderIndices.empty() &&
3471                "Unexpected reordering of gathers.");
3472         if (!Gather->ReuseShuffleIndices.empty()) {
3473           // Just reorder reuses indices.
3474           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3475           continue;
3476         }
3477         reorderScalars(Gather->Scalars, Mask);
3478         OrderedEntries.remove(Gather);
3479       }
3480       // Reorder operands of the user node and set the ordering for the user
3481       // node itself.
3482       if (Data.first->State != TreeEntry::Vectorize ||
3483           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3484               Data.first->getMainOp()) ||
3485           Data.first->isAltShuffle())
3486         Data.first->reorderOperands(Mask);
3487       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3488           Data.first->isAltShuffle()) {
3489         reorderScalars(Data.first->Scalars, Mask);
3490         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3491         if (Data.first->ReuseShuffleIndices.empty() &&
3492             !Data.first->ReorderIndices.empty() &&
3493             !Data.first->isAltShuffle()) {
3494           // Insert user node to the list to try to sink reordering deeper in
3495           // the graph.
3496           OrderedEntries.insert(Data.first);
3497         }
3498       } else {
3499         reorderOrder(Data.first->ReorderIndices, Mask);
3500       }
3501     }
3502   }
3503   // If the reordering is unnecessary, just remove the reorder.
3504   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3505       VectorizableTree.front()->ReuseShuffleIndices.empty())
3506     VectorizableTree.front()->ReorderIndices.clear();
3507 }
3508 
3509 void BoUpSLP::buildExternalUses(
3510     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3511   // Collect the values that we need to extract from the tree.
3512   for (auto &TEPtr : VectorizableTree) {
3513     TreeEntry *Entry = TEPtr.get();
3514 
3515     // No need to handle users of gathered values.
3516     if (Entry->State == TreeEntry::NeedToGather)
3517       continue;
3518 
3519     // For each lane:
3520     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3521       Value *Scalar = Entry->Scalars[Lane];
3522       int FoundLane = Entry->findLaneForValue(Scalar);
3523 
3524       // Check if the scalar is externally used as an extra arg.
3525       auto ExtI = ExternallyUsedValues.find(Scalar);
3526       if (ExtI != ExternallyUsedValues.end()) {
3527         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3528                           << Lane << " from " << *Scalar << ".\n");
3529         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3530       }
3531       for (User *U : Scalar->users()) {
3532         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3533 
3534         Instruction *UserInst = dyn_cast<Instruction>(U);
3535         if (!UserInst)
3536           continue;
3537 
3538         if (isDeleted(UserInst))
3539           continue;
3540 
3541         // Skip in-tree scalars that become vectors
3542         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3543           Value *UseScalar = UseEntry->Scalars[0];
3544           // Some in-tree scalars will remain as scalar in vectorized
3545           // instructions. If that is the case, the one in Lane 0 will
3546           // be used.
3547           if (UseScalar != U ||
3548               UseEntry->State == TreeEntry::ScatterVectorize ||
3549               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3550             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3551                               << ".\n");
3552             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3553             continue;
3554           }
3555         }
3556 
3557         // Ignore users in the user ignore list.
3558         if (is_contained(UserIgnoreList, UserInst))
3559           continue;
3560 
3561         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3562                           << Lane << " from " << *Scalar << ".\n");
3563         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3564       }
3565     }
3566   }
3567 }
3568 
3569 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3570                         ArrayRef<Value *> UserIgnoreLst) {
3571   deleteTree();
3572   UserIgnoreList = UserIgnoreLst;
3573   if (!allSameType(Roots))
3574     return;
3575   buildTree_rec(Roots, 0, EdgeInfo());
3576 }
3577 
3578 namespace {
3579 /// Tracks the state we can represent the loads in the given sequence.
3580 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3581 } // anonymous namespace
3582 
3583 /// Checks if the given array of loads can be represented as a vectorized,
3584 /// scatter or just simple gather.
3585 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3586                                     const TargetTransformInfo &TTI,
3587                                     const DataLayout &DL, ScalarEvolution &SE,
3588                                     SmallVectorImpl<unsigned> &Order,
3589                                     SmallVectorImpl<Value *> &PointerOps) {
3590   // Check that a vectorized load would load the same memory as a scalar
3591   // load. For example, we don't want to vectorize loads that are smaller
3592   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3593   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3594   // from such a struct, we read/write packed bits disagreeing with the
3595   // unvectorized version.
3596   Type *ScalarTy = VL0->getType();
3597 
3598   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3599     return LoadsState::Gather;
3600 
3601   // Make sure all loads in the bundle are simple - we can't vectorize
3602   // atomic or volatile loads.
3603   PointerOps.clear();
3604   PointerOps.resize(VL.size());
3605   auto *POIter = PointerOps.begin();
3606   for (Value *V : VL) {
3607     auto *L = cast<LoadInst>(V);
3608     if (!L->isSimple())
3609       return LoadsState::Gather;
3610     *POIter = L->getPointerOperand();
3611     ++POIter;
3612   }
3613 
3614   Order.clear();
3615   // Check the order of pointer operands.
3616   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3617     Value *Ptr0;
3618     Value *PtrN;
3619     if (Order.empty()) {
3620       Ptr0 = PointerOps.front();
3621       PtrN = PointerOps.back();
3622     } else {
3623       Ptr0 = PointerOps[Order.front()];
3624       PtrN = PointerOps[Order.back()];
3625     }
3626     Optional<int> Diff =
3627         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3628     // Check that the sorted loads are consecutive.
3629     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3630       return LoadsState::Vectorize;
3631     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3632     for (Value *V : VL)
3633       CommonAlignment =
3634           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3635     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3636                                 CommonAlignment))
3637       return LoadsState::ScatterVectorize;
3638   }
3639 
3640   return LoadsState::Gather;
3641 }
3642 
3643 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3644                             const EdgeInfo &UserTreeIdx) {
3645   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3646 
3647   SmallVector<int> ReuseShuffleIndicies;
3648   SmallVector<Value *> UniqueValues;
3649   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3650                                 &UserTreeIdx,
3651                                 this](const InstructionsState &S) {
3652     // Check that every instruction appears once in this bundle.
3653     DenseMap<Value *, unsigned> UniquePositions;
3654     for (Value *V : VL) {
3655       if (isConstant(V)) {
3656         ReuseShuffleIndicies.emplace_back(
3657             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3658         UniqueValues.emplace_back(V);
3659         continue;
3660       }
3661       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3662       ReuseShuffleIndicies.emplace_back(Res.first->second);
3663       if (Res.second)
3664         UniqueValues.emplace_back(V);
3665     }
3666     size_t NumUniqueScalarValues = UniqueValues.size();
3667     if (NumUniqueScalarValues == VL.size()) {
3668       ReuseShuffleIndicies.clear();
3669     } else {
3670       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3671       if (NumUniqueScalarValues <= 1 ||
3672           (UniquePositions.size() == 1 && all_of(UniqueValues,
3673                                                  [](Value *V) {
3674                                                    return isa<UndefValue>(V) ||
3675                                                           !isConstant(V);
3676                                                  })) ||
3677           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3678         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3679         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3680         return false;
3681       }
3682       VL = UniqueValues;
3683     }
3684     return true;
3685   };
3686 
3687   InstructionsState S = getSameOpcode(VL);
3688   if (Depth == RecursionMaxDepth) {
3689     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3690     if (TryToFindDuplicates(S))
3691       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3692                    ReuseShuffleIndicies);
3693     return;
3694   }
3695 
3696   // Don't handle scalable vectors
3697   if (S.getOpcode() == Instruction::ExtractElement &&
3698       isa<ScalableVectorType>(
3699           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3700     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3701     if (TryToFindDuplicates(S))
3702       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3703                    ReuseShuffleIndicies);
3704     return;
3705   }
3706 
3707   // Don't handle vectors.
3708   if (S.OpValue->getType()->isVectorTy() &&
3709       !isa<InsertElementInst>(S.OpValue)) {
3710     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3711     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3712     return;
3713   }
3714 
3715   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3716     if (SI->getValueOperand()->getType()->isVectorTy()) {
3717       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3718       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3719       return;
3720     }
3721 
3722   // If all of the operands are identical or constant we have a simple solution.
3723   // If we deal with insert/extract instructions, they all must have constant
3724   // indices, otherwise we should gather them, not try to vectorize.
3725   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3726       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3727        !all_of(VL, isVectorLikeInstWithConstOps))) {
3728     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3729     if (TryToFindDuplicates(S))
3730       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3731                    ReuseShuffleIndicies);
3732     return;
3733   }
3734 
3735   // We now know that this is a vector of instructions of the same type from
3736   // the same block.
3737 
3738   // Don't vectorize ephemeral values.
3739   for (Value *V : VL) {
3740     if (EphValues.count(V)) {
3741       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3742                         << ") is ephemeral.\n");
3743       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3744       return;
3745     }
3746   }
3747 
3748   // Check if this is a duplicate of another entry.
3749   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3750     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3751     if (!E->isSame(VL)) {
3752       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3753       if (TryToFindDuplicates(S))
3754         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3755                      ReuseShuffleIndicies);
3756       return;
3757     }
3758     // Record the reuse of the tree node.  FIXME, currently this is only used to
3759     // properly draw the graph rather than for the actual vectorization.
3760     E->UserTreeIndices.push_back(UserTreeIdx);
3761     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3762                       << ".\n");
3763     return;
3764   }
3765 
3766   // Check that none of the instructions in the bundle are already in the tree.
3767   for (Value *V : VL) {
3768     auto *I = dyn_cast<Instruction>(V);
3769     if (!I)
3770       continue;
3771     if (getTreeEntry(I)) {
3772       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3773                         << ") is already in tree.\n");
3774       if (TryToFindDuplicates(S))
3775         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3776                      ReuseShuffleIndicies);
3777       return;
3778     }
3779   }
3780 
3781   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3782   for (Value *V : VL) {
3783     if (is_contained(UserIgnoreList, V)) {
3784       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3785       if (TryToFindDuplicates(S))
3786         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3787                      ReuseShuffleIndicies);
3788       return;
3789     }
3790   }
3791 
3792   // Check that all of the users of the scalars that we want to vectorize are
3793   // schedulable.
3794   auto *VL0 = cast<Instruction>(S.OpValue);
3795   BasicBlock *BB = VL0->getParent();
3796 
3797   if (!DT->isReachableFromEntry(BB)) {
3798     // Don't go into unreachable blocks. They may contain instructions with
3799     // dependency cycles which confuse the final scheduling.
3800     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3801     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3802     return;
3803   }
3804 
3805   // Check that every instruction appears once in this bundle.
3806   if (!TryToFindDuplicates(S))
3807     return;
3808 
3809   auto &BSRef = BlocksSchedules[BB];
3810   if (!BSRef)
3811     BSRef = std::make_unique<BlockScheduling>(BB);
3812 
3813   BlockScheduling &BS = *BSRef.get();
3814 
3815   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3816   if (!Bundle) {
3817     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3818     assert((!BS.getScheduleData(VL0) ||
3819             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3820            "tryScheduleBundle should cancelScheduling on failure");
3821     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3822                  ReuseShuffleIndicies);
3823     return;
3824   }
3825   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3826 
3827   unsigned ShuffleOrOp = S.isAltShuffle() ?
3828                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3829   switch (ShuffleOrOp) {
3830     case Instruction::PHI: {
3831       auto *PH = cast<PHINode>(VL0);
3832 
3833       // Check for terminator values (e.g. invoke).
3834       for (Value *V : VL)
3835         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3836           Instruction *Term = dyn_cast<Instruction>(
3837               cast<PHINode>(V)->getIncomingValueForBlock(
3838                   PH->getIncomingBlock(I)));
3839           if (Term && Term->isTerminator()) {
3840             LLVM_DEBUG(dbgs()
3841                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3842             BS.cancelScheduling(VL, VL0);
3843             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3844                          ReuseShuffleIndicies);
3845             return;
3846           }
3847         }
3848 
3849       TreeEntry *TE =
3850           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3851       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3852 
3853       // Keeps the reordered operands to avoid code duplication.
3854       SmallVector<ValueList, 2> OperandsVec;
3855       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3856         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3857           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3858           TE->setOperand(I, Operands);
3859           OperandsVec.push_back(Operands);
3860           continue;
3861         }
3862         ValueList Operands;
3863         // Prepare the operand vector.
3864         for (Value *V : VL)
3865           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3866               PH->getIncomingBlock(I)));
3867         TE->setOperand(I, Operands);
3868         OperandsVec.push_back(Operands);
3869       }
3870       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3871         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3872       return;
3873     }
3874     case Instruction::ExtractValue:
3875     case Instruction::ExtractElement: {
3876       OrdersType CurrentOrder;
3877       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3878       if (Reuse) {
3879         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3880         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3881                      ReuseShuffleIndicies);
3882         // This is a special case, as it does not gather, but at the same time
3883         // we are not extending buildTree_rec() towards the operands.
3884         ValueList Op0;
3885         Op0.assign(VL.size(), VL0->getOperand(0));
3886         VectorizableTree.back()->setOperand(0, Op0);
3887         return;
3888       }
3889       if (!CurrentOrder.empty()) {
3890         LLVM_DEBUG({
3891           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3892                     "with order";
3893           for (unsigned Idx : CurrentOrder)
3894             dbgs() << " " << Idx;
3895           dbgs() << "\n";
3896         });
3897         fixupOrderingIndices(CurrentOrder);
3898         // Insert new order with initial value 0, if it does not exist,
3899         // otherwise return the iterator to the existing one.
3900         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3901                      ReuseShuffleIndicies, CurrentOrder);
3902         // This is a special case, as it does not gather, but at the same time
3903         // we are not extending buildTree_rec() towards the operands.
3904         ValueList Op0;
3905         Op0.assign(VL.size(), VL0->getOperand(0));
3906         VectorizableTree.back()->setOperand(0, Op0);
3907         return;
3908       }
3909       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3910       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3911                    ReuseShuffleIndicies);
3912       BS.cancelScheduling(VL, VL0);
3913       return;
3914     }
3915     case Instruction::InsertElement: {
3916       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3917 
3918       // Check that we have a buildvector and not a shuffle of 2 or more
3919       // different vectors.
3920       ValueSet SourceVectors;
3921       int MinIdx = std::numeric_limits<int>::max();
3922       for (Value *V : VL) {
3923         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3924         Optional<int> Idx = *getInsertIndex(V, 0);
3925         if (!Idx || *Idx == UndefMaskElem)
3926           continue;
3927         MinIdx = std::min(MinIdx, *Idx);
3928       }
3929 
3930       if (count_if(VL, [&SourceVectors](Value *V) {
3931             return !SourceVectors.contains(V);
3932           }) >= 2) {
3933         // Found 2nd source vector - cancel.
3934         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3935                              "different source vectors.\n");
3936         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3937         BS.cancelScheduling(VL, VL0);
3938         return;
3939       }
3940 
3941       auto OrdCompare = [](const std::pair<int, int> &P1,
3942                            const std::pair<int, int> &P2) {
3943         return P1.first > P2.first;
3944       };
3945       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3946                     decltype(OrdCompare)>
3947           Indices(OrdCompare);
3948       for (int I = 0, E = VL.size(); I < E; ++I) {
3949         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3950         if (!Idx || *Idx == UndefMaskElem)
3951           continue;
3952         Indices.emplace(*Idx, I);
3953       }
3954       OrdersType CurrentOrder(VL.size(), VL.size());
3955       bool IsIdentity = true;
3956       for (int I = 0, E = VL.size(); I < E; ++I) {
3957         CurrentOrder[Indices.top().second] = I;
3958         IsIdentity &= Indices.top().second == I;
3959         Indices.pop();
3960       }
3961       if (IsIdentity)
3962         CurrentOrder.clear();
3963       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3964                                    None, CurrentOrder);
3965       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3966 
3967       constexpr int NumOps = 2;
3968       ValueList VectorOperands[NumOps];
3969       for (int I = 0; I < NumOps; ++I) {
3970         for (Value *V : VL)
3971           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3972 
3973         TE->setOperand(I, VectorOperands[I]);
3974       }
3975       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3976       return;
3977     }
3978     case Instruction::Load: {
3979       // Check that a vectorized load would load the same memory as a scalar
3980       // load. For example, we don't want to vectorize loads that are smaller
3981       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3982       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3983       // from such a struct, we read/write packed bits disagreeing with the
3984       // unvectorized version.
3985       SmallVector<Value *> PointerOps;
3986       OrdersType CurrentOrder;
3987       TreeEntry *TE = nullptr;
3988       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3989                                 PointerOps)) {
3990       case LoadsState::Vectorize:
3991         if (CurrentOrder.empty()) {
3992           // Original loads are consecutive and does not require reordering.
3993           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3994                             ReuseShuffleIndicies);
3995           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3996         } else {
3997           fixupOrderingIndices(CurrentOrder);
3998           // Need to reorder.
3999           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4000                             ReuseShuffleIndicies, CurrentOrder);
4001           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4002         }
4003         TE->setOperandsInOrder();
4004         break;
4005       case LoadsState::ScatterVectorize:
4006         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4007         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4008                           UserTreeIdx, ReuseShuffleIndicies);
4009         TE->setOperandsInOrder();
4010         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4011         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4012         break;
4013       case LoadsState::Gather:
4014         BS.cancelScheduling(VL, VL0);
4015         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4016                      ReuseShuffleIndicies);
4017 #ifndef NDEBUG
4018         Type *ScalarTy = VL0->getType();
4019         if (DL->getTypeSizeInBits(ScalarTy) !=
4020             DL->getTypeAllocSizeInBits(ScalarTy))
4021           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4022         else if (any_of(VL, [](Value *V) {
4023                    return !cast<LoadInst>(V)->isSimple();
4024                  }))
4025           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4026         else
4027           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4028 #endif // NDEBUG
4029         break;
4030       }
4031       return;
4032     }
4033     case Instruction::ZExt:
4034     case Instruction::SExt:
4035     case Instruction::FPToUI:
4036     case Instruction::FPToSI:
4037     case Instruction::FPExt:
4038     case Instruction::PtrToInt:
4039     case Instruction::IntToPtr:
4040     case Instruction::SIToFP:
4041     case Instruction::UIToFP:
4042     case Instruction::Trunc:
4043     case Instruction::FPTrunc:
4044     case Instruction::BitCast: {
4045       Type *SrcTy = VL0->getOperand(0)->getType();
4046       for (Value *V : VL) {
4047         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4048         if (Ty != SrcTy || !isValidElementType(Ty)) {
4049           BS.cancelScheduling(VL, VL0);
4050           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4051                        ReuseShuffleIndicies);
4052           LLVM_DEBUG(dbgs()
4053                      << "SLP: Gathering casts with different src types.\n");
4054           return;
4055         }
4056       }
4057       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4058                                    ReuseShuffleIndicies);
4059       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4060 
4061       TE->setOperandsInOrder();
4062       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4063         ValueList Operands;
4064         // Prepare the operand vector.
4065         for (Value *V : VL)
4066           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4067 
4068         buildTree_rec(Operands, Depth + 1, {TE, i});
4069       }
4070       return;
4071     }
4072     case Instruction::ICmp:
4073     case Instruction::FCmp: {
4074       // Check that all of the compares have the same predicate.
4075       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4076       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4077       Type *ComparedTy = VL0->getOperand(0)->getType();
4078       for (Value *V : VL) {
4079         CmpInst *Cmp = cast<CmpInst>(V);
4080         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4081             Cmp->getOperand(0)->getType() != ComparedTy) {
4082           BS.cancelScheduling(VL, VL0);
4083           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4084                        ReuseShuffleIndicies);
4085           LLVM_DEBUG(dbgs()
4086                      << "SLP: Gathering cmp with different predicate.\n");
4087           return;
4088         }
4089       }
4090 
4091       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4092                                    ReuseShuffleIndicies);
4093       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4094 
4095       ValueList Left, Right;
4096       if (cast<CmpInst>(VL0)->isCommutative()) {
4097         // Commutative predicate - collect + sort operands of the instructions
4098         // so that each side is more likely to have the same opcode.
4099         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4100         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4101       } else {
4102         // Collect operands - commute if it uses the swapped predicate.
4103         for (Value *V : VL) {
4104           auto *Cmp = cast<CmpInst>(V);
4105           Value *LHS = Cmp->getOperand(0);
4106           Value *RHS = Cmp->getOperand(1);
4107           if (Cmp->getPredicate() != P0)
4108             std::swap(LHS, RHS);
4109           Left.push_back(LHS);
4110           Right.push_back(RHS);
4111         }
4112       }
4113       TE->setOperand(0, Left);
4114       TE->setOperand(1, Right);
4115       buildTree_rec(Left, Depth + 1, {TE, 0});
4116       buildTree_rec(Right, Depth + 1, {TE, 1});
4117       return;
4118     }
4119     case Instruction::Select:
4120     case Instruction::FNeg:
4121     case Instruction::Add:
4122     case Instruction::FAdd:
4123     case Instruction::Sub:
4124     case Instruction::FSub:
4125     case Instruction::Mul:
4126     case Instruction::FMul:
4127     case Instruction::UDiv:
4128     case Instruction::SDiv:
4129     case Instruction::FDiv:
4130     case Instruction::URem:
4131     case Instruction::SRem:
4132     case Instruction::FRem:
4133     case Instruction::Shl:
4134     case Instruction::LShr:
4135     case Instruction::AShr:
4136     case Instruction::And:
4137     case Instruction::Or:
4138     case Instruction::Xor: {
4139       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4140                                    ReuseShuffleIndicies);
4141       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4142 
4143       // Sort operands of the instructions so that each side is more likely to
4144       // have the same opcode.
4145       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4146         ValueList Left, Right;
4147         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4148         TE->setOperand(0, Left);
4149         TE->setOperand(1, Right);
4150         buildTree_rec(Left, Depth + 1, {TE, 0});
4151         buildTree_rec(Right, Depth + 1, {TE, 1});
4152         return;
4153       }
4154 
4155       TE->setOperandsInOrder();
4156       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4157         ValueList Operands;
4158         // Prepare the operand vector.
4159         for (Value *V : VL)
4160           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4161 
4162         buildTree_rec(Operands, Depth + 1, {TE, i});
4163       }
4164       return;
4165     }
4166     case Instruction::GetElementPtr: {
4167       // We don't combine GEPs with complicated (nested) indexing.
4168       for (Value *V : VL) {
4169         if (cast<Instruction>(V)->getNumOperands() != 2) {
4170           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4171           BS.cancelScheduling(VL, VL0);
4172           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4173                        ReuseShuffleIndicies);
4174           return;
4175         }
4176       }
4177 
4178       // We can't combine several GEPs into one vector if they operate on
4179       // different types.
4180       Type *Ty0 = VL0->getOperand(0)->getType();
4181       for (Value *V : VL) {
4182         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4183         if (Ty0 != CurTy) {
4184           LLVM_DEBUG(dbgs()
4185                      << "SLP: not-vectorizable GEP (different types).\n");
4186           BS.cancelScheduling(VL, VL0);
4187           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4188                        ReuseShuffleIndicies);
4189           return;
4190         }
4191       }
4192 
4193       // We don't combine GEPs with non-constant indexes.
4194       Type *Ty1 = VL0->getOperand(1)->getType();
4195       for (Value *V : VL) {
4196         auto Op = cast<Instruction>(V)->getOperand(1);
4197         if (!isa<ConstantInt>(Op) ||
4198             (Op->getType() != Ty1 &&
4199              Op->getType()->getScalarSizeInBits() >
4200                  DL->getIndexSizeInBits(
4201                      V->getType()->getPointerAddressSpace()))) {
4202           LLVM_DEBUG(dbgs()
4203                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4204           BS.cancelScheduling(VL, VL0);
4205           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4206                        ReuseShuffleIndicies);
4207           return;
4208         }
4209       }
4210 
4211       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4212                                    ReuseShuffleIndicies);
4213       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4214       SmallVector<ValueList, 2> Operands(2);
4215       // Prepare the operand vector for pointer operands.
4216       for (Value *V : VL)
4217         Operands.front().push_back(
4218             cast<GetElementPtrInst>(V)->getPointerOperand());
4219       TE->setOperand(0, Operands.front());
4220       // Need to cast all indices to the same type before vectorization to
4221       // avoid crash.
4222       // Required to be able to find correct matches between different gather
4223       // nodes and reuse the vectorized values rather than trying to gather them
4224       // again.
4225       int IndexIdx = 1;
4226       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4227       Type *Ty = all_of(VL,
4228                         [VL0Ty, IndexIdx](Value *V) {
4229                           return VL0Ty == cast<GetElementPtrInst>(V)
4230                                               ->getOperand(IndexIdx)
4231                                               ->getType();
4232                         })
4233                      ? VL0Ty
4234                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4235                                             ->getPointerOperandType()
4236                                             ->getScalarType());
4237       // Prepare the operand vector.
4238       for (Value *V : VL) {
4239         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4240         auto *CI = cast<ConstantInt>(Op);
4241         Operands.back().push_back(ConstantExpr::getIntegerCast(
4242             CI, Ty, CI->getValue().isSignBitSet()));
4243       }
4244       TE->setOperand(IndexIdx, Operands.back());
4245 
4246       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4247         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4248       return;
4249     }
4250     case Instruction::Store: {
4251       // Check if the stores are consecutive or if we need to swizzle them.
4252       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4253       // Avoid types that are padded when being allocated as scalars, while
4254       // being packed together in a vector (such as i1).
4255       if (DL->getTypeSizeInBits(ScalarTy) !=
4256           DL->getTypeAllocSizeInBits(ScalarTy)) {
4257         BS.cancelScheduling(VL, VL0);
4258         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4259                      ReuseShuffleIndicies);
4260         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4261         return;
4262       }
4263       // Make sure all stores in the bundle are simple - we can't vectorize
4264       // atomic or volatile stores.
4265       SmallVector<Value *, 4> PointerOps(VL.size());
4266       ValueList Operands(VL.size());
4267       auto POIter = PointerOps.begin();
4268       auto OIter = Operands.begin();
4269       for (Value *V : VL) {
4270         auto *SI = cast<StoreInst>(V);
4271         if (!SI->isSimple()) {
4272           BS.cancelScheduling(VL, VL0);
4273           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4274                        ReuseShuffleIndicies);
4275           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4276           return;
4277         }
4278         *POIter = SI->getPointerOperand();
4279         *OIter = SI->getValueOperand();
4280         ++POIter;
4281         ++OIter;
4282       }
4283 
4284       OrdersType CurrentOrder;
4285       // Check the order of pointer operands.
4286       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4287         Value *Ptr0;
4288         Value *PtrN;
4289         if (CurrentOrder.empty()) {
4290           Ptr0 = PointerOps.front();
4291           PtrN = PointerOps.back();
4292         } else {
4293           Ptr0 = PointerOps[CurrentOrder.front()];
4294           PtrN = PointerOps[CurrentOrder.back()];
4295         }
4296         Optional<int> Dist =
4297             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4298         // Check that the sorted pointer operands are consecutive.
4299         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4300           if (CurrentOrder.empty()) {
4301             // Original stores are consecutive and does not require reordering.
4302             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4303                                          UserTreeIdx, ReuseShuffleIndicies);
4304             TE->setOperandsInOrder();
4305             buildTree_rec(Operands, Depth + 1, {TE, 0});
4306             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4307           } else {
4308             fixupOrderingIndices(CurrentOrder);
4309             TreeEntry *TE =
4310                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4311                              ReuseShuffleIndicies, CurrentOrder);
4312             TE->setOperandsInOrder();
4313             buildTree_rec(Operands, Depth + 1, {TE, 0});
4314             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4315           }
4316           return;
4317         }
4318       }
4319 
4320       BS.cancelScheduling(VL, VL0);
4321       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4322                    ReuseShuffleIndicies);
4323       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4324       return;
4325     }
4326     case Instruction::Call: {
4327       // Check if the calls are all to the same vectorizable intrinsic or
4328       // library function.
4329       CallInst *CI = cast<CallInst>(VL0);
4330       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4331 
4332       VFShape Shape = VFShape::get(
4333           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4334           false /*HasGlobalPred*/);
4335       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4336 
4337       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4338         BS.cancelScheduling(VL, VL0);
4339         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4340                      ReuseShuffleIndicies);
4341         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4342         return;
4343       }
4344       Function *F = CI->getCalledFunction();
4345       unsigned NumArgs = CI->arg_size();
4346       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4347       for (unsigned j = 0; j != NumArgs; ++j)
4348         if (hasVectorInstrinsicScalarOpd(ID, j))
4349           ScalarArgs[j] = CI->getArgOperand(j);
4350       for (Value *V : VL) {
4351         CallInst *CI2 = dyn_cast<CallInst>(V);
4352         if (!CI2 || CI2->getCalledFunction() != F ||
4353             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4354             (VecFunc &&
4355              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4356             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4357           BS.cancelScheduling(VL, VL0);
4358           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4359                        ReuseShuffleIndicies);
4360           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4361                             << "\n");
4362           return;
4363         }
4364         // Some intrinsics have scalar arguments and should be same in order for
4365         // them to be vectorized.
4366         for (unsigned j = 0; j != NumArgs; ++j) {
4367           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4368             Value *A1J = CI2->getArgOperand(j);
4369             if (ScalarArgs[j] != A1J) {
4370               BS.cancelScheduling(VL, VL0);
4371               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4372                            ReuseShuffleIndicies);
4373               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4374                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4375                                 << "\n");
4376               return;
4377             }
4378           }
4379         }
4380         // Verify that the bundle operands are identical between the two calls.
4381         if (CI->hasOperandBundles() &&
4382             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4383                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4384                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4385           BS.cancelScheduling(VL, VL0);
4386           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4387                        ReuseShuffleIndicies);
4388           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4389                             << *CI << "!=" << *V << '\n');
4390           return;
4391         }
4392       }
4393 
4394       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4395                                    ReuseShuffleIndicies);
4396       TE->setOperandsInOrder();
4397       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4398         // For scalar operands no need to to create an entry since no need to
4399         // vectorize it.
4400         if (hasVectorInstrinsicScalarOpd(ID, i))
4401           continue;
4402         ValueList Operands;
4403         // Prepare the operand vector.
4404         for (Value *V : VL) {
4405           auto *CI2 = cast<CallInst>(V);
4406           Operands.push_back(CI2->getArgOperand(i));
4407         }
4408         buildTree_rec(Operands, Depth + 1, {TE, i});
4409       }
4410       return;
4411     }
4412     case Instruction::ShuffleVector: {
4413       // If this is not an alternate sequence of opcode like add-sub
4414       // then do not vectorize this instruction.
4415       if (!S.isAltShuffle()) {
4416         BS.cancelScheduling(VL, VL0);
4417         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4418                      ReuseShuffleIndicies);
4419         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4420         return;
4421       }
4422       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4423                                    ReuseShuffleIndicies);
4424       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4425 
4426       // Reorder operands if reordering would enable vectorization.
4427       auto *CI = dyn_cast<CmpInst>(VL0);
4428       if (isa<BinaryOperator>(VL0) || CI) {
4429         ValueList Left, Right;
4430         if (!CI || all_of(VL, [](Value *V) {
4431               return cast<CmpInst>(V)->isCommutative();
4432             })) {
4433           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4434         } else {
4435           CmpInst::Predicate P0 = CI->getPredicate();
4436           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4437           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4438           Value *BaseOp0 = VL0->getOperand(0);
4439           Value *BaseOp1 = VL0->getOperand(1);
4440           // Collect operands - commute if it uses the swapped predicate or
4441           // alternate operation.
4442           for (Value *V : VL) {
4443             auto *Cmp = cast<CmpInst>(V);
4444             Value *LHS = Cmp->getOperand(0);
4445             Value *RHS = Cmp->getOperand(1);
4446             CmpInst::Predicate CurrentPred = CI->getPredicate();
4447             CmpInst::Predicate CurrentPredSwapped =
4448                 CmpInst::getSwappedPredicate(CurrentPred);
4449             if (P0 == AltP0 || P0 == AltP0Swapped) {
4450               if ((P0 == CurrentPred &&
4451                    !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4452                   (P0 == CurrentPredSwapped &&
4453                    !areCompatibleCmpOps(BaseOp0, BaseOp1, RHS, LHS)))
4454                 std::swap(LHS, RHS);
4455             } else if (!areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) {
4456               std::swap(LHS, RHS);
4457             }
4458             Left.push_back(LHS);
4459             Right.push_back(RHS);
4460           }
4461         }
4462         TE->setOperand(0, Left);
4463         TE->setOperand(1, Right);
4464         buildTree_rec(Left, Depth + 1, {TE, 0});
4465         buildTree_rec(Right, Depth + 1, {TE, 1});
4466         return;
4467       }
4468 
4469       TE->setOperandsInOrder();
4470       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4471         ValueList Operands;
4472         // Prepare the operand vector.
4473         for (Value *V : VL)
4474           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4475 
4476         buildTree_rec(Operands, Depth + 1, {TE, i});
4477       }
4478       return;
4479     }
4480     default:
4481       BS.cancelScheduling(VL, VL0);
4482       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4483                    ReuseShuffleIndicies);
4484       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4485       return;
4486   }
4487 }
4488 
4489 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4490   unsigned N = 1;
4491   Type *EltTy = T;
4492 
4493   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4494          isa<VectorType>(EltTy)) {
4495     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4496       // Check that struct is homogeneous.
4497       for (const auto *Ty : ST->elements())
4498         if (Ty != *ST->element_begin())
4499           return 0;
4500       N *= ST->getNumElements();
4501       EltTy = *ST->element_begin();
4502     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4503       N *= AT->getNumElements();
4504       EltTy = AT->getElementType();
4505     } else {
4506       auto *VT = cast<FixedVectorType>(EltTy);
4507       N *= VT->getNumElements();
4508       EltTy = VT->getElementType();
4509     }
4510   }
4511 
4512   if (!isValidElementType(EltTy))
4513     return 0;
4514   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4515   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4516     return 0;
4517   return N;
4518 }
4519 
4520 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4521                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4522   const auto *It = find_if(VL, [](Value *V) {
4523     return isa<ExtractElementInst, ExtractValueInst>(V);
4524   });
4525   assert(It != VL.end() && "Expected at least one extract instruction.");
4526   auto *E0 = cast<Instruction>(*It);
4527   assert(all_of(VL,
4528                 [](Value *V) {
4529                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4530                       V);
4531                 }) &&
4532          "Invalid opcode");
4533   // Check if all of the extracts come from the same vector and from the
4534   // correct offset.
4535   Value *Vec = E0->getOperand(0);
4536 
4537   CurrentOrder.clear();
4538 
4539   // We have to extract from a vector/aggregate with the same number of elements.
4540   unsigned NElts;
4541   if (E0->getOpcode() == Instruction::ExtractValue) {
4542     const DataLayout &DL = E0->getModule()->getDataLayout();
4543     NElts = canMapToVector(Vec->getType(), DL);
4544     if (!NElts)
4545       return false;
4546     // Check if load can be rewritten as load of vector.
4547     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4548     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4549       return false;
4550   } else {
4551     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4552   }
4553 
4554   if (NElts != VL.size())
4555     return false;
4556 
4557   // Check that all of the indices extract from the correct offset.
4558   bool ShouldKeepOrder = true;
4559   unsigned E = VL.size();
4560   // Assign to all items the initial value E + 1 so we can check if the extract
4561   // instruction index was used already.
4562   // Also, later we can check that all the indices are used and we have a
4563   // consecutive access in the extract instructions, by checking that no
4564   // element of CurrentOrder still has value E + 1.
4565   CurrentOrder.assign(E, E);
4566   unsigned I = 0;
4567   for (; I < E; ++I) {
4568     auto *Inst = dyn_cast<Instruction>(VL[I]);
4569     if (!Inst)
4570       continue;
4571     if (Inst->getOperand(0) != Vec)
4572       break;
4573     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4574       if (isa<UndefValue>(EE->getIndexOperand()))
4575         continue;
4576     Optional<unsigned> Idx = getExtractIndex(Inst);
4577     if (!Idx)
4578       break;
4579     const unsigned ExtIdx = *Idx;
4580     if (ExtIdx != I) {
4581       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4582         break;
4583       ShouldKeepOrder = false;
4584       CurrentOrder[ExtIdx] = I;
4585     } else {
4586       if (CurrentOrder[I] != E)
4587         break;
4588       CurrentOrder[I] = I;
4589     }
4590   }
4591   if (I < E) {
4592     CurrentOrder.clear();
4593     return false;
4594   }
4595   if (ShouldKeepOrder)
4596     CurrentOrder.clear();
4597 
4598   return ShouldKeepOrder;
4599 }
4600 
4601 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4602                                     ArrayRef<Value *> VectorizedVals) const {
4603   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4604          all_of(I->users(), [this](User *U) {
4605            return ScalarToTreeEntry.count(U) > 0 || MustGather.contains(U);
4606          });
4607 }
4608 
4609 static std::pair<InstructionCost, InstructionCost>
4610 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4611                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4612   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4613 
4614   // Calculate the cost of the scalar and vector calls.
4615   SmallVector<Type *, 4> VecTys;
4616   for (Use &Arg : CI->args())
4617     VecTys.push_back(
4618         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4619   FastMathFlags FMF;
4620   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4621     FMF = FPCI->getFastMathFlags();
4622   SmallVector<const Value *> Arguments(CI->args());
4623   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4624                                     dyn_cast<IntrinsicInst>(CI));
4625   auto IntrinsicCost =
4626     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4627 
4628   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4629                                      VecTy->getNumElements())),
4630                             false /*HasGlobalPred*/);
4631   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4632   auto LibCost = IntrinsicCost;
4633   if (!CI->isNoBuiltin() && VecFunc) {
4634     // Calculate the cost of the vector library call.
4635     // If the corresponding vector call is cheaper, return its cost.
4636     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4637                                     TTI::TCK_RecipThroughput);
4638   }
4639   return {IntrinsicCost, LibCost};
4640 }
4641 
4642 /// Compute the cost of creating a vector of type \p VecTy containing the
4643 /// extracted values from \p VL.
4644 static InstructionCost
4645 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4646                    TargetTransformInfo::ShuffleKind ShuffleKind,
4647                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4648   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4649 
4650   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4651       VecTy->getNumElements() < NumOfParts)
4652     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4653 
4654   bool AllConsecutive = true;
4655   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4656   unsigned Idx = -1;
4657   InstructionCost Cost = 0;
4658 
4659   // Process extracts in blocks of EltsPerVector to check if the source vector
4660   // operand can be re-used directly. If not, add the cost of creating a shuffle
4661   // to extract the values into a vector register.
4662   for (auto *V : VL) {
4663     ++Idx;
4664 
4665     // Need to exclude undefs from analysis.
4666     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4667       continue;
4668 
4669     // Reached the start of a new vector registers.
4670     if (Idx % EltsPerVector == 0) {
4671       AllConsecutive = true;
4672       continue;
4673     }
4674 
4675     // Check all extracts for a vector register on the target directly
4676     // extract values in order.
4677     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4678     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4679       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4680       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4681                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4682     }
4683 
4684     if (AllConsecutive)
4685       continue;
4686 
4687     // Skip all indices, except for the last index per vector block.
4688     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4689       continue;
4690 
4691     // If we have a series of extracts which are not consecutive and hence
4692     // cannot re-use the source vector register directly, compute the shuffle
4693     // cost to extract the a vector with EltsPerVector elements.
4694     Cost += TTI.getShuffleCost(
4695         TargetTransformInfo::SK_PermuteSingleSrc,
4696         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4697   }
4698   return Cost;
4699 }
4700 
4701 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4702 /// operations operands.
4703 static void
4704 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4705                      ArrayRef<int> ReusesIndices,
4706                      const function_ref<bool(Instruction *)> IsAltOp,
4707                      SmallVectorImpl<int> &Mask,
4708                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4709                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4710   unsigned Sz = VL.size();
4711   Mask.assign(Sz, UndefMaskElem);
4712   SmallVector<int> OrderMask;
4713   if (!ReorderIndices.empty())
4714     inversePermutation(ReorderIndices, OrderMask);
4715   for (unsigned I = 0; I < Sz; ++I) {
4716     unsigned Idx = I;
4717     if (!ReorderIndices.empty())
4718       Idx = OrderMask[I];
4719     auto *OpInst = cast<Instruction>(VL[Idx]);
4720     if (IsAltOp(OpInst)) {
4721       Mask[I] = Sz + Idx;
4722       if (AltScalars)
4723         AltScalars->push_back(OpInst);
4724     } else {
4725       Mask[I] = Idx;
4726       if (OpScalars)
4727         OpScalars->push_back(OpInst);
4728     }
4729   }
4730   if (!ReusesIndices.empty()) {
4731     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4732     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4733       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4734     });
4735     Mask.swap(NewMask);
4736   }
4737 }
4738 
4739 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4740                                       ArrayRef<Value *> VectorizedVals) {
4741   ArrayRef<Value*> VL = E->Scalars;
4742 
4743   Type *ScalarTy = VL[0]->getType();
4744   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4745     ScalarTy = SI->getValueOperand()->getType();
4746   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4747     ScalarTy = CI->getOperand(0)->getType();
4748   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4749     ScalarTy = IE->getOperand(1)->getType();
4750   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4751   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4752 
4753   // If we have computed a smaller type for the expression, update VecTy so
4754   // that the costs will be accurate.
4755   if (MinBWs.count(VL[0]))
4756     VecTy = FixedVectorType::get(
4757         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4758   unsigned EntryVF = E->getVectorFactor();
4759   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4760 
4761   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4762   // FIXME: it tries to fix a problem with MSVC buildbots.
4763   TargetTransformInfo &TTIRef = *TTI;
4764   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4765                                VectorizedVals, E](InstructionCost &Cost) {
4766     DenseMap<Value *, int> ExtractVectorsTys;
4767     SmallPtrSet<Value *, 4> CheckedExtracts;
4768     for (auto *V : VL) {
4769       if (isa<UndefValue>(V))
4770         continue;
4771       // If all users of instruction are going to be vectorized and this
4772       // instruction itself is not going to be vectorized, consider this
4773       // instruction as dead and remove its cost from the final cost of the
4774       // vectorized tree.
4775       // Also, avoid adjusting the cost for extractelements with multiple uses
4776       // in different graph entries.
4777       const TreeEntry *VE = getTreeEntry(V);
4778       if (!CheckedExtracts.insert(V).second ||
4779           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4780           (VE && VE != E))
4781         continue;
4782       auto *EE = cast<ExtractElementInst>(V);
4783       Optional<unsigned> EEIdx = getExtractIndex(EE);
4784       if (!EEIdx)
4785         continue;
4786       unsigned Idx = *EEIdx;
4787       if (TTIRef.getNumberOfParts(VecTy) !=
4788           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4789         auto It =
4790             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4791         It->getSecond() = std::min<int>(It->second, Idx);
4792       }
4793       // Take credit for instruction that will become dead.
4794       if (EE->hasOneUse()) {
4795         Instruction *Ext = EE->user_back();
4796         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4797             all_of(Ext->users(),
4798                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4799           // Use getExtractWithExtendCost() to calculate the cost of
4800           // extractelement/ext pair.
4801           Cost -=
4802               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4803                                               EE->getVectorOperandType(), Idx);
4804           // Add back the cost of s|zext which is subtracted separately.
4805           Cost += TTIRef.getCastInstrCost(
4806               Ext->getOpcode(), Ext->getType(), EE->getType(),
4807               TTI::getCastContextHint(Ext), CostKind, Ext);
4808           continue;
4809         }
4810       }
4811       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4812                                         EE->getVectorOperandType(), Idx);
4813     }
4814     // Add a cost for subvector extracts/inserts if required.
4815     for (const auto &Data : ExtractVectorsTys) {
4816       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4817       unsigned NumElts = VecTy->getNumElements();
4818       if (Data.second % NumElts == 0)
4819         continue;
4820       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4821         unsigned Idx = (Data.second / NumElts) * NumElts;
4822         unsigned EENumElts = EEVTy->getNumElements();
4823         if (Idx + NumElts <= EENumElts) {
4824           Cost +=
4825               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4826                                     EEVTy, None, Idx, VecTy);
4827         } else {
4828           // Need to round up the subvector type vectorization factor to avoid a
4829           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4830           // <= EENumElts.
4831           auto *SubVT =
4832               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4833           Cost +=
4834               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4835                                     EEVTy, None, Idx, SubVT);
4836         }
4837       } else {
4838         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4839                                       VecTy, None, 0, EEVTy);
4840       }
4841     }
4842   };
4843   if (E->State == TreeEntry::NeedToGather) {
4844     if (allConstant(VL))
4845       return 0;
4846     if (isa<InsertElementInst>(VL[0]))
4847       return InstructionCost::getInvalid();
4848     SmallVector<int> Mask;
4849     SmallVector<const TreeEntry *> Entries;
4850     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4851         isGatherShuffledEntry(E, Mask, Entries);
4852     if (Shuffle.hasValue()) {
4853       InstructionCost GatherCost = 0;
4854       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4855         // Perfect match in the graph, will reuse the previously vectorized
4856         // node. Cost is 0.
4857         LLVM_DEBUG(
4858             dbgs()
4859             << "SLP: perfect diamond match for gather bundle that starts with "
4860             << *VL.front() << ".\n");
4861         if (NeedToShuffleReuses)
4862           GatherCost =
4863               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4864                                   FinalVecTy, E->ReuseShuffleIndices);
4865       } else {
4866         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4867                           << " entries for bundle that starts with "
4868                           << *VL.front() << ".\n");
4869         // Detected that instead of gather we can emit a shuffle of single/two
4870         // previously vectorized nodes. Add the cost of the permutation rather
4871         // than gather.
4872         ::addMask(Mask, E->ReuseShuffleIndices);
4873         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4874       }
4875       return GatherCost;
4876     }
4877     if ((E->getOpcode() == Instruction::ExtractElement ||
4878          all_of(E->Scalars,
4879                 [](Value *V) {
4880                   return isa<ExtractElementInst, UndefValue>(V);
4881                 })) &&
4882         allSameType(VL)) {
4883       // Check that gather of extractelements can be represented as just a
4884       // shuffle of a single/two vectors the scalars are extracted from.
4885       SmallVector<int> Mask;
4886       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4887           isFixedVectorShuffle(VL, Mask);
4888       if (ShuffleKind.hasValue()) {
4889         // Found the bunch of extractelement instructions that must be gathered
4890         // into a vector and can be represented as a permutation elements in a
4891         // single input vector or of 2 input vectors.
4892         InstructionCost Cost =
4893             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4894         AdjustExtractsCost(Cost);
4895         if (NeedToShuffleReuses)
4896           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4897                                       FinalVecTy, E->ReuseShuffleIndices);
4898         return Cost;
4899       }
4900     }
4901     if (isSplat(VL)) {
4902       // Found the broadcasting of the single scalar, calculate the cost as the
4903       // broadcast.
4904       assert(VecTy == FinalVecTy &&
4905              "No reused scalars expected for broadcast.");
4906       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4907     }
4908     InstructionCost ReuseShuffleCost = 0;
4909     if (NeedToShuffleReuses)
4910       ReuseShuffleCost = TTI->getShuffleCost(
4911           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4912     // Improve gather cost for gather of loads, if we can group some of the
4913     // loads into vector loads.
4914     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4915         !E->isAltShuffle()) {
4916       BoUpSLP::ValueSet VectorizedLoads;
4917       unsigned StartIdx = 0;
4918       unsigned VF = VL.size() / 2;
4919       unsigned VectorizedCnt = 0;
4920       unsigned ScatterVectorizeCnt = 0;
4921       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4922       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4923         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4924              Cnt += VF) {
4925           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4926           if (!VectorizedLoads.count(Slice.front()) &&
4927               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4928             SmallVector<Value *> PointerOps;
4929             OrdersType CurrentOrder;
4930             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4931                                               *SE, CurrentOrder, PointerOps);
4932             switch (LS) {
4933             case LoadsState::Vectorize:
4934             case LoadsState::ScatterVectorize:
4935               // Mark the vectorized loads so that we don't vectorize them
4936               // again.
4937               if (LS == LoadsState::Vectorize)
4938                 ++VectorizedCnt;
4939               else
4940                 ++ScatterVectorizeCnt;
4941               VectorizedLoads.insert(Slice.begin(), Slice.end());
4942               // If we vectorized initial block, no need to try to vectorize it
4943               // again.
4944               if (Cnt == StartIdx)
4945                 StartIdx += VF;
4946               break;
4947             case LoadsState::Gather:
4948               break;
4949             }
4950           }
4951         }
4952         // Check if the whole array was vectorized already - exit.
4953         if (StartIdx >= VL.size())
4954           break;
4955         // Found vectorizable parts - exit.
4956         if (!VectorizedLoads.empty())
4957           break;
4958       }
4959       if (!VectorizedLoads.empty()) {
4960         InstructionCost GatherCost = 0;
4961         unsigned NumParts = TTI->getNumberOfParts(VecTy);
4962         bool NeedInsertSubvectorAnalysis =
4963             !NumParts || (VL.size() / VF) > NumParts;
4964         // Get the cost for gathered loads.
4965         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4966           if (VectorizedLoads.contains(VL[I]))
4967             continue;
4968           GatherCost += getGatherCost(VL.slice(I, VF));
4969         }
4970         // The cost for vectorized loads.
4971         InstructionCost ScalarsCost = 0;
4972         for (Value *V : VectorizedLoads) {
4973           auto *LI = cast<LoadInst>(V);
4974           ScalarsCost += TTI->getMemoryOpCost(
4975               Instruction::Load, LI->getType(), LI->getAlign(),
4976               LI->getPointerAddressSpace(), CostKind, LI);
4977         }
4978         auto *LI = cast<LoadInst>(E->getMainOp());
4979         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4980         Align Alignment = LI->getAlign();
4981         GatherCost +=
4982             VectorizedCnt *
4983             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4984                                  LI->getPointerAddressSpace(), CostKind, LI);
4985         GatherCost += ScatterVectorizeCnt *
4986                       TTI->getGatherScatterOpCost(
4987                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4988                           /*VariableMask=*/false, Alignment, CostKind, LI);
4989         if (NeedInsertSubvectorAnalysis) {
4990           // Add the cost for the subvectors insert.
4991           for (int I = VF, E = VL.size(); I < E; I += VF)
4992             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
4993                                               None, I, LoadTy);
4994         }
4995         return ReuseShuffleCost + GatherCost - ScalarsCost;
4996       }
4997     }
4998     return ReuseShuffleCost + getGatherCost(VL);
4999   }
5000   InstructionCost CommonCost = 0;
5001   SmallVector<int> Mask;
5002   if (!E->ReorderIndices.empty()) {
5003     SmallVector<int> NewMask;
5004     if (E->getOpcode() == Instruction::Store) {
5005       // For stores the order is actually a mask.
5006       NewMask.resize(E->ReorderIndices.size());
5007       copy(E->ReorderIndices, NewMask.begin());
5008     } else {
5009       inversePermutation(E->ReorderIndices, NewMask);
5010     }
5011     ::addMask(Mask, NewMask);
5012   }
5013   if (NeedToShuffleReuses)
5014     ::addMask(Mask, E->ReuseShuffleIndices);
5015   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5016     CommonCost =
5017         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5018   assert((E->State == TreeEntry::Vectorize ||
5019           E->State == TreeEntry::ScatterVectorize) &&
5020          "Unhandled state");
5021   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5022   Instruction *VL0 = E->getMainOp();
5023   unsigned ShuffleOrOp =
5024       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5025   switch (ShuffleOrOp) {
5026     case Instruction::PHI:
5027       return 0;
5028 
5029     case Instruction::ExtractValue:
5030     case Instruction::ExtractElement: {
5031       // The common cost of removal ExtractElement/ExtractValue instructions +
5032       // the cost of shuffles, if required to resuffle the original vector.
5033       if (NeedToShuffleReuses) {
5034         unsigned Idx = 0;
5035         for (unsigned I : E->ReuseShuffleIndices) {
5036           if (ShuffleOrOp == Instruction::ExtractElement) {
5037             auto *EE = cast<ExtractElementInst>(VL[I]);
5038             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5039                                                   EE->getVectorOperandType(),
5040                                                   *getExtractIndex(EE));
5041           } else {
5042             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5043                                                   VecTy, Idx);
5044             ++Idx;
5045           }
5046         }
5047         Idx = EntryVF;
5048         for (Value *V : VL) {
5049           if (ShuffleOrOp == Instruction::ExtractElement) {
5050             auto *EE = cast<ExtractElementInst>(V);
5051             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5052                                                   EE->getVectorOperandType(),
5053                                                   *getExtractIndex(EE));
5054           } else {
5055             --Idx;
5056             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5057                                                   VecTy, Idx);
5058           }
5059         }
5060       }
5061       if (ShuffleOrOp == Instruction::ExtractValue) {
5062         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5063           auto *EI = cast<Instruction>(VL[I]);
5064           // Take credit for instruction that will become dead.
5065           if (EI->hasOneUse()) {
5066             Instruction *Ext = EI->user_back();
5067             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5068                 all_of(Ext->users(),
5069                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5070               // Use getExtractWithExtendCost() to calculate the cost of
5071               // extractelement/ext pair.
5072               CommonCost -= TTI->getExtractWithExtendCost(
5073                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5074               // Add back the cost of s|zext which is subtracted separately.
5075               CommonCost += TTI->getCastInstrCost(
5076                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5077                   TTI::getCastContextHint(Ext), CostKind, Ext);
5078               continue;
5079             }
5080           }
5081           CommonCost -=
5082               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5083         }
5084       } else {
5085         AdjustExtractsCost(CommonCost);
5086       }
5087       return CommonCost;
5088     }
5089     case Instruction::InsertElement: {
5090       assert(E->ReuseShuffleIndices.empty() &&
5091              "Unique insertelements only are expected.");
5092       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5093 
5094       unsigned const NumElts = SrcVecTy->getNumElements();
5095       unsigned const NumScalars = VL.size();
5096       APInt DemandedElts = APInt::getZero(NumElts);
5097       // TODO: Add support for Instruction::InsertValue.
5098       SmallVector<int> Mask;
5099       if (!E->ReorderIndices.empty()) {
5100         inversePermutation(E->ReorderIndices, Mask);
5101         Mask.append(NumElts - NumScalars, UndefMaskElem);
5102       } else {
5103         Mask.assign(NumElts, UndefMaskElem);
5104         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5105       }
5106       unsigned Offset = *getInsertIndex(VL0, 0);
5107       bool IsIdentity = true;
5108       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5109       Mask.swap(PrevMask);
5110       for (unsigned I = 0; I < NumScalars; ++I) {
5111         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
5112         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5113           continue;
5114         DemandedElts.setBit(*InsertIdx);
5115         IsIdentity &= *InsertIdx - Offset == I;
5116         Mask[*InsertIdx - Offset] = I;
5117       }
5118       assert(Offset < NumElts && "Failed to find vector index offset");
5119 
5120       InstructionCost Cost = 0;
5121       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5122                                             /*Insert*/ true, /*Extract*/ false);
5123 
5124       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5125         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5126         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5127         Cost += TTI->getShuffleCost(
5128             TargetTransformInfo::SK_PermuteSingleSrc,
5129             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5130       } else if (!IsIdentity) {
5131         auto *FirstInsert =
5132             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5133               return !is_contained(E->Scalars,
5134                                    cast<Instruction>(V)->getOperand(0));
5135             }));
5136         if (isUndefVector(FirstInsert->getOperand(0))) {
5137           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5138         } else {
5139           SmallVector<int> InsertMask(NumElts);
5140           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5141           for (unsigned I = 0; I < NumElts; I++) {
5142             if (Mask[I] != UndefMaskElem)
5143               InsertMask[Offset + I] = NumElts + I;
5144           }
5145           Cost +=
5146               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5147         }
5148       }
5149 
5150       return Cost;
5151     }
5152     case Instruction::ZExt:
5153     case Instruction::SExt:
5154     case Instruction::FPToUI:
5155     case Instruction::FPToSI:
5156     case Instruction::FPExt:
5157     case Instruction::PtrToInt:
5158     case Instruction::IntToPtr:
5159     case Instruction::SIToFP:
5160     case Instruction::UIToFP:
5161     case Instruction::Trunc:
5162     case Instruction::FPTrunc:
5163     case Instruction::BitCast: {
5164       Type *SrcTy = VL0->getOperand(0)->getType();
5165       InstructionCost ScalarEltCost =
5166           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5167                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5168       if (NeedToShuffleReuses) {
5169         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5170       }
5171 
5172       // Calculate the cost of this instruction.
5173       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5174 
5175       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5176       InstructionCost VecCost = 0;
5177       // Check if the values are candidates to demote.
5178       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5179         VecCost = CommonCost + TTI->getCastInstrCost(
5180                                    E->getOpcode(), VecTy, SrcVecTy,
5181                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5182       }
5183       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5184       return VecCost - ScalarCost;
5185     }
5186     case Instruction::FCmp:
5187     case Instruction::ICmp:
5188     case Instruction::Select: {
5189       // Calculate the cost of this instruction.
5190       InstructionCost ScalarEltCost =
5191           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5192                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5193       if (NeedToShuffleReuses) {
5194         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5195       }
5196       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5197       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5198 
5199       // Check if all entries in VL are either compares or selects with compares
5200       // as condition that have the same predicates.
5201       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5202       bool First = true;
5203       for (auto *V : VL) {
5204         CmpInst::Predicate CurrentPred;
5205         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5206         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5207              !match(V, MatchCmp)) ||
5208             (!First && VecPred != CurrentPred)) {
5209           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5210           break;
5211         }
5212         First = false;
5213         VecPred = CurrentPred;
5214       }
5215 
5216       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5217           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5218       // Check if it is possible and profitable to use min/max for selects in
5219       // VL.
5220       //
5221       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5222       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5223         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5224                                           {VecTy, VecTy});
5225         InstructionCost IntrinsicCost =
5226             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5227         // If the selects are the only uses of the compares, they will be dead
5228         // and we can adjust the cost by removing their cost.
5229         if (IntrinsicAndUse.second)
5230           IntrinsicCost -=
5231               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5232                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5233         VecCost = std::min(VecCost, IntrinsicCost);
5234       }
5235       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5236       return CommonCost + VecCost - ScalarCost;
5237     }
5238     case Instruction::FNeg:
5239     case Instruction::Add:
5240     case Instruction::FAdd:
5241     case Instruction::Sub:
5242     case Instruction::FSub:
5243     case Instruction::Mul:
5244     case Instruction::FMul:
5245     case Instruction::UDiv:
5246     case Instruction::SDiv:
5247     case Instruction::FDiv:
5248     case Instruction::URem:
5249     case Instruction::SRem:
5250     case Instruction::FRem:
5251     case Instruction::Shl:
5252     case Instruction::LShr:
5253     case Instruction::AShr:
5254     case Instruction::And:
5255     case Instruction::Or:
5256     case Instruction::Xor: {
5257       // Certain instructions can be cheaper to vectorize if they have a
5258       // constant second vector operand.
5259       TargetTransformInfo::OperandValueKind Op1VK =
5260           TargetTransformInfo::OK_AnyValue;
5261       TargetTransformInfo::OperandValueKind Op2VK =
5262           TargetTransformInfo::OK_UniformConstantValue;
5263       TargetTransformInfo::OperandValueProperties Op1VP =
5264           TargetTransformInfo::OP_None;
5265       TargetTransformInfo::OperandValueProperties Op2VP =
5266           TargetTransformInfo::OP_PowerOf2;
5267 
5268       // If all operands are exactly the same ConstantInt then set the
5269       // operand kind to OK_UniformConstantValue.
5270       // If instead not all operands are constants, then set the operand kind
5271       // to OK_AnyValue. If all operands are constants but not the same,
5272       // then set the operand kind to OK_NonUniformConstantValue.
5273       ConstantInt *CInt0 = nullptr;
5274       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5275         const Instruction *I = cast<Instruction>(VL[i]);
5276         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5277         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5278         if (!CInt) {
5279           Op2VK = TargetTransformInfo::OK_AnyValue;
5280           Op2VP = TargetTransformInfo::OP_None;
5281           break;
5282         }
5283         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5284             !CInt->getValue().isPowerOf2())
5285           Op2VP = TargetTransformInfo::OP_None;
5286         if (i == 0) {
5287           CInt0 = CInt;
5288           continue;
5289         }
5290         if (CInt0 != CInt)
5291           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5292       }
5293 
5294       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5295       InstructionCost ScalarEltCost =
5296           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5297                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5298       if (NeedToShuffleReuses) {
5299         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5300       }
5301       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5302       InstructionCost VecCost =
5303           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5304                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5305       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5306       return CommonCost + VecCost - ScalarCost;
5307     }
5308     case Instruction::GetElementPtr: {
5309       TargetTransformInfo::OperandValueKind Op1VK =
5310           TargetTransformInfo::OK_AnyValue;
5311       TargetTransformInfo::OperandValueKind Op2VK =
5312           TargetTransformInfo::OK_UniformConstantValue;
5313 
5314       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5315           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5316       if (NeedToShuffleReuses) {
5317         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5318       }
5319       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5320       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5321           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5322       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5323       return CommonCost + VecCost - ScalarCost;
5324     }
5325     case Instruction::Load: {
5326       // Cost of wide load - cost of scalar loads.
5327       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5328       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5329           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5330       if (NeedToShuffleReuses) {
5331         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5332       }
5333       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5334       InstructionCost VecLdCost;
5335       if (E->State == TreeEntry::Vectorize) {
5336         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5337                                          CostKind, VL0);
5338       } else {
5339         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5340         Align CommonAlignment = Alignment;
5341         for (Value *V : VL)
5342           CommonAlignment =
5343               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5344         VecLdCost = TTI->getGatherScatterOpCost(
5345             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5346             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5347       }
5348       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5349       return CommonCost + VecLdCost - ScalarLdCost;
5350     }
5351     case Instruction::Store: {
5352       // We know that we can merge the stores. Calculate the cost.
5353       bool IsReorder = !E->ReorderIndices.empty();
5354       auto *SI =
5355           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5356       Align Alignment = SI->getAlign();
5357       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5358           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5359       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5360       InstructionCost VecStCost = TTI->getMemoryOpCost(
5361           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5362       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5363       return CommonCost + VecStCost - ScalarStCost;
5364     }
5365     case Instruction::Call: {
5366       CallInst *CI = cast<CallInst>(VL0);
5367       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5368 
5369       // Calculate the cost of the scalar and vector calls.
5370       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5371       InstructionCost ScalarEltCost =
5372           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5373       if (NeedToShuffleReuses) {
5374         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5375       }
5376       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5377 
5378       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5379       InstructionCost VecCallCost =
5380           std::min(VecCallCosts.first, VecCallCosts.second);
5381 
5382       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5383                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5384                         << " for " << *CI << "\n");
5385 
5386       return CommonCost + VecCallCost - ScalarCallCost;
5387     }
5388     case Instruction::ShuffleVector: {
5389       assert(E->isAltShuffle() &&
5390              ((Instruction::isBinaryOp(E->getOpcode()) &&
5391                Instruction::isBinaryOp(E->getAltOpcode())) ||
5392               (Instruction::isCast(E->getOpcode()) &&
5393                Instruction::isCast(E->getAltOpcode())) ||
5394               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5395              "Invalid Shuffle Vector Operand");
5396       InstructionCost ScalarCost = 0;
5397       if (NeedToShuffleReuses) {
5398         for (unsigned Idx : E->ReuseShuffleIndices) {
5399           Instruction *I = cast<Instruction>(VL[Idx]);
5400           CommonCost -= TTI->getInstructionCost(I, CostKind);
5401         }
5402         for (Value *V : VL) {
5403           Instruction *I = cast<Instruction>(V);
5404           CommonCost += TTI->getInstructionCost(I, CostKind);
5405         }
5406       }
5407       for (Value *V : VL) {
5408         Instruction *I = cast<Instruction>(V);
5409         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5410         ScalarCost += TTI->getInstructionCost(I, CostKind);
5411       }
5412       // VecCost is equal to sum of the cost of creating 2 vectors
5413       // and the cost of creating shuffle.
5414       InstructionCost VecCost = 0;
5415       // Try to find the previous shuffle node with the same operands and same
5416       // main/alternate ops.
5417       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5418         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5419           if (TE.get() == E)
5420             break;
5421           if (TE->isAltShuffle() &&
5422               ((TE->getOpcode() == E->getOpcode() &&
5423                 TE->getAltOpcode() == E->getAltOpcode()) ||
5424                (TE->getOpcode() == E->getAltOpcode() &&
5425                 TE->getAltOpcode() == E->getOpcode())) &&
5426               TE->hasEqualOperands(*E))
5427             return true;
5428         }
5429         return false;
5430       };
5431       if (TryFindNodeWithEqualOperands()) {
5432         LLVM_DEBUG({
5433           dbgs() << "SLP: diamond match for alternate node found.\n";
5434           E->dump();
5435         });
5436         // No need to add new vector costs here since we're going to reuse
5437         // same main/alternate vector ops, just do different shuffling.
5438       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5439         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5440         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5441                                                CostKind);
5442       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5443         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5444                                           Builder.getInt1Ty(),
5445                                           CI0->getPredicate(), CostKind, VL0);
5446         VecCost += TTI->getCmpSelInstrCost(
5447             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5448             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5449             E->getAltOp());
5450       } else {
5451         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5452         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5453         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5454         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5455         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5456                                         TTI::CastContextHint::None, CostKind);
5457         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5458                                          TTI::CastContextHint::None, CostKind);
5459       }
5460 
5461       SmallVector<int> Mask;
5462       buildSuffleEntryMask(
5463           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5464           [E](Instruction *I) {
5465             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5466             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
5467               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
5468               auto *CI = cast<CmpInst>(I);
5469               CmpInst::Predicate P0 = CI0->getPredicate();
5470               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5471               CmpInst::Predicate AltP0Swapped =
5472                   CmpInst::getSwappedPredicate(AltP0);
5473               CmpInst::Predicate CurrentPred = CI->getPredicate();
5474               CmpInst::Predicate CurrentPredSwapped =
5475                   CmpInst::getSwappedPredicate(CurrentPred);
5476               if (P0 == AltP0 || P0 == AltP0Swapped) {
5477                 // Alternate cmps have same/swapped predicate as main cmps but
5478                 // different order of compatible operands.
5479                 return !(
5480                     (P0 == CurrentPred &&
5481                      areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5482                                          I->getOperand(0), I->getOperand(1))) ||
5483                     (P0 == CurrentPredSwapped &&
5484                      areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5485                                          I->getOperand(1), I->getOperand(0))));
5486               }
5487               return CurrentPred != P0 && CurrentPredSwapped != P0;
5488             }
5489             return I->getOpcode() == E->getAltOpcode();
5490           },
5491           Mask);
5492       CommonCost =
5493           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5494       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5495       return CommonCost + VecCost - ScalarCost;
5496     }
5497     default:
5498       llvm_unreachable("Unknown instruction");
5499   }
5500 }
5501 
5502 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5503   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5504                     << VectorizableTree.size() << " is fully vectorizable .\n");
5505 
5506   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5507     SmallVector<int> Mask;
5508     return TE->State == TreeEntry::NeedToGather &&
5509            !any_of(TE->Scalars,
5510                    [this](Value *V) { return EphValues.contains(V); }) &&
5511            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5512             TE->Scalars.size() < Limit ||
5513             ((TE->getOpcode() == Instruction::ExtractElement ||
5514               all_of(TE->Scalars,
5515                      [](Value *V) {
5516                        return isa<ExtractElementInst, UndefValue>(V);
5517                      })) &&
5518              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5519             (TE->State == TreeEntry::NeedToGather &&
5520              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5521   };
5522 
5523   // We only handle trees of heights 1 and 2.
5524   if (VectorizableTree.size() == 1 &&
5525       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5526        (ForReduction &&
5527         AreVectorizableGathers(VectorizableTree[0].get(),
5528                                VectorizableTree[0]->Scalars.size()) &&
5529         VectorizableTree[0]->getVectorFactor() > 2)))
5530     return true;
5531 
5532   if (VectorizableTree.size() != 2)
5533     return false;
5534 
5535   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5536   // with the second gather nodes if they have less scalar operands rather than
5537   // the initial tree element (may be profitable to shuffle the second gather)
5538   // or they are extractelements, which form shuffle.
5539   SmallVector<int> Mask;
5540   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5541       AreVectorizableGathers(VectorizableTree[1].get(),
5542                              VectorizableTree[0]->Scalars.size()))
5543     return true;
5544 
5545   // Gathering cost would be too much for tiny trees.
5546   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5547       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5548        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5549     return false;
5550 
5551   return true;
5552 }
5553 
5554 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5555                                        TargetTransformInfo *TTI,
5556                                        bool MustMatchOrInst) {
5557   // Look past the root to find a source value. Arbitrarily follow the
5558   // path through operand 0 of any 'or'. Also, peek through optional
5559   // shift-left-by-multiple-of-8-bits.
5560   Value *ZextLoad = Root;
5561   const APInt *ShAmtC;
5562   bool FoundOr = false;
5563   while (!isa<ConstantExpr>(ZextLoad) &&
5564          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5565           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5566            ShAmtC->urem(8) == 0))) {
5567     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5568     ZextLoad = BinOp->getOperand(0);
5569     if (BinOp->getOpcode() == Instruction::Or)
5570       FoundOr = true;
5571   }
5572   // Check if the input is an extended load of the required or/shift expression.
5573   Value *Load;
5574   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5575       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5576     return false;
5577 
5578   // Require that the total load bit width is a legal integer type.
5579   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5580   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5581   Type *SrcTy = Load->getType();
5582   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5583   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5584     return false;
5585 
5586   // Everything matched - assume that we can fold the whole sequence using
5587   // load combining.
5588   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5589              << *(cast<Instruction>(Root)) << "\n");
5590 
5591   return true;
5592 }
5593 
5594 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5595   if (RdxKind != RecurKind::Or)
5596     return false;
5597 
5598   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5599   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5600   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5601                                     /* MatchOr */ false);
5602 }
5603 
5604 bool BoUpSLP::isLoadCombineCandidate() const {
5605   // Peek through a final sequence of stores and check if all operations are
5606   // likely to be load-combined.
5607   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5608   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5609     Value *X;
5610     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5611         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5612       return false;
5613   }
5614   return true;
5615 }
5616 
5617 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5618   // No need to vectorize inserts of gathered values.
5619   if (VectorizableTree.size() == 2 &&
5620       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5621       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5622     return true;
5623 
5624   // We can vectorize the tree if its size is greater than or equal to the
5625   // minimum size specified by the MinTreeSize command line option.
5626   if (VectorizableTree.size() >= MinTreeSize)
5627     return false;
5628 
5629   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5630   // can vectorize it if we can prove it fully vectorizable.
5631   if (isFullyVectorizableTinyTree(ForReduction))
5632     return false;
5633 
5634   assert(VectorizableTree.empty()
5635              ? ExternalUses.empty()
5636              : true && "We shouldn't have any external users");
5637 
5638   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5639   // vectorizable.
5640   return true;
5641 }
5642 
5643 InstructionCost BoUpSLP::getSpillCost() const {
5644   // Walk from the bottom of the tree to the top, tracking which values are
5645   // live. When we see a call instruction that is not part of our tree,
5646   // query TTI to see if there is a cost to keeping values live over it
5647   // (for example, if spills and fills are required).
5648   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5649   InstructionCost Cost = 0;
5650 
5651   SmallPtrSet<Instruction*, 4> LiveValues;
5652   Instruction *PrevInst = nullptr;
5653 
5654   // The entries in VectorizableTree are not necessarily ordered by their
5655   // position in basic blocks. Collect them and order them by dominance so later
5656   // instructions are guaranteed to be visited first. For instructions in
5657   // different basic blocks, we only scan to the beginning of the block, so
5658   // their order does not matter, as long as all instructions in a basic block
5659   // are grouped together. Using dominance ensures a deterministic order.
5660   SmallVector<Instruction *, 16> OrderedScalars;
5661   for (const auto &TEPtr : VectorizableTree) {
5662     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5663     if (!Inst)
5664       continue;
5665     OrderedScalars.push_back(Inst);
5666   }
5667   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5668     auto *NodeA = DT->getNode(A->getParent());
5669     auto *NodeB = DT->getNode(B->getParent());
5670     assert(NodeA && "Should only process reachable instructions");
5671     assert(NodeB && "Should only process reachable instructions");
5672     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5673            "Different nodes should have different DFS numbers");
5674     if (NodeA != NodeB)
5675       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5676     return B->comesBefore(A);
5677   });
5678 
5679   for (Instruction *Inst : OrderedScalars) {
5680     if (!PrevInst) {
5681       PrevInst = Inst;
5682       continue;
5683     }
5684 
5685     // Update LiveValues.
5686     LiveValues.erase(PrevInst);
5687     for (auto &J : PrevInst->operands()) {
5688       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5689         LiveValues.insert(cast<Instruction>(&*J));
5690     }
5691 
5692     LLVM_DEBUG({
5693       dbgs() << "SLP: #LV: " << LiveValues.size();
5694       for (auto *X : LiveValues)
5695         dbgs() << " " << X->getName();
5696       dbgs() << ", Looking at ";
5697       Inst->dump();
5698     });
5699 
5700     // Now find the sequence of instructions between PrevInst and Inst.
5701     unsigned NumCalls = 0;
5702     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5703                                  PrevInstIt =
5704                                      PrevInst->getIterator().getReverse();
5705     while (InstIt != PrevInstIt) {
5706       if (PrevInstIt == PrevInst->getParent()->rend()) {
5707         PrevInstIt = Inst->getParent()->rbegin();
5708         continue;
5709       }
5710 
5711       // Debug information does not impact spill cost.
5712       if ((isa<CallInst>(&*PrevInstIt) &&
5713            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5714           &*PrevInstIt != PrevInst)
5715         NumCalls++;
5716 
5717       ++PrevInstIt;
5718     }
5719 
5720     if (NumCalls) {
5721       SmallVector<Type*, 4> V;
5722       for (auto *II : LiveValues) {
5723         auto *ScalarTy = II->getType();
5724         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5725           ScalarTy = VectorTy->getElementType();
5726         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5727       }
5728       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5729     }
5730 
5731     PrevInst = Inst;
5732   }
5733 
5734   return Cost;
5735 }
5736 
5737 /// Check if two insertelement instructions are from the same buildvector.
5738 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5739                                             InsertElementInst *V) {
5740   // Instructions must be from the same basic blocks.
5741   if (VU->getParent() != V->getParent())
5742     return false;
5743   // Checks if 2 insertelements are from the same buildvector.
5744   if (VU->getType() != V->getType())
5745     return false;
5746   // Multiple used inserts are separate nodes.
5747   if (!VU->hasOneUse() && !V->hasOneUse())
5748     return false;
5749   auto *IE1 = VU;
5750   auto *IE2 = V;
5751   // Go through the vector operand of insertelement instructions trying to find
5752   // either VU as the original vector for IE2 or V as the original vector for
5753   // IE1.
5754   do {
5755     if (IE2 == VU || IE1 == V)
5756       return true;
5757     if (IE1) {
5758       if (IE1 != VU && !IE1->hasOneUse())
5759         IE1 = nullptr;
5760       else
5761         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5762     }
5763     if (IE2) {
5764       if (IE2 != V && !IE2->hasOneUse())
5765         IE2 = nullptr;
5766       else
5767         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5768     }
5769   } while (IE1 || IE2);
5770   return false;
5771 }
5772 
5773 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5774   InstructionCost Cost = 0;
5775   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5776                     << VectorizableTree.size() << ".\n");
5777 
5778   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5779 
5780   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5781     TreeEntry &TE = *VectorizableTree[I].get();
5782 
5783     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5784     Cost += C;
5785     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5786                       << " for bundle that starts with " << *TE.Scalars[0]
5787                       << ".\n"
5788                       << "SLP: Current total cost = " << Cost << "\n");
5789   }
5790 
5791   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5792   InstructionCost ExtractCost = 0;
5793   SmallVector<unsigned> VF;
5794   SmallVector<SmallVector<int>> ShuffleMask;
5795   SmallVector<Value *> FirstUsers;
5796   SmallVector<APInt> DemandedElts;
5797   for (ExternalUser &EU : ExternalUses) {
5798     // We only add extract cost once for the same scalar.
5799     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5800         !ExtractCostCalculated.insert(EU.Scalar).second)
5801       continue;
5802 
5803     // Uses by ephemeral values are free (because the ephemeral value will be
5804     // removed prior to code generation, and so the extraction will be
5805     // removed as well).
5806     if (EphValues.count(EU.User))
5807       continue;
5808 
5809     // No extract cost for vector "scalar"
5810     if (isa<FixedVectorType>(EU.Scalar->getType()))
5811       continue;
5812 
5813     // Already counted the cost for external uses when tried to adjust the cost
5814     // for extractelements, no need to add it again.
5815     if (isa<ExtractElementInst>(EU.Scalar))
5816       continue;
5817 
5818     // If found user is an insertelement, do not calculate extract cost but try
5819     // to detect it as a final shuffled/identity match.
5820     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5821       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5822         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5823         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5824           continue;
5825         auto *It = find_if(FirstUsers, [VU](Value *V) {
5826           return areTwoInsertFromSameBuildVector(VU,
5827                                                  cast<InsertElementInst>(V));
5828         });
5829         int VecId = -1;
5830         if (It == FirstUsers.end()) {
5831           VF.push_back(FTy->getNumElements());
5832           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5833           // Find the insertvector, vectorized in tree, if any.
5834           Value *Base = VU;
5835           while (isa<InsertElementInst>(Base)) {
5836             // Build the mask for the vectorized insertelement instructions.
5837             if (const TreeEntry *E = getTreeEntry(Base)) {
5838               VU = cast<InsertElementInst>(Base);
5839               do {
5840                 int Idx = E->findLaneForValue(Base);
5841                 ShuffleMask.back()[Idx] = Idx;
5842                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5843               } while (E == getTreeEntry(Base));
5844               break;
5845             }
5846             Base = cast<InsertElementInst>(Base)->getOperand(0);
5847           }
5848           FirstUsers.push_back(VU);
5849           DemandedElts.push_back(APInt::getZero(VF.back()));
5850           VecId = FirstUsers.size() - 1;
5851         } else {
5852           VecId = std::distance(FirstUsers.begin(), It);
5853         }
5854         int Idx = *InsertIdx;
5855         ShuffleMask[VecId][Idx] = EU.Lane;
5856         DemandedElts[VecId].setBit(Idx);
5857         continue;
5858       }
5859     }
5860 
5861     // If we plan to rewrite the tree in a smaller type, we will need to sign
5862     // extend the extracted value back to the original type. Here, we account
5863     // for the extract and the added cost of the sign extend if needed.
5864     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5865     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5866     if (MinBWs.count(ScalarRoot)) {
5867       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5868       auto Extend =
5869           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5870       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5871       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5872                                                    VecTy, EU.Lane);
5873     } else {
5874       ExtractCost +=
5875           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5876     }
5877   }
5878 
5879   InstructionCost SpillCost = getSpillCost();
5880   Cost += SpillCost + ExtractCost;
5881   if (FirstUsers.size() == 1) {
5882     int Limit = ShuffleMask.front().size() * 2;
5883     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5884         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5885       InstructionCost C = TTI->getShuffleCost(
5886           TTI::SK_PermuteSingleSrc,
5887           cast<FixedVectorType>(FirstUsers.front()->getType()),
5888           ShuffleMask.front());
5889       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5890                         << " for final shuffle of insertelement external users "
5891                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5892                         << "SLP: Current total cost = " << Cost << "\n");
5893       Cost += C;
5894     }
5895     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5896         cast<FixedVectorType>(FirstUsers.front()->getType()),
5897         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5898     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5899                       << " for insertelements gather.\n"
5900                       << "SLP: Current total cost = " << Cost << "\n");
5901     Cost -= InsertCost;
5902   } else if (FirstUsers.size() >= 2) {
5903     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5904     // Combined masks of the first 2 vectors.
5905     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5906     copy(ShuffleMask.front(), CombinedMask.begin());
5907     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5908     auto *VecTy = FixedVectorType::get(
5909         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5910         MaxVF);
5911     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5912       if (ShuffleMask[1][I] != UndefMaskElem) {
5913         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5914         CombinedDemandedElts.setBit(I);
5915       }
5916     }
5917     InstructionCost C =
5918         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5919     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5920                       << " for final shuffle of vector node and external "
5921                          "insertelement users "
5922                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5923                       << "SLP: Current total cost = " << Cost << "\n");
5924     Cost += C;
5925     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5926         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5927     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5928                       << " for insertelements gather.\n"
5929                       << "SLP: Current total cost = " << Cost << "\n");
5930     Cost -= InsertCost;
5931     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5932       // Other elements - permutation of 2 vectors (the initial one and the
5933       // next Ith incoming vector).
5934       unsigned VF = ShuffleMask[I].size();
5935       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5936         int Mask = ShuffleMask[I][Idx];
5937         if (Mask != UndefMaskElem)
5938           CombinedMask[Idx] = MaxVF + Mask;
5939         else if (CombinedMask[Idx] != UndefMaskElem)
5940           CombinedMask[Idx] = Idx;
5941       }
5942       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5943         if (CombinedMask[Idx] != UndefMaskElem)
5944           CombinedMask[Idx] = Idx;
5945       InstructionCost C =
5946           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5947       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5948                         << " for final shuffle of vector node and external "
5949                            "insertelement users "
5950                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5951                         << "SLP: Current total cost = " << Cost << "\n");
5952       Cost += C;
5953       InstructionCost InsertCost = TTI->getScalarizationOverhead(
5954           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5955           /*Insert*/ true, /*Extract*/ false);
5956       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5957                         << " for insertelements gather.\n"
5958                         << "SLP: Current total cost = " << Cost << "\n");
5959       Cost -= InsertCost;
5960     }
5961   }
5962 
5963 #ifndef NDEBUG
5964   SmallString<256> Str;
5965   {
5966     raw_svector_ostream OS(Str);
5967     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5968        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5969        << "SLP: Total Cost = " << Cost << ".\n";
5970   }
5971   LLVM_DEBUG(dbgs() << Str);
5972   if (ViewSLPTree)
5973     ViewGraph(this, "SLP" + F->getName(), false, Str);
5974 #endif
5975 
5976   return Cost;
5977 }
5978 
5979 Optional<TargetTransformInfo::ShuffleKind>
5980 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5981                                SmallVectorImpl<const TreeEntry *> &Entries) {
5982   // TODO: currently checking only for Scalars in the tree entry, need to count
5983   // reused elements too for better cost estimation.
5984   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5985   Entries.clear();
5986   // Build a lists of values to tree entries.
5987   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5988   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5989     if (EntryPtr.get() == TE)
5990       break;
5991     if (EntryPtr->State != TreeEntry::NeedToGather)
5992       continue;
5993     for (Value *V : EntryPtr->Scalars)
5994       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5995   }
5996   // Find all tree entries used by the gathered values. If no common entries
5997   // found - not a shuffle.
5998   // Here we build a set of tree nodes for each gathered value and trying to
5999   // find the intersection between these sets. If we have at least one common
6000   // tree node for each gathered value - we have just a permutation of the
6001   // single vector. If we have 2 different sets, we're in situation where we
6002   // have a permutation of 2 input vectors.
6003   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6004   DenseMap<Value *, int> UsedValuesEntry;
6005   for (Value *V : TE->Scalars) {
6006     if (isa<UndefValue>(V))
6007       continue;
6008     // Build a list of tree entries where V is used.
6009     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6010     auto It = ValueToTEs.find(V);
6011     if (It != ValueToTEs.end())
6012       VToTEs = It->second;
6013     if (const TreeEntry *VTE = getTreeEntry(V))
6014       VToTEs.insert(VTE);
6015     if (VToTEs.empty())
6016       return None;
6017     if (UsedTEs.empty()) {
6018       // The first iteration, just insert the list of nodes to vector.
6019       UsedTEs.push_back(VToTEs);
6020     } else {
6021       // Need to check if there are any previously used tree nodes which use V.
6022       // If there are no such nodes, consider that we have another one input
6023       // vector.
6024       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6025       unsigned Idx = 0;
6026       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6027         // Do we have a non-empty intersection of previously listed tree entries
6028         // and tree entries using current V?
6029         set_intersect(VToTEs, Set);
6030         if (!VToTEs.empty()) {
6031           // Yes, write the new subset and continue analysis for the next
6032           // scalar.
6033           Set.swap(VToTEs);
6034           break;
6035         }
6036         VToTEs = SavedVToTEs;
6037         ++Idx;
6038       }
6039       // No non-empty intersection found - need to add a second set of possible
6040       // source vectors.
6041       if (Idx == UsedTEs.size()) {
6042         // If the number of input vectors is greater than 2 - not a permutation,
6043         // fallback to the regular gather.
6044         if (UsedTEs.size() == 2)
6045           return None;
6046         UsedTEs.push_back(SavedVToTEs);
6047         Idx = UsedTEs.size() - 1;
6048       }
6049       UsedValuesEntry.try_emplace(V, Idx);
6050     }
6051   }
6052 
6053   unsigned VF = 0;
6054   if (UsedTEs.size() == 1) {
6055     // Try to find the perfect match in another gather node at first.
6056     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6057       return EntryPtr->isSame(TE->Scalars);
6058     });
6059     if (It != UsedTEs.front().end()) {
6060       Entries.push_back(*It);
6061       std::iota(Mask.begin(), Mask.end(), 0);
6062       return TargetTransformInfo::SK_PermuteSingleSrc;
6063     }
6064     // No perfect match, just shuffle, so choose the first tree node.
6065     Entries.push_back(*UsedTEs.front().begin());
6066   } else {
6067     // Try to find nodes with the same vector factor.
6068     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6069     DenseMap<int, const TreeEntry *> VFToTE;
6070     for (const TreeEntry *TE : UsedTEs.front())
6071       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6072     for (const TreeEntry *TE : UsedTEs.back()) {
6073       auto It = VFToTE.find(TE->getVectorFactor());
6074       if (It != VFToTE.end()) {
6075         VF = It->first;
6076         Entries.push_back(It->second);
6077         Entries.push_back(TE);
6078         break;
6079       }
6080     }
6081     // No 2 source vectors with the same vector factor - give up and do regular
6082     // gather.
6083     if (Entries.empty())
6084       return None;
6085   }
6086 
6087   // Build a shuffle mask for better cost estimation and vector emission.
6088   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6089     Value *V = TE->Scalars[I];
6090     if (isa<UndefValue>(V))
6091       continue;
6092     unsigned Idx = UsedValuesEntry.lookup(V);
6093     const TreeEntry *VTE = Entries[Idx];
6094     int FoundLane = VTE->findLaneForValue(V);
6095     Mask[I] = Idx * VF + FoundLane;
6096     // Extra check required by isSingleSourceMaskImpl function (called by
6097     // ShuffleVectorInst::isSingleSourceMask).
6098     if (Mask[I] >= 2 * E)
6099       return None;
6100   }
6101   switch (Entries.size()) {
6102   case 1:
6103     return TargetTransformInfo::SK_PermuteSingleSrc;
6104   case 2:
6105     return TargetTransformInfo::SK_PermuteTwoSrc;
6106   default:
6107     break;
6108   }
6109   return None;
6110 }
6111 
6112 InstructionCost
6113 BoUpSLP::getGatherCost(FixedVectorType *Ty,
6114                        const DenseSet<unsigned> &ShuffledIndices,
6115                        bool NeedToShuffle) const {
6116   unsigned NumElts = Ty->getNumElements();
6117   APInt DemandedElts = APInt::getZero(NumElts);
6118   for (unsigned I = 0; I < NumElts; ++I)
6119     if (!ShuffledIndices.count(I))
6120       DemandedElts.setBit(I);
6121   InstructionCost Cost =
6122       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
6123                                     /*Extract*/ false);
6124   if (NeedToShuffle)
6125     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6126   return Cost;
6127 }
6128 
6129 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6130   // Find the type of the operands in VL.
6131   Type *ScalarTy = VL[0]->getType();
6132   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6133     ScalarTy = SI->getValueOperand()->getType();
6134   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6135   bool DuplicateNonConst = false;
6136   // Find the cost of inserting/extracting values from the vector.
6137   // Check if the same elements are inserted several times and count them as
6138   // shuffle candidates.
6139   DenseSet<unsigned> ShuffledElements;
6140   DenseSet<Value *> UniqueElements;
6141   // Iterate in reverse order to consider insert elements with the high cost.
6142   for (unsigned I = VL.size(); I > 0; --I) {
6143     unsigned Idx = I - 1;
6144     // No need to shuffle duplicates for constants.
6145     if (isConstant(VL[Idx])) {
6146       ShuffledElements.insert(Idx);
6147       continue;
6148     }
6149     if (!UniqueElements.insert(VL[Idx]).second) {
6150       DuplicateNonConst = true;
6151       ShuffledElements.insert(Idx);
6152     }
6153   }
6154   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6155 }
6156 
6157 // Perform operand reordering on the instructions in VL and return the reordered
6158 // operands in Left and Right.
6159 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6160                                              SmallVectorImpl<Value *> &Left,
6161                                              SmallVectorImpl<Value *> &Right,
6162                                              const DataLayout &DL,
6163                                              ScalarEvolution &SE,
6164                                              const BoUpSLP &R) {
6165   if (VL.empty())
6166     return;
6167   VLOperands Ops(VL, DL, SE, R);
6168   // Reorder the operands in place.
6169   Ops.reorder();
6170   Left = Ops.getVL(0);
6171   Right = Ops.getVL(1);
6172 }
6173 
6174 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6175   // Get the basic block this bundle is in. All instructions in the bundle
6176   // should be in this block.
6177   auto *Front = E->getMainOp();
6178   auto *BB = Front->getParent();
6179   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6180     auto *I = cast<Instruction>(V);
6181     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6182   }));
6183 
6184   // The last instruction in the bundle in program order.
6185   Instruction *LastInst = nullptr;
6186 
6187   // Find the last instruction. The common case should be that BB has been
6188   // scheduled, and the last instruction is VL.back(). So we start with
6189   // VL.back() and iterate over schedule data until we reach the end of the
6190   // bundle. The end of the bundle is marked by null ScheduleData.
6191   if (BlocksSchedules.count(BB)) {
6192     auto *Bundle =
6193         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6194     if (Bundle && Bundle->isPartOfBundle())
6195       for (; Bundle; Bundle = Bundle->NextInBundle)
6196         if (Bundle->OpValue == Bundle->Inst)
6197           LastInst = Bundle->Inst;
6198   }
6199 
6200   // LastInst can still be null at this point if there's either not an entry
6201   // for BB in BlocksSchedules or there's no ScheduleData available for
6202   // VL.back(). This can be the case if buildTree_rec aborts for various
6203   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6204   // size is reached, etc.). ScheduleData is initialized in the scheduling
6205   // "dry-run".
6206   //
6207   // If this happens, we can still find the last instruction by brute force. We
6208   // iterate forwards from Front (inclusive) until we either see all
6209   // instructions in the bundle or reach the end of the block. If Front is the
6210   // last instruction in program order, LastInst will be set to Front, and we
6211   // will visit all the remaining instructions in the block.
6212   //
6213   // One of the reasons we exit early from buildTree_rec is to place an upper
6214   // bound on compile-time. Thus, taking an additional compile-time hit here is
6215   // not ideal. However, this should be exceedingly rare since it requires that
6216   // we both exit early from buildTree_rec and that the bundle be out-of-order
6217   // (causing us to iterate all the way to the end of the block).
6218   if (!LastInst) {
6219     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6220     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6221       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6222         LastInst = &I;
6223       if (Bundle.empty())
6224         break;
6225     }
6226   }
6227   assert(LastInst && "Failed to find last instruction in bundle");
6228 
6229   // Set the insertion point after the last instruction in the bundle. Set the
6230   // debug location to Front.
6231   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6232   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6233 }
6234 
6235 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6236   // List of instructions/lanes from current block and/or the blocks which are
6237   // part of the current loop. These instructions will be inserted at the end to
6238   // make it possible to optimize loops and hoist invariant instructions out of
6239   // the loops body with better chances for success.
6240   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6241   SmallSet<int, 4> PostponedIndices;
6242   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6243   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6244     SmallPtrSet<BasicBlock *, 4> Visited;
6245     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6246       InsertBB = InsertBB->getSinglePredecessor();
6247     return InsertBB && InsertBB == InstBB;
6248   };
6249   for (int I = 0, E = VL.size(); I < E; ++I) {
6250     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6251       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6252            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6253           PostponedIndices.insert(I).second)
6254         PostponedInsts.emplace_back(Inst, I);
6255   }
6256 
6257   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6258     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6259     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6260     if (!InsElt)
6261       return Vec;
6262     GatherShuffleSeq.insert(InsElt);
6263     CSEBlocks.insert(InsElt->getParent());
6264     // Add to our 'need-to-extract' list.
6265     if (TreeEntry *Entry = getTreeEntry(V)) {
6266       // Find which lane we need to extract.
6267       unsigned FoundLane = Entry->findLaneForValue(V);
6268       ExternalUses.emplace_back(V, InsElt, FoundLane);
6269     }
6270     return Vec;
6271   };
6272   Value *Val0 =
6273       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6274   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6275   Value *Vec = PoisonValue::get(VecTy);
6276   SmallVector<int> NonConsts;
6277   // Insert constant values at first.
6278   for (int I = 0, E = VL.size(); I < E; ++I) {
6279     if (PostponedIndices.contains(I))
6280       continue;
6281     if (!isConstant(VL[I])) {
6282       NonConsts.push_back(I);
6283       continue;
6284     }
6285     Vec = CreateInsertElement(Vec, VL[I], I);
6286   }
6287   // Insert non-constant values.
6288   for (int I : NonConsts)
6289     Vec = CreateInsertElement(Vec, VL[I], I);
6290   // Append instructions, which are/may be part of the loop, in the end to make
6291   // it possible to hoist non-loop-based instructions.
6292   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6293     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6294 
6295   return Vec;
6296 }
6297 
6298 namespace {
6299 /// Merges shuffle masks and emits final shuffle instruction, if required.
6300 class ShuffleInstructionBuilder {
6301   IRBuilderBase &Builder;
6302   const unsigned VF = 0;
6303   bool IsFinalized = false;
6304   SmallVector<int, 4> Mask;
6305   /// Holds all of the instructions that we gathered.
6306   SetVector<Instruction *> &GatherShuffleSeq;
6307   /// A list of blocks that we are going to CSE.
6308   SetVector<BasicBlock *> &CSEBlocks;
6309 
6310 public:
6311   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6312                             SetVector<Instruction *> &GatherShuffleSeq,
6313                             SetVector<BasicBlock *> &CSEBlocks)
6314       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6315         CSEBlocks(CSEBlocks) {}
6316 
6317   /// Adds a mask, inverting it before applying.
6318   void addInversedMask(ArrayRef<unsigned> SubMask) {
6319     if (SubMask.empty())
6320       return;
6321     SmallVector<int, 4> NewMask;
6322     inversePermutation(SubMask, NewMask);
6323     addMask(NewMask);
6324   }
6325 
6326   /// Functions adds masks, merging them into  single one.
6327   void addMask(ArrayRef<unsigned> SubMask) {
6328     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6329     addMask(NewMask);
6330   }
6331 
6332   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6333 
6334   Value *finalize(Value *V) {
6335     IsFinalized = true;
6336     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6337     if (VF == ValueVF && Mask.empty())
6338       return V;
6339     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6340     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6341     addMask(NormalizedMask);
6342 
6343     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6344       return V;
6345     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6346     if (auto *I = dyn_cast<Instruction>(Vec)) {
6347       GatherShuffleSeq.insert(I);
6348       CSEBlocks.insert(I->getParent());
6349     }
6350     return Vec;
6351   }
6352 
6353   ~ShuffleInstructionBuilder() {
6354     assert((IsFinalized || Mask.empty()) &&
6355            "Shuffle construction must be finalized.");
6356   }
6357 };
6358 } // namespace
6359 
6360 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6361   unsigned VF = VL.size();
6362   InstructionsState S = getSameOpcode(VL);
6363   if (S.getOpcode()) {
6364     if (TreeEntry *E = getTreeEntry(S.OpValue))
6365       if (E->isSame(VL)) {
6366         Value *V = vectorizeTree(E);
6367         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6368           if (!E->ReuseShuffleIndices.empty()) {
6369             // Reshuffle to get only unique values.
6370             // If some of the scalars are duplicated in the vectorization tree
6371             // entry, we do not vectorize them but instead generate a mask for
6372             // the reuses. But if there are several users of the same entry,
6373             // they may have different vectorization factors. This is especially
6374             // important for PHI nodes. In this case, we need to adapt the
6375             // resulting instruction for the user vectorization factor and have
6376             // to reshuffle it again to take only unique elements of the vector.
6377             // Without this code the function incorrectly returns reduced vector
6378             // instruction with the same elements, not with the unique ones.
6379 
6380             // block:
6381             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6382             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6383             // ... (use %2)
6384             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6385             // br %block
6386             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6387             SmallSet<int, 4> UsedIdxs;
6388             int Pos = 0;
6389             int Sz = VL.size();
6390             for (int Idx : E->ReuseShuffleIndices) {
6391               if (Idx != Sz && Idx != UndefMaskElem &&
6392                   UsedIdxs.insert(Idx).second)
6393                 UniqueIdxs[Idx] = Pos;
6394               ++Pos;
6395             }
6396             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6397                                             "less than original vector size.");
6398             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6399             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6400           } else {
6401             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6402                    "Expected vectorization factor less "
6403                    "than original vector size.");
6404             SmallVector<int> UniformMask(VF, 0);
6405             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6406             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6407           }
6408           if (auto *I = dyn_cast<Instruction>(V)) {
6409             GatherShuffleSeq.insert(I);
6410             CSEBlocks.insert(I->getParent());
6411           }
6412         }
6413         return V;
6414       }
6415   }
6416 
6417   // Check that every instruction appears once in this bundle.
6418   SmallVector<int> ReuseShuffleIndicies;
6419   SmallVector<Value *> UniqueValues;
6420   if (VL.size() > 2) {
6421     DenseMap<Value *, unsigned> UniquePositions;
6422     unsigned NumValues =
6423         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6424                                     return !isa<UndefValue>(V);
6425                                   }).base());
6426     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6427     int UniqueVals = 0;
6428     for (Value *V : VL.drop_back(VL.size() - VF)) {
6429       if (isa<UndefValue>(V)) {
6430         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6431         continue;
6432       }
6433       if (isConstant(V)) {
6434         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6435         UniqueValues.emplace_back(V);
6436         continue;
6437       }
6438       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6439       ReuseShuffleIndicies.emplace_back(Res.first->second);
6440       if (Res.second) {
6441         UniqueValues.emplace_back(V);
6442         ++UniqueVals;
6443       }
6444     }
6445     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6446       // Emit pure splat vector.
6447       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6448                                   UndefMaskElem);
6449     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6450       ReuseShuffleIndicies.clear();
6451       UniqueValues.clear();
6452       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6453     }
6454     UniqueValues.append(VF - UniqueValues.size(),
6455                         PoisonValue::get(VL[0]->getType()));
6456     VL = UniqueValues;
6457   }
6458 
6459   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6460                                            CSEBlocks);
6461   Value *Vec = gather(VL);
6462   if (!ReuseShuffleIndicies.empty()) {
6463     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6464     Vec = ShuffleBuilder.finalize(Vec);
6465   }
6466   return Vec;
6467 }
6468 
6469 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6470   IRBuilder<>::InsertPointGuard Guard(Builder);
6471 
6472   if (E->VectorizedValue) {
6473     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6474     return E->VectorizedValue;
6475   }
6476 
6477   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6478   unsigned VF = E->getVectorFactor();
6479   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6480                                            CSEBlocks);
6481   if (E->State == TreeEntry::NeedToGather) {
6482     if (E->getMainOp())
6483       setInsertPointAfterBundle(E);
6484     Value *Vec;
6485     SmallVector<int> Mask;
6486     SmallVector<const TreeEntry *> Entries;
6487     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6488         isGatherShuffledEntry(E, Mask, Entries);
6489     if (Shuffle.hasValue()) {
6490       assert((Entries.size() == 1 || Entries.size() == 2) &&
6491              "Expected shuffle of 1 or 2 entries.");
6492       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6493                                         Entries.back()->VectorizedValue, Mask);
6494       if (auto *I = dyn_cast<Instruction>(Vec)) {
6495         GatherShuffleSeq.insert(I);
6496         CSEBlocks.insert(I->getParent());
6497       }
6498     } else {
6499       Vec = gather(E->Scalars);
6500     }
6501     if (NeedToShuffleReuses) {
6502       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6503       Vec = ShuffleBuilder.finalize(Vec);
6504     }
6505     E->VectorizedValue = Vec;
6506     return Vec;
6507   }
6508 
6509   assert((E->State == TreeEntry::Vectorize ||
6510           E->State == TreeEntry::ScatterVectorize) &&
6511          "Unhandled state");
6512   unsigned ShuffleOrOp =
6513       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6514   Instruction *VL0 = E->getMainOp();
6515   Type *ScalarTy = VL0->getType();
6516   if (auto *Store = dyn_cast<StoreInst>(VL0))
6517     ScalarTy = Store->getValueOperand()->getType();
6518   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6519     ScalarTy = IE->getOperand(1)->getType();
6520   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6521   switch (ShuffleOrOp) {
6522     case Instruction::PHI: {
6523       assert(
6524           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6525           "PHI reordering is free.");
6526       auto *PH = cast<PHINode>(VL0);
6527       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6528       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6529       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6530       Value *V = NewPhi;
6531       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6532       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6533       V = ShuffleBuilder.finalize(V);
6534 
6535       E->VectorizedValue = V;
6536 
6537       // PHINodes may have multiple entries from the same block. We want to
6538       // visit every block once.
6539       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6540 
6541       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6542         ValueList Operands;
6543         BasicBlock *IBB = PH->getIncomingBlock(i);
6544 
6545         if (!VisitedBBs.insert(IBB).second) {
6546           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6547           continue;
6548         }
6549 
6550         Builder.SetInsertPoint(IBB->getTerminator());
6551         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6552         Value *Vec = vectorizeTree(E->getOperand(i));
6553         NewPhi->addIncoming(Vec, IBB);
6554       }
6555 
6556       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6557              "Invalid number of incoming values");
6558       return V;
6559     }
6560 
6561     case Instruction::ExtractElement: {
6562       Value *V = E->getSingleOperand(0);
6563       Builder.SetInsertPoint(VL0);
6564       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6565       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6566       V = ShuffleBuilder.finalize(V);
6567       E->VectorizedValue = V;
6568       return V;
6569     }
6570     case Instruction::ExtractValue: {
6571       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6572       Builder.SetInsertPoint(LI);
6573       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6574       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6575       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6576       Value *NewV = propagateMetadata(V, E->Scalars);
6577       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6578       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6579       NewV = ShuffleBuilder.finalize(NewV);
6580       E->VectorizedValue = NewV;
6581       return NewV;
6582     }
6583     case Instruction::InsertElement: {
6584       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6585       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6586       Value *V = vectorizeTree(E->getOperand(1));
6587 
6588       // Create InsertVector shuffle if necessary
6589       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6590         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6591       }));
6592       const unsigned NumElts =
6593           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6594       const unsigned NumScalars = E->Scalars.size();
6595 
6596       unsigned Offset = *getInsertIndex(VL0, 0);
6597       assert(Offset < NumElts && "Failed to find vector index offset");
6598 
6599       // Create shuffle to resize vector
6600       SmallVector<int> Mask;
6601       if (!E->ReorderIndices.empty()) {
6602         inversePermutation(E->ReorderIndices, Mask);
6603         Mask.append(NumElts - NumScalars, UndefMaskElem);
6604       } else {
6605         Mask.assign(NumElts, UndefMaskElem);
6606         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6607       }
6608       // Create InsertVector shuffle if necessary
6609       bool IsIdentity = true;
6610       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6611       Mask.swap(PrevMask);
6612       for (unsigned I = 0; I < NumScalars; ++I) {
6613         Value *Scalar = E->Scalars[PrevMask[I]];
6614         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6615         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6616           continue;
6617         IsIdentity &= *InsertIdx - Offset == I;
6618         Mask[*InsertIdx - Offset] = I;
6619       }
6620       if (!IsIdentity || NumElts != NumScalars) {
6621         V = Builder.CreateShuffleVector(V, Mask);
6622         if (auto *I = dyn_cast<Instruction>(V)) {
6623           GatherShuffleSeq.insert(I);
6624           CSEBlocks.insert(I->getParent());
6625         }
6626       }
6627 
6628       if ((!IsIdentity || Offset != 0 ||
6629            !isUndefVector(FirstInsert->getOperand(0))) &&
6630           NumElts != NumScalars) {
6631         SmallVector<int> InsertMask(NumElts);
6632         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6633         for (unsigned I = 0; I < NumElts; I++) {
6634           if (Mask[I] != UndefMaskElem)
6635             InsertMask[Offset + I] = NumElts + I;
6636         }
6637 
6638         V = Builder.CreateShuffleVector(
6639             FirstInsert->getOperand(0), V, InsertMask,
6640             cast<Instruction>(E->Scalars.back())->getName());
6641         if (auto *I = dyn_cast<Instruction>(V)) {
6642           GatherShuffleSeq.insert(I);
6643           CSEBlocks.insert(I->getParent());
6644         }
6645       }
6646 
6647       ++NumVectorInstructions;
6648       E->VectorizedValue = V;
6649       return V;
6650     }
6651     case Instruction::ZExt:
6652     case Instruction::SExt:
6653     case Instruction::FPToUI:
6654     case Instruction::FPToSI:
6655     case Instruction::FPExt:
6656     case Instruction::PtrToInt:
6657     case Instruction::IntToPtr:
6658     case Instruction::SIToFP:
6659     case Instruction::UIToFP:
6660     case Instruction::Trunc:
6661     case Instruction::FPTrunc:
6662     case Instruction::BitCast: {
6663       setInsertPointAfterBundle(E);
6664 
6665       Value *InVec = vectorizeTree(E->getOperand(0));
6666 
6667       if (E->VectorizedValue) {
6668         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6669         return E->VectorizedValue;
6670       }
6671 
6672       auto *CI = cast<CastInst>(VL0);
6673       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6674       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6675       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6676       V = ShuffleBuilder.finalize(V);
6677 
6678       E->VectorizedValue = V;
6679       ++NumVectorInstructions;
6680       return V;
6681     }
6682     case Instruction::FCmp:
6683     case Instruction::ICmp: {
6684       setInsertPointAfterBundle(E);
6685 
6686       Value *L = vectorizeTree(E->getOperand(0));
6687       Value *R = vectorizeTree(E->getOperand(1));
6688 
6689       if (E->VectorizedValue) {
6690         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6691         return E->VectorizedValue;
6692       }
6693 
6694       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6695       Value *V = Builder.CreateCmp(P0, L, R);
6696       propagateIRFlags(V, E->Scalars, VL0);
6697       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6698       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6699       V = ShuffleBuilder.finalize(V);
6700 
6701       E->VectorizedValue = V;
6702       ++NumVectorInstructions;
6703       return V;
6704     }
6705     case Instruction::Select: {
6706       setInsertPointAfterBundle(E);
6707 
6708       Value *Cond = vectorizeTree(E->getOperand(0));
6709       Value *True = vectorizeTree(E->getOperand(1));
6710       Value *False = vectorizeTree(E->getOperand(2));
6711 
6712       if (E->VectorizedValue) {
6713         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6714         return E->VectorizedValue;
6715       }
6716 
6717       Value *V = Builder.CreateSelect(Cond, True, False);
6718       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6719       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6720       V = ShuffleBuilder.finalize(V);
6721 
6722       E->VectorizedValue = V;
6723       ++NumVectorInstructions;
6724       return V;
6725     }
6726     case Instruction::FNeg: {
6727       setInsertPointAfterBundle(E);
6728 
6729       Value *Op = vectorizeTree(E->getOperand(0));
6730 
6731       if (E->VectorizedValue) {
6732         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6733         return E->VectorizedValue;
6734       }
6735 
6736       Value *V = Builder.CreateUnOp(
6737           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6738       propagateIRFlags(V, E->Scalars, VL0);
6739       if (auto *I = dyn_cast<Instruction>(V))
6740         V = propagateMetadata(I, E->Scalars);
6741 
6742       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6743       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6744       V = ShuffleBuilder.finalize(V);
6745 
6746       E->VectorizedValue = V;
6747       ++NumVectorInstructions;
6748 
6749       return V;
6750     }
6751     case Instruction::Add:
6752     case Instruction::FAdd:
6753     case Instruction::Sub:
6754     case Instruction::FSub:
6755     case Instruction::Mul:
6756     case Instruction::FMul:
6757     case Instruction::UDiv:
6758     case Instruction::SDiv:
6759     case Instruction::FDiv:
6760     case Instruction::URem:
6761     case Instruction::SRem:
6762     case Instruction::FRem:
6763     case Instruction::Shl:
6764     case Instruction::LShr:
6765     case Instruction::AShr:
6766     case Instruction::And:
6767     case Instruction::Or:
6768     case Instruction::Xor: {
6769       setInsertPointAfterBundle(E);
6770 
6771       Value *LHS = vectorizeTree(E->getOperand(0));
6772       Value *RHS = vectorizeTree(E->getOperand(1));
6773 
6774       if (E->VectorizedValue) {
6775         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6776         return E->VectorizedValue;
6777       }
6778 
6779       Value *V = Builder.CreateBinOp(
6780           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6781           RHS);
6782       propagateIRFlags(V, E->Scalars, VL0);
6783       if (auto *I = dyn_cast<Instruction>(V))
6784         V = propagateMetadata(I, E->Scalars);
6785 
6786       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6787       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6788       V = ShuffleBuilder.finalize(V);
6789 
6790       E->VectorizedValue = V;
6791       ++NumVectorInstructions;
6792 
6793       return V;
6794     }
6795     case Instruction::Load: {
6796       // Loads are inserted at the head of the tree because we don't want to
6797       // sink them all the way down past store instructions.
6798       setInsertPointAfterBundle(E);
6799 
6800       LoadInst *LI = cast<LoadInst>(VL0);
6801       Instruction *NewLI;
6802       unsigned AS = LI->getPointerAddressSpace();
6803       Value *PO = LI->getPointerOperand();
6804       if (E->State == TreeEntry::Vectorize) {
6805 
6806         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6807 
6808         // The pointer operand uses an in-tree scalar so we add the new BitCast
6809         // to ExternalUses list to make sure that an extract will be generated
6810         // in the future.
6811         if (TreeEntry *Entry = getTreeEntry(PO)) {
6812           // Find which lane we need to extract.
6813           unsigned FoundLane = Entry->findLaneForValue(PO);
6814           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6815         }
6816 
6817         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6818       } else {
6819         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6820         Value *VecPtr = vectorizeTree(E->getOperand(0));
6821         // Use the minimum alignment of the gathered loads.
6822         Align CommonAlignment = LI->getAlign();
6823         for (Value *V : E->Scalars)
6824           CommonAlignment =
6825               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6826         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6827       }
6828       Value *V = propagateMetadata(NewLI, E->Scalars);
6829 
6830       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6831       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6832       V = ShuffleBuilder.finalize(V);
6833       E->VectorizedValue = V;
6834       ++NumVectorInstructions;
6835       return V;
6836     }
6837     case Instruction::Store: {
6838       auto *SI = cast<StoreInst>(VL0);
6839       unsigned AS = SI->getPointerAddressSpace();
6840 
6841       setInsertPointAfterBundle(E);
6842 
6843       Value *VecValue = vectorizeTree(E->getOperand(0));
6844       ShuffleBuilder.addMask(E->ReorderIndices);
6845       VecValue = ShuffleBuilder.finalize(VecValue);
6846 
6847       Value *ScalarPtr = SI->getPointerOperand();
6848       Value *VecPtr = Builder.CreateBitCast(
6849           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6850       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6851                                                  SI->getAlign());
6852 
6853       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6854       // ExternalUses to make sure that an extract will be generated in the
6855       // future.
6856       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6857         // Find which lane we need to extract.
6858         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6859         ExternalUses.push_back(
6860             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6861       }
6862 
6863       Value *V = propagateMetadata(ST, E->Scalars);
6864 
6865       E->VectorizedValue = V;
6866       ++NumVectorInstructions;
6867       return V;
6868     }
6869     case Instruction::GetElementPtr: {
6870       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6871       setInsertPointAfterBundle(E);
6872 
6873       Value *Op0 = vectorizeTree(E->getOperand(0));
6874 
6875       SmallVector<Value *> OpVecs;
6876       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6877         Value *OpVec = vectorizeTree(E->getOperand(J));
6878         OpVecs.push_back(OpVec);
6879       }
6880 
6881       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6882       if (Instruction *I = dyn_cast<Instruction>(V))
6883         V = propagateMetadata(I, E->Scalars);
6884 
6885       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6886       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6887       V = ShuffleBuilder.finalize(V);
6888 
6889       E->VectorizedValue = V;
6890       ++NumVectorInstructions;
6891 
6892       return V;
6893     }
6894     case Instruction::Call: {
6895       CallInst *CI = cast<CallInst>(VL0);
6896       setInsertPointAfterBundle(E);
6897 
6898       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6899       if (Function *FI = CI->getCalledFunction())
6900         IID = FI->getIntrinsicID();
6901 
6902       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6903 
6904       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6905       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6906                           VecCallCosts.first <= VecCallCosts.second;
6907 
6908       Value *ScalarArg = nullptr;
6909       std::vector<Value *> OpVecs;
6910       SmallVector<Type *, 2> TysForDecl =
6911           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6912       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6913         ValueList OpVL;
6914         // Some intrinsics have scalar arguments. This argument should not be
6915         // vectorized.
6916         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6917           CallInst *CEI = cast<CallInst>(VL0);
6918           ScalarArg = CEI->getArgOperand(j);
6919           OpVecs.push_back(CEI->getArgOperand(j));
6920           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6921             TysForDecl.push_back(ScalarArg->getType());
6922           continue;
6923         }
6924 
6925         Value *OpVec = vectorizeTree(E->getOperand(j));
6926         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6927         OpVecs.push_back(OpVec);
6928       }
6929 
6930       Function *CF;
6931       if (!UseIntrinsic) {
6932         VFShape Shape =
6933             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6934                                   VecTy->getNumElements())),
6935                          false /*HasGlobalPred*/);
6936         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6937       } else {
6938         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6939       }
6940 
6941       SmallVector<OperandBundleDef, 1> OpBundles;
6942       CI->getOperandBundlesAsDefs(OpBundles);
6943       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6944 
6945       // The scalar argument uses an in-tree scalar so we add the new vectorized
6946       // call to ExternalUses list to make sure that an extract will be
6947       // generated in the future.
6948       if (ScalarArg) {
6949         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6950           // Find which lane we need to extract.
6951           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6952           ExternalUses.push_back(
6953               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6954         }
6955       }
6956 
6957       propagateIRFlags(V, E->Scalars, VL0);
6958       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6959       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6960       V = ShuffleBuilder.finalize(V);
6961 
6962       E->VectorizedValue = V;
6963       ++NumVectorInstructions;
6964       return V;
6965     }
6966     case Instruction::ShuffleVector: {
6967       assert(E->isAltShuffle() &&
6968              ((Instruction::isBinaryOp(E->getOpcode()) &&
6969                Instruction::isBinaryOp(E->getAltOpcode())) ||
6970               (Instruction::isCast(E->getOpcode()) &&
6971                Instruction::isCast(E->getAltOpcode())) ||
6972               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6973              "Invalid Shuffle Vector Operand");
6974 
6975       Value *LHS = nullptr, *RHS = nullptr;
6976       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
6977         setInsertPointAfterBundle(E);
6978         LHS = vectorizeTree(E->getOperand(0));
6979         RHS = vectorizeTree(E->getOperand(1));
6980       } else {
6981         setInsertPointAfterBundle(E);
6982         LHS = vectorizeTree(E->getOperand(0));
6983       }
6984 
6985       if (E->VectorizedValue) {
6986         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6987         return E->VectorizedValue;
6988       }
6989 
6990       Value *V0, *V1;
6991       if (Instruction::isBinaryOp(E->getOpcode())) {
6992         V0 = Builder.CreateBinOp(
6993             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6994         V1 = Builder.CreateBinOp(
6995             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6996       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6997         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
6998         auto *AltCI = cast<CmpInst>(E->getAltOp());
6999         CmpInst::Predicate AltPred = AltCI->getPredicate();
7000         unsigned AltIdx =
7001             std::distance(E->Scalars.begin(), find(E->Scalars, AltCI));
7002         if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx])
7003           AltPred = CmpInst::getSwappedPredicate(AltPred);
7004         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7005       } else {
7006         V0 = Builder.CreateCast(
7007             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7008         V1 = Builder.CreateCast(
7009             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7010       }
7011       // Add V0 and V1 to later analysis to try to find and remove matching
7012       // instruction, if any.
7013       for (Value *V : {V0, V1}) {
7014         if (auto *I = dyn_cast<Instruction>(V)) {
7015           GatherShuffleSeq.insert(I);
7016           CSEBlocks.insert(I->getParent());
7017         }
7018       }
7019 
7020       // Create shuffle to take alternate operations from the vector.
7021       // Also, gather up main and alt scalar ops to propagate IR flags to
7022       // each vector operation.
7023       ValueList OpScalars, AltScalars;
7024       SmallVector<int> Mask;
7025       buildSuffleEntryMask(
7026           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7027           [E](Instruction *I) {
7028             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7029             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
7030               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
7031               auto *CI = cast<CmpInst>(I);
7032               CmpInst::Predicate P0 = CI0->getPredicate();
7033               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
7034               CmpInst::Predicate AltP0Swapped =
7035                   CmpInst::getSwappedPredicate(AltP0);
7036               CmpInst::Predicate CurrentPred = CI->getPredicate();
7037               CmpInst::Predicate CurrentPredSwapped =
7038                   CmpInst::getSwappedPredicate(CurrentPred);
7039               if (P0 == AltP0 || P0 == AltP0Swapped) {
7040                 // Alternate cmps have same/swapped predicate as main cmps but
7041                 // different order of compatible operands.
7042                 return !(
7043                     (P0 == CurrentPred &&
7044                      areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
7045                                          I->getOperand(0), I->getOperand(1))) ||
7046                     (P0 == CurrentPredSwapped &&
7047                      areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
7048                                          I->getOperand(1), I->getOperand(0))));
7049               }
7050               return CurrentPred != P0 && CurrentPredSwapped != P0;
7051             }
7052             return I->getOpcode() == E->getAltOpcode();
7053           },
7054           Mask, &OpScalars, &AltScalars);
7055 
7056       propagateIRFlags(V0, OpScalars);
7057       propagateIRFlags(V1, AltScalars);
7058 
7059       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7060       if (auto *I = dyn_cast<Instruction>(V)) {
7061         V = propagateMetadata(I, E->Scalars);
7062         GatherShuffleSeq.insert(I);
7063         CSEBlocks.insert(I->getParent());
7064       }
7065       V = ShuffleBuilder.finalize(V);
7066 
7067       E->VectorizedValue = V;
7068       ++NumVectorInstructions;
7069 
7070       return V;
7071     }
7072     default:
7073     llvm_unreachable("unknown inst");
7074   }
7075   return nullptr;
7076 }
7077 
7078 Value *BoUpSLP::vectorizeTree() {
7079   ExtraValueToDebugLocsMap ExternallyUsedValues;
7080   return vectorizeTree(ExternallyUsedValues);
7081 }
7082 
7083 Value *
7084 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7085   // All blocks must be scheduled before any instructions are inserted.
7086   for (auto &BSIter : BlocksSchedules) {
7087     scheduleBlock(BSIter.second.get());
7088   }
7089 
7090   Builder.SetInsertPoint(&F->getEntryBlock().front());
7091   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7092 
7093   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7094   // vectorized root. InstCombine will then rewrite the entire expression. We
7095   // sign extend the extracted values below.
7096   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7097   if (MinBWs.count(ScalarRoot)) {
7098     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7099       // If current instr is a phi and not the last phi, insert it after the
7100       // last phi node.
7101       if (isa<PHINode>(I))
7102         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7103       else
7104         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7105     }
7106     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7107     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7108     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7109     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7110     VectorizableTree[0]->VectorizedValue = Trunc;
7111   }
7112 
7113   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7114                     << " values .\n");
7115 
7116   // Extract all of the elements with the external uses.
7117   for (const auto &ExternalUse : ExternalUses) {
7118     Value *Scalar = ExternalUse.Scalar;
7119     llvm::User *User = ExternalUse.User;
7120 
7121     // Skip users that we already RAUW. This happens when one instruction
7122     // has multiple uses of the same value.
7123     if (User && !is_contained(Scalar->users(), User))
7124       continue;
7125     TreeEntry *E = getTreeEntry(Scalar);
7126     assert(E && "Invalid scalar");
7127     assert(E->State != TreeEntry::NeedToGather &&
7128            "Extracting from a gather list");
7129 
7130     Value *Vec = E->VectorizedValue;
7131     assert(Vec && "Can't find vectorizable value");
7132 
7133     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7134     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7135       if (Scalar->getType() != Vec->getType()) {
7136         Value *Ex;
7137         // "Reuse" the existing extract to improve final codegen.
7138         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7139           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7140                                             ES->getOperand(1));
7141         } else {
7142           Ex = Builder.CreateExtractElement(Vec, Lane);
7143         }
7144         // If necessary, sign-extend or zero-extend ScalarRoot
7145         // to the larger type.
7146         if (!MinBWs.count(ScalarRoot))
7147           return Ex;
7148         if (MinBWs[ScalarRoot].second)
7149           return Builder.CreateSExt(Ex, Scalar->getType());
7150         return Builder.CreateZExt(Ex, Scalar->getType());
7151       }
7152       assert(isa<FixedVectorType>(Scalar->getType()) &&
7153              isa<InsertElementInst>(Scalar) &&
7154              "In-tree scalar of vector type is not insertelement?");
7155       return Vec;
7156     };
7157     // If User == nullptr, the Scalar is used as extra arg. Generate
7158     // ExtractElement instruction and update the record for this scalar in
7159     // ExternallyUsedValues.
7160     if (!User) {
7161       assert(ExternallyUsedValues.count(Scalar) &&
7162              "Scalar with nullptr as an external user must be registered in "
7163              "ExternallyUsedValues map");
7164       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7165         Builder.SetInsertPoint(VecI->getParent(),
7166                                std::next(VecI->getIterator()));
7167       } else {
7168         Builder.SetInsertPoint(&F->getEntryBlock().front());
7169       }
7170       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7171       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7172       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7173       auto It = ExternallyUsedValues.find(Scalar);
7174       assert(It != ExternallyUsedValues.end() &&
7175              "Externally used scalar is not found in ExternallyUsedValues");
7176       NewInstLocs.append(It->second);
7177       ExternallyUsedValues.erase(Scalar);
7178       // Required to update internally referenced instructions.
7179       Scalar->replaceAllUsesWith(NewInst);
7180       continue;
7181     }
7182 
7183     // Generate extracts for out-of-tree users.
7184     // Find the insertion point for the extractelement lane.
7185     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7186       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7187         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7188           if (PH->getIncomingValue(i) == Scalar) {
7189             Instruction *IncomingTerminator =
7190                 PH->getIncomingBlock(i)->getTerminator();
7191             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7192               Builder.SetInsertPoint(VecI->getParent(),
7193                                      std::next(VecI->getIterator()));
7194             } else {
7195               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7196             }
7197             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7198             CSEBlocks.insert(PH->getIncomingBlock(i));
7199             PH->setOperand(i, NewInst);
7200           }
7201         }
7202       } else {
7203         Builder.SetInsertPoint(cast<Instruction>(User));
7204         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7205         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7206         User->replaceUsesOfWith(Scalar, NewInst);
7207       }
7208     } else {
7209       Builder.SetInsertPoint(&F->getEntryBlock().front());
7210       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7211       CSEBlocks.insert(&F->getEntryBlock());
7212       User->replaceUsesOfWith(Scalar, NewInst);
7213     }
7214 
7215     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7216   }
7217 
7218   // For each vectorized value:
7219   for (auto &TEPtr : VectorizableTree) {
7220     TreeEntry *Entry = TEPtr.get();
7221 
7222     // No need to handle users of gathered values.
7223     if (Entry->State == TreeEntry::NeedToGather)
7224       continue;
7225 
7226     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7227 
7228     // For each lane:
7229     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7230       Value *Scalar = Entry->Scalars[Lane];
7231 
7232 #ifndef NDEBUG
7233       Type *Ty = Scalar->getType();
7234       if (!Ty->isVoidTy()) {
7235         for (User *U : Scalar->users()) {
7236           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7237 
7238           // It is legal to delete users in the ignorelist.
7239           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7240                   (isa_and_nonnull<Instruction>(U) &&
7241                    isDeleted(cast<Instruction>(U)))) &&
7242                  "Deleting out-of-tree value");
7243         }
7244       }
7245 #endif
7246       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7247       eraseInstruction(cast<Instruction>(Scalar));
7248     }
7249   }
7250 
7251   Builder.ClearInsertionPoint();
7252   InstrElementSize.clear();
7253 
7254   return VectorizableTree[0]->VectorizedValue;
7255 }
7256 
7257 void BoUpSLP::optimizeGatherSequence() {
7258   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7259                     << " gather sequences instructions.\n");
7260   // LICM InsertElementInst sequences.
7261   for (Instruction *I : GatherShuffleSeq) {
7262     if (isDeleted(I))
7263       continue;
7264 
7265     // Check if this block is inside a loop.
7266     Loop *L = LI->getLoopFor(I->getParent());
7267     if (!L)
7268       continue;
7269 
7270     // Check if it has a preheader.
7271     BasicBlock *PreHeader = L->getLoopPreheader();
7272     if (!PreHeader)
7273       continue;
7274 
7275     // If the vector or the element that we insert into it are
7276     // instructions that are defined in this basic block then we can't
7277     // hoist this instruction.
7278     if (any_of(I->operands(), [L](Value *V) {
7279           auto *OpI = dyn_cast<Instruction>(V);
7280           return OpI && L->contains(OpI);
7281         }))
7282       continue;
7283 
7284     // We can hoist this instruction. Move it to the pre-header.
7285     I->moveBefore(PreHeader->getTerminator());
7286   }
7287 
7288   // Make a list of all reachable blocks in our CSE queue.
7289   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7290   CSEWorkList.reserve(CSEBlocks.size());
7291   for (BasicBlock *BB : CSEBlocks)
7292     if (DomTreeNode *N = DT->getNode(BB)) {
7293       assert(DT->isReachableFromEntry(N));
7294       CSEWorkList.push_back(N);
7295     }
7296 
7297   // Sort blocks by domination. This ensures we visit a block after all blocks
7298   // dominating it are visited.
7299   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7300     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7301            "Different nodes should have different DFS numbers");
7302     return A->getDFSNumIn() < B->getDFSNumIn();
7303   });
7304 
7305   // Less defined shuffles can be replaced by the more defined copies.
7306   // Between two shuffles one is less defined if it has the same vector operands
7307   // and its mask indeces are the same as in the first one or undefs. E.g.
7308   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7309   // poison, <0, 0, 0, 0>.
7310   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7311                                            SmallVectorImpl<int> &NewMask) {
7312     if (I1->getType() != I2->getType())
7313       return false;
7314     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7315     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7316     if (!SI1 || !SI2)
7317       return I1->isIdenticalTo(I2);
7318     if (SI1->isIdenticalTo(SI2))
7319       return true;
7320     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7321       if (SI1->getOperand(I) != SI2->getOperand(I))
7322         return false;
7323     // Check if the second instruction is more defined than the first one.
7324     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7325     ArrayRef<int> SM1 = SI1->getShuffleMask();
7326     // Count trailing undefs in the mask to check the final number of used
7327     // registers.
7328     unsigned LastUndefsCnt = 0;
7329     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7330       if (SM1[I] == UndefMaskElem)
7331         ++LastUndefsCnt;
7332       else
7333         LastUndefsCnt = 0;
7334       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7335           NewMask[I] != SM1[I])
7336         return false;
7337       if (NewMask[I] == UndefMaskElem)
7338         NewMask[I] = SM1[I];
7339     }
7340     // Check if the last undefs actually change the final number of used vector
7341     // registers.
7342     return SM1.size() - LastUndefsCnt > 1 &&
7343            TTI->getNumberOfParts(SI1->getType()) ==
7344                TTI->getNumberOfParts(
7345                    FixedVectorType::get(SI1->getType()->getElementType(),
7346                                         SM1.size() - LastUndefsCnt));
7347   };
7348   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7349   // instructions. TODO: We can further optimize this scan if we split the
7350   // instructions into different buckets based on the insert lane.
7351   SmallVector<Instruction *, 16> Visited;
7352   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7353     assert(*I &&
7354            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7355            "Worklist not sorted properly!");
7356     BasicBlock *BB = (*I)->getBlock();
7357     // For all instructions in blocks containing gather sequences:
7358     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7359       if (isDeleted(&In))
7360         continue;
7361       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7362           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7363         continue;
7364 
7365       // Check if we can replace this instruction with any of the
7366       // visited instructions.
7367       bool Replaced = false;
7368       for (Instruction *&V : Visited) {
7369         SmallVector<int> NewMask;
7370         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7371             DT->dominates(V->getParent(), In.getParent())) {
7372           In.replaceAllUsesWith(V);
7373           eraseInstruction(&In);
7374           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7375             if (!NewMask.empty())
7376               SI->setShuffleMask(NewMask);
7377           Replaced = true;
7378           break;
7379         }
7380         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7381             GatherShuffleSeq.contains(V) &&
7382             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7383             DT->dominates(In.getParent(), V->getParent())) {
7384           In.moveAfter(V);
7385           V->replaceAllUsesWith(&In);
7386           eraseInstruction(V);
7387           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7388             if (!NewMask.empty())
7389               SI->setShuffleMask(NewMask);
7390           V = &In;
7391           Replaced = true;
7392           break;
7393         }
7394       }
7395       if (!Replaced) {
7396         assert(!is_contained(Visited, &In));
7397         Visited.push_back(&In);
7398       }
7399     }
7400   }
7401   CSEBlocks.clear();
7402   GatherShuffleSeq.clear();
7403 }
7404 
7405 BoUpSLP::ScheduleData *
7406 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7407   ScheduleData *Bundle = nullptr;
7408   ScheduleData *PrevInBundle = nullptr;
7409   for (Value *V : VL) {
7410     ScheduleData *BundleMember = getScheduleData(V);
7411     assert(BundleMember &&
7412            "no ScheduleData for bundle member "
7413            "(maybe not in same basic block)");
7414     assert(BundleMember->isSchedulingEntity() &&
7415            "bundle member already part of other bundle");
7416     if (PrevInBundle) {
7417       PrevInBundle->NextInBundle = BundleMember;
7418     } else {
7419       Bundle = BundleMember;
7420     }
7421     BundleMember->UnscheduledDepsInBundle = 0;
7422     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7423 
7424     // Group the instructions to a bundle.
7425     BundleMember->FirstInBundle = Bundle;
7426     PrevInBundle = BundleMember;
7427   }
7428   assert(Bundle && "Failed to find schedule bundle");
7429   return Bundle;
7430 }
7431 
7432 // Groups the instructions to a bundle (which is then a single scheduling entity)
7433 // and schedules instructions until the bundle gets ready.
7434 Optional<BoUpSLP::ScheduleData *>
7435 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7436                                             const InstructionsState &S) {
7437   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7438   // instructions.
7439   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7440     return nullptr;
7441 
7442   // Initialize the instruction bundle.
7443   Instruction *OldScheduleEnd = ScheduleEnd;
7444   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7445 
7446   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7447                                                          ScheduleData *Bundle) {
7448     // The scheduling region got new instructions at the lower end (or it is a
7449     // new region for the first bundle). This makes it necessary to
7450     // recalculate all dependencies.
7451     // It is seldom that this needs to be done a second time after adding the
7452     // initial bundle to the region.
7453     if (ScheduleEnd != OldScheduleEnd) {
7454       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7455         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7456       ReSchedule = true;
7457     }
7458     if (ReSchedule) {
7459       resetSchedule();
7460       initialFillReadyList(ReadyInsts);
7461     }
7462     if (Bundle) {
7463       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7464                         << " in block " << BB->getName() << "\n");
7465       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7466     }
7467 
7468     // Now try to schedule the new bundle or (if no bundle) just calculate
7469     // dependencies. As soon as the bundle is "ready" it means that there are no
7470     // cyclic dependencies and we can schedule it. Note that's important that we
7471     // don't "schedule" the bundle yet (see cancelScheduling).
7472     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7473            !ReadyInsts.empty()) {
7474       ScheduleData *Picked = ReadyInsts.pop_back_val();
7475       if (Picked->isSchedulingEntity() && Picked->isReady())
7476         schedule(Picked, ReadyInsts);
7477     }
7478   };
7479 
7480   // Make sure that the scheduling region contains all
7481   // instructions of the bundle.
7482   for (Value *V : VL) {
7483     if (!extendSchedulingRegion(V, S)) {
7484       // If the scheduling region got new instructions at the lower end (or it
7485       // is a new region for the first bundle). This makes it necessary to
7486       // recalculate all dependencies.
7487       // Otherwise the compiler may crash trying to incorrectly calculate
7488       // dependencies and emit instruction in the wrong order at the actual
7489       // scheduling.
7490       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7491       return None;
7492     }
7493   }
7494 
7495   bool ReSchedule = false;
7496   for (Value *V : VL) {
7497     ScheduleData *BundleMember = getScheduleData(V);
7498     assert(BundleMember &&
7499            "no ScheduleData for bundle member (maybe not in same basic block)");
7500     if (!BundleMember->IsScheduled)
7501       continue;
7502     // A bundle member was scheduled as single instruction before and now
7503     // needs to be scheduled as part of the bundle. We just get rid of the
7504     // existing schedule.
7505     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7506                       << " was already scheduled\n");
7507     ReSchedule = true;
7508   }
7509 
7510   auto *Bundle = buildBundle(VL);
7511   TryScheduleBundleImpl(ReSchedule, Bundle);
7512   if (!Bundle->isReady()) {
7513     cancelScheduling(VL, S.OpValue);
7514     return None;
7515   }
7516   return Bundle;
7517 }
7518 
7519 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7520                                                 Value *OpValue) {
7521   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7522     return;
7523 
7524   ScheduleData *Bundle = getScheduleData(OpValue);
7525   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7526   assert(!Bundle->IsScheduled &&
7527          "Can't cancel bundle which is already scheduled");
7528   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7529          "tried to unbundle something which is not a bundle");
7530 
7531   // Un-bundle: make single instructions out of the bundle.
7532   ScheduleData *BundleMember = Bundle;
7533   while (BundleMember) {
7534     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7535     BundleMember->FirstInBundle = BundleMember;
7536     ScheduleData *Next = BundleMember->NextInBundle;
7537     BundleMember->NextInBundle = nullptr;
7538     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7539     if (BundleMember->UnscheduledDepsInBundle == 0) {
7540       ReadyInsts.insert(BundleMember);
7541     }
7542     BundleMember = Next;
7543   }
7544 }
7545 
7546 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7547   // Allocate a new ScheduleData for the instruction.
7548   if (ChunkPos >= ChunkSize) {
7549     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7550     ChunkPos = 0;
7551   }
7552   return &(ScheduleDataChunks.back()[ChunkPos++]);
7553 }
7554 
7555 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7556                                                       const InstructionsState &S) {
7557   if (getScheduleData(V, isOneOf(S, V)))
7558     return true;
7559   Instruction *I = dyn_cast<Instruction>(V);
7560   assert(I && "bundle member must be an instruction");
7561   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7562          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7563          "be scheduled");
7564   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7565     ScheduleData *ISD = getScheduleData(I);
7566     if (!ISD)
7567       return false;
7568     assert(isInSchedulingRegion(ISD) &&
7569            "ScheduleData not in scheduling region");
7570     ScheduleData *SD = allocateScheduleDataChunks();
7571     SD->Inst = I;
7572     SD->init(SchedulingRegionID, S.OpValue);
7573     ExtraScheduleDataMap[I][S.OpValue] = SD;
7574     return true;
7575   };
7576   if (CheckSheduleForI(I))
7577     return true;
7578   if (!ScheduleStart) {
7579     // It's the first instruction in the new region.
7580     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7581     ScheduleStart = I;
7582     ScheduleEnd = I->getNextNode();
7583     if (isOneOf(S, I) != I)
7584       CheckSheduleForI(I);
7585     assert(ScheduleEnd && "tried to vectorize a terminator?");
7586     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7587     return true;
7588   }
7589   // Search up and down at the same time, because we don't know if the new
7590   // instruction is above or below the existing scheduling region.
7591   BasicBlock::reverse_iterator UpIter =
7592       ++ScheduleStart->getIterator().getReverse();
7593   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7594   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7595   BasicBlock::iterator LowerEnd = BB->end();
7596   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7597          &*DownIter != I) {
7598     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7599       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7600       return false;
7601     }
7602 
7603     ++UpIter;
7604     ++DownIter;
7605   }
7606   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7607     assert(I->getParent() == ScheduleStart->getParent() &&
7608            "Instruction is in wrong basic block.");
7609     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7610     ScheduleStart = I;
7611     if (isOneOf(S, I) != I)
7612       CheckSheduleForI(I);
7613     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7614                       << "\n");
7615     return true;
7616   }
7617   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7618          "Expected to reach top of the basic block or instruction down the "
7619          "lower end.");
7620   assert(I->getParent() == ScheduleEnd->getParent() &&
7621          "Instruction is in wrong basic block.");
7622   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7623                    nullptr);
7624   ScheduleEnd = I->getNextNode();
7625   if (isOneOf(S, I) != I)
7626     CheckSheduleForI(I);
7627   assert(ScheduleEnd && "tried to vectorize a terminator?");
7628   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7629   return true;
7630 }
7631 
7632 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7633                                                 Instruction *ToI,
7634                                                 ScheduleData *PrevLoadStore,
7635                                                 ScheduleData *NextLoadStore) {
7636   ScheduleData *CurrentLoadStore = PrevLoadStore;
7637   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7638     ScheduleData *SD = ScheduleDataMap[I];
7639     if (!SD) {
7640       SD = allocateScheduleDataChunks();
7641       ScheduleDataMap[I] = SD;
7642       SD->Inst = I;
7643     }
7644     assert(!isInSchedulingRegion(SD) &&
7645            "new ScheduleData already in scheduling region");
7646     SD->init(SchedulingRegionID, I);
7647 
7648     if (I->mayReadOrWriteMemory() &&
7649         (!isa<IntrinsicInst>(I) ||
7650          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7651           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7652               Intrinsic::pseudoprobe))) {
7653       // Update the linked list of memory accessing instructions.
7654       if (CurrentLoadStore) {
7655         CurrentLoadStore->NextLoadStore = SD;
7656       } else {
7657         FirstLoadStoreInRegion = SD;
7658       }
7659       CurrentLoadStore = SD;
7660     }
7661   }
7662   if (NextLoadStore) {
7663     if (CurrentLoadStore)
7664       CurrentLoadStore->NextLoadStore = NextLoadStore;
7665   } else {
7666     LastLoadStoreInRegion = CurrentLoadStore;
7667   }
7668 }
7669 
7670 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7671                                                      bool InsertInReadyList,
7672                                                      BoUpSLP *SLP) {
7673   assert(SD->isSchedulingEntity());
7674 
7675   SmallVector<ScheduleData *, 10> WorkList;
7676   WorkList.push_back(SD);
7677 
7678   while (!WorkList.empty()) {
7679     ScheduleData *SD = WorkList.pop_back_val();
7680     for (ScheduleData *BundleMember = SD; BundleMember;
7681          BundleMember = BundleMember->NextInBundle) {
7682       assert(isInSchedulingRegion(BundleMember));
7683       if (BundleMember->hasValidDependencies())
7684         continue;
7685 
7686       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7687                  << "\n");
7688       BundleMember->Dependencies = 0;
7689       BundleMember->resetUnscheduledDeps();
7690 
7691       // Handle def-use chain dependencies.
7692       if (BundleMember->OpValue != BundleMember->Inst) {
7693         ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7694         if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7695           BundleMember->Dependencies++;
7696           ScheduleData *DestBundle = UseSD->FirstInBundle;
7697           if (!DestBundle->IsScheduled)
7698             BundleMember->incrementUnscheduledDeps(1);
7699           if (!DestBundle->hasValidDependencies())
7700             WorkList.push_back(DestBundle);
7701         }
7702       } else {
7703         for (User *U : BundleMember->Inst->users()) {
7704           assert(isa<Instruction>(U) &&
7705                  "user of instruction must be instruction");
7706           ScheduleData *UseSD = getScheduleData(U);
7707           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7708             BundleMember->Dependencies++;
7709             ScheduleData *DestBundle = UseSD->FirstInBundle;
7710             if (!DestBundle->IsScheduled)
7711               BundleMember->incrementUnscheduledDeps(1);
7712             if (!DestBundle->hasValidDependencies())
7713               WorkList.push_back(DestBundle);
7714           }
7715         }
7716       }
7717 
7718       // Handle the memory dependencies (if any).
7719       ScheduleData *DepDest = BundleMember->NextLoadStore;
7720       if (!DepDest)
7721         continue;
7722       Instruction *SrcInst = BundleMember->Inst;
7723       assert(SrcInst->mayReadOrWriteMemory() &&
7724              "NextLoadStore list for non memory effecting bundle?");
7725       MemoryLocation SrcLoc = getLocation(SrcInst);
7726       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7727       unsigned numAliased = 0;
7728       unsigned DistToSrc = 1;
7729 
7730       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7731         assert(isInSchedulingRegion(DepDest));
7732 
7733         // We have two limits to reduce the complexity:
7734         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7735         //    SLP->isAliased (which is the expensive part in this loop).
7736         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7737         //    the whole loop (even if the loop is fast, it's quadratic).
7738         //    It's important for the loop break condition (see below) to
7739         //    check this limit even between two read-only instructions.
7740         if (DistToSrc >= MaxMemDepDistance ||
7741             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7742              (numAliased >= AliasedCheckLimit ||
7743               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7744 
7745           // We increment the counter only if the locations are aliased
7746           // (instead of counting all alias checks). This gives a better
7747           // balance between reduced runtime and accurate dependencies.
7748           numAliased++;
7749 
7750           DepDest->MemoryDependencies.push_back(BundleMember);
7751           BundleMember->Dependencies++;
7752           ScheduleData *DestBundle = DepDest->FirstInBundle;
7753           if (!DestBundle->IsScheduled) {
7754             BundleMember->incrementUnscheduledDeps(1);
7755           }
7756           if (!DestBundle->hasValidDependencies()) {
7757             WorkList.push_back(DestBundle);
7758           }
7759         }
7760 
7761         // Example, explaining the loop break condition: Let's assume our
7762         // starting instruction is i0 and MaxMemDepDistance = 3.
7763         //
7764         //                      +--------v--v--v
7765         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7766         //             +--------^--^--^
7767         //
7768         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7769         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7770         // Previously we already added dependencies from i3 to i6,i7,i8
7771         // (because of MaxMemDepDistance). As we added a dependency from
7772         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7773         // and we can abort this loop at i6.
7774         if (DistToSrc >= 2 * MaxMemDepDistance)
7775           break;
7776         DistToSrc++;
7777       }
7778     }
7779     if (InsertInReadyList && SD->isReady()) {
7780       ReadyInsts.push_back(SD);
7781       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7782                         << "\n");
7783     }
7784   }
7785 }
7786 
7787 void BoUpSLP::BlockScheduling::resetSchedule() {
7788   assert(ScheduleStart &&
7789          "tried to reset schedule on block which has not been scheduled");
7790   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7791     doForAllOpcodes(I, [&](ScheduleData *SD) {
7792       assert(isInSchedulingRegion(SD) &&
7793              "ScheduleData not in scheduling region");
7794       SD->IsScheduled = false;
7795       SD->resetUnscheduledDeps();
7796     });
7797   }
7798   ReadyInsts.clear();
7799 }
7800 
7801 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7802   if (!BS->ScheduleStart)
7803     return;
7804 
7805   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7806 
7807   BS->resetSchedule();
7808 
7809   // For the real scheduling we use a more sophisticated ready-list: it is
7810   // sorted by the original instruction location. This lets the final schedule
7811   // be as  close as possible to the original instruction order.
7812   struct ScheduleDataCompare {
7813     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7814       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7815     }
7816   };
7817   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7818 
7819   // Ensure that all dependency data is updated and fill the ready-list with
7820   // initial instructions.
7821   int Idx = 0;
7822   int NumToSchedule = 0;
7823   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7824        I = I->getNextNode()) {
7825     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7826       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7827               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7828              "scheduler and vectorizer bundle mismatch");
7829       SD->FirstInBundle->SchedulingPriority = Idx++;
7830       if (SD->isSchedulingEntity()) {
7831         BS->calculateDependencies(SD, false, this);
7832         NumToSchedule++;
7833       }
7834     });
7835   }
7836   BS->initialFillReadyList(ReadyInsts);
7837 
7838   Instruction *LastScheduledInst = BS->ScheduleEnd;
7839 
7840   // Do the "real" scheduling.
7841   while (!ReadyInsts.empty()) {
7842     ScheduleData *picked = *ReadyInsts.begin();
7843     ReadyInsts.erase(ReadyInsts.begin());
7844 
7845     // Move the scheduled instruction(s) to their dedicated places, if not
7846     // there yet.
7847     for (ScheduleData *BundleMember = picked; BundleMember;
7848          BundleMember = BundleMember->NextInBundle) {
7849       Instruction *pickedInst = BundleMember->Inst;
7850       if (pickedInst->getNextNode() != LastScheduledInst)
7851         pickedInst->moveBefore(LastScheduledInst);
7852       LastScheduledInst = pickedInst;
7853     }
7854 
7855     BS->schedule(picked, ReadyInsts);
7856     NumToSchedule--;
7857   }
7858   assert(NumToSchedule == 0 && "could not schedule all instructions");
7859 
7860   // Avoid duplicate scheduling of the block.
7861   BS->ScheduleStart = nullptr;
7862 }
7863 
7864 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7865   // If V is a store, just return the width of the stored value (or value
7866   // truncated just before storing) without traversing the expression tree.
7867   // This is the common case.
7868   if (auto *Store = dyn_cast<StoreInst>(V)) {
7869     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7870       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7871     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7872   }
7873 
7874   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7875     return getVectorElementSize(IEI->getOperand(1));
7876 
7877   auto E = InstrElementSize.find(V);
7878   if (E != InstrElementSize.end())
7879     return E->second;
7880 
7881   // If V is not a store, we can traverse the expression tree to find loads
7882   // that feed it. The type of the loaded value may indicate a more suitable
7883   // width than V's type. We want to base the vector element size on the width
7884   // of memory operations where possible.
7885   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7886   SmallPtrSet<Instruction *, 16> Visited;
7887   if (auto *I = dyn_cast<Instruction>(V)) {
7888     Worklist.emplace_back(I, I->getParent());
7889     Visited.insert(I);
7890   }
7891 
7892   // Traverse the expression tree in bottom-up order looking for loads. If we
7893   // encounter an instruction we don't yet handle, we give up.
7894   auto Width = 0u;
7895   while (!Worklist.empty()) {
7896     Instruction *I;
7897     BasicBlock *Parent;
7898     std::tie(I, Parent) = Worklist.pop_back_val();
7899 
7900     // We should only be looking at scalar instructions here. If the current
7901     // instruction has a vector type, skip.
7902     auto *Ty = I->getType();
7903     if (isa<VectorType>(Ty))
7904       continue;
7905 
7906     // If the current instruction is a load, update MaxWidth to reflect the
7907     // width of the loaded value.
7908     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7909         isa<ExtractValueInst>(I))
7910       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7911 
7912     // Otherwise, we need to visit the operands of the instruction. We only
7913     // handle the interesting cases from buildTree here. If an operand is an
7914     // instruction we haven't yet visited and from the same basic block as the
7915     // user or the use is a PHI node, we add it to the worklist.
7916     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7917              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7918              isa<UnaryOperator>(I)) {
7919       for (Use &U : I->operands())
7920         if (auto *J = dyn_cast<Instruction>(U.get()))
7921           if (Visited.insert(J).second &&
7922               (isa<PHINode>(I) || J->getParent() == Parent))
7923             Worklist.emplace_back(J, J->getParent());
7924     } else {
7925       break;
7926     }
7927   }
7928 
7929   // If we didn't encounter a memory access in the expression tree, or if we
7930   // gave up for some reason, just return the width of V. Otherwise, return the
7931   // maximum width we found.
7932   if (!Width) {
7933     if (auto *CI = dyn_cast<CmpInst>(V))
7934       V = CI->getOperand(0);
7935     Width = DL->getTypeSizeInBits(V->getType());
7936   }
7937 
7938   for (Instruction *I : Visited)
7939     InstrElementSize[I] = Width;
7940 
7941   return Width;
7942 }
7943 
7944 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7945 // smaller type with a truncation. We collect the values that will be demoted
7946 // in ToDemote and additional roots that require investigating in Roots.
7947 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7948                                   SmallVectorImpl<Value *> &ToDemote,
7949                                   SmallVectorImpl<Value *> &Roots) {
7950   // We can always demote constants.
7951   if (isa<Constant>(V)) {
7952     ToDemote.push_back(V);
7953     return true;
7954   }
7955 
7956   // If the value is not an instruction in the expression with only one use, it
7957   // cannot be demoted.
7958   auto *I = dyn_cast<Instruction>(V);
7959   if (!I || !I->hasOneUse() || !Expr.count(I))
7960     return false;
7961 
7962   switch (I->getOpcode()) {
7963 
7964   // We can always demote truncations and extensions. Since truncations can
7965   // seed additional demotion, we save the truncated value.
7966   case Instruction::Trunc:
7967     Roots.push_back(I->getOperand(0));
7968     break;
7969   case Instruction::ZExt:
7970   case Instruction::SExt:
7971     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7972         isa<InsertElementInst>(I->getOperand(0)))
7973       return false;
7974     break;
7975 
7976   // We can demote certain binary operations if we can demote both of their
7977   // operands.
7978   case Instruction::Add:
7979   case Instruction::Sub:
7980   case Instruction::Mul:
7981   case Instruction::And:
7982   case Instruction::Or:
7983   case Instruction::Xor:
7984     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7985         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7986       return false;
7987     break;
7988 
7989   // We can demote selects if we can demote their true and false values.
7990   case Instruction::Select: {
7991     SelectInst *SI = cast<SelectInst>(I);
7992     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7993         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7994       return false;
7995     break;
7996   }
7997 
7998   // We can demote phis if we can demote all their incoming operands. Note that
7999   // we don't need to worry about cycles since we ensure single use above.
8000   case Instruction::PHI: {
8001     PHINode *PN = cast<PHINode>(I);
8002     for (Value *IncValue : PN->incoming_values())
8003       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8004         return false;
8005     break;
8006   }
8007 
8008   // Otherwise, conservatively give up.
8009   default:
8010     return false;
8011   }
8012 
8013   // Record the value that we can demote.
8014   ToDemote.push_back(V);
8015   return true;
8016 }
8017 
8018 void BoUpSLP::computeMinimumValueSizes() {
8019   // If there are no external uses, the expression tree must be rooted by a
8020   // store. We can't demote in-memory values, so there is nothing to do here.
8021   if (ExternalUses.empty())
8022     return;
8023 
8024   // We only attempt to truncate integer expressions.
8025   auto &TreeRoot = VectorizableTree[0]->Scalars;
8026   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8027   if (!TreeRootIT)
8028     return;
8029 
8030   // If the expression is not rooted by a store, these roots should have
8031   // external uses. We will rely on InstCombine to rewrite the expression in
8032   // the narrower type. However, InstCombine only rewrites single-use values.
8033   // This means that if a tree entry other than a root is used externally, it
8034   // must have multiple uses and InstCombine will not rewrite it. The code
8035   // below ensures that only the roots are used externally.
8036   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8037   for (auto &EU : ExternalUses)
8038     if (!Expr.erase(EU.Scalar))
8039       return;
8040   if (!Expr.empty())
8041     return;
8042 
8043   // Collect the scalar values of the vectorizable expression. We will use this
8044   // context to determine which values can be demoted. If we see a truncation,
8045   // we mark it as seeding another demotion.
8046   for (auto &EntryPtr : VectorizableTree)
8047     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8048 
8049   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8050   // have a single external user that is not in the vectorizable tree.
8051   for (auto *Root : TreeRoot)
8052     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8053       return;
8054 
8055   // Conservatively determine if we can actually truncate the roots of the
8056   // expression. Collect the values that can be demoted in ToDemote and
8057   // additional roots that require investigating in Roots.
8058   SmallVector<Value *, 32> ToDemote;
8059   SmallVector<Value *, 4> Roots;
8060   for (auto *Root : TreeRoot)
8061     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8062       return;
8063 
8064   // The maximum bit width required to represent all the values that can be
8065   // demoted without loss of precision. It would be safe to truncate the roots
8066   // of the expression to this width.
8067   auto MaxBitWidth = 8u;
8068 
8069   // We first check if all the bits of the roots are demanded. If they're not,
8070   // we can truncate the roots to this narrower type.
8071   for (auto *Root : TreeRoot) {
8072     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8073     MaxBitWidth = std::max<unsigned>(
8074         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8075   }
8076 
8077   // True if the roots can be zero-extended back to their original type, rather
8078   // than sign-extended. We know that if the leading bits are not demanded, we
8079   // can safely zero-extend. So we initialize IsKnownPositive to True.
8080   bool IsKnownPositive = true;
8081 
8082   // If all the bits of the roots are demanded, we can try a little harder to
8083   // compute a narrower type. This can happen, for example, if the roots are
8084   // getelementptr indices. InstCombine promotes these indices to the pointer
8085   // width. Thus, all their bits are technically demanded even though the
8086   // address computation might be vectorized in a smaller type.
8087   //
8088   // We start by looking at each entry that can be demoted. We compute the
8089   // maximum bit width required to store the scalar by using ValueTracking to
8090   // compute the number of high-order bits we can truncate.
8091   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8092       llvm::all_of(TreeRoot, [](Value *R) {
8093         assert(R->hasOneUse() && "Root should have only one use!");
8094         return isa<GetElementPtrInst>(R->user_back());
8095       })) {
8096     MaxBitWidth = 8u;
8097 
8098     // Determine if the sign bit of all the roots is known to be zero. If not,
8099     // IsKnownPositive is set to False.
8100     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8101       KnownBits Known = computeKnownBits(R, *DL);
8102       return Known.isNonNegative();
8103     });
8104 
8105     // Determine the maximum number of bits required to store the scalar
8106     // values.
8107     for (auto *Scalar : ToDemote) {
8108       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8109       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8110       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8111     }
8112 
8113     // If we can't prove that the sign bit is zero, we must add one to the
8114     // maximum bit width to account for the unknown sign bit. This preserves
8115     // the existing sign bit so we can safely sign-extend the root back to the
8116     // original type. Otherwise, if we know the sign bit is zero, we will
8117     // zero-extend the root instead.
8118     //
8119     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8120     //        one to the maximum bit width will yield a larger-than-necessary
8121     //        type. In general, we need to add an extra bit only if we can't
8122     //        prove that the upper bit of the original type is equal to the
8123     //        upper bit of the proposed smaller type. If these two bits are the
8124     //        same (either zero or one) we know that sign-extending from the
8125     //        smaller type will result in the same value. Here, since we can't
8126     //        yet prove this, we are just making the proposed smaller type
8127     //        larger to ensure correctness.
8128     if (!IsKnownPositive)
8129       ++MaxBitWidth;
8130   }
8131 
8132   // Round MaxBitWidth up to the next power-of-two.
8133   if (!isPowerOf2_64(MaxBitWidth))
8134     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8135 
8136   // If the maximum bit width we compute is less than the with of the roots'
8137   // type, we can proceed with the narrowing. Otherwise, do nothing.
8138   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8139     return;
8140 
8141   // If we can truncate the root, we must collect additional values that might
8142   // be demoted as a result. That is, those seeded by truncations we will
8143   // modify.
8144   while (!Roots.empty())
8145     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8146 
8147   // Finally, map the values we can demote to the maximum bit with we computed.
8148   for (auto *Scalar : ToDemote)
8149     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8150 }
8151 
8152 namespace {
8153 
8154 /// The SLPVectorizer Pass.
8155 struct SLPVectorizer : public FunctionPass {
8156   SLPVectorizerPass Impl;
8157 
8158   /// Pass identification, replacement for typeid
8159   static char ID;
8160 
8161   explicit SLPVectorizer() : FunctionPass(ID) {
8162     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8163   }
8164 
8165   bool doInitialization(Module &M) override { return false; }
8166 
8167   bool runOnFunction(Function &F) override {
8168     if (skipFunction(F))
8169       return false;
8170 
8171     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8172     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8173     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8174     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8175     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8176     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8177     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8178     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8179     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8180     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8181 
8182     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8183   }
8184 
8185   void getAnalysisUsage(AnalysisUsage &AU) const override {
8186     FunctionPass::getAnalysisUsage(AU);
8187     AU.addRequired<AssumptionCacheTracker>();
8188     AU.addRequired<ScalarEvolutionWrapperPass>();
8189     AU.addRequired<AAResultsWrapperPass>();
8190     AU.addRequired<TargetTransformInfoWrapperPass>();
8191     AU.addRequired<LoopInfoWrapperPass>();
8192     AU.addRequired<DominatorTreeWrapperPass>();
8193     AU.addRequired<DemandedBitsWrapperPass>();
8194     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8195     AU.addRequired<InjectTLIMappingsLegacy>();
8196     AU.addPreserved<LoopInfoWrapperPass>();
8197     AU.addPreserved<DominatorTreeWrapperPass>();
8198     AU.addPreserved<AAResultsWrapperPass>();
8199     AU.addPreserved<GlobalsAAWrapperPass>();
8200     AU.setPreservesCFG();
8201   }
8202 };
8203 
8204 } // end anonymous namespace
8205 
8206 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8207   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8208   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8209   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8210   auto *AA = &AM.getResult<AAManager>(F);
8211   auto *LI = &AM.getResult<LoopAnalysis>(F);
8212   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8213   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8214   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8215   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8216 
8217   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8218   if (!Changed)
8219     return PreservedAnalyses::all();
8220 
8221   PreservedAnalyses PA;
8222   PA.preserveSet<CFGAnalyses>();
8223   return PA;
8224 }
8225 
8226 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8227                                 TargetTransformInfo *TTI_,
8228                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8229                                 LoopInfo *LI_, DominatorTree *DT_,
8230                                 AssumptionCache *AC_, DemandedBits *DB_,
8231                                 OptimizationRemarkEmitter *ORE_) {
8232   if (!RunSLPVectorization)
8233     return false;
8234   SE = SE_;
8235   TTI = TTI_;
8236   TLI = TLI_;
8237   AA = AA_;
8238   LI = LI_;
8239   DT = DT_;
8240   AC = AC_;
8241   DB = DB_;
8242   DL = &F.getParent()->getDataLayout();
8243 
8244   Stores.clear();
8245   GEPs.clear();
8246   bool Changed = false;
8247 
8248   // If the target claims to have no vector registers don't attempt
8249   // vectorization.
8250   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8251     LLVM_DEBUG(
8252         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8253     return false;
8254   }
8255 
8256   // Don't vectorize when the attribute NoImplicitFloat is used.
8257   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8258     return false;
8259 
8260   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8261 
8262   // Use the bottom up slp vectorizer to construct chains that start with
8263   // store instructions.
8264   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8265 
8266   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8267   // delete instructions.
8268 
8269   // Update DFS numbers now so that we can use them for ordering.
8270   DT->updateDFSNumbers();
8271 
8272   // Scan the blocks in the function in post order.
8273   for (auto BB : post_order(&F.getEntryBlock())) {
8274     collectSeedInstructions(BB);
8275 
8276     // Vectorize trees that end at stores.
8277     if (!Stores.empty()) {
8278       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8279                         << " underlying objects.\n");
8280       Changed |= vectorizeStoreChains(R);
8281     }
8282 
8283     // Vectorize trees that end at reductions.
8284     Changed |= vectorizeChainsInBlock(BB, R);
8285 
8286     // Vectorize the index computations of getelementptr instructions. This
8287     // is primarily intended to catch gather-like idioms ending at
8288     // non-consecutive loads.
8289     if (!GEPs.empty()) {
8290       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8291                         << " underlying objects.\n");
8292       Changed |= vectorizeGEPIndices(BB, R);
8293     }
8294   }
8295 
8296   if (Changed) {
8297     R.optimizeGatherSequence();
8298     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8299   }
8300   return Changed;
8301 }
8302 
8303 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8304                                             unsigned Idx) {
8305   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8306                     << "\n");
8307   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8308   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8309   unsigned VF = Chain.size();
8310 
8311   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8312     return false;
8313 
8314   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8315                     << "\n");
8316 
8317   R.buildTree(Chain);
8318   if (R.isTreeTinyAndNotFullyVectorizable())
8319     return false;
8320   if (R.isLoadCombineCandidate())
8321     return false;
8322   R.reorderTopToBottom();
8323   R.reorderBottomToTop();
8324   R.buildExternalUses();
8325 
8326   R.computeMinimumValueSizes();
8327 
8328   InstructionCost Cost = R.getTreeCost();
8329 
8330   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8331   if (Cost < -SLPCostThreshold) {
8332     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8333 
8334     using namespace ore;
8335 
8336     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8337                                         cast<StoreInst>(Chain[0]))
8338                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8339                      << " and with tree size "
8340                      << NV("TreeSize", R.getTreeSize()));
8341 
8342     R.vectorizeTree();
8343     return true;
8344   }
8345 
8346   return false;
8347 }
8348 
8349 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8350                                         BoUpSLP &R) {
8351   // We may run into multiple chains that merge into a single chain. We mark the
8352   // stores that we vectorized so that we don't visit the same store twice.
8353   BoUpSLP::ValueSet VectorizedStores;
8354   bool Changed = false;
8355 
8356   int E = Stores.size();
8357   SmallBitVector Tails(E, false);
8358   int MaxIter = MaxStoreLookup.getValue();
8359   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8360       E, std::make_pair(E, INT_MAX));
8361   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8362   int IterCnt;
8363   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8364                                   &CheckedPairs,
8365                                   &ConsecutiveChain](int K, int Idx) {
8366     if (IterCnt >= MaxIter)
8367       return true;
8368     if (CheckedPairs[Idx].test(K))
8369       return ConsecutiveChain[K].second == 1 &&
8370              ConsecutiveChain[K].first == Idx;
8371     ++IterCnt;
8372     CheckedPairs[Idx].set(K);
8373     CheckedPairs[K].set(Idx);
8374     Optional<int> Diff = getPointersDiff(
8375         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8376         Stores[Idx]->getValueOperand()->getType(),
8377         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8378     if (!Diff || *Diff == 0)
8379       return false;
8380     int Val = *Diff;
8381     if (Val < 0) {
8382       if (ConsecutiveChain[Idx].second > -Val) {
8383         Tails.set(K);
8384         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8385       }
8386       return false;
8387     }
8388     if (ConsecutiveChain[K].second <= Val)
8389       return false;
8390 
8391     Tails.set(Idx);
8392     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8393     return Val == 1;
8394   };
8395   // Do a quadratic search on all of the given stores in reverse order and find
8396   // all of the pairs of stores that follow each other.
8397   for (int Idx = E - 1; Idx >= 0; --Idx) {
8398     // If a store has multiple consecutive store candidates, search according
8399     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8400     // This is because usually pairing with immediate succeeding or preceding
8401     // candidate create the best chance to find slp vectorization opportunity.
8402     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8403     IterCnt = 0;
8404     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8405       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8406           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8407         break;
8408   }
8409 
8410   // Tracks if we tried to vectorize stores starting from the given tail
8411   // already.
8412   SmallBitVector TriedTails(E, false);
8413   // For stores that start but don't end a link in the chain:
8414   for (int Cnt = E; Cnt > 0; --Cnt) {
8415     int I = Cnt - 1;
8416     if (ConsecutiveChain[I].first == E || Tails.test(I))
8417       continue;
8418     // We found a store instr that starts a chain. Now follow the chain and try
8419     // to vectorize it.
8420     BoUpSLP::ValueList Operands;
8421     // Collect the chain into a list.
8422     while (I != E && !VectorizedStores.count(Stores[I])) {
8423       Operands.push_back(Stores[I]);
8424       Tails.set(I);
8425       if (ConsecutiveChain[I].second != 1) {
8426         // Mark the new end in the chain and go back, if required. It might be
8427         // required if the original stores come in reversed order, for example.
8428         if (ConsecutiveChain[I].first != E &&
8429             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8430             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8431           TriedTails.set(I);
8432           Tails.reset(ConsecutiveChain[I].first);
8433           if (Cnt < ConsecutiveChain[I].first + 2)
8434             Cnt = ConsecutiveChain[I].first + 2;
8435         }
8436         break;
8437       }
8438       // Move to the next value in the chain.
8439       I = ConsecutiveChain[I].first;
8440     }
8441     assert(!Operands.empty() && "Expected non-empty list of stores.");
8442 
8443     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8444     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8445     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8446 
8447     unsigned MinVF = R.getMinVF(EltSize);
8448     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8449                               MaxElts);
8450 
8451     // FIXME: Is division-by-2 the correct step? Should we assert that the
8452     // register size is a power-of-2?
8453     unsigned StartIdx = 0;
8454     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8455       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8456         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8457         if (!VectorizedStores.count(Slice.front()) &&
8458             !VectorizedStores.count(Slice.back()) &&
8459             vectorizeStoreChain(Slice, R, Cnt)) {
8460           // Mark the vectorized stores so that we don't vectorize them again.
8461           VectorizedStores.insert(Slice.begin(), Slice.end());
8462           Changed = true;
8463           // If we vectorized initial block, no need to try to vectorize it
8464           // again.
8465           if (Cnt == StartIdx)
8466             StartIdx += Size;
8467           Cnt += Size;
8468           continue;
8469         }
8470         ++Cnt;
8471       }
8472       // Check if the whole array was vectorized already - exit.
8473       if (StartIdx >= Operands.size())
8474         break;
8475     }
8476   }
8477 
8478   return Changed;
8479 }
8480 
8481 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8482   // Initialize the collections. We will make a single pass over the block.
8483   Stores.clear();
8484   GEPs.clear();
8485 
8486   // Visit the store and getelementptr instructions in BB and organize them in
8487   // Stores and GEPs according to the underlying objects of their pointer
8488   // operands.
8489   for (Instruction &I : *BB) {
8490     // Ignore store instructions that are volatile or have a pointer operand
8491     // that doesn't point to a scalar type.
8492     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8493       if (!SI->isSimple())
8494         continue;
8495       if (!isValidElementType(SI->getValueOperand()->getType()))
8496         continue;
8497       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8498     }
8499 
8500     // Ignore getelementptr instructions that have more than one index, a
8501     // constant index, or a pointer operand that doesn't point to a scalar
8502     // type.
8503     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8504       auto Idx = GEP->idx_begin()->get();
8505       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8506         continue;
8507       if (!isValidElementType(Idx->getType()))
8508         continue;
8509       if (GEP->getType()->isVectorTy())
8510         continue;
8511       GEPs[GEP->getPointerOperand()].push_back(GEP);
8512     }
8513   }
8514 }
8515 
8516 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8517   if (!A || !B)
8518     return false;
8519   Value *VL[] = {A, B};
8520   return tryToVectorizeList(VL, R);
8521 }
8522 
8523 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8524                                            bool LimitForRegisterSize) {
8525   if (VL.size() < 2)
8526     return false;
8527 
8528   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8529                     << VL.size() << ".\n");
8530 
8531   // Check that all of the parts are instructions of the same type,
8532   // we permit an alternate opcode via InstructionsState.
8533   InstructionsState S = getSameOpcode(VL);
8534   if (!S.getOpcode())
8535     return false;
8536 
8537   Instruction *I0 = cast<Instruction>(S.OpValue);
8538   // Make sure invalid types (including vector type) are rejected before
8539   // determining vectorization factor for scalar instructions.
8540   for (Value *V : VL) {
8541     Type *Ty = V->getType();
8542     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8543       // NOTE: the following will give user internal llvm type name, which may
8544       // not be useful.
8545       R.getORE()->emit([&]() {
8546         std::string type_str;
8547         llvm::raw_string_ostream rso(type_str);
8548         Ty->print(rso);
8549         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8550                << "Cannot SLP vectorize list: type "
8551                << rso.str() + " is unsupported by vectorizer";
8552       });
8553       return false;
8554     }
8555   }
8556 
8557   unsigned Sz = R.getVectorElementSize(I0);
8558   unsigned MinVF = R.getMinVF(Sz);
8559   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8560   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8561   if (MaxVF < 2) {
8562     R.getORE()->emit([&]() {
8563       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8564              << "Cannot SLP vectorize list: vectorization factor "
8565              << "less than 2 is not supported";
8566     });
8567     return false;
8568   }
8569 
8570   bool Changed = false;
8571   bool CandidateFound = false;
8572   InstructionCost MinCost = SLPCostThreshold.getValue();
8573   Type *ScalarTy = VL[0]->getType();
8574   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8575     ScalarTy = IE->getOperand(1)->getType();
8576 
8577   unsigned NextInst = 0, MaxInst = VL.size();
8578   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8579     // No actual vectorization should happen, if number of parts is the same as
8580     // provided vectorization factor (i.e. the scalar type is used for vector
8581     // code during codegen).
8582     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8583     if (TTI->getNumberOfParts(VecTy) == VF)
8584       continue;
8585     for (unsigned I = NextInst; I < MaxInst; ++I) {
8586       unsigned OpsWidth = 0;
8587 
8588       if (I + VF > MaxInst)
8589         OpsWidth = MaxInst - I;
8590       else
8591         OpsWidth = VF;
8592 
8593       if (!isPowerOf2_32(OpsWidth))
8594         continue;
8595 
8596       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8597           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8598         break;
8599 
8600       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8601       // Check that a previous iteration of this loop did not delete the Value.
8602       if (llvm::any_of(Ops, [&R](Value *V) {
8603             auto *I = dyn_cast<Instruction>(V);
8604             return I && R.isDeleted(I);
8605           }))
8606         continue;
8607 
8608       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8609                         << "\n");
8610 
8611       R.buildTree(Ops);
8612       if (R.isTreeTinyAndNotFullyVectorizable())
8613         continue;
8614       R.reorderTopToBottom();
8615       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8616       R.buildExternalUses();
8617 
8618       R.computeMinimumValueSizes();
8619       InstructionCost Cost = R.getTreeCost();
8620       CandidateFound = true;
8621       MinCost = std::min(MinCost, Cost);
8622 
8623       if (Cost < -SLPCostThreshold) {
8624         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8625         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8626                                                     cast<Instruction>(Ops[0]))
8627                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8628                                  << " and with tree size "
8629                                  << ore::NV("TreeSize", R.getTreeSize()));
8630 
8631         R.vectorizeTree();
8632         // Move to the next bundle.
8633         I += VF - 1;
8634         NextInst = I + 1;
8635         Changed = true;
8636       }
8637     }
8638   }
8639 
8640   if (!Changed && CandidateFound) {
8641     R.getORE()->emit([&]() {
8642       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8643              << "List vectorization was possible but not beneficial with cost "
8644              << ore::NV("Cost", MinCost) << " >= "
8645              << ore::NV("Treshold", -SLPCostThreshold);
8646     });
8647   } else if (!Changed) {
8648     R.getORE()->emit([&]() {
8649       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8650              << "Cannot SLP vectorize list: vectorization was impossible"
8651              << " with available vectorization factors";
8652     });
8653   }
8654   return Changed;
8655 }
8656 
8657 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8658   if (!I)
8659     return false;
8660 
8661   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8662     return false;
8663 
8664   Value *P = I->getParent();
8665 
8666   // Vectorize in current basic block only.
8667   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8668   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8669   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8670     return false;
8671 
8672   // Try to vectorize V.
8673   if (tryToVectorizePair(Op0, Op1, R))
8674     return true;
8675 
8676   auto *A = dyn_cast<BinaryOperator>(Op0);
8677   auto *B = dyn_cast<BinaryOperator>(Op1);
8678   // Try to skip B.
8679   if (B && B->hasOneUse()) {
8680     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8681     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8682     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8683       return true;
8684     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8685       return true;
8686   }
8687 
8688   // Try to skip A.
8689   if (A && A->hasOneUse()) {
8690     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8691     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8692     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8693       return true;
8694     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8695       return true;
8696   }
8697   return false;
8698 }
8699 
8700 namespace {
8701 
8702 /// Model horizontal reductions.
8703 ///
8704 /// A horizontal reduction is a tree of reduction instructions that has values
8705 /// that can be put into a vector as its leaves. For example:
8706 ///
8707 /// mul mul mul mul
8708 ///  \  /    \  /
8709 ///   +       +
8710 ///    \     /
8711 ///       +
8712 /// This tree has "mul" as its leaf values and "+" as its reduction
8713 /// instructions. A reduction can feed into a store or a binary operation
8714 /// feeding a phi.
8715 ///    ...
8716 ///    \  /
8717 ///     +
8718 ///     |
8719 ///  phi +=
8720 ///
8721 ///  Or:
8722 ///    ...
8723 ///    \  /
8724 ///     +
8725 ///     |
8726 ///   *p =
8727 ///
8728 class HorizontalReduction {
8729   using ReductionOpsType = SmallVector<Value *, 16>;
8730   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8731   ReductionOpsListType ReductionOps;
8732   SmallVector<Value *, 32> ReducedVals;
8733   // Use map vector to make stable output.
8734   MapVector<Instruction *, Value *> ExtraArgs;
8735   WeakTrackingVH ReductionRoot;
8736   /// The type of reduction operation.
8737   RecurKind RdxKind;
8738 
8739   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8740 
8741   static bool isCmpSelMinMax(Instruction *I) {
8742     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8743            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8744   }
8745 
8746   // And/or are potentially poison-safe logical patterns like:
8747   // select x, y, false
8748   // select x, true, y
8749   static bool isBoolLogicOp(Instruction *I) {
8750     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8751            match(I, m_LogicalOr(m_Value(), m_Value()));
8752   }
8753 
8754   /// Checks if instruction is associative and can be vectorized.
8755   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8756     if (Kind == RecurKind::None)
8757       return false;
8758 
8759     // Integer ops that map to select instructions or intrinsics are fine.
8760     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8761         isBoolLogicOp(I))
8762       return true;
8763 
8764     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8765       // FP min/max are associative except for NaN and -0.0. We do not
8766       // have to rule out -0.0 here because the intrinsic semantics do not
8767       // specify a fixed result for it.
8768       return I->getFastMathFlags().noNaNs();
8769     }
8770 
8771     return I->isAssociative();
8772   }
8773 
8774   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8775     // Poison-safe 'or' takes the form: select X, true, Y
8776     // To make that work with the normal operand processing, we skip the
8777     // true value operand.
8778     // TODO: Change the code and data structures to handle this without a hack.
8779     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8780       return I->getOperand(2);
8781     return I->getOperand(Index);
8782   }
8783 
8784   /// Checks if the ParentStackElem.first should be marked as a reduction
8785   /// operation with an extra argument or as extra argument itself.
8786   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8787                     Value *ExtraArg) {
8788     if (ExtraArgs.count(ParentStackElem.first)) {
8789       ExtraArgs[ParentStackElem.first] = nullptr;
8790       // We ran into something like:
8791       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8792       // The whole ParentStackElem.first should be considered as an extra value
8793       // in this case.
8794       // Do not perform analysis of remaining operands of ParentStackElem.first
8795       // instruction, this whole instruction is an extra argument.
8796       ParentStackElem.second = INVALID_OPERAND_INDEX;
8797     } else {
8798       // We ran into something like:
8799       // ParentStackElem.first += ... + ExtraArg + ...
8800       ExtraArgs[ParentStackElem.first] = ExtraArg;
8801     }
8802   }
8803 
8804   /// Creates reduction operation with the current opcode.
8805   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8806                          Value *RHS, const Twine &Name, bool UseSelect) {
8807     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8808     switch (Kind) {
8809     case RecurKind::Or:
8810       if (UseSelect &&
8811           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8812         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8813       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8814                                  Name);
8815     case RecurKind::And:
8816       if (UseSelect &&
8817           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8818         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8819       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8820                                  Name);
8821     case RecurKind::Add:
8822     case RecurKind::Mul:
8823     case RecurKind::Xor:
8824     case RecurKind::FAdd:
8825     case RecurKind::FMul:
8826       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8827                                  Name);
8828     case RecurKind::FMax:
8829       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8830     case RecurKind::FMin:
8831       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8832     case RecurKind::SMax:
8833       if (UseSelect) {
8834         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8835         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8836       }
8837       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8838     case RecurKind::SMin:
8839       if (UseSelect) {
8840         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8841         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8842       }
8843       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8844     case RecurKind::UMax:
8845       if (UseSelect) {
8846         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8847         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8848       }
8849       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8850     case RecurKind::UMin:
8851       if (UseSelect) {
8852         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8853         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8854       }
8855       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8856     default:
8857       llvm_unreachable("Unknown reduction operation.");
8858     }
8859   }
8860 
8861   /// Creates reduction operation with the current opcode with the IR flags
8862   /// from \p ReductionOps.
8863   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8864                          Value *RHS, const Twine &Name,
8865                          const ReductionOpsListType &ReductionOps) {
8866     bool UseSelect = ReductionOps.size() == 2 ||
8867                      // Logical or/and.
8868                      (ReductionOps.size() == 1 &&
8869                       isa<SelectInst>(ReductionOps.front().front()));
8870     assert((!UseSelect || ReductionOps.size() != 2 ||
8871             isa<SelectInst>(ReductionOps[1][0])) &&
8872            "Expected cmp + select pairs for reduction");
8873     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8874     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8875       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8876         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8877         propagateIRFlags(Op, ReductionOps[1]);
8878         return Op;
8879       }
8880     }
8881     propagateIRFlags(Op, ReductionOps[0]);
8882     return Op;
8883   }
8884 
8885   /// Creates reduction operation with the current opcode with the IR flags
8886   /// from \p I.
8887   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8888                          Value *RHS, const Twine &Name, Instruction *I) {
8889     auto *SelI = dyn_cast<SelectInst>(I);
8890     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8891     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8892       if (auto *Sel = dyn_cast<SelectInst>(Op))
8893         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8894     }
8895     propagateIRFlags(Op, I);
8896     return Op;
8897   }
8898 
8899   static RecurKind getRdxKind(Instruction *I) {
8900     assert(I && "Expected instruction for reduction matching");
8901     if (match(I, m_Add(m_Value(), m_Value())))
8902       return RecurKind::Add;
8903     if (match(I, m_Mul(m_Value(), m_Value())))
8904       return RecurKind::Mul;
8905     if (match(I, m_And(m_Value(), m_Value())) ||
8906         match(I, m_LogicalAnd(m_Value(), m_Value())))
8907       return RecurKind::And;
8908     if (match(I, m_Or(m_Value(), m_Value())) ||
8909         match(I, m_LogicalOr(m_Value(), m_Value())))
8910       return RecurKind::Or;
8911     if (match(I, m_Xor(m_Value(), m_Value())))
8912       return RecurKind::Xor;
8913     if (match(I, m_FAdd(m_Value(), m_Value())))
8914       return RecurKind::FAdd;
8915     if (match(I, m_FMul(m_Value(), m_Value())))
8916       return RecurKind::FMul;
8917 
8918     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8919       return RecurKind::FMax;
8920     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8921       return RecurKind::FMin;
8922 
8923     // This matches either cmp+select or intrinsics. SLP is expected to handle
8924     // either form.
8925     // TODO: If we are canonicalizing to intrinsics, we can remove several
8926     //       special-case paths that deal with selects.
8927     if (match(I, m_SMax(m_Value(), m_Value())))
8928       return RecurKind::SMax;
8929     if (match(I, m_SMin(m_Value(), m_Value())))
8930       return RecurKind::SMin;
8931     if (match(I, m_UMax(m_Value(), m_Value())))
8932       return RecurKind::UMax;
8933     if (match(I, m_UMin(m_Value(), m_Value())))
8934       return RecurKind::UMin;
8935 
8936     if (auto *Select = dyn_cast<SelectInst>(I)) {
8937       // Try harder: look for min/max pattern based on instructions producing
8938       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8939       // During the intermediate stages of SLP, it's very common to have
8940       // pattern like this (since optimizeGatherSequence is run only once
8941       // at the end):
8942       // %1 = extractelement <2 x i32> %a, i32 0
8943       // %2 = extractelement <2 x i32> %a, i32 1
8944       // %cond = icmp sgt i32 %1, %2
8945       // %3 = extractelement <2 x i32> %a, i32 0
8946       // %4 = extractelement <2 x i32> %a, i32 1
8947       // %select = select i1 %cond, i32 %3, i32 %4
8948       CmpInst::Predicate Pred;
8949       Instruction *L1;
8950       Instruction *L2;
8951 
8952       Value *LHS = Select->getTrueValue();
8953       Value *RHS = Select->getFalseValue();
8954       Value *Cond = Select->getCondition();
8955 
8956       // TODO: Support inverse predicates.
8957       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8958         if (!isa<ExtractElementInst>(RHS) ||
8959             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8960           return RecurKind::None;
8961       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8962         if (!isa<ExtractElementInst>(LHS) ||
8963             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8964           return RecurKind::None;
8965       } else {
8966         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8967           return RecurKind::None;
8968         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8969             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8970             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8971           return RecurKind::None;
8972       }
8973 
8974       switch (Pred) {
8975       default:
8976         return RecurKind::None;
8977       case CmpInst::ICMP_SGT:
8978       case CmpInst::ICMP_SGE:
8979         return RecurKind::SMax;
8980       case CmpInst::ICMP_SLT:
8981       case CmpInst::ICMP_SLE:
8982         return RecurKind::SMin;
8983       case CmpInst::ICMP_UGT:
8984       case CmpInst::ICMP_UGE:
8985         return RecurKind::UMax;
8986       case CmpInst::ICMP_ULT:
8987       case CmpInst::ICMP_ULE:
8988         return RecurKind::UMin;
8989       }
8990     }
8991     return RecurKind::None;
8992   }
8993 
8994   /// Get the index of the first operand.
8995   static unsigned getFirstOperandIndex(Instruction *I) {
8996     return isCmpSelMinMax(I) ? 1 : 0;
8997   }
8998 
8999   /// Total number of operands in the reduction operation.
9000   static unsigned getNumberOfOperands(Instruction *I) {
9001     return isCmpSelMinMax(I) ? 3 : 2;
9002   }
9003 
9004   /// Checks if the instruction is in basic block \p BB.
9005   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9006   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9007     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9008       auto *Sel = cast<SelectInst>(I);
9009       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9010       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9011     }
9012     return I->getParent() == BB;
9013   }
9014 
9015   /// Expected number of uses for reduction operations/reduced values.
9016   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9017     if (IsCmpSelMinMax) {
9018       // SelectInst must be used twice while the condition op must have single
9019       // use only.
9020       if (auto *Sel = dyn_cast<SelectInst>(I))
9021         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9022       return I->hasNUses(2);
9023     }
9024 
9025     // Arithmetic reduction operation must be used once only.
9026     return I->hasOneUse();
9027   }
9028 
9029   /// Initializes the list of reduction operations.
9030   void initReductionOps(Instruction *I) {
9031     if (isCmpSelMinMax(I))
9032       ReductionOps.assign(2, ReductionOpsType());
9033     else
9034       ReductionOps.assign(1, ReductionOpsType());
9035   }
9036 
9037   /// Add all reduction operations for the reduction instruction \p I.
9038   void addReductionOps(Instruction *I) {
9039     if (isCmpSelMinMax(I)) {
9040       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9041       ReductionOps[1].emplace_back(I);
9042     } else {
9043       ReductionOps[0].emplace_back(I);
9044     }
9045   }
9046 
9047   static Value *getLHS(RecurKind Kind, Instruction *I) {
9048     if (Kind == RecurKind::None)
9049       return nullptr;
9050     return I->getOperand(getFirstOperandIndex(I));
9051   }
9052   static Value *getRHS(RecurKind Kind, Instruction *I) {
9053     if (Kind == RecurKind::None)
9054       return nullptr;
9055     return I->getOperand(getFirstOperandIndex(I) + 1);
9056   }
9057 
9058 public:
9059   HorizontalReduction() = default;
9060 
9061   /// Try to find a reduction tree.
9062   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9063     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9064            "Phi needs to use the binary operator");
9065     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9066             isa<IntrinsicInst>(Inst)) &&
9067            "Expected binop, select, or intrinsic for reduction matching");
9068     RdxKind = getRdxKind(Inst);
9069 
9070     // We could have a initial reductions that is not an add.
9071     //  r *= v1 + v2 + v3 + v4
9072     // In such a case start looking for a tree rooted in the first '+'.
9073     if (Phi) {
9074       if (getLHS(RdxKind, Inst) == Phi) {
9075         Phi = nullptr;
9076         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9077         if (!Inst)
9078           return false;
9079         RdxKind = getRdxKind(Inst);
9080       } else if (getRHS(RdxKind, Inst) == Phi) {
9081         Phi = nullptr;
9082         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9083         if (!Inst)
9084           return false;
9085         RdxKind = getRdxKind(Inst);
9086       }
9087     }
9088 
9089     if (!isVectorizable(RdxKind, Inst))
9090       return false;
9091 
9092     // Analyze "regular" integer/FP types for reductions - no target-specific
9093     // types or pointers.
9094     Type *Ty = Inst->getType();
9095     if (!isValidElementType(Ty) || Ty->isPointerTy())
9096       return false;
9097 
9098     // Though the ultimate reduction may have multiple uses, its condition must
9099     // have only single use.
9100     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9101       if (!Sel->getCondition()->hasOneUse())
9102         return false;
9103 
9104     ReductionRoot = Inst;
9105 
9106     // The opcode for leaf values that we perform a reduction on.
9107     // For example: load(x) + load(y) + load(z) + fptoui(w)
9108     // The leaf opcode for 'w' does not match, so we don't include it as a
9109     // potential candidate for the reduction.
9110     unsigned LeafOpcode = 0;
9111 
9112     // Post-order traverse the reduction tree starting at Inst. We only handle
9113     // true trees containing binary operators or selects.
9114     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9115     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9116     initReductionOps(Inst);
9117     while (!Stack.empty()) {
9118       Instruction *TreeN = Stack.back().first;
9119       unsigned EdgeToVisit = Stack.back().second++;
9120       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9121       bool IsReducedValue = TreeRdxKind != RdxKind;
9122 
9123       // Postorder visit.
9124       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9125         if (IsReducedValue)
9126           ReducedVals.push_back(TreeN);
9127         else {
9128           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9129           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9130             // Check if TreeN is an extra argument of its parent operation.
9131             if (Stack.size() <= 1) {
9132               // TreeN can't be an extra argument as it is a root reduction
9133               // operation.
9134               return false;
9135             }
9136             // Yes, TreeN is an extra argument, do not add it to a list of
9137             // reduction operations.
9138             // Stack[Stack.size() - 2] always points to the parent operation.
9139             markExtraArg(Stack[Stack.size() - 2], TreeN);
9140             ExtraArgs.erase(TreeN);
9141           } else
9142             addReductionOps(TreeN);
9143         }
9144         // Retract.
9145         Stack.pop_back();
9146         continue;
9147       }
9148 
9149       // Visit operands.
9150       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9151       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9152       if (!EdgeInst) {
9153         // Edge value is not a reduction instruction or a leaf instruction.
9154         // (It may be a constant, function argument, or something else.)
9155         markExtraArg(Stack.back(), EdgeVal);
9156         continue;
9157       }
9158       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9159       // Continue analysis if the next operand is a reduction operation or
9160       // (possibly) a leaf value. If the leaf value opcode is not set,
9161       // the first met operation != reduction operation is considered as the
9162       // leaf opcode.
9163       // Only handle trees in the current basic block.
9164       // Each tree node needs to have minimal number of users except for the
9165       // ultimate reduction.
9166       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9167       if (EdgeInst != Phi && EdgeInst != Inst &&
9168           hasSameParent(EdgeInst, Inst->getParent()) &&
9169           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9170           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9171         if (IsRdxInst) {
9172           // We need to be able to reassociate the reduction operations.
9173           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9174             // I is an extra argument for TreeN (its parent operation).
9175             markExtraArg(Stack.back(), EdgeInst);
9176             continue;
9177           }
9178         } else if (!LeafOpcode) {
9179           LeafOpcode = EdgeInst->getOpcode();
9180         }
9181         Stack.push_back(
9182             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9183         continue;
9184       }
9185       // I is an extra argument for TreeN (its parent operation).
9186       markExtraArg(Stack.back(), EdgeInst);
9187     }
9188     return true;
9189   }
9190 
9191   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9192   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9193     // If there are a sufficient number of reduction values, reduce
9194     // to a nearby power-of-2. We can safely generate oversized
9195     // vectors and rely on the backend to split them to legal sizes.
9196     unsigned NumReducedVals = ReducedVals.size();
9197     if (NumReducedVals < 4)
9198       return nullptr;
9199 
9200     // Intersect the fast-math-flags from all reduction operations.
9201     FastMathFlags RdxFMF;
9202     RdxFMF.set();
9203     for (ReductionOpsType &RdxOp : ReductionOps) {
9204       for (Value *RdxVal : RdxOp) {
9205         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9206           RdxFMF &= FPMO->getFastMathFlags();
9207       }
9208     }
9209 
9210     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9211     Builder.setFastMathFlags(RdxFMF);
9212 
9213     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9214     // The same extra argument may be used several times, so log each attempt
9215     // to use it.
9216     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9217       assert(Pair.first && "DebugLoc must be set.");
9218       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9219     }
9220 
9221     // The compare instruction of a min/max is the insertion point for new
9222     // instructions and may be replaced with a new compare instruction.
9223     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9224       assert(isa<SelectInst>(RdxRootInst) &&
9225              "Expected min/max reduction to have select root instruction");
9226       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9227       assert(isa<Instruction>(ScalarCond) &&
9228              "Expected min/max reduction to have compare condition");
9229       return cast<Instruction>(ScalarCond);
9230     };
9231 
9232     // The reduction root is used as the insertion point for new instructions,
9233     // so set it as externally used to prevent it from being deleted.
9234     ExternallyUsedValues[ReductionRoot];
9235     SmallVector<Value *, 16> IgnoreList;
9236     for (ReductionOpsType &RdxOp : ReductionOps)
9237       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9238 
9239     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9240     if (NumReducedVals > ReduxWidth) {
9241       // In the loop below, we are building a tree based on a window of
9242       // 'ReduxWidth' values.
9243       // If the operands of those values have common traits (compare predicate,
9244       // constant operand, etc), then we want to group those together to
9245       // minimize the cost of the reduction.
9246 
9247       // TODO: This should be extended to count common operands for
9248       //       compares and binops.
9249 
9250       // Step 1: Count the number of times each compare predicate occurs.
9251       SmallDenseMap<unsigned, unsigned> PredCountMap;
9252       for (Value *RdxVal : ReducedVals) {
9253         CmpInst::Predicate Pred;
9254         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9255           ++PredCountMap[Pred];
9256       }
9257       // Step 2: Sort the values so the most common predicates come first.
9258       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9259         CmpInst::Predicate PredA, PredB;
9260         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9261             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9262           return PredCountMap[PredA] > PredCountMap[PredB];
9263         }
9264         return false;
9265       });
9266     }
9267 
9268     Value *VectorizedTree = nullptr;
9269     unsigned i = 0;
9270     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9271       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9272       V.buildTree(VL, IgnoreList);
9273       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9274         break;
9275       if (V.isLoadCombineReductionCandidate(RdxKind))
9276         break;
9277       V.reorderTopToBottom();
9278       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9279       V.buildExternalUses(ExternallyUsedValues);
9280 
9281       // For a poison-safe boolean logic reduction, do not replace select
9282       // instructions with logic ops. All reduced values will be frozen (see
9283       // below) to prevent leaking poison.
9284       if (isa<SelectInst>(ReductionRoot) &&
9285           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9286           NumReducedVals != ReduxWidth)
9287         break;
9288 
9289       V.computeMinimumValueSizes();
9290 
9291       // Estimate cost.
9292       InstructionCost TreeCost =
9293           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9294       InstructionCost ReductionCost =
9295           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9296       InstructionCost Cost = TreeCost + ReductionCost;
9297       if (!Cost.isValid()) {
9298         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9299         return nullptr;
9300       }
9301       if (Cost >= -SLPCostThreshold) {
9302         V.getORE()->emit([&]() {
9303           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9304                                           cast<Instruction>(VL[0]))
9305                  << "Vectorizing horizontal reduction is possible"
9306                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9307                  << " and threshold "
9308                  << ore::NV("Threshold", -SLPCostThreshold);
9309         });
9310         break;
9311       }
9312 
9313       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9314                         << Cost << ". (HorRdx)\n");
9315       V.getORE()->emit([&]() {
9316         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9317                                   cast<Instruction>(VL[0]))
9318                << "Vectorized horizontal reduction with cost "
9319                << ore::NV("Cost", Cost) << " and with tree size "
9320                << ore::NV("TreeSize", V.getTreeSize());
9321       });
9322 
9323       // Vectorize a tree.
9324       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9325       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9326 
9327       // Emit a reduction. If the root is a select (min/max idiom), the insert
9328       // point is the compare condition of that select.
9329       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9330       if (isCmpSelMinMax(RdxRootInst))
9331         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9332       else
9333         Builder.SetInsertPoint(RdxRootInst);
9334 
9335       // To prevent poison from leaking across what used to be sequential, safe,
9336       // scalar boolean logic operations, the reduction operand must be frozen.
9337       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9338         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9339 
9340       Value *ReducedSubTree =
9341           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9342 
9343       if (!VectorizedTree) {
9344         // Initialize the final value in the reduction.
9345         VectorizedTree = ReducedSubTree;
9346       } else {
9347         // Update the final value in the reduction.
9348         Builder.SetCurrentDebugLocation(Loc);
9349         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9350                                   ReducedSubTree, "op.rdx", ReductionOps);
9351       }
9352       i += ReduxWidth;
9353       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9354     }
9355 
9356     if (VectorizedTree) {
9357       // Finish the reduction.
9358       for (; i < NumReducedVals; ++i) {
9359         auto *I = cast<Instruction>(ReducedVals[i]);
9360         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9361         VectorizedTree =
9362             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9363       }
9364       for (auto &Pair : ExternallyUsedValues) {
9365         // Add each externally used value to the final reduction.
9366         for (auto *I : Pair.second) {
9367           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9368           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9369                                     Pair.first, "op.extra", I);
9370         }
9371       }
9372 
9373       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9374 
9375       // Mark all scalar reduction ops for deletion, they are replaced by the
9376       // vector reductions.
9377       V.eraseInstructions(IgnoreList);
9378     }
9379     return VectorizedTree;
9380   }
9381 
9382   unsigned numReductionValues() const { return ReducedVals.size(); }
9383 
9384 private:
9385   /// Calculate the cost of a reduction.
9386   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9387                                    Value *FirstReducedVal, unsigned ReduxWidth,
9388                                    FastMathFlags FMF) {
9389     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9390     Type *ScalarTy = FirstReducedVal->getType();
9391     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9392     InstructionCost VectorCost, ScalarCost;
9393     switch (RdxKind) {
9394     case RecurKind::Add:
9395     case RecurKind::Mul:
9396     case RecurKind::Or:
9397     case RecurKind::And:
9398     case RecurKind::Xor:
9399     case RecurKind::FAdd:
9400     case RecurKind::FMul: {
9401       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9402       VectorCost =
9403           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9404       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9405       break;
9406     }
9407     case RecurKind::FMax:
9408     case RecurKind::FMin: {
9409       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9410       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9411       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9412                                                /*IsUnsigned=*/false, CostKind);
9413       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9414       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9415                                            SclCondTy, RdxPred, CostKind) +
9416                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9417                                            SclCondTy, RdxPred, CostKind);
9418       break;
9419     }
9420     case RecurKind::SMax:
9421     case RecurKind::SMin:
9422     case RecurKind::UMax:
9423     case RecurKind::UMin: {
9424       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9425       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9426       bool IsUnsigned =
9427           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9428       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9429                                                CostKind);
9430       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9431       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9432                                            SclCondTy, RdxPred, CostKind) +
9433                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9434                                            SclCondTy, RdxPred, CostKind);
9435       break;
9436     }
9437     default:
9438       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9439     }
9440 
9441     // Scalar cost is repeated for N-1 elements.
9442     ScalarCost *= (ReduxWidth - 1);
9443     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9444                       << " for reduction that starts with " << *FirstReducedVal
9445                       << " (It is a splitting reduction)\n");
9446     return VectorCost - ScalarCost;
9447   }
9448 
9449   /// Emit a horizontal reduction of the vectorized value.
9450   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9451                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9452     assert(VectorizedValue && "Need to have a vectorized tree node");
9453     assert(isPowerOf2_32(ReduxWidth) &&
9454            "We only handle power-of-two reductions for now");
9455     assert(RdxKind != RecurKind::FMulAdd &&
9456            "A call to the llvm.fmuladd intrinsic is not handled yet");
9457 
9458     ++NumVectorInstructions;
9459     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9460   }
9461 };
9462 
9463 } // end anonymous namespace
9464 
9465 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9466   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9467     return cast<FixedVectorType>(IE->getType())->getNumElements();
9468 
9469   unsigned AggregateSize = 1;
9470   auto *IV = cast<InsertValueInst>(InsertInst);
9471   Type *CurrentType = IV->getType();
9472   do {
9473     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9474       for (auto *Elt : ST->elements())
9475         if (Elt != ST->getElementType(0)) // check homogeneity
9476           return None;
9477       AggregateSize *= ST->getNumElements();
9478       CurrentType = ST->getElementType(0);
9479     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9480       AggregateSize *= AT->getNumElements();
9481       CurrentType = AT->getElementType();
9482     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9483       AggregateSize *= VT->getNumElements();
9484       return AggregateSize;
9485     } else if (CurrentType->isSingleValueType()) {
9486       return AggregateSize;
9487     } else {
9488       return None;
9489     }
9490   } while (true);
9491 }
9492 
9493 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9494                                    TargetTransformInfo *TTI,
9495                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9496                                    SmallVectorImpl<Value *> &InsertElts,
9497                                    unsigned OperandOffset) {
9498   do {
9499     Value *InsertedOperand = LastInsertInst->getOperand(1);
9500     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9501     if (!OperandIndex)
9502       return false;
9503     if (isa<InsertElementInst>(InsertedOperand) ||
9504         isa<InsertValueInst>(InsertedOperand)) {
9505       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9506                                   BuildVectorOpds, InsertElts, *OperandIndex))
9507         return false;
9508     } else {
9509       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9510       InsertElts[*OperandIndex] = LastInsertInst;
9511     }
9512     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9513   } while (LastInsertInst != nullptr &&
9514            (isa<InsertValueInst>(LastInsertInst) ||
9515             isa<InsertElementInst>(LastInsertInst)) &&
9516            LastInsertInst->hasOneUse());
9517   return true;
9518 }
9519 
9520 /// Recognize construction of vectors like
9521 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9522 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9523 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9524 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9525 ///  starting from the last insertelement or insertvalue instruction.
9526 ///
9527 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9528 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9529 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9530 ///
9531 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9532 ///
9533 /// \return true if it matches.
9534 static bool findBuildAggregate(Instruction *LastInsertInst,
9535                                TargetTransformInfo *TTI,
9536                                SmallVectorImpl<Value *> &BuildVectorOpds,
9537                                SmallVectorImpl<Value *> &InsertElts) {
9538 
9539   assert((isa<InsertElementInst>(LastInsertInst) ||
9540           isa<InsertValueInst>(LastInsertInst)) &&
9541          "Expected insertelement or insertvalue instruction!");
9542 
9543   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9544          "Expected empty result vectors!");
9545 
9546   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9547   if (!AggregateSize)
9548     return false;
9549   BuildVectorOpds.resize(*AggregateSize);
9550   InsertElts.resize(*AggregateSize);
9551 
9552   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9553                              0)) {
9554     llvm::erase_value(BuildVectorOpds, nullptr);
9555     llvm::erase_value(InsertElts, nullptr);
9556     if (BuildVectorOpds.size() >= 2)
9557       return true;
9558   }
9559 
9560   return false;
9561 }
9562 
9563 /// Try and get a reduction value from a phi node.
9564 ///
9565 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9566 /// if they come from either \p ParentBB or a containing loop latch.
9567 ///
9568 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9569 /// if not possible.
9570 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9571                                 BasicBlock *ParentBB, LoopInfo *LI) {
9572   // There are situations where the reduction value is not dominated by the
9573   // reduction phi. Vectorizing such cases has been reported to cause
9574   // miscompiles. See PR25787.
9575   auto DominatedReduxValue = [&](Value *R) {
9576     return isa<Instruction>(R) &&
9577            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9578   };
9579 
9580   Value *Rdx = nullptr;
9581 
9582   // Return the incoming value if it comes from the same BB as the phi node.
9583   if (P->getIncomingBlock(0) == ParentBB) {
9584     Rdx = P->getIncomingValue(0);
9585   } else if (P->getIncomingBlock(1) == ParentBB) {
9586     Rdx = P->getIncomingValue(1);
9587   }
9588 
9589   if (Rdx && DominatedReduxValue(Rdx))
9590     return Rdx;
9591 
9592   // Otherwise, check whether we have a loop latch to look at.
9593   Loop *BBL = LI->getLoopFor(ParentBB);
9594   if (!BBL)
9595     return nullptr;
9596   BasicBlock *BBLatch = BBL->getLoopLatch();
9597   if (!BBLatch)
9598     return nullptr;
9599 
9600   // There is a loop latch, return the incoming value if it comes from
9601   // that. This reduction pattern occasionally turns up.
9602   if (P->getIncomingBlock(0) == BBLatch) {
9603     Rdx = P->getIncomingValue(0);
9604   } else if (P->getIncomingBlock(1) == BBLatch) {
9605     Rdx = P->getIncomingValue(1);
9606   }
9607 
9608   if (Rdx && DominatedReduxValue(Rdx))
9609     return Rdx;
9610 
9611   return nullptr;
9612 }
9613 
9614 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9615   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9616     return true;
9617   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9618     return true;
9619   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9620     return true;
9621   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9622     return true;
9623   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9624     return true;
9625   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9626     return true;
9627   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9628     return true;
9629   return false;
9630 }
9631 
9632 /// Attempt to reduce a horizontal reduction.
9633 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9634 /// with reduction operators \a Root (or one of its operands) in a basic block
9635 /// \a BB, then check if it can be done. If horizontal reduction is not found
9636 /// and root instruction is a binary operation, vectorization of the operands is
9637 /// attempted.
9638 /// \returns true if a horizontal reduction was matched and reduced or operands
9639 /// of one of the binary instruction were vectorized.
9640 /// \returns false if a horizontal reduction was not matched (or not possible)
9641 /// or no vectorization of any binary operation feeding \a Root instruction was
9642 /// performed.
9643 static bool tryToVectorizeHorReductionOrInstOperands(
9644     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9645     TargetTransformInfo *TTI,
9646     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9647   if (!ShouldVectorizeHor)
9648     return false;
9649 
9650   if (!Root)
9651     return false;
9652 
9653   if (Root->getParent() != BB || isa<PHINode>(Root))
9654     return false;
9655   // Start analysis starting from Root instruction. If horizontal reduction is
9656   // found, try to vectorize it. If it is not a horizontal reduction or
9657   // vectorization is not possible or not effective, and currently analyzed
9658   // instruction is a binary operation, try to vectorize the operands, using
9659   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9660   // the same procedure considering each operand as a possible root of the
9661   // horizontal reduction.
9662   // Interrupt the process if the Root instruction itself was vectorized or all
9663   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9664   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9665   // CmpInsts so we can skip extra attempts in
9666   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9667   std::queue<std::pair<Instruction *, unsigned>> Stack;
9668   Stack.emplace(Root, 0);
9669   SmallPtrSet<Value *, 8> VisitedInstrs;
9670   SmallVector<WeakTrackingVH> PostponedInsts;
9671   bool Res = false;
9672   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9673                                      Value *&B1) -> Value * {
9674     bool IsBinop = matchRdxBop(Inst, B0, B1);
9675     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9676     if (IsBinop || IsSelect) {
9677       HorizontalReduction HorRdx;
9678       if (HorRdx.matchAssociativeReduction(P, Inst))
9679         return HorRdx.tryToReduce(R, TTI);
9680     }
9681     return nullptr;
9682   };
9683   while (!Stack.empty()) {
9684     Instruction *Inst;
9685     unsigned Level;
9686     std::tie(Inst, Level) = Stack.front();
9687     Stack.pop();
9688     // Do not try to analyze instruction that has already been vectorized.
9689     // This may happen when we vectorize instruction operands on a previous
9690     // iteration while stack was populated before that happened.
9691     if (R.isDeleted(Inst))
9692       continue;
9693     Value *B0 = nullptr, *B1 = nullptr;
9694     if (Value *V = TryToReduce(Inst, B0, B1)) {
9695       Res = true;
9696       // Set P to nullptr to avoid re-analysis of phi node in
9697       // matchAssociativeReduction function unless this is the root node.
9698       P = nullptr;
9699       if (auto *I = dyn_cast<Instruction>(V)) {
9700         // Try to find another reduction.
9701         Stack.emplace(I, Level);
9702         continue;
9703       }
9704     } else {
9705       bool IsBinop = B0 && B1;
9706       if (P && IsBinop) {
9707         Inst = dyn_cast<Instruction>(B0);
9708         if (Inst == P)
9709           Inst = dyn_cast<Instruction>(B1);
9710         if (!Inst) {
9711           // Set P to nullptr to avoid re-analysis of phi node in
9712           // matchAssociativeReduction function unless this is the root node.
9713           P = nullptr;
9714           continue;
9715         }
9716       }
9717       // Set P to nullptr to avoid re-analysis of phi node in
9718       // matchAssociativeReduction function unless this is the root node.
9719       P = nullptr;
9720       // Do not try to vectorize CmpInst operands, this is done separately.
9721       // Final attempt for binop args vectorization should happen after the loop
9722       // to try to find reductions.
9723       if (!isa<CmpInst>(Inst))
9724         PostponedInsts.push_back(Inst);
9725     }
9726 
9727     // Try to vectorize operands.
9728     // Continue analysis for the instruction from the same basic block only to
9729     // save compile time.
9730     if (++Level < RecursionMaxDepth)
9731       for (auto *Op : Inst->operand_values())
9732         if (VisitedInstrs.insert(Op).second)
9733           if (auto *I = dyn_cast<Instruction>(Op))
9734             // Do not try to vectorize CmpInst operands,  this is done
9735             // separately.
9736             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9737                 I->getParent() == BB)
9738               Stack.emplace(I, Level);
9739   }
9740   // Try to vectorized binops where reductions were not found.
9741   for (Value *V : PostponedInsts)
9742     if (auto *Inst = dyn_cast<Instruction>(V))
9743       if (!R.isDeleted(Inst))
9744         Res |= Vectorize(Inst, R);
9745   return Res;
9746 }
9747 
9748 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9749                                                  BasicBlock *BB, BoUpSLP &R,
9750                                                  TargetTransformInfo *TTI) {
9751   auto *I = dyn_cast_or_null<Instruction>(V);
9752   if (!I)
9753     return false;
9754 
9755   if (!isa<BinaryOperator>(I))
9756     P = nullptr;
9757   // Try to match and vectorize a horizontal reduction.
9758   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9759     return tryToVectorize(I, R);
9760   };
9761   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9762                                                   ExtraVectorization);
9763 }
9764 
9765 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9766                                                  BasicBlock *BB, BoUpSLP &R) {
9767   const DataLayout &DL = BB->getModule()->getDataLayout();
9768   if (!R.canMapToVector(IVI->getType(), DL))
9769     return false;
9770 
9771   SmallVector<Value *, 16> BuildVectorOpds;
9772   SmallVector<Value *, 16> BuildVectorInsts;
9773   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9774     return false;
9775 
9776   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9777   // Aggregate value is unlikely to be processed in vector register.
9778   return tryToVectorizeList(BuildVectorOpds, R);
9779 }
9780 
9781 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9782                                                    BasicBlock *BB, BoUpSLP &R) {
9783   SmallVector<Value *, 16> BuildVectorInsts;
9784   SmallVector<Value *, 16> BuildVectorOpds;
9785   SmallVector<int> Mask;
9786   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9787       (llvm::all_of(
9788            BuildVectorOpds,
9789            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9790        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9791     return false;
9792 
9793   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9794   return tryToVectorizeList(BuildVectorInsts, R);
9795 }
9796 
9797 template <typename T>
9798 static bool
9799 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9800                        function_ref<unsigned(T *)> Limit,
9801                        function_ref<bool(T *, T *)> Comparator,
9802                        function_ref<bool(T *, T *)> AreCompatible,
9803                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9804                        bool LimitForRegisterSize) {
9805   bool Changed = false;
9806   // Sort by type, parent, operands.
9807   stable_sort(Incoming, Comparator);
9808 
9809   // Try to vectorize elements base on their type.
9810   SmallVector<T *> Candidates;
9811   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9812     // Look for the next elements with the same type, parent and operand
9813     // kinds.
9814     auto *SameTypeIt = IncIt;
9815     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9816       ++SameTypeIt;
9817 
9818     // Try to vectorize them.
9819     unsigned NumElts = (SameTypeIt - IncIt);
9820     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9821                       << NumElts << ")\n");
9822     // The vectorization is a 3-state attempt:
9823     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9824     // size of maximal register at first.
9825     // 2. Try to vectorize remaining instructions with the same type, if
9826     // possible. This may result in the better vectorization results rather than
9827     // if we try just to vectorize instructions with the same/alternate opcodes.
9828     // 3. Final attempt to try to vectorize all instructions with the
9829     // same/alternate ops only, this may result in some extra final
9830     // vectorization.
9831     if (NumElts > 1 &&
9832         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9833       // Success start over because instructions might have been changed.
9834       Changed = true;
9835     } else if (NumElts < Limit(*IncIt) &&
9836                (Candidates.empty() ||
9837                 Candidates.front()->getType() == (*IncIt)->getType())) {
9838       Candidates.append(IncIt, std::next(IncIt, NumElts));
9839     }
9840     // Final attempt to vectorize instructions with the same types.
9841     if (Candidates.size() > 1 &&
9842         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9843       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
9844         // Success start over because instructions might have been changed.
9845         Changed = true;
9846       } else if (LimitForRegisterSize) {
9847         // Try to vectorize using small vectors.
9848         for (auto *It = Candidates.begin(), *End = Candidates.end();
9849              It != End;) {
9850           auto *SameTypeIt = It;
9851           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9852             ++SameTypeIt;
9853           unsigned NumElts = (SameTypeIt - It);
9854           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
9855                                             /*LimitForRegisterSize=*/false))
9856             Changed = true;
9857           It = SameTypeIt;
9858         }
9859       }
9860       Candidates.clear();
9861     }
9862 
9863     // Start over at the next instruction of a different type (or the end).
9864     IncIt = SameTypeIt;
9865   }
9866   return Changed;
9867 }
9868 
9869 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9870 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9871 /// operands. If IsCompatibility is false, function implements strict weak
9872 /// ordering relation between two cmp instructions, returning true if the first
9873 /// instruction is "less" than the second, i.e. its predicate is less than the
9874 /// predicate of the second or the operands IDs are less than the operands IDs
9875 /// of the second cmp instruction.
9876 template <bool IsCompatibility>
9877 static bool compareCmp(Value *V, Value *V2,
9878                        function_ref<bool(Instruction *)> IsDeleted) {
9879   auto *CI1 = cast<CmpInst>(V);
9880   auto *CI2 = cast<CmpInst>(V2);
9881   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9882     return false;
9883   if (CI1->getOperand(0)->getType()->getTypeID() <
9884       CI2->getOperand(0)->getType()->getTypeID())
9885     return !IsCompatibility;
9886   if (CI1->getOperand(0)->getType()->getTypeID() >
9887       CI2->getOperand(0)->getType()->getTypeID())
9888     return false;
9889   CmpInst::Predicate Pred1 = CI1->getPredicate();
9890   CmpInst::Predicate Pred2 = CI2->getPredicate();
9891   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9892   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9893   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9894   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9895   if (BasePred1 < BasePred2)
9896     return !IsCompatibility;
9897   if (BasePred1 > BasePred2)
9898     return false;
9899   // Compare operands.
9900   bool LEPreds = Pred1 <= Pred2;
9901   bool GEPreds = Pred1 >= Pred2;
9902   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
9903     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
9904     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
9905     if (Op1->getValueID() < Op2->getValueID())
9906       return !IsCompatibility;
9907     if (Op1->getValueID() > Op2->getValueID())
9908       return false;
9909     if (auto *I1 = dyn_cast<Instruction>(Op1))
9910       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
9911         if (I1->getParent() != I2->getParent())
9912           return false;
9913         InstructionsState S = getSameOpcode({I1, I2});
9914         if (S.getOpcode())
9915           continue;
9916         return false;
9917       }
9918   }
9919   return IsCompatibility;
9920 }
9921 
9922 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9923     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9924     bool AtTerminator) {
9925   bool OpsChanged = false;
9926   SmallVector<Instruction *, 4> PostponedCmps;
9927   for (auto *I : reverse(Instructions)) {
9928     if (R.isDeleted(I))
9929       continue;
9930     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9931       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9932     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9933       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9934     else if (isa<CmpInst>(I))
9935       PostponedCmps.push_back(I);
9936   }
9937   if (AtTerminator) {
9938     // Try to find reductions first.
9939     for (Instruction *I : PostponedCmps) {
9940       if (R.isDeleted(I))
9941         continue;
9942       for (Value *Op : I->operands())
9943         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9944     }
9945     // Try to vectorize operands as vector bundles.
9946     for (Instruction *I : PostponedCmps) {
9947       if (R.isDeleted(I))
9948         continue;
9949       OpsChanged |= tryToVectorize(I, R);
9950     }
9951     // Try to vectorize list of compares.
9952     // Sort by type, compare predicate, etc.
9953     auto &&CompareSorter = [&R](Value *V, Value *V2) {
9954       return compareCmp<false>(V, V2,
9955                                [&R](Instruction *I) { return R.isDeleted(I); });
9956     };
9957 
9958     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
9959       if (V1 == V2)
9960         return true;
9961       return compareCmp<true>(V1, V2,
9962                               [&R](Instruction *I) { return R.isDeleted(I); });
9963     };
9964     auto Limit = [&R](Value *V) {
9965       unsigned EltSize = R.getVectorElementSize(V);
9966       return std::max(2U, R.getMaxVecRegSize() / EltSize);
9967     };
9968 
9969     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
9970     OpsChanged |= tryToVectorizeSequence<Value>(
9971         Vals, Limit, CompareSorter, AreCompatibleCompares,
9972         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9973           // Exclude possible reductions from other blocks.
9974           bool ArePossiblyReducedInOtherBlock =
9975               any_of(Candidates, [](Value *V) {
9976                 return any_of(V->users(), [V](User *U) {
9977                   return isa<SelectInst>(U) &&
9978                          cast<SelectInst>(U)->getParent() !=
9979                              cast<Instruction>(V)->getParent();
9980                 });
9981               });
9982           if (ArePossiblyReducedInOtherBlock)
9983             return false;
9984           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9985         },
9986         /*LimitForRegisterSize=*/true);
9987     Instructions.clear();
9988   } else {
9989     // Insert in reverse order since the PostponedCmps vector was filled in
9990     // reverse order.
9991     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9992   }
9993   return OpsChanged;
9994 }
9995 
9996 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9997   bool Changed = false;
9998   SmallVector<Value *, 4> Incoming;
9999   SmallPtrSet<Value *, 16> VisitedInstrs;
10000   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10001   // node. Allows better to identify the chains that can be vectorized in the
10002   // better way.
10003   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10004   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10005     assert(isValidElementType(V1->getType()) &&
10006            isValidElementType(V2->getType()) &&
10007            "Expected vectorizable types only.");
10008     // It is fine to compare type IDs here, since we expect only vectorizable
10009     // types, like ints, floats and pointers, we don't care about other type.
10010     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10011       return true;
10012     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10013       return false;
10014     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10015     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10016     if (Opcodes1.size() < Opcodes2.size())
10017       return true;
10018     if (Opcodes1.size() > Opcodes2.size())
10019       return false;
10020     Optional<bool> ConstOrder;
10021     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10022       // Undefs are compatible with any other value.
10023       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10024         if (!ConstOrder)
10025           ConstOrder =
10026               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10027         continue;
10028       }
10029       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10030         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10031           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10032           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10033           if (!NodeI1)
10034             return NodeI2 != nullptr;
10035           if (!NodeI2)
10036             return false;
10037           assert((NodeI1 == NodeI2) ==
10038                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10039                  "Different nodes should have different DFS numbers");
10040           if (NodeI1 != NodeI2)
10041             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10042           InstructionsState S = getSameOpcode({I1, I2});
10043           if (S.getOpcode())
10044             continue;
10045           return I1->getOpcode() < I2->getOpcode();
10046         }
10047       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10048         if (!ConstOrder)
10049           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10050         continue;
10051       }
10052       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10053         return true;
10054       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10055         return false;
10056     }
10057     return ConstOrder && *ConstOrder;
10058   };
10059   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10060     if (V1 == V2)
10061       return true;
10062     if (V1->getType() != V2->getType())
10063       return false;
10064     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10065     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10066     if (Opcodes1.size() != Opcodes2.size())
10067       return false;
10068     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10069       // Undefs are compatible with any other value.
10070       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10071         continue;
10072       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10073         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10074           if (I1->getParent() != I2->getParent())
10075             return false;
10076           InstructionsState S = getSameOpcode({I1, I2});
10077           if (S.getOpcode())
10078             continue;
10079           return false;
10080         }
10081       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10082         continue;
10083       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10084         return false;
10085     }
10086     return true;
10087   };
10088   auto Limit = [&R](Value *V) {
10089     unsigned EltSize = R.getVectorElementSize(V);
10090     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10091   };
10092 
10093   bool HaveVectorizedPhiNodes = false;
10094   do {
10095     // Collect the incoming values from the PHIs.
10096     Incoming.clear();
10097     for (Instruction &I : *BB) {
10098       PHINode *P = dyn_cast<PHINode>(&I);
10099       if (!P)
10100         break;
10101 
10102       // No need to analyze deleted, vectorized and non-vectorizable
10103       // instructions.
10104       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10105           isValidElementType(P->getType()))
10106         Incoming.push_back(P);
10107     }
10108 
10109     // Find the corresponding non-phi nodes for better matching when trying to
10110     // build the tree.
10111     for (Value *V : Incoming) {
10112       SmallVectorImpl<Value *> &Opcodes =
10113           PHIToOpcodes.try_emplace(V).first->getSecond();
10114       if (!Opcodes.empty())
10115         continue;
10116       SmallVector<Value *, 4> Nodes(1, V);
10117       SmallPtrSet<Value *, 4> Visited;
10118       while (!Nodes.empty()) {
10119         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10120         if (!Visited.insert(PHI).second)
10121           continue;
10122         for (Value *V : PHI->incoming_values()) {
10123           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10124             Nodes.push_back(PHI1);
10125             continue;
10126           }
10127           Opcodes.emplace_back(V);
10128         }
10129       }
10130     }
10131 
10132     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10133         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10134         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10135           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10136         },
10137         /*LimitForRegisterSize=*/true);
10138     Changed |= HaveVectorizedPhiNodes;
10139     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10140   } while (HaveVectorizedPhiNodes);
10141 
10142   VisitedInstrs.clear();
10143 
10144   SmallVector<Instruction *, 8> PostProcessInstructions;
10145   SmallDenseSet<Instruction *, 4> KeyNodes;
10146   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10147     // Skip instructions with scalable type. The num of elements is unknown at
10148     // compile-time for scalable type.
10149     if (isa<ScalableVectorType>(it->getType()))
10150       continue;
10151 
10152     // Skip instructions marked for the deletion.
10153     if (R.isDeleted(&*it))
10154       continue;
10155     // We may go through BB multiple times so skip the one we have checked.
10156     if (!VisitedInstrs.insert(&*it).second) {
10157       if (it->use_empty() && KeyNodes.contains(&*it) &&
10158           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10159                                       it->isTerminator())) {
10160         // We would like to start over since some instructions are deleted
10161         // and the iterator may become invalid value.
10162         Changed = true;
10163         it = BB->begin();
10164         e = BB->end();
10165       }
10166       continue;
10167     }
10168 
10169     if (isa<DbgInfoIntrinsic>(it))
10170       continue;
10171 
10172     // Try to vectorize reductions that use PHINodes.
10173     if (PHINode *P = dyn_cast<PHINode>(it)) {
10174       // Check that the PHI is a reduction PHI.
10175       if (P->getNumIncomingValues() == 2) {
10176         // Try to match and vectorize a horizontal reduction.
10177         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10178                                      TTI)) {
10179           Changed = true;
10180           it = BB->begin();
10181           e = BB->end();
10182           continue;
10183         }
10184       }
10185       // Try to vectorize the incoming values of the PHI, to catch reductions
10186       // that feed into PHIs.
10187       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10188         // Skip if the incoming block is the current BB for now. Also, bypass
10189         // unreachable IR for efficiency and to avoid crashing.
10190         // TODO: Collect the skipped incoming values and try to vectorize them
10191         // after processing BB.
10192         if (BB == P->getIncomingBlock(I) ||
10193             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10194           continue;
10195 
10196         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10197                                             P->getIncomingBlock(I), R, TTI);
10198       }
10199       continue;
10200     }
10201 
10202     // Ran into an instruction without users, like terminator, or function call
10203     // with ignored return value, store. Ignore unused instructions (basing on
10204     // instruction type, except for CallInst and InvokeInst).
10205     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10206                             isa<InvokeInst>(it))) {
10207       KeyNodes.insert(&*it);
10208       bool OpsChanged = false;
10209       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10210         for (auto *V : it->operand_values()) {
10211           // Try to match and vectorize a horizontal reduction.
10212           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10213         }
10214       }
10215       // Start vectorization of post-process list of instructions from the
10216       // top-tree instructions to try to vectorize as many instructions as
10217       // possible.
10218       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10219                                                 it->isTerminator());
10220       if (OpsChanged) {
10221         // We would like to start over since some instructions are deleted
10222         // and the iterator may become invalid value.
10223         Changed = true;
10224         it = BB->begin();
10225         e = BB->end();
10226         continue;
10227       }
10228     }
10229 
10230     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10231         isa<InsertValueInst>(it))
10232       PostProcessInstructions.push_back(&*it);
10233   }
10234 
10235   return Changed;
10236 }
10237 
10238 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10239   auto Changed = false;
10240   for (auto &Entry : GEPs) {
10241     // If the getelementptr list has fewer than two elements, there's nothing
10242     // to do.
10243     if (Entry.second.size() < 2)
10244       continue;
10245 
10246     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10247                       << Entry.second.size() << ".\n");
10248 
10249     // Process the GEP list in chunks suitable for the target's supported
10250     // vector size. If a vector register can't hold 1 element, we are done. We
10251     // are trying to vectorize the index computations, so the maximum number of
10252     // elements is based on the size of the index expression, rather than the
10253     // size of the GEP itself (the target's pointer size).
10254     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10255     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10256     if (MaxVecRegSize < EltSize)
10257       continue;
10258 
10259     unsigned MaxElts = MaxVecRegSize / EltSize;
10260     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10261       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10262       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10263 
10264       // Initialize a set a candidate getelementptrs. Note that we use a
10265       // SetVector here to preserve program order. If the index computations
10266       // are vectorizable and begin with loads, we want to minimize the chance
10267       // of having to reorder them later.
10268       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10269 
10270       // Some of the candidates may have already been vectorized after we
10271       // initially collected them. If so, they are marked as deleted, so remove
10272       // them from the set of candidates.
10273       Candidates.remove_if(
10274           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10275 
10276       // Remove from the set of candidates all pairs of getelementptrs with
10277       // constant differences. Such getelementptrs are likely not good
10278       // candidates for vectorization in a bottom-up phase since one can be
10279       // computed from the other. We also ensure all candidate getelementptr
10280       // indices are unique.
10281       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10282         auto *GEPI = GEPList[I];
10283         if (!Candidates.count(GEPI))
10284           continue;
10285         auto *SCEVI = SE->getSCEV(GEPList[I]);
10286         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10287           auto *GEPJ = GEPList[J];
10288           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10289           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10290             Candidates.remove(GEPI);
10291             Candidates.remove(GEPJ);
10292           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10293             Candidates.remove(GEPJ);
10294           }
10295         }
10296       }
10297 
10298       // We break out of the above computation as soon as we know there are
10299       // fewer than two candidates remaining.
10300       if (Candidates.size() < 2)
10301         continue;
10302 
10303       // Add the single, non-constant index of each candidate to the bundle. We
10304       // ensured the indices met these constraints when we originally collected
10305       // the getelementptrs.
10306       SmallVector<Value *, 16> Bundle(Candidates.size());
10307       auto BundleIndex = 0u;
10308       for (auto *V : Candidates) {
10309         auto *GEP = cast<GetElementPtrInst>(V);
10310         auto *GEPIdx = GEP->idx_begin()->get();
10311         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10312         Bundle[BundleIndex++] = GEPIdx;
10313       }
10314 
10315       // Try and vectorize the indices. We are currently only interested in
10316       // gather-like cases of the form:
10317       //
10318       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10319       //
10320       // where the loads of "a", the loads of "b", and the subtractions can be
10321       // performed in parallel. It's likely that detecting this pattern in a
10322       // bottom-up phase will be simpler and less costly than building a
10323       // full-blown top-down phase beginning at the consecutive loads.
10324       Changed |= tryToVectorizeList(Bundle, R);
10325     }
10326   }
10327   return Changed;
10328 }
10329 
10330 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10331   bool Changed = false;
10332   // Sort by type, base pointers and values operand. Value operands must be
10333   // compatible (have the same opcode, same parent), otherwise it is
10334   // definitely not profitable to try to vectorize them.
10335   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10336     if (V->getPointerOperandType()->getTypeID() <
10337         V2->getPointerOperandType()->getTypeID())
10338       return true;
10339     if (V->getPointerOperandType()->getTypeID() >
10340         V2->getPointerOperandType()->getTypeID())
10341       return false;
10342     // UndefValues are compatible with all other values.
10343     if (isa<UndefValue>(V->getValueOperand()) ||
10344         isa<UndefValue>(V2->getValueOperand()))
10345       return false;
10346     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10347       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10348         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10349             DT->getNode(I1->getParent());
10350         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10351             DT->getNode(I2->getParent());
10352         assert(NodeI1 && "Should only process reachable instructions");
10353         assert(NodeI1 && "Should only process reachable instructions");
10354         assert((NodeI1 == NodeI2) ==
10355                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10356                "Different nodes should have different DFS numbers");
10357         if (NodeI1 != NodeI2)
10358           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10359         InstructionsState S = getSameOpcode({I1, I2});
10360         if (S.getOpcode())
10361           return false;
10362         return I1->getOpcode() < I2->getOpcode();
10363       }
10364     if (isa<Constant>(V->getValueOperand()) &&
10365         isa<Constant>(V2->getValueOperand()))
10366       return false;
10367     return V->getValueOperand()->getValueID() <
10368            V2->getValueOperand()->getValueID();
10369   };
10370 
10371   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10372     if (V1 == V2)
10373       return true;
10374     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10375       return false;
10376     // Undefs are compatible with any other value.
10377     if (isa<UndefValue>(V1->getValueOperand()) ||
10378         isa<UndefValue>(V2->getValueOperand()))
10379       return true;
10380     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10381       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10382         if (I1->getParent() != I2->getParent())
10383           return false;
10384         InstructionsState S = getSameOpcode({I1, I2});
10385         return S.getOpcode() > 0;
10386       }
10387     if (isa<Constant>(V1->getValueOperand()) &&
10388         isa<Constant>(V2->getValueOperand()))
10389       return true;
10390     return V1->getValueOperand()->getValueID() ==
10391            V2->getValueOperand()->getValueID();
10392   };
10393   auto Limit = [&R, this](StoreInst *SI) {
10394     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10395     return R.getMinVF(EltSize);
10396   };
10397 
10398   // Attempt to sort and vectorize each of the store-groups.
10399   for (auto &Pair : Stores) {
10400     if (Pair.second.size() < 2)
10401       continue;
10402 
10403     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10404                       << Pair.second.size() << ".\n");
10405 
10406     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10407       continue;
10408 
10409     Changed |= tryToVectorizeSequence<StoreInst>(
10410         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10411         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10412           return vectorizeStores(Candidates, R);
10413         },
10414         /*LimitForRegisterSize=*/false);
10415   }
10416   return Changed;
10417 }
10418 
10419 char SLPVectorizer::ID = 0;
10420 
10421 static const char lv_name[] = "SLP Vectorizer";
10422 
10423 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10424 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10425 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10426 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10427 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10428 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10429 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10430 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10431 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10432 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10433 
10434 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10435