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