xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The Look-ahead heuristic goes through the users of the bundle to calculate
168 // the users cost in getExternalUsesCost(). To avoid compilation time increase
169 // we limit the number of users visited to this value.
170 static cl::opt<unsigned> LookAheadUsersBudget(
171     "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
172     cl::desc("The maximum number of users to visit while visiting the "
173              "predecessors. This prevents compilation time increase."));
174 
175 static cl::opt<bool>
176     ViewSLPTree("view-slp-tree", cl::Hidden,
177                 cl::desc("Display the SLP trees with Graphviz"));
178 
179 // Limit the number of alias checks. The limit is chosen so that
180 // it has no negative effect on the llvm benchmarks.
181 static const unsigned AliasedCheckLimit = 10;
182 
183 // Another limit for the alias checks: The maximum distance between load/store
184 // instructions where alias checks are done.
185 // This limit is useful for very large basic blocks.
186 static const unsigned MaxMemDepDistance = 160;
187 
188 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
189 /// regions to be handled.
190 static const int MinScheduleRegionSize = 16;
191 
192 /// Predicate for the element types that the SLP vectorizer supports.
193 ///
194 /// The most important thing to filter here are types which are invalid in LLVM
195 /// vectors. We also filter target specific types which have absolutely no
196 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
197 /// avoids spending time checking the cost model and realizing that they will
198 /// be inevitably scalarized.
199 static bool isValidElementType(Type *Ty) {
200   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
201          !Ty->isPPC_FP128Ty();
202 }
203 
204 /// \returns True if the value is a constant (but not globals/constant
205 /// expressions).
206 static bool isConstant(Value *V) {
207   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
208 }
209 
210 /// Checks if \p V is one of vector-like instructions, i.e. undef,
211 /// insertelement/extractelement with constant indices for fixed vector type or
212 /// extractvalue instruction.
213 static bool isVectorLikeInstWithConstOps(Value *V) {
214   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
215       !isa<ExtractValueInst, UndefValue>(V))
216     return false;
217   auto *I = dyn_cast<Instruction>(V);
218   if (!I || isa<ExtractValueInst>(I))
219     return true;
220   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
221     return false;
222   if (isa<ExtractElementInst>(I))
223     return isConstant(I->getOperand(1));
224   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
225   return isConstant(I->getOperand(2));
226 }
227 
228 /// \returns true if all of the instructions in \p VL are in the same block or
229 /// false otherwise.
230 static bool allSameBlock(ArrayRef<Value *> VL) {
231   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
232   if (!I0)
233     return false;
234   if (all_of(VL, isVectorLikeInstWithConstOps))
235     return true;
236 
237   BasicBlock *BB = I0->getParent();
238   for (int I = 1, E = VL.size(); I < E; I++) {
239     auto *II = dyn_cast<Instruction>(VL[I]);
240     if (!II)
241       return false;
242 
243     if (BB != II->getParent())
244       return false;
245   }
246   return true;
247 }
248 
249 /// \returns True if all of the values in \p VL are constants (but not
250 /// globals/constant expressions).
251 static bool allConstant(ArrayRef<Value *> VL) {
252   // Constant expressions and globals can't be vectorized like normal integer/FP
253   // constants.
254   return all_of(VL, isConstant);
255 }
256 
257 /// \returns True if all of the values in \p VL are identical or some of them
258 /// are UndefValue.
259 static bool isSplat(ArrayRef<Value *> VL) {
260   Value *FirstNonUndef = nullptr;
261   for (Value *V : VL) {
262     if (isa<UndefValue>(V))
263       continue;
264     if (!FirstNonUndef) {
265       FirstNonUndef = V;
266       continue;
267     }
268     if (V != FirstNonUndef)
269       return false;
270   }
271   return FirstNonUndef != nullptr;
272 }
273 
274 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
275 static bool isCommutative(Instruction *I) {
276   if (auto *Cmp = dyn_cast<CmpInst>(I))
277     return Cmp->isCommutative();
278   if (auto *BO = dyn_cast<BinaryOperator>(I))
279     return BO->isCommutative();
280   // TODO: This should check for generic Instruction::isCommutative(), but
281   //       we need to confirm that the caller code correctly handles Intrinsics
282   //       for example (does not have 2 operands).
283   return false;
284 }
285 
286 /// Checks if the given value is actually an undefined constant vector.
287 static bool isUndefVector(const Value *V) {
288   if (isa<UndefValue>(V))
289     return true;
290   auto *C = dyn_cast<Constant>(V);
291   if (!C)
292     return false;
293   if (!C->containsUndefOrPoisonElement())
294     return false;
295   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
296   if (!VecTy)
297     return false;
298   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
299     if (Constant *Elem = C->getAggregateElement(I))
300       if (!isa<UndefValue>(Elem))
301         return false;
302   }
303   return true;
304 }
305 
306 /// Checks if the vector of instructions can be represented as a shuffle, like:
307 /// %x0 = extractelement <4 x i8> %x, i32 0
308 /// %x3 = extractelement <4 x i8> %x, i32 3
309 /// %y1 = extractelement <4 x i8> %y, i32 1
310 /// %y2 = extractelement <4 x i8> %y, i32 2
311 /// %x0x0 = mul i8 %x0, %x0
312 /// %x3x3 = mul i8 %x3, %x3
313 /// %y1y1 = mul i8 %y1, %y1
314 /// %y2y2 = mul i8 %y2, %y2
315 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
316 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
317 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
318 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
319 /// ret <4 x i8> %ins4
320 /// can be transformed into:
321 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
322 ///                                                         i32 6>
323 /// %2 = mul <4 x i8> %1, %1
324 /// ret <4 x i8> %2
325 /// We convert this initially to something like:
326 /// %x0 = extractelement <4 x i8> %x, i32 0
327 /// %x3 = extractelement <4 x i8> %x, i32 3
328 /// %y1 = extractelement <4 x i8> %y, i32 1
329 /// %y2 = extractelement <4 x i8> %y, i32 2
330 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
331 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
332 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
333 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
334 /// %5 = mul <4 x i8> %4, %4
335 /// %6 = extractelement <4 x i8> %5, i32 0
336 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
337 /// %7 = extractelement <4 x i8> %5, i32 1
338 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
339 /// %8 = extractelement <4 x i8> %5, i32 2
340 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
341 /// %9 = extractelement <4 x i8> %5, i32 3
342 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
343 /// ret <4 x i8> %ins4
344 /// InstCombiner transforms this into a shuffle and vector mul
345 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
346 /// TODO: Can we split off and reuse the shuffle mask detection from
347 /// TargetTransformInfo::getInstructionThroughput?
348 static Optional<TargetTransformInfo::ShuffleKind>
349 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
350   const auto *It =
351       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
352   if (It == VL.end())
353     return None;
354   auto *EI0 = cast<ExtractElementInst>(*It);
355   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
356     return None;
357   unsigned Size =
358       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
359   Value *Vec1 = nullptr;
360   Value *Vec2 = nullptr;
361   enum ShuffleMode { Unknown, Select, Permute };
362   ShuffleMode CommonShuffleMode = Unknown;
363   Mask.assign(VL.size(), UndefMaskElem);
364   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
365     // Undef can be represented as an undef element in a vector.
366     if (isa<UndefValue>(VL[I]))
367       continue;
368     auto *EI = cast<ExtractElementInst>(VL[I]);
369     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
370       return None;
371     auto *Vec = EI->getVectorOperand();
372     // We can extractelement from undef or poison vector.
373     if (isUndefVector(Vec))
374       continue;
375     // All vector operands must have the same number of vector elements.
376     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
377       return None;
378     if (isa<UndefValue>(EI->getIndexOperand()))
379       continue;
380     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
381     if (!Idx)
382       return None;
383     // Undefined behavior if Idx is negative or >= Size.
384     if (Idx->getValue().uge(Size))
385       continue;
386     unsigned IntIdx = Idx->getValue().getZExtValue();
387     Mask[I] = IntIdx;
388     // For correct shuffling we have to have at most 2 different vector operands
389     // in all extractelement instructions.
390     if (!Vec1 || Vec1 == Vec) {
391       Vec1 = Vec;
392     } else if (!Vec2 || Vec2 == Vec) {
393       Vec2 = Vec;
394       Mask[I] += Size;
395     } else {
396       return None;
397     }
398     if (CommonShuffleMode == Permute)
399       continue;
400     // If the extract index is not the same as the operation number, it is a
401     // permutation.
402     if (IntIdx != I) {
403       CommonShuffleMode = Permute;
404       continue;
405     }
406     CommonShuffleMode = Select;
407   }
408   // If we're not crossing lanes in different vectors, consider it as blending.
409   if (CommonShuffleMode == Select && Vec2)
410     return TargetTransformInfo::SK_Select;
411   // If Vec2 was never used, we have a permutation of a single vector, otherwise
412   // we have permutation of 2 vectors.
413   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
414               : TargetTransformInfo::SK_PermuteSingleSrc;
415 }
416 
417 namespace {
418 
419 /// Main data required for vectorization of instructions.
420 struct InstructionsState {
421   /// The very first instruction in the list with the main opcode.
422   Value *OpValue = nullptr;
423 
424   /// The main/alternate instruction.
425   Instruction *MainOp = nullptr;
426   Instruction *AltOp = nullptr;
427 
428   /// The main/alternate opcodes for the list of instructions.
429   unsigned getOpcode() const {
430     return MainOp ? MainOp->getOpcode() : 0;
431   }
432 
433   unsigned getAltOpcode() const {
434     return AltOp ? AltOp->getOpcode() : 0;
435   }
436 
437   /// Some of the instructions in the list have alternate opcodes.
438   bool isAltShuffle() const { return AltOp != MainOp; }
439 
440   bool isOpcodeOrAlt(Instruction *I) const {
441     unsigned CheckedOpcode = I->getOpcode();
442     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
443   }
444 
445   InstructionsState() = delete;
446   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
447       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
448 };
449 
450 } // end anonymous namespace
451 
452 /// Chooses the correct key for scheduling data. If \p Op has the same (or
453 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
454 /// OpValue.
455 static Value *isOneOf(const InstructionsState &S, Value *Op) {
456   auto *I = dyn_cast<Instruction>(Op);
457   if (I && S.isOpcodeOrAlt(I))
458     return Op;
459   return S.OpValue;
460 }
461 
462 /// \returns true if \p Opcode is allowed as part of of the main/alternate
463 /// instruction for SLP vectorization.
464 ///
465 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
466 /// "shuffled out" lane would result in division by zero.
467 static bool isValidForAlternation(unsigned Opcode) {
468   if (Instruction::isIntDivRem(Opcode))
469     return false;
470 
471   return true;
472 }
473 
474 /// \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) {
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 UnusedIndices(Sz, /*t=*/true);
635   SmallBitVector MaskedIndices(Sz);
636   for (unsigned I = 0; I < Sz; ++I) {
637     if (Order[I] < Sz)
638       UnusedIndices.reset(Order[I]);
639     else
640       MaskedIndices.set(I);
641   }
642   if (MaskedIndices.none())
643     return;
644   assert(UnusedIndices.count() == MaskedIndices.count() &&
645          "Non-synced masked/available indices.");
646   int Idx = UnusedIndices.find_first();
647   int MIdx = MaskedIndices.find_first();
648   while (MIdx >= 0) {
649     assert(Idx >= 0 && "Indices must be synced.");
650     Order[MIdx] = Idx;
651     Idx = UnusedIndices.find_next(Idx);
652     MIdx = MaskedIndices.find_next(MIdx);
653   }
654 }
655 
656 namespace llvm {
657 
658 static void inversePermutation(ArrayRef<unsigned> Indices,
659                                SmallVectorImpl<int> &Mask) {
660   Mask.clear();
661   const unsigned E = Indices.size();
662   Mask.resize(E, UndefMaskElem);
663   for (unsigned I = 0; I < E; ++I)
664     Mask[Indices[I]] = I;
665 }
666 
667 /// \returns inserting index of InsertElement or InsertValue instruction,
668 /// using Offset as base offset for index.
669 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
670   int Index = Offset;
671   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
672     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
673       auto *VT = cast<FixedVectorType>(IE->getType());
674       if (CI->getValue().uge(VT->getNumElements()))
675         return UndefMaskElem;
676       Index *= VT->getNumElements();
677       Index += CI->getZExtValue();
678       return Index;
679     }
680     if (isa<UndefValue>(IE->getOperand(2)))
681       return UndefMaskElem;
682     return None;
683   }
684 
685   auto *IV = cast<InsertValueInst>(InsertInst);
686   Type *CurrentType = IV->getType();
687   for (unsigned I : IV->indices()) {
688     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
689       Index *= ST->getNumElements();
690       CurrentType = ST->getElementType(I);
691     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
692       Index *= AT->getNumElements();
693       CurrentType = AT->getElementType();
694     } else {
695       return None;
696     }
697     Index += I;
698   }
699   return Index;
700 }
701 
702 /// Reorders the list of scalars in accordance with the given \p Order and then
703 /// the \p Mask. \p Order - is the original order of the scalars, need to
704 /// reorder scalars into an unordered state at first according to the given
705 /// order. Then the ordered scalars are shuffled once again in accordance with
706 /// the provided mask.
707 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
708                            ArrayRef<int> Mask) {
709   assert(!Mask.empty() && "Expected non-empty mask.");
710   SmallVector<Value *> Prev(Scalars.size(),
711                             UndefValue::get(Scalars.front()->getType()));
712   Prev.swap(Scalars);
713   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
714     if (Mask[I] != UndefMaskElem)
715       Scalars[Mask[I]] = Prev[I];
716 }
717 
718 namespace slpvectorizer {
719 
720 /// Bottom Up SLP Vectorizer.
721 class BoUpSLP {
722   struct TreeEntry;
723   struct ScheduleData;
724 
725 public:
726   using ValueList = SmallVector<Value *, 8>;
727   using InstrList = SmallVector<Instruction *, 16>;
728   using ValueSet = SmallPtrSet<Value *, 16>;
729   using StoreList = SmallVector<StoreInst *, 8>;
730   using ExtraValueToDebugLocsMap =
731       MapVector<Value *, SmallVector<Instruction *, 2>>;
732   using OrdersType = SmallVector<unsigned, 4>;
733 
734   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
735           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
736           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
737           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
738       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
739         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
740     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
741     // Use the vector register size specified by the target unless overridden
742     // by a command-line option.
743     // TODO: It would be better to limit the vectorization factor based on
744     //       data type rather than just register size. For example, x86 AVX has
745     //       256-bit registers, but it does not support integer operations
746     //       at that width (that requires AVX2).
747     if (MaxVectorRegSizeOption.getNumOccurrences())
748       MaxVecRegSize = MaxVectorRegSizeOption;
749     else
750       MaxVecRegSize =
751           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
752               .getFixedSize();
753 
754     if (MinVectorRegSizeOption.getNumOccurrences())
755       MinVecRegSize = MinVectorRegSizeOption;
756     else
757       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
758   }
759 
760   /// Vectorize the tree that starts with the elements in \p VL.
761   /// Returns the vectorized root.
762   Value *vectorizeTree();
763 
764   /// Vectorize the tree but with the list of externally used values \p
765   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
766   /// generated extractvalue instructions.
767   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
768 
769   /// \returns the cost incurred by unwanted spills and fills, caused by
770   /// holding live values over call sites.
771   InstructionCost getSpillCost() const;
772 
773   /// \returns the vectorization cost of the subtree that starts at \p VL.
774   /// A negative number means that this is profitable.
775   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
776 
777   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
778   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
779   void buildTree(ArrayRef<Value *> Roots,
780                  ArrayRef<Value *> UserIgnoreLst = None);
781 
782   /// Builds external uses of the vectorized scalars, i.e. the list of
783   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
784   /// ExternallyUsedValues contains additional list of external uses to handle
785   /// vectorization of reductions.
786   void
787   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
788 
789   /// Clear the internal data structures that are created by 'buildTree'.
790   void deleteTree() {
791     VectorizableTree.clear();
792     ScalarToTreeEntry.clear();
793     MustGather.clear();
794     ExternalUses.clear();
795     for (auto &Iter : BlocksSchedules) {
796       BlockScheduling *BS = Iter.second.get();
797       BS->clear();
798     }
799     MinBWs.clear();
800     InstrElementSize.clear();
801   }
802 
803   unsigned getTreeSize() const { return VectorizableTree.size(); }
804 
805   /// Perform LICM and CSE on the newly generated gather sequences.
806   void optimizeGatherSequence();
807 
808   /// Checks if the specified gather tree entry \p TE can be represented as a
809   /// shuffled vector entry + (possibly) permutation with other gathers. It
810   /// implements the checks only for possibly ordered scalars (Loads,
811   /// ExtractElement, ExtractValue), which can be part of the graph.
812   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
813 
814   /// Gets reordering data for the given tree entry. If the entry is vectorized
815   /// - just return ReorderIndices, otherwise check if the scalars can be
816   /// reordered and return the most optimal order.
817   /// \param TopToBottom If true, include the order of vectorized stores and
818   /// insertelement nodes, otherwise skip them.
819   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
820 
821   /// Reorders the current graph to the most profitable order starting from the
822   /// root node to the leaf nodes. The best order is chosen only from the nodes
823   /// of the same size (vectorization factor). Smaller nodes are considered
824   /// parts of subgraph with smaller VF and they are reordered independently. We
825   /// can make it because we still need to extend smaller nodes to the wider VF
826   /// and we can merge reordering shuffles with the widening shuffles.
827   void reorderTopToBottom();
828 
829   /// Reorders the current graph to the most profitable order starting from
830   /// leaves to the root. It allows to rotate small subgraphs and reduce the
831   /// number of reshuffles if the leaf nodes use the same order. In this case we
832   /// can merge the orders and just shuffle user node instead of shuffling its
833   /// operands. Plus, even the leaf nodes have different orders, it allows to
834   /// sink reordering in the graph closer to the root node and merge it later
835   /// during analysis.
836   void reorderBottomToTop(bool IgnoreReorder = false);
837 
838   /// \return The vector element size in bits to use when vectorizing the
839   /// expression tree ending at \p V. If V is a store, the size is the width of
840   /// the stored value. Otherwise, the size is the width of the largest loaded
841   /// value reaching V. This method is used by the vectorizer to calculate
842   /// vectorization factors.
843   unsigned getVectorElementSize(Value *V);
844 
845   /// Compute the minimum type sizes required to represent the entries in a
846   /// vectorizable tree.
847   void computeMinimumValueSizes();
848 
849   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
850   unsigned getMaxVecRegSize() const {
851     return MaxVecRegSize;
852   }
853 
854   // \returns minimum vector register size as set by cl::opt.
855   unsigned getMinVecRegSize() const {
856     return MinVecRegSize;
857   }
858 
859   unsigned getMinVF(unsigned Sz) const {
860     return std::max(2U, getMinVecRegSize() / Sz);
861   }
862 
863   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
864     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
865       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
866     return MaxVF ? MaxVF : UINT_MAX;
867   }
868 
869   /// Check if homogeneous aggregate is isomorphic to some VectorType.
870   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
871   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
872   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
873   ///
874   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
875   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
876 
877   /// \returns True if the VectorizableTree is both tiny and not fully
878   /// vectorizable. We do not vectorize such trees.
879   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
880 
881   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
882   /// can be load combined in the backend. Load combining may not be allowed in
883   /// the IR optimizer, so we do not want to alter the pattern. For example,
884   /// partially transforming a scalar bswap() pattern into vector code is
885   /// effectively impossible for the backend to undo.
886   /// TODO: If load combining is allowed in the IR optimizer, this analysis
887   ///       may not be necessary.
888   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
889 
890   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
891   /// can be load combined in the backend. Load combining may not be allowed in
892   /// the IR optimizer, so we do not want to alter the pattern. For example,
893   /// partially transforming a scalar bswap() pattern into vector code is
894   /// effectively impossible for the backend to undo.
895   /// TODO: If load combining is allowed in the IR optimizer, this analysis
896   ///       may not be necessary.
897   bool isLoadCombineCandidate() const;
898 
899   OptimizationRemarkEmitter *getORE() { return ORE; }
900 
901   /// This structure holds any data we need about the edges being traversed
902   /// during buildTree_rec(). We keep track of:
903   /// (i) the user TreeEntry index, and
904   /// (ii) the index of the edge.
905   struct EdgeInfo {
906     EdgeInfo() = default;
907     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
908         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
909     /// The user TreeEntry.
910     TreeEntry *UserTE = nullptr;
911     /// The operand index of the use.
912     unsigned EdgeIdx = UINT_MAX;
913 #ifndef NDEBUG
914     friend inline raw_ostream &operator<<(raw_ostream &OS,
915                                           const BoUpSLP::EdgeInfo &EI) {
916       EI.dump(OS);
917       return OS;
918     }
919     /// Debug print.
920     void dump(raw_ostream &OS) const {
921       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
922          << " EdgeIdx:" << EdgeIdx << "}";
923     }
924     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
925 #endif
926   };
927 
928   /// A helper data structure to hold the operands of a vector of instructions.
929   /// This supports a fixed vector length for all operand vectors.
930   class VLOperands {
931     /// For each operand we need (i) the value, and (ii) the opcode that it
932     /// would be attached to if the expression was in a left-linearized form.
933     /// This is required to avoid illegal operand reordering.
934     /// For example:
935     /// \verbatim
936     ///                         0 Op1
937     ///                         |/
938     /// Op1 Op2   Linearized    + Op2
939     ///   \ /     ---------->   |/
940     ///    -                    -
941     ///
942     /// Op1 - Op2            (0 + Op1) - Op2
943     /// \endverbatim
944     ///
945     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
946     ///
947     /// Another way to think of this is to track all the operations across the
948     /// path from the operand all the way to the root of the tree and to
949     /// calculate the operation that corresponds to this path. For example, the
950     /// path from Op2 to the root crosses the RHS of the '-', therefore the
951     /// corresponding operation is a '-' (which matches the one in the
952     /// linearized tree, as shown above).
953     ///
954     /// For lack of a better term, we refer to this operation as Accumulated
955     /// Path Operation (APO).
956     struct OperandData {
957       OperandData() = default;
958       OperandData(Value *V, bool APO, bool IsUsed)
959           : V(V), APO(APO), IsUsed(IsUsed) {}
960       /// The operand value.
961       Value *V = nullptr;
962       /// TreeEntries only allow a single opcode, or an alternate sequence of
963       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
964       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
965       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
966       /// (e.g., Add/Mul)
967       bool APO = false;
968       /// Helper data for the reordering function.
969       bool IsUsed = false;
970     };
971 
972     /// During operand reordering, we are trying to select the operand at lane
973     /// that matches best with the operand at the neighboring lane. Our
974     /// selection is based on the type of value we are looking for. For example,
975     /// if the neighboring lane has a load, we need to look for a load that is
976     /// accessing a consecutive address. These strategies are summarized in the
977     /// 'ReorderingMode' enumerator.
978     enum class ReorderingMode {
979       Load,     ///< Matching loads to consecutive memory addresses
980       Opcode,   ///< Matching instructions based on opcode (same or alternate)
981       Constant, ///< Matching constants
982       Splat,    ///< Matching the same instruction multiple times (broadcast)
983       Failed,   ///< We failed to create a vectorizable group
984     };
985 
986     using OperandDataVec = SmallVector<OperandData, 2>;
987 
988     /// A vector of operand vectors.
989     SmallVector<OperandDataVec, 4> OpsVec;
990 
991     const DataLayout &DL;
992     ScalarEvolution &SE;
993     const BoUpSLP &R;
994 
995     /// \returns the operand data at \p OpIdx and \p Lane.
996     OperandData &getData(unsigned OpIdx, unsigned Lane) {
997       return OpsVec[OpIdx][Lane];
998     }
999 
1000     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1001     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1002       return OpsVec[OpIdx][Lane];
1003     }
1004 
1005     /// Clears the used flag for all entries.
1006     void clearUsed() {
1007       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1008            OpIdx != NumOperands; ++OpIdx)
1009         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1010              ++Lane)
1011           OpsVec[OpIdx][Lane].IsUsed = false;
1012     }
1013 
1014     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1015     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1016       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1017     }
1018 
1019     // The hard-coded scores listed here are not very important, though it shall
1020     // be higher for better matches to improve the resulting cost. When
1021     // computing the scores of matching one sub-tree with another, we are
1022     // basically counting the number of values that are matching. So even if all
1023     // scores are set to 1, we would still get a decent matching result.
1024     // However, sometimes we have to break ties. For example we may have to
1025     // choose between matching loads vs matching opcodes. This is what these
1026     // scores are helping us with: they provide the order of preference. Also,
1027     // this is important if the scalar is externally used or used in another
1028     // tree entry node in the different lane.
1029 
1030     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1031     static const int ScoreConsecutiveLoads = 4;
1032     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1033     static const int ScoreReversedLoads = 3;
1034     /// ExtractElementInst from same vector and consecutive indexes.
1035     static const int ScoreConsecutiveExtracts = 4;
1036     /// ExtractElementInst from same vector and reversed indices.
1037     static const int ScoreReversedExtracts = 3;
1038     /// Constants.
1039     static const int ScoreConstants = 2;
1040     /// Instructions with the same opcode.
1041     static const int ScoreSameOpcode = 2;
1042     /// Instructions with alt opcodes (e.g, add + sub).
1043     static const int ScoreAltOpcodes = 1;
1044     /// Identical instructions (a.k.a. splat or broadcast).
1045     static const int ScoreSplat = 1;
1046     /// Matching with an undef is preferable to failing.
1047     static const int ScoreUndef = 1;
1048     /// Score for failing to find a decent match.
1049     static const int ScoreFail = 0;
1050     /// User exteranl to the vectorized code.
1051     static const int ExternalUseCost = 1;
1052     /// The user is internal but in a different lane.
1053     static const int UserInDiffLaneCost = ExternalUseCost;
1054 
1055     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1056     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1057                                ScalarEvolution &SE, int NumLanes) {
1058       if (V1 == V2)
1059         return VLOperands::ScoreSplat;
1060 
1061       auto *LI1 = dyn_cast<LoadInst>(V1);
1062       auto *LI2 = dyn_cast<LoadInst>(V2);
1063       if (LI1 && LI2) {
1064         if (LI1->getParent() != LI2->getParent())
1065           return VLOperands::ScoreFail;
1066 
1067         Optional<int> Dist = getPointersDiff(
1068             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1069             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1070         if (!Dist)
1071           return VLOperands::ScoreFail;
1072         // The distance is too large - still may be profitable to use masked
1073         // loads/gathers.
1074         if (std::abs(*Dist) > NumLanes / 2)
1075           return VLOperands::ScoreAltOpcodes;
1076         // This still will detect consecutive loads, but we might have "holes"
1077         // in some cases. It is ok for non-power-2 vectorization and may produce
1078         // better results. It should not affect current vectorization.
1079         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1080                            : VLOperands::ScoreReversedLoads;
1081       }
1082 
1083       auto *C1 = dyn_cast<Constant>(V1);
1084       auto *C2 = dyn_cast<Constant>(V2);
1085       if (C1 && C2)
1086         return VLOperands::ScoreConstants;
1087 
1088       // Extracts from consecutive indexes of the same vector better score as
1089       // the extracts could be optimized away.
1090       Value *EV1;
1091       ConstantInt *Ex1Idx;
1092       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1093         // Undefs are always profitable for extractelements.
1094         if (isa<UndefValue>(V2))
1095           return VLOperands::ScoreConsecutiveExtracts;
1096         Value *EV2 = nullptr;
1097         ConstantInt *Ex2Idx = nullptr;
1098         if (match(V2,
1099                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1100                                                          m_Undef())))) {
1101           // Undefs are always profitable for extractelements.
1102           if (!Ex2Idx)
1103             return VLOperands::ScoreConsecutiveExtracts;
1104           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1105             return VLOperands::ScoreConsecutiveExtracts;
1106           if (EV2 == EV1) {
1107             int Idx1 = Ex1Idx->getZExtValue();
1108             int Idx2 = Ex2Idx->getZExtValue();
1109             int Dist = Idx2 - Idx1;
1110             // The distance is too large - still may be profitable to use
1111             // shuffles.
1112             if (std::abs(Dist) > NumLanes / 2)
1113               return VLOperands::ScoreAltOpcodes;
1114             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1115                               : VLOperands::ScoreReversedExtracts;
1116           }
1117         }
1118       }
1119 
1120       auto *I1 = dyn_cast<Instruction>(V1);
1121       auto *I2 = dyn_cast<Instruction>(V2);
1122       if (I1 && I2) {
1123         if (I1->getParent() != I2->getParent())
1124           return VLOperands::ScoreFail;
1125         InstructionsState S = getSameOpcode({I1, I2});
1126         // Note: Only consider instructions with <= 2 operands to avoid
1127         // complexity explosion.
1128         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1129           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1130                                   : VLOperands::ScoreSameOpcode;
1131       }
1132 
1133       if (isa<UndefValue>(V2))
1134         return VLOperands::ScoreUndef;
1135 
1136       return VLOperands::ScoreFail;
1137     }
1138 
1139     /// Holds the values and their lanes that are taking part in the look-ahead
1140     /// score calculation. This is used in the external uses cost calculation.
1141     /// Need to hold all the lanes in case of splat/broadcast at least to
1142     /// correctly check for the use in the different lane.
1143     SmallDenseMap<Value *, SmallSet<int, 4>> InLookAheadValues;
1144 
1145     /// \returns the additional cost due to uses of \p LHS and \p RHS that are
1146     /// either external to the vectorized code, or require shuffling.
1147     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1148                             const std::pair<Value *, int> &RHS) {
1149       int Cost = 0;
1150       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1151       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1152         Value *V = Values[Idx].first;
1153         if (isa<Constant>(V)) {
1154           // Since this is a function pass, it doesn't make semantic sense to
1155           // walk the users of a subclass of Constant. The users could be in
1156           // another function, or even another module that happens to be in
1157           // the same LLVMContext.
1158           continue;
1159         }
1160 
1161         // Calculate the absolute lane, using the minimum relative lane of LHS
1162         // and RHS as base and Idx as the offset.
1163         int Ln = std::min(LHS.second, RHS.second) + Idx;
1164         assert(Ln >= 0 && "Bad lane calculation");
1165         unsigned UsersBudget = LookAheadUsersBudget;
1166         for (User *U : V->users()) {
1167           if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1168             // The user is in the VectorizableTree. Check if we need to insert.
1169             int UserLn = UserTE->findLaneForValue(U);
1170             assert(UserLn >= 0 && "Bad lane");
1171             // If the values are different, check just the line of the current
1172             // value. If the values are the same, need to add UserInDiffLaneCost
1173             // only if UserLn does not match both line numbers.
1174             if ((LHS.first != RHS.first && UserLn != Ln) ||
1175                 (LHS.first == RHS.first && UserLn != LHS.second &&
1176                  UserLn != RHS.second)) {
1177               Cost += UserInDiffLaneCost;
1178               break;
1179             }
1180           } else {
1181             // Check if the user is in the look-ahead code.
1182             auto It2 = InLookAheadValues.find(U);
1183             if (It2 != InLookAheadValues.end()) {
1184               // The user is in the look-ahead code. Check the lane.
1185               if (!It2->getSecond().contains(Ln)) {
1186                 Cost += UserInDiffLaneCost;
1187                 break;
1188               }
1189             } else {
1190               // The user is neither in SLP tree nor in the look-ahead code.
1191               Cost += ExternalUseCost;
1192               break;
1193             }
1194           }
1195           // Limit the number of visited uses to cap compilation time.
1196           if (--UsersBudget == 0)
1197             break;
1198         }
1199       }
1200       return Cost;
1201     }
1202 
1203     /// Go through the operands of \p LHS and \p RHS recursively until \p
1204     /// MaxLevel, and return the cummulative score. For example:
1205     /// \verbatim
1206     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1207     ///     \ /         \ /         \ /        \ /
1208     ///      +           +           +          +
1209     ///     G1          G2          G3         G4
1210     /// \endverbatim
1211     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1212     /// each level recursively, accumulating the score. It starts from matching
1213     /// the additions at level 0, then moves on to the loads (level 1). The
1214     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1215     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1216     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1217     /// Please note that the order of the operands does not matter, as we
1218     /// evaluate the score of all profitable combinations of operands. In
1219     /// other words the score of G1 and G4 is the same as G1 and G2. This
1220     /// heuristic is based on ideas described in:
1221     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1222     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1223     ///   Luís F. W. Góes
1224     int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1225                            const std::pair<Value *, int> &RHS, int CurrLevel,
1226                            int MaxLevel) {
1227 
1228       Value *V1 = LHS.first;
1229       Value *V2 = RHS.first;
1230       // Get the shallow score of V1 and V2.
1231       int ShallowScoreAtThisLevel = std::max(
1232           (int)ScoreFail, getShallowScore(V1, V2, DL, SE, getNumLanes()) -
1233                               getExternalUsesCost(LHS, RHS));
1234       int Lane1 = LHS.second;
1235       int Lane2 = RHS.second;
1236 
1237       // If reached MaxLevel,
1238       //  or if V1 and V2 are not instructions,
1239       //  or if they are SPLAT,
1240       //  or if they are not consecutive,
1241       //  or if profitable to vectorize loads or extractelements, early return
1242       //  the current cost.
1243       auto *I1 = dyn_cast<Instruction>(V1);
1244       auto *I2 = dyn_cast<Instruction>(V2);
1245       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1246           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1247           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1248             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1249            ShallowScoreAtThisLevel))
1250         return ShallowScoreAtThisLevel;
1251       assert(I1 && I2 && "Should have early exited.");
1252 
1253       // Keep track of in-tree values for determining the external-use cost.
1254       InLookAheadValues[V1].insert(Lane1);
1255       InLookAheadValues[V2].insert(Lane2);
1256 
1257       // Contains the I2 operand indexes that got matched with I1 operands.
1258       SmallSet<unsigned, 4> Op2Used;
1259 
1260       // Recursion towards the operands of I1 and I2. We are trying all possible
1261       // operand pairs, and keeping track of the best score.
1262       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1263            OpIdx1 != NumOperands1; ++OpIdx1) {
1264         // Try to pair op1I with the best operand of I2.
1265         int MaxTmpScore = 0;
1266         unsigned MaxOpIdx2 = 0;
1267         bool FoundBest = false;
1268         // If I2 is commutative try all combinations.
1269         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1270         unsigned ToIdx = isCommutative(I2)
1271                              ? I2->getNumOperands()
1272                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1273         assert(FromIdx <= ToIdx && "Bad index");
1274         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1275           // Skip operands already paired with OpIdx1.
1276           if (Op2Used.count(OpIdx2))
1277             continue;
1278           // Recursively calculate the cost at each level
1279           int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1280                                             {I2->getOperand(OpIdx2), Lane2},
1281                                             CurrLevel + 1, MaxLevel);
1282           // Look for the best score.
1283           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1284             MaxTmpScore = TmpScore;
1285             MaxOpIdx2 = OpIdx2;
1286             FoundBest = true;
1287           }
1288         }
1289         if (FoundBest) {
1290           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1291           Op2Used.insert(MaxOpIdx2);
1292           ShallowScoreAtThisLevel += MaxTmpScore;
1293         }
1294       }
1295       return ShallowScoreAtThisLevel;
1296     }
1297 
1298     /// \Returns the look-ahead score, which tells us how much the sub-trees
1299     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1300     /// score. This helps break ties in an informed way when we cannot decide on
1301     /// the order of the operands by just considering the immediate
1302     /// predecessors.
1303     int getLookAheadScore(const std::pair<Value *, int> &LHS,
1304                           const std::pair<Value *, int> &RHS) {
1305       InLookAheadValues.clear();
1306       return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1307     }
1308 
1309     // Search all operands in Ops[*][Lane] for the one that matches best
1310     // Ops[OpIdx][LastLane] and return its opreand index.
1311     // If no good match can be found, return None.
1312     Optional<unsigned>
1313     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1314                    ArrayRef<ReorderingMode> ReorderingModes) {
1315       unsigned NumOperands = getNumOperands();
1316 
1317       // The operand of the previous lane at OpIdx.
1318       Value *OpLastLane = getData(OpIdx, LastLane).V;
1319 
1320       // Our strategy mode for OpIdx.
1321       ReorderingMode RMode = ReorderingModes[OpIdx];
1322 
1323       // The linearized opcode of the operand at OpIdx, Lane.
1324       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1325 
1326       // The best operand index and its score.
1327       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1328       // are using the score to differentiate between the two.
1329       struct BestOpData {
1330         Optional<unsigned> Idx = None;
1331         unsigned Score = 0;
1332       } BestOp;
1333 
1334       // Iterate through all unused operands and look for the best.
1335       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1336         // Get the operand at Idx and Lane.
1337         OperandData &OpData = getData(Idx, Lane);
1338         Value *Op = OpData.V;
1339         bool OpAPO = OpData.APO;
1340 
1341         // Skip already selected operands.
1342         if (OpData.IsUsed)
1343           continue;
1344 
1345         // Skip if we are trying to move the operand to a position with a
1346         // different opcode in the linearized tree form. This would break the
1347         // semantics.
1348         if (OpAPO != OpIdxAPO)
1349           continue;
1350 
1351         // Look for an operand that matches the current mode.
1352         switch (RMode) {
1353         case ReorderingMode::Load:
1354         case ReorderingMode::Constant:
1355         case ReorderingMode::Opcode: {
1356           bool LeftToRight = Lane > LastLane;
1357           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1358           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1359           unsigned Score =
1360               getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1361           if (Score > BestOp.Score) {
1362             BestOp.Idx = Idx;
1363             BestOp.Score = Score;
1364           }
1365           break;
1366         }
1367         case ReorderingMode::Splat:
1368           if (Op == OpLastLane)
1369             BestOp.Idx = Idx;
1370           break;
1371         case ReorderingMode::Failed:
1372           return None;
1373         }
1374       }
1375 
1376       if (BestOp.Idx) {
1377         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1378         return BestOp.Idx;
1379       }
1380       // If we could not find a good match return None.
1381       return None;
1382     }
1383 
1384     /// Helper for reorderOperandVecs.
1385     /// \returns the lane that we should start reordering from. This is the one
1386     /// which has the least number of operands that can freely move about or
1387     /// less profitable because it already has the most optimal set of operands.
1388     unsigned getBestLaneToStartReordering() const {
1389       unsigned Min = UINT_MAX;
1390       unsigned SameOpNumber = 0;
1391       // std::pair<unsigned, unsigned> is used to implement a simple voting
1392       // algorithm and choose the lane with the least number of operands that
1393       // can freely move about or less profitable because it already has the
1394       // most optimal set of operands. The first unsigned is a counter for
1395       // voting, the second unsigned is the counter of lanes with instructions
1396       // with same/alternate opcodes and same parent basic block.
1397       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1398       // Try to be closer to the original results, if we have multiple lanes
1399       // with same cost. If 2 lanes have the same cost, use the one with the
1400       // lowest index.
1401       for (int I = getNumLanes(); I > 0; --I) {
1402         unsigned Lane = I - 1;
1403         OperandsOrderData NumFreeOpsHash =
1404             getMaxNumOperandsThatCanBeReordered(Lane);
1405         // Compare the number of operands that can move and choose the one with
1406         // the least number.
1407         if (NumFreeOpsHash.NumOfAPOs < Min) {
1408           Min = NumFreeOpsHash.NumOfAPOs;
1409           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1410           HashMap.clear();
1411           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1412         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1413                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1414           // Select the most optimal lane in terms of number of operands that
1415           // should be moved around.
1416           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1417           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1418         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1419                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1420           auto It = HashMap.find(NumFreeOpsHash.Hash);
1421           if (It == HashMap.end())
1422             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1423           else
1424             ++It->second.first;
1425         }
1426       }
1427       // Select the lane with the minimum counter.
1428       unsigned BestLane = 0;
1429       unsigned CntMin = UINT_MAX;
1430       for (const auto &Data : reverse(HashMap)) {
1431         if (Data.second.first < CntMin) {
1432           CntMin = Data.second.first;
1433           BestLane = Data.second.second;
1434         }
1435       }
1436       return BestLane;
1437     }
1438 
1439     /// Data structure that helps to reorder operands.
1440     struct OperandsOrderData {
1441       /// The best number of operands with the same APOs, which can be
1442       /// reordered.
1443       unsigned NumOfAPOs = UINT_MAX;
1444       /// Number of operands with the same/alternate instruction opcode and
1445       /// parent.
1446       unsigned NumOpsWithSameOpcodeParent = 0;
1447       /// Hash for the actual operands ordering.
1448       /// Used to count operands, actually their position id and opcode
1449       /// value. It is used in the voting mechanism to find the lane with the
1450       /// least number of operands that can freely move about or less profitable
1451       /// because it already has the most optimal set of operands. Can be
1452       /// replaced with SmallVector<unsigned> instead but hash code is faster
1453       /// and requires less memory.
1454       unsigned Hash = 0;
1455     };
1456     /// \returns the maximum number of operands that are allowed to be reordered
1457     /// for \p Lane and the number of compatible instructions(with the same
1458     /// parent/opcode). This is used as a heuristic for selecting the first lane
1459     /// to start operand reordering.
1460     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1461       unsigned CntTrue = 0;
1462       unsigned NumOperands = getNumOperands();
1463       // Operands with the same APO can be reordered. We therefore need to count
1464       // how many of them we have for each APO, like this: Cnt[APO] = x.
1465       // Since we only have two APOs, namely true and false, we can avoid using
1466       // a map. Instead we can simply count the number of operands that
1467       // correspond to one of them (in this case the 'true' APO), and calculate
1468       // the other by subtracting it from the total number of operands.
1469       // Operands with the same instruction opcode and parent are more
1470       // profitable since we don't need to move them in many cases, with a high
1471       // probability such lane already can be vectorized effectively.
1472       bool AllUndefs = true;
1473       unsigned NumOpsWithSameOpcodeParent = 0;
1474       Instruction *OpcodeI = nullptr;
1475       BasicBlock *Parent = nullptr;
1476       unsigned Hash = 0;
1477       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1478         const OperandData &OpData = getData(OpIdx, Lane);
1479         if (OpData.APO)
1480           ++CntTrue;
1481         // Use Boyer-Moore majority voting for finding the majority opcode and
1482         // the number of times it occurs.
1483         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1484           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1485               I->getParent() != Parent) {
1486             if (NumOpsWithSameOpcodeParent == 0) {
1487               NumOpsWithSameOpcodeParent = 1;
1488               OpcodeI = I;
1489               Parent = I->getParent();
1490             } else {
1491               --NumOpsWithSameOpcodeParent;
1492             }
1493           } else {
1494             ++NumOpsWithSameOpcodeParent;
1495           }
1496         }
1497         Hash = hash_combine(
1498             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1499         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1500       }
1501       if (AllUndefs)
1502         return {};
1503       OperandsOrderData Data;
1504       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1505       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1506       Data.Hash = Hash;
1507       return Data;
1508     }
1509 
1510     /// Go through the instructions in VL and append their operands.
1511     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1512       assert(!VL.empty() && "Bad VL");
1513       assert((empty() || VL.size() == getNumLanes()) &&
1514              "Expected same number of lanes");
1515       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1516       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1517       OpsVec.resize(NumOperands);
1518       unsigned NumLanes = VL.size();
1519       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1520         OpsVec[OpIdx].resize(NumLanes);
1521         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1522           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1523           // Our tree has just 3 nodes: the root and two operands.
1524           // It is therefore trivial to get the APO. We only need to check the
1525           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1526           // RHS operand. The LHS operand of both add and sub is never attached
1527           // to an inversese operation in the linearized form, therefore its APO
1528           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1529 
1530           // Since operand reordering is performed on groups of commutative
1531           // operations or alternating sequences (e.g., +, -), we can safely
1532           // tell the inverse operations by checking commutativity.
1533           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1534           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1535           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1536                                  APO, false};
1537         }
1538       }
1539     }
1540 
1541     /// \returns the number of operands.
1542     unsigned getNumOperands() const { return OpsVec.size(); }
1543 
1544     /// \returns the number of lanes.
1545     unsigned getNumLanes() const { return OpsVec[0].size(); }
1546 
1547     /// \returns the operand value at \p OpIdx and \p Lane.
1548     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1549       return getData(OpIdx, Lane).V;
1550     }
1551 
1552     /// \returns true if the data structure is empty.
1553     bool empty() const { return OpsVec.empty(); }
1554 
1555     /// Clears the data.
1556     void clear() { OpsVec.clear(); }
1557 
1558     /// \Returns true if there are enough operands identical to \p Op to fill
1559     /// the whole vector.
1560     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1561     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1562       bool OpAPO = getData(OpIdx, Lane).APO;
1563       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1564         if (Ln == Lane)
1565           continue;
1566         // This is set to true if we found a candidate for broadcast at Lane.
1567         bool FoundCandidate = false;
1568         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1569           OperandData &Data = getData(OpI, Ln);
1570           if (Data.APO != OpAPO || Data.IsUsed)
1571             continue;
1572           if (Data.V == Op) {
1573             FoundCandidate = true;
1574             Data.IsUsed = true;
1575             break;
1576           }
1577         }
1578         if (!FoundCandidate)
1579           return false;
1580       }
1581       return true;
1582     }
1583 
1584   public:
1585     /// Initialize with all the operands of the instruction vector \p RootVL.
1586     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1587                ScalarEvolution &SE, const BoUpSLP &R)
1588         : DL(DL), SE(SE), R(R) {
1589       // Append all the operands of RootVL.
1590       appendOperandsOfVL(RootVL);
1591     }
1592 
1593     /// \Returns a value vector with the operands across all lanes for the
1594     /// opearnd at \p OpIdx.
1595     ValueList getVL(unsigned OpIdx) const {
1596       ValueList OpVL(OpsVec[OpIdx].size());
1597       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1598              "Expected same num of lanes across all operands");
1599       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1600         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1601       return OpVL;
1602     }
1603 
1604     // Performs operand reordering for 2 or more operands.
1605     // The original operands are in OrigOps[OpIdx][Lane].
1606     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1607     void reorder() {
1608       unsigned NumOperands = getNumOperands();
1609       unsigned NumLanes = getNumLanes();
1610       // Each operand has its own mode. We are using this mode to help us select
1611       // the instructions for each lane, so that they match best with the ones
1612       // we have selected so far.
1613       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1614 
1615       // This is a greedy single-pass algorithm. We are going over each lane
1616       // once and deciding on the best order right away with no back-tracking.
1617       // However, in order to increase its effectiveness, we start with the lane
1618       // that has operands that can move the least. For example, given the
1619       // following lanes:
1620       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1621       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1622       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1623       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1624       // we will start at Lane 1, since the operands of the subtraction cannot
1625       // be reordered. Then we will visit the rest of the lanes in a circular
1626       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1627 
1628       // Find the first lane that we will start our search from.
1629       unsigned FirstLane = getBestLaneToStartReordering();
1630 
1631       // Initialize the modes.
1632       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1633         Value *OpLane0 = getValue(OpIdx, FirstLane);
1634         // Keep track if we have instructions with all the same opcode on one
1635         // side.
1636         if (isa<LoadInst>(OpLane0))
1637           ReorderingModes[OpIdx] = ReorderingMode::Load;
1638         else if (isa<Instruction>(OpLane0)) {
1639           // Check if OpLane0 should be broadcast.
1640           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1641             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1642           else
1643             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1644         }
1645         else if (isa<Constant>(OpLane0))
1646           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1647         else if (isa<Argument>(OpLane0))
1648           // Our best hope is a Splat. It may save some cost in some cases.
1649           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1650         else
1651           // NOTE: This should be unreachable.
1652           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1653       }
1654 
1655       // Check that we don't have same operands. No need to reorder if operands
1656       // are just perfect diamond or shuffled diamond match. Do not do it only
1657       // for possible broadcasts or non-power of 2 number of scalars (just for
1658       // now).
1659       auto &&SkipReordering = [this]() {
1660         SmallPtrSet<Value *, 4> UniqueValues;
1661         ArrayRef<OperandData> Op0 = OpsVec.front();
1662         for (const OperandData &Data : Op0)
1663           UniqueValues.insert(Data.V);
1664         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1665           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1666                 return !UniqueValues.contains(Data.V);
1667               }))
1668             return false;
1669         }
1670         // TODO: Check if we can remove a check for non-power-2 number of
1671         // scalars after full support of non-power-2 vectorization.
1672         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1673       };
1674 
1675       // If the initial strategy fails for any of the operand indexes, then we
1676       // perform reordering again in a second pass. This helps avoid assigning
1677       // high priority to the failed strategy, and should improve reordering for
1678       // the non-failed operand indexes.
1679       for (int Pass = 0; Pass != 2; ++Pass) {
1680         // Check if no need to reorder operands since they're are perfect or
1681         // shuffled diamond match.
1682         // Need to to do it to avoid extra external use cost counting for
1683         // shuffled matches, which may cause regressions.
1684         if (SkipReordering())
1685           break;
1686         // Skip the second pass if the first pass did not fail.
1687         bool StrategyFailed = false;
1688         // Mark all operand data as free to use.
1689         clearUsed();
1690         // We keep the original operand order for the FirstLane, so reorder the
1691         // rest of the lanes. We are visiting the nodes in a circular fashion,
1692         // using FirstLane as the center point and increasing the radius
1693         // distance.
1694         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1695           // Visit the lane on the right and then the lane on the left.
1696           for (int Direction : {+1, -1}) {
1697             int Lane = FirstLane + Direction * Distance;
1698             if (Lane < 0 || Lane >= (int)NumLanes)
1699               continue;
1700             int LastLane = Lane - Direction;
1701             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1702                    "Out of bounds");
1703             // Look for a good match for each operand.
1704             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1705               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1706               Optional<unsigned> BestIdx =
1707                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1708               // By not selecting a value, we allow the operands that follow to
1709               // select a better matching value. We will get a non-null value in
1710               // the next run of getBestOperand().
1711               if (BestIdx) {
1712                 // Swap the current operand with the one returned by
1713                 // getBestOperand().
1714                 swap(OpIdx, BestIdx.getValue(), Lane);
1715               } else {
1716                 // We failed to find a best operand, set mode to 'Failed'.
1717                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1718                 // Enable the second pass.
1719                 StrategyFailed = true;
1720               }
1721             }
1722           }
1723         }
1724         // Skip second pass if the strategy did not fail.
1725         if (!StrategyFailed)
1726           break;
1727       }
1728     }
1729 
1730 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1731     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1732       switch (RMode) {
1733       case ReorderingMode::Load:
1734         return "Load";
1735       case ReorderingMode::Opcode:
1736         return "Opcode";
1737       case ReorderingMode::Constant:
1738         return "Constant";
1739       case ReorderingMode::Splat:
1740         return "Splat";
1741       case ReorderingMode::Failed:
1742         return "Failed";
1743       }
1744       llvm_unreachable("Unimplemented Reordering Type");
1745     }
1746 
1747     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1748                                                    raw_ostream &OS) {
1749       return OS << getModeStr(RMode);
1750     }
1751 
1752     /// Debug print.
1753     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1754       printMode(RMode, dbgs());
1755     }
1756 
1757     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1758       return printMode(RMode, OS);
1759     }
1760 
1761     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1762       const unsigned Indent = 2;
1763       unsigned Cnt = 0;
1764       for (const OperandDataVec &OpDataVec : OpsVec) {
1765         OS << "Operand " << Cnt++ << "\n";
1766         for (const OperandData &OpData : OpDataVec) {
1767           OS.indent(Indent) << "{";
1768           if (Value *V = OpData.V)
1769             OS << *V;
1770           else
1771             OS << "null";
1772           OS << ", APO:" << OpData.APO << "}\n";
1773         }
1774         OS << "\n";
1775       }
1776       return OS;
1777     }
1778 
1779     /// Debug print.
1780     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1781 #endif
1782   };
1783 
1784   /// Checks if the instruction is marked for deletion.
1785   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1786 
1787   /// Marks values operands for later deletion by replacing them with Undefs.
1788   void eraseInstructions(ArrayRef<Value *> AV);
1789 
1790   ~BoUpSLP();
1791 
1792 private:
1793   /// Checks if all users of \p I are the part of the vectorization tree.
1794   bool areAllUsersVectorized(Instruction *I,
1795                              ArrayRef<Value *> VectorizedVals) const;
1796 
1797   /// \returns the cost of the vectorizable entry.
1798   InstructionCost getEntryCost(const TreeEntry *E,
1799                                ArrayRef<Value *> VectorizedVals);
1800 
1801   /// This is the recursive part of buildTree.
1802   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1803                      const EdgeInfo &EI);
1804 
1805   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1806   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1807   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1808   /// returns false, setting \p CurrentOrder to either an empty vector or a
1809   /// non-identity permutation that allows to reuse extract instructions.
1810   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1811                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1812 
1813   /// Vectorize a single entry in the tree.
1814   Value *vectorizeTree(TreeEntry *E);
1815 
1816   /// Vectorize a single entry in the tree, starting in \p VL.
1817   Value *vectorizeTree(ArrayRef<Value *> VL);
1818 
1819   /// \returns the scalarization cost for this type. Scalarization in this
1820   /// context means the creation of vectors from a group of scalars. If \p
1821   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1822   /// vector elements.
1823   InstructionCost getGatherCost(FixedVectorType *Ty,
1824                                 const DenseSet<unsigned> &ShuffledIndices,
1825                                 bool NeedToShuffle) const;
1826 
1827   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1828   /// tree entries.
1829   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1830   /// previous tree entries. \p Mask is filled with the shuffle mask.
1831   Optional<TargetTransformInfo::ShuffleKind>
1832   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1833                         SmallVectorImpl<const TreeEntry *> &Entries);
1834 
1835   /// \returns the scalarization cost for this list of values. Assuming that
1836   /// this subtree gets vectorized, we may need to extract the values from the
1837   /// roots. This method calculates the cost of extracting the values.
1838   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1839 
1840   /// Set the Builder insert point to one after the last instruction in
1841   /// the bundle
1842   void setInsertPointAfterBundle(const TreeEntry *E);
1843 
1844   /// \returns a vector from a collection of scalars in \p VL.
1845   Value *gather(ArrayRef<Value *> VL);
1846 
1847   /// \returns whether the VectorizableTree is fully vectorizable and will
1848   /// be beneficial even the tree height is tiny.
1849   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1850 
1851   /// Reorder commutative or alt operands to get better probability of
1852   /// generating vectorized code.
1853   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1854                                              SmallVectorImpl<Value *> &Left,
1855                                              SmallVectorImpl<Value *> &Right,
1856                                              const DataLayout &DL,
1857                                              ScalarEvolution &SE,
1858                                              const BoUpSLP &R);
1859   struct TreeEntry {
1860     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1861     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1862 
1863     /// \returns true if the scalars in VL are equal to this entry.
1864     bool isSame(ArrayRef<Value *> VL) const {
1865       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1866         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1867           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1868         return VL.size() == Mask.size() &&
1869                std::equal(VL.begin(), VL.end(), Mask.begin(),
1870                           [Scalars](Value *V, int Idx) {
1871                             return (isa<UndefValue>(V) &&
1872                                     Idx == UndefMaskElem) ||
1873                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1874                           });
1875       };
1876       if (!ReorderIndices.empty()) {
1877         // TODO: implement matching if the nodes are just reordered, still can
1878         // treat the vector as the same if the list of scalars matches VL
1879         // directly, without reordering.
1880         SmallVector<int> Mask;
1881         inversePermutation(ReorderIndices, Mask);
1882         if (VL.size() == Scalars.size())
1883           return IsSame(Scalars, Mask);
1884         if (VL.size() == ReuseShuffleIndices.size()) {
1885           ::addMask(Mask, ReuseShuffleIndices);
1886           return IsSame(Scalars, Mask);
1887         }
1888         return false;
1889       }
1890       return IsSame(Scalars, ReuseShuffleIndices);
1891     }
1892 
1893     /// \returns true if current entry has same operands as \p TE.
1894     bool hasEqualOperands(const TreeEntry &TE) const {
1895       if (TE.getNumOperands() != getNumOperands())
1896         return false;
1897       SmallBitVector Used(getNumOperands());
1898       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1899         unsigned PrevCount = Used.count();
1900         for (unsigned K = 0; K < E; ++K) {
1901           if (Used.test(K))
1902             continue;
1903           if (getOperand(K) == TE.getOperand(I)) {
1904             Used.set(K);
1905             break;
1906           }
1907         }
1908         // Check if we actually found the matching operand.
1909         if (PrevCount == Used.count())
1910           return false;
1911       }
1912       return true;
1913     }
1914 
1915     /// \return Final vectorization factor for the node. Defined by the total
1916     /// number of vectorized scalars, including those, used several times in the
1917     /// entry and counted in the \a ReuseShuffleIndices, if any.
1918     unsigned getVectorFactor() const {
1919       if (!ReuseShuffleIndices.empty())
1920         return ReuseShuffleIndices.size();
1921       return Scalars.size();
1922     };
1923 
1924     /// A vector of scalars.
1925     ValueList Scalars;
1926 
1927     /// The Scalars are vectorized into this value. It is initialized to Null.
1928     Value *VectorizedValue = nullptr;
1929 
1930     /// Do we need to gather this sequence or vectorize it
1931     /// (either with vector instruction or with scatter/gather
1932     /// intrinsics for store/load)?
1933     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
1934     EntryState State;
1935 
1936     /// Does this sequence require some shuffling?
1937     SmallVector<int, 4> ReuseShuffleIndices;
1938 
1939     /// Does this entry require reordering?
1940     SmallVector<unsigned, 4> ReorderIndices;
1941 
1942     /// Points back to the VectorizableTree.
1943     ///
1944     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
1945     /// to be a pointer and needs to be able to initialize the child iterator.
1946     /// Thus we need a reference back to the container to translate the indices
1947     /// to entries.
1948     VecTreeTy &Container;
1949 
1950     /// The TreeEntry index containing the user of this entry.  We can actually
1951     /// have multiple users so the data structure is not truly a tree.
1952     SmallVector<EdgeInfo, 1> UserTreeIndices;
1953 
1954     /// The index of this treeEntry in VectorizableTree.
1955     int Idx = -1;
1956 
1957   private:
1958     /// The operands of each instruction in each lane Operands[op_index][lane].
1959     /// Note: This helps avoid the replication of the code that performs the
1960     /// reordering of operands during buildTree_rec() and vectorizeTree().
1961     SmallVector<ValueList, 2> Operands;
1962 
1963     /// The main/alternate instruction.
1964     Instruction *MainOp = nullptr;
1965     Instruction *AltOp = nullptr;
1966 
1967   public:
1968     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1969     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
1970       if (Operands.size() < OpIdx + 1)
1971         Operands.resize(OpIdx + 1);
1972       assert(Operands[OpIdx].empty() && "Already resized?");
1973       assert(OpVL.size() <= Scalars.size() &&
1974              "Number of operands is greater than the number of scalars.");
1975       Operands[OpIdx].resize(OpVL.size());
1976       copy(OpVL, Operands[OpIdx].begin());
1977     }
1978 
1979     /// Set the operands of this bundle in their original order.
1980     void setOperandsInOrder() {
1981       assert(Operands.empty() && "Already initialized?");
1982       auto *I0 = cast<Instruction>(Scalars[0]);
1983       Operands.resize(I0->getNumOperands());
1984       unsigned NumLanes = Scalars.size();
1985       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1986            OpIdx != NumOperands; ++OpIdx) {
1987         Operands[OpIdx].resize(NumLanes);
1988         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1989           auto *I = cast<Instruction>(Scalars[Lane]);
1990           assert(I->getNumOperands() == NumOperands &&
1991                  "Expected same number of operands");
1992           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
1993         }
1994       }
1995     }
1996 
1997     /// Reorders operands of the node to the given mask \p Mask.
1998     void reorderOperands(ArrayRef<int> Mask) {
1999       for (ValueList &Operand : Operands)
2000         reorderScalars(Operand, Mask);
2001     }
2002 
2003     /// \returns the \p OpIdx operand of this TreeEntry.
2004     ValueList &getOperand(unsigned OpIdx) {
2005       assert(OpIdx < Operands.size() && "Off bounds");
2006       return Operands[OpIdx];
2007     }
2008 
2009     /// \returns the \p OpIdx operand of this TreeEntry.
2010     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2011       assert(OpIdx < Operands.size() && "Off bounds");
2012       return Operands[OpIdx];
2013     }
2014 
2015     /// \returns the number of operands.
2016     unsigned getNumOperands() const { return Operands.size(); }
2017 
2018     /// \return the single \p OpIdx operand.
2019     Value *getSingleOperand(unsigned OpIdx) const {
2020       assert(OpIdx < Operands.size() && "Off bounds");
2021       assert(!Operands[OpIdx].empty() && "No operand available");
2022       return Operands[OpIdx][0];
2023     }
2024 
2025     /// Some of the instructions in the list have alternate opcodes.
2026     bool isAltShuffle() const { return MainOp != AltOp; }
2027 
2028     bool isOpcodeOrAlt(Instruction *I) const {
2029       unsigned CheckedOpcode = I->getOpcode();
2030       return (getOpcode() == CheckedOpcode ||
2031               getAltOpcode() == CheckedOpcode);
2032     }
2033 
2034     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2035     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2036     /// \p OpValue.
2037     Value *isOneOf(Value *Op) const {
2038       auto *I = dyn_cast<Instruction>(Op);
2039       if (I && isOpcodeOrAlt(I))
2040         return Op;
2041       return MainOp;
2042     }
2043 
2044     void setOperations(const InstructionsState &S) {
2045       MainOp = S.MainOp;
2046       AltOp = S.AltOp;
2047     }
2048 
2049     Instruction *getMainOp() const {
2050       return MainOp;
2051     }
2052 
2053     Instruction *getAltOp() const {
2054       return AltOp;
2055     }
2056 
2057     /// The main/alternate opcodes for the list of instructions.
2058     unsigned getOpcode() const {
2059       return MainOp ? MainOp->getOpcode() : 0;
2060     }
2061 
2062     unsigned getAltOpcode() const {
2063       return AltOp ? AltOp->getOpcode() : 0;
2064     }
2065 
2066     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2067     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2068     int findLaneForValue(Value *V) const {
2069       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2070       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2071       if (!ReorderIndices.empty())
2072         FoundLane = ReorderIndices[FoundLane];
2073       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2074       if (!ReuseShuffleIndices.empty()) {
2075         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2076                                   find(ReuseShuffleIndices, FoundLane));
2077       }
2078       return FoundLane;
2079     }
2080 
2081 #ifndef NDEBUG
2082     /// Debug printer.
2083     LLVM_DUMP_METHOD void dump() const {
2084       dbgs() << Idx << ".\n";
2085       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2086         dbgs() << "Operand " << OpI << ":\n";
2087         for (const Value *V : Operands[OpI])
2088           dbgs().indent(2) << *V << "\n";
2089       }
2090       dbgs() << "Scalars: \n";
2091       for (Value *V : Scalars)
2092         dbgs().indent(2) << *V << "\n";
2093       dbgs() << "State: ";
2094       switch (State) {
2095       case Vectorize:
2096         dbgs() << "Vectorize\n";
2097         break;
2098       case ScatterVectorize:
2099         dbgs() << "ScatterVectorize\n";
2100         break;
2101       case NeedToGather:
2102         dbgs() << "NeedToGather\n";
2103         break;
2104       }
2105       dbgs() << "MainOp: ";
2106       if (MainOp)
2107         dbgs() << *MainOp << "\n";
2108       else
2109         dbgs() << "NULL\n";
2110       dbgs() << "AltOp: ";
2111       if (AltOp)
2112         dbgs() << *AltOp << "\n";
2113       else
2114         dbgs() << "NULL\n";
2115       dbgs() << "VectorizedValue: ";
2116       if (VectorizedValue)
2117         dbgs() << *VectorizedValue << "\n";
2118       else
2119         dbgs() << "NULL\n";
2120       dbgs() << "ReuseShuffleIndices: ";
2121       if (ReuseShuffleIndices.empty())
2122         dbgs() << "Empty";
2123       else
2124         for (int ReuseIdx : ReuseShuffleIndices)
2125           dbgs() << ReuseIdx << ", ";
2126       dbgs() << "\n";
2127       dbgs() << "ReorderIndices: ";
2128       for (unsigned ReorderIdx : ReorderIndices)
2129         dbgs() << ReorderIdx << ", ";
2130       dbgs() << "\n";
2131       dbgs() << "UserTreeIndices: ";
2132       for (const auto &EInfo : UserTreeIndices)
2133         dbgs() << EInfo << ", ";
2134       dbgs() << "\n";
2135     }
2136 #endif
2137   };
2138 
2139 #ifndef NDEBUG
2140   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2141                      InstructionCost VecCost,
2142                      InstructionCost ScalarCost) const {
2143     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2144     dbgs() << "SLP: Costs:\n";
2145     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2146     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2147     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2148     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2149                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2150   }
2151 #endif
2152 
2153   /// Create a new VectorizableTree entry.
2154   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2155                           const InstructionsState &S,
2156                           const EdgeInfo &UserTreeIdx,
2157                           ArrayRef<int> ReuseShuffleIndices = None,
2158                           ArrayRef<unsigned> ReorderIndices = None) {
2159     TreeEntry::EntryState EntryState =
2160         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2161     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2162                         ReuseShuffleIndices, ReorderIndices);
2163   }
2164 
2165   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2166                           TreeEntry::EntryState EntryState,
2167                           Optional<ScheduleData *> Bundle,
2168                           const InstructionsState &S,
2169                           const EdgeInfo &UserTreeIdx,
2170                           ArrayRef<int> ReuseShuffleIndices = None,
2171                           ArrayRef<unsigned> ReorderIndices = None) {
2172     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2173             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2174            "Need to vectorize gather entry?");
2175     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2176     TreeEntry *Last = VectorizableTree.back().get();
2177     Last->Idx = VectorizableTree.size() - 1;
2178     Last->State = EntryState;
2179     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2180                                      ReuseShuffleIndices.end());
2181     if (ReorderIndices.empty()) {
2182       Last->Scalars.assign(VL.begin(), VL.end());
2183       Last->setOperations(S);
2184     } else {
2185       // Reorder scalars and build final mask.
2186       Last->Scalars.assign(VL.size(), nullptr);
2187       transform(ReorderIndices, Last->Scalars.begin(),
2188                 [VL](unsigned Idx) -> Value * {
2189                   if (Idx >= VL.size())
2190                     return UndefValue::get(VL.front()->getType());
2191                   return VL[Idx];
2192                 });
2193       InstructionsState S = getSameOpcode(Last->Scalars);
2194       Last->setOperations(S);
2195       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2196     }
2197     if (Last->State != TreeEntry::NeedToGather) {
2198       for (Value *V : VL) {
2199         assert(!getTreeEntry(V) && "Scalar already in tree!");
2200         ScalarToTreeEntry[V] = Last;
2201       }
2202       // Update the scheduler bundle to point to this TreeEntry.
2203       unsigned Lane = 0;
2204       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2205            BundleMember = BundleMember->NextInBundle) {
2206         BundleMember->TE = Last;
2207         BundleMember->Lane = Lane;
2208         ++Lane;
2209       }
2210       assert((!Bundle.getValue() || Lane == VL.size()) &&
2211              "Bundle and VL out of sync");
2212     } else {
2213       MustGather.insert(VL.begin(), VL.end());
2214     }
2215 
2216     if (UserTreeIdx.UserTE)
2217       Last->UserTreeIndices.push_back(UserTreeIdx);
2218 
2219     return Last;
2220   }
2221 
2222   /// -- Vectorization State --
2223   /// Holds all of the tree entries.
2224   TreeEntry::VecTreeTy VectorizableTree;
2225 
2226 #ifndef NDEBUG
2227   /// Debug printer.
2228   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2229     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2230       VectorizableTree[Id]->dump();
2231       dbgs() << "\n";
2232     }
2233   }
2234 #endif
2235 
2236   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2237 
2238   const TreeEntry *getTreeEntry(Value *V) const {
2239     return ScalarToTreeEntry.lookup(V);
2240   }
2241 
2242   /// Maps a specific scalar to its tree entry.
2243   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2244 
2245   /// Maps a value to the proposed vectorizable size.
2246   SmallDenseMap<Value *, unsigned> InstrElementSize;
2247 
2248   /// A list of scalars that we found that we need to keep as scalars.
2249   ValueSet MustGather;
2250 
2251   /// This POD struct describes one external user in the vectorized tree.
2252   struct ExternalUser {
2253     ExternalUser(Value *S, llvm::User *U, int L)
2254         : Scalar(S), User(U), Lane(L) {}
2255 
2256     // Which scalar in our function.
2257     Value *Scalar;
2258 
2259     // Which user that uses the scalar.
2260     llvm::User *User;
2261 
2262     // Which lane does the scalar belong to.
2263     int Lane;
2264   };
2265   using UserList = SmallVector<ExternalUser, 16>;
2266 
2267   /// Checks if two instructions may access the same memory.
2268   ///
2269   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2270   /// is invariant in the calling loop.
2271   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2272                  Instruction *Inst2) {
2273     // First check if the result is already in the cache.
2274     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2275     Optional<bool> &result = AliasCache[key];
2276     if (result.hasValue()) {
2277       return result.getValue();
2278     }
2279     bool aliased = true;
2280     if (Loc1.Ptr && isSimple(Inst1))
2281       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2282     // Store the result in the cache.
2283     result = aliased;
2284     return aliased;
2285   }
2286 
2287   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2288 
2289   /// Cache for alias results.
2290   /// TODO: consider moving this to the AliasAnalysis itself.
2291   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2292 
2293   /// Removes an instruction from its block and eventually deletes it.
2294   /// It's like Instruction::eraseFromParent() except that the actual deletion
2295   /// is delayed until BoUpSLP is destructed.
2296   /// This is required to ensure that there are no incorrect collisions in the
2297   /// AliasCache, which can happen if a new instruction is allocated at the
2298   /// same address as a previously deleted instruction.
2299   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2300     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2301     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2302   }
2303 
2304   /// Temporary store for deleted instructions. Instructions will be deleted
2305   /// eventually when the BoUpSLP is destructed.
2306   DenseMap<Instruction *, bool> DeletedInstructions;
2307 
2308   /// A list of values that need to extracted out of the tree.
2309   /// This list holds pairs of (Internal Scalar : External User). External User
2310   /// can be nullptr, it means that this Internal Scalar will be used later,
2311   /// after vectorization.
2312   UserList ExternalUses;
2313 
2314   /// Values used only by @llvm.assume calls.
2315   SmallPtrSet<const Value *, 32> EphValues;
2316 
2317   /// Holds all of the instructions that we gathered.
2318   SetVector<Instruction *> GatherShuffleSeq;
2319 
2320   /// A list of blocks that we are going to CSE.
2321   SetVector<BasicBlock *> CSEBlocks;
2322 
2323   /// Contains all scheduling relevant data for an instruction.
2324   /// A ScheduleData either represents a single instruction or a member of an
2325   /// instruction bundle (= a group of instructions which is combined into a
2326   /// vector instruction).
2327   struct ScheduleData {
2328     // The initial value for the dependency counters. It means that the
2329     // dependencies are not calculated yet.
2330     enum { InvalidDeps = -1 };
2331 
2332     ScheduleData() = default;
2333 
2334     void init(int BlockSchedulingRegionID, Value *OpVal) {
2335       FirstInBundle = this;
2336       NextInBundle = nullptr;
2337       NextLoadStore = nullptr;
2338       IsScheduled = false;
2339       SchedulingRegionID = BlockSchedulingRegionID;
2340       UnscheduledDepsInBundle = UnscheduledDeps;
2341       clearDependencies();
2342       OpValue = OpVal;
2343       TE = nullptr;
2344       Lane = -1;
2345     }
2346 
2347     /// Returns true if the dependency information has been calculated.
2348     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2349 
2350     /// Returns true for single instructions and for bundle representatives
2351     /// (= the head of a bundle).
2352     bool isSchedulingEntity() const { return FirstInBundle == this; }
2353 
2354     /// Returns true if it represents an instruction bundle and not only a
2355     /// single instruction.
2356     bool isPartOfBundle() const {
2357       return NextInBundle != nullptr || FirstInBundle != this;
2358     }
2359 
2360     /// Returns true if it is ready for scheduling, i.e. it has no more
2361     /// unscheduled depending instructions/bundles.
2362     bool isReady() const {
2363       assert(isSchedulingEntity() &&
2364              "can't consider non-scheduling entity for ready list");
2365       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2366     }
2367 
2368     /// Modifies the number of unscheduled dependencies, also updating it for
2369     /// the whole bundle.
2370     int incrementUnscheduledDeps(int Incr) {
2371       UnscheduledDeps += Incr;
2372       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2373     }
2374 
2375     /// Sets the number of unscheduled dependencies to the number of
2376     /// dependencies.
2377     void resetUnscheduledDeps() {
2378       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2379     }
2380 
2381     /// Clears all dependency information.
2382     void clearDependencies() {
2383       Dependencies = InvalidDeps;
2384       resetUnscheduledDeps();
2385       MemoryDependencies.clear();
2386     }
2387 
2388     void dump(raw_ostream &os) const {
2389       if (!isSchedulingEntity()) {
2390         os << "/ " << *Inst;
2391       } else if (NextInBundle) {
2392         os << '[' << *Inst;
2393         ScheduleData *SD = NextInBundle;
2394         while (SD) {
2395           os << ';' << *SD->Inst;
2396           SD = SD->NextInBundle;
2397         }
2398         os << ']';
2399       } else {
2400         os << *Inst;
2401       }
2402     }
2403 
2404     Instruction *Inst = nullptr;
2405 
2406     /// Points to the head in an instruction bundle (and always to this for
2407     /// single instructions).
2408     ScheduleData *FirstInBundle = nullptr;
2409 
2410     /// Single linked list of all instructions in a bundle. Null if it is a
2411     /// single instruction.
2412     ScheduleData *NextInBundle = nullptr;
2413 
2414     /// Single linked list of all memory instructions (e.g. load, store, call)
2415     /// in the block - until the end of the scheduling region.
2416     ScheduleData *NextLoadStore = nullptr;
2417 
2418     /// The dependent memory instructions.
2419     /// This list is derived on demand in calculateDependencies().
2420     SmallVector<ScheduleData *, 4> MemoryDependencies;
2421 
2422     /// This ScheduleData is in the current scheduling region if this matches
2423     /// the current SchedulingRegionID of BlockScheduling.
2424     int SchedulingRegionID = 0;
2425 
2426     /// Used for getting a "good" final ordering of instructions.
2427     int SchedulingPriority = 0;
2428 
2429     /// The number of dependencies. Constitutes of the number of users of the
2430     /// instruction plus the number of dependent memory instructions (if any).
2431     /// This value is calculated on demand.
2432     /// If InvalidDeps, the number of dependencies is not calculated yet.
2433     int Dependencies = InvalidDeps;
2434 
2435     /// The number of dependencies minus the number of dependencies of scheduled
2436     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2437     /// for scheduling.
2438     /// Note that this is negative as long as Dependencies is not calculated.
2439     int UnscheduledDeps = InvalidDeps;
2440 
2441     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2442     /// single instructions.
2443     int UnscheduledDepsInBundle = InvalidDeps;
2444 
2445     /// True if this instruction is scheduled (or considered as scheduled in the
2446     /// dry-run).
2447     bool IsScheduled = false;
2448 
2449     /// Opcode of the current instruction in the schedule data.
2450     Value *OpValue = nullptr;
2451 
2452     /// The TreeEntry that this instruction corresponds to.
2453     TreeEntry *TE = nullptr;
2454 
2455     /// The lane of this node in the TreeEntry.
2456     int Lane = -1;
2457   };
2458 
2459 #ifndef NDEBUG
2460   friend inline raw_ostream &operator<<(raw_ostream &os,
2461                                         const BoUpSLP::ScheduleData &SD) {
2462     SD.dump(os);
2463     return os;
2464   }
2465 #endif
2466 
2467   friend struct GraphTraits<BoUpSLP *>;
2468   friend struct DOTGraphTraits<BoUpSLP *>;
2469 
2470   /// Contains all scheduling data for a basic block.
2471   struct BlockScheduling {
2472     BlockScheduling(BasicBlock *BB)
2473         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2474 
2475     void clear() {
2476       ReadyInsts.clear();
2477       ScheduleStart = nullptr;
2478       ScheduleEnd = nullptr;
2479       FirstLoadStoreInRegion = nullptr;
2480       LastLoadStoreInRegion = nullptr;
2481 
2482       // Reduce the maximum schedule region size by the size of the
2483       // previous scheduling run.
2484       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2485       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2486         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2487       ScheduleRegionSize = 0;
2488 
2489       // Make a new scheduling region, i.e. all existing ScheduleData is not
2490       // in the new region yet.
2491       ++SchedulingRegionID;
2492     }
2493 
2494     ScheduleData *getScheduleData(Value *V) {
2495       ScheduleData *SD = ScheduleDataMap[V];
2496       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2497         return SD;
2498       return nullptr;
2499     }
2500 
2501     ScheduleData *getScheduleData(Value *V, Value *Key) {
2502       if (V == Key)
2503         return getScheduleData(V);
2504       auto I = ExtraScheduleDataMap.find(V);
2505       if (I != ExtraScheduleDataMap.end()) {
2506         ScheduleData *SD = I->second[Key];
2507         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2508           return SD;
2509       }
2510       return nullptr;
2511     }
2512 
2513     bool isInSchedulingRegion(ScheduleData *SD) const {
2514       return SD->SchedulingRegionID == SchedulingRegionID;
2515     }
2516 
2517     /// Marks an instruction as scheduled and puts all dependent ready
2518     /// instructions into the ready-list.
2519     template <typename ReadyListType>
2520     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2521       SD->IsScheduled = true;
2522       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2523 
2524       for (ScheduleData *BundleMember = SD; BundleMember;
2525            BundleMember = BundleMember->NextInBundle) {
2526         if (BundleMember->Inst != BundleMember->OpValue)
2527           continue;
2528 
2529         // Handle the def-use chain dependencies.
2530 
2531         // Decrement the unscheduled counter and insert to ready list if ready.
2532         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2533           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2534             if (OpDef && OpDef->hasValidDependencies() &&
2535                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2536               // There are no more unscheduled dependencies after
2537               // decrementing, so we can put the dependent instruction
2538               // into the ready list.
2539               ScheduleData *DepBundle = OpDef->FirstInBundle;
2540               assert(!DepBundle->IsScheduled &&
2541                      "already scheduled bundle gets ready");
2542               ReadyList.insert(DepBundle);
2543               LLVM_DEBUG(dbgs()
2544                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2545             }
2546           });
2547         };
2548 
2549         // If BundleMember is a vector bundle, its operands may have been
2550         // reordered duiring buildTree(). We therefore need to get its operands
2551         // through the TreeEntry.
2552         if (TreeEntry *TE = BundleMember->TE) {
2553           int Lane = BundleMember->Lane;
2554           assert(Lane >= 0 && "Lane not set");
2555 
2556           // Since vectorization tree is being built recursively this assertion
2557           // ensures that the tree entry has all operands set before reaching
2558           // this code. Couple of exceptions known at the moment are extracts
2559           // where their second (immediate) operand is not added. Since
2560           // immediates do not affect scheduler behavior this is considered
2561           // okay.
2562           auto *In = TE->getMainOp();
2563           assert(In &&
2564                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2565                   In->getNumOperands() == TE->getNumOperands()) &&
2566                  "Missed TreeEntry operands?");
2567           (void)In; // fake use to avoid build failure when assertions disabled
2568 
2569           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2570                OpIdx != NumOperands; ++OpIdx)
2571             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2572               DecrUnsched(I);
2573         } else {
2574           // If BundleMember is a stand-alone instruction, no operand reordering
2575           // has taken place, so we directly access its operands.
2576           for (Use &U : BundleMember->Inst->operands())
2577             if (auto *I = dyn_cast<Instruction>(U.get()))
2578               DecrUnsched(I);
2579         }
2580         // Handle the memory dependencies.
2581         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2582           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2583             // There are no more unscheduled dependencies after decrementing,
2584             // so we can put the dependent instruction into the ready list.
2585             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2586             assert(!DepBundle->IsScheduled &&
2587                    "already scheduled bundle gets ready");
2588             ReadyList.insert(DepBundle);
2589             LLVM_DEBUG(dbgs()
2590                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2591           }
2592         }
2593       }
2594     }
2595 
2596     void doForAllOpcodes(Value *V,
2597                          function_ref<void(ScheduleData *SD)> Action) {
2598       if (ScheduleData *SD = getScheduleData(V))
2599         Action(SD);
2600       auto I = ExtraScheduleDataMap.find(V);
2601       if (I != ExtraScheduleDataMap.end())
2602         for (auto &P : I->second)
2603           if (P.second->SchedulingRegionID == SchedulingRegionID)
2604             Action(P.second);
2605     }
2606 
2607     /// Put all instructions into the ReadyList which are ready for scheduling.
2608     template <typename ReadyListType>
2609     void initialFillReadyList(ReadyListType &ReadyList) {
2610       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2611         doForAllOpcodes(I, [&](ScheduleData *SD) {
2612           if (SD->isSchedulingEntity() && SD->isReady()) {
2613             ReadyList.insert(SD);
2614             LLVM_DEBUG(dbgs()
2615                        << "SLP:    initially in ready list: " << *I << "\n");
2616           }
2617         });
2618       }
2619     }
2620 
2621     /// Build a bundle from the ScheduleData nodes corresponding to the
2622     /// scalar instruction for each lane.
2623     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2624 
2625     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2626     /// cyclic dependencies. This is only a dry-run, no instructions are
2627     /// actually moved at this stage.
2628     /// \returns the scheduling bundle. The returned Optional value is non-None
2629     /// if \p VL is allowed to be scheduled.
2630     Optional<ScheduleData *>
2631     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2632                       const InstructionsState &S);
2633 
2634     /// Un-bundles a group of instructions.
2635     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2636 
2637     /// Allocates schedule data chunk.
2638     ScheduleData *allocateScheduleDataChunks();
2639 
2640     /// Extends the scheduling region so that V is inside the region.
2641     /// \returns true if the region size is within the limit.
2642     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2643 
2644     /// Initialize the ScheduleData structures for new instructions in the
2645     /// scheduling region.
2646     void initScheduleData(Instruction *FromI, Instruction *ToI,
2647                           ScheduleData *PrevLoadStore,
2648                           ScheduleData *NextLoadStore);
2649 
2650     /// Updates the dependency information of a bundle and of all instructions/
2651     /// bundles which depend on the original bundle.
2652     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2653                                BoUpSLP *SLP);
2654 
2655     /// Sets all instruction in the scheduling region to un-scheduled.
2656     void resetSchedule();
2657 
2658     BasicBlock *BB;
2659 
2660     /// Simple memory allocation for ScheduleData.
2661     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2662 
2663     /// The size of a ScheduleData array in ScheduleDataChunks.
2664     int ChunkSize;
2665 
2666     /// The allocator position in the current chunk, which is the last entry
2667     /// of ScheduleDataChunks.
2668     int ChunkPos;
2669 
2670     /// Attaches ScheduleData to Instruction.
2671     /// Note that the mapping survives during all vectorization iterations, i.e.
2672     /// ScheduleData structures are recycled.
2673     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2674 
2675     /// Attaches ScheduleData to Instruction with the leading key.
2676     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2677         ExtraScheduleDataMap;
2678 
2679     struct ReadyList : SmallVector<ScheduleData *, 8> {
2680       void insert(ScheduleData *SD) { push_back(SD); }
2681     };
2682 
2683     /// The ready-list for scheduling (only used for the dry-run).
2684     ReadyList ReadyInsts;
2685 
2686     /// The first instruction of the scheduling region.
2687     Instruction *ScheduleStart = nullptr;
2688 
2689     /// The first instruction _after_ the scheduling region.
2690     Instruction *ScheduleEnd = nullptr;
2691 
2692     /// The first memory accessing instruction in the scheduling region
2693     /// (can be null).
2694     ScheduleData *FirstLoadStoreInRegion = nullptr;
2695 
2696     /// The last memory accessing instruction in the scheduling region
2697     /// (can be null).
2698     ScheduleData *LastLoadStoreInRegion = nullptr;
2699 
2700     /// The current size of the scheduling region.
2701     int ScheduleRegionSize = 0;
2702 
2703     /// The maximum size allowed for the scheduling region.
2704     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2705 
2706     /// The ID of the scheduling region. For a new vectorization iteration this
2707     /// is incremented which "removes" all ScheduleData from the region.
2708     // Make sure that the initial SchedulingRegionID is greater than the
2709     // initial SchedulingRegionID in ScheduleData (which is 0).
2710     int SchedulingRegionID = 1;
2711   };
2712 
2713   /// Attaches the BlockScheduling structures to basic blocks.
2714   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2715 
2716   /// Performs the "real" scheduling. Done before vectorization is actually
2717   /// performed in a basic block.
2718   void scheduleBlock(BlockScheduling *BS);
2719 
2720   /// List of users to ignore during scheduling and that don't need extracting.
2721   ArrayRef<Value *> UserIgnoreList;
2722 
2723   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2724   /// sorted SmallVectors of unsigned.
2725   struct OrdersTypeDenseMapInfo {
2726     static OrdersType getEmptyKey() {
2727       OrdersType V;
2728       V.push_back(~1U);
2729       return V;
2730     }
2731 
2732     static OrdersType getTombstoneKey() {
2733       OrdersType V;
2734       V.push_back(~2U);
2735       return V;
2736     }
2737 
2738     static unsigned getHashValue(const OrdersType &V) {
2739       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2740     }
2741 
2742     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2743       return LHS == RHS;
2744     }
2745   };
2746 
2747   // Analysis and block reference.
2748   Function *F;
2749   ScalarEvolution *SE;
2750   TargetTransformInfo *TTI;
2751   TargetLibraryInfo *TLI;
2752   AAResults *AA;
2753   LoopInfo *LI;
2754   DominatorTree *DT;
2755   AssumptionCache *AC;
2756   DemandedBits *DB;
2757   const DataLayout *DL;
2758   OptimizationRemarkEmitter *ORE;
2759 
2760   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2761   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2762 
2763   /// Instruction builder to construct the vectorized tree.
2764   IRBuilder<> Builder;
2765 
2766   /// A map of scalar integer values to the smallest bit width with which they
2767   /// can legally be represented. The values map to (width, signed) pairs,
2768   /// where "width" indicates the minimum bit width and "signed" is True if the
2769   /// value must be signed-extended, rather than zero-extended, back to its
2770   /// original width.
2771   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2772 };
2773 
2774 } // end namespace slpvectorizer
2775 
2776 template <> struct GraphTraits<BoUpSLP *> {
2777   using TreeEntry = BoUpSLP::TreeEntry;
2778 
2779   /// NodeRef has to be a pointer per the GraphWriter.
2780   using NodeRef = TreeEntry *;
2781 
2782   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2783 
2784   /// Add the VectorizableTree to the index iterator to be able to return
2785   /// TreeEntry pointers.
2786   struct ChildIteratorType
2787       : public iterator_adaptor_base<
2788             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2789     ContainerTy &VectorizableTree;
2790 
2791     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2792                       ContainerTy &VT)
2793         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2794 
2795     NodeRef operator*() { return I->UserTE; }
2796   };
2797 
2798   static NodeRef getEntryNode(BoUpSLP &R) {
2799     return R.VectorizableTree[0].get();
2800   }
2801 
2802   static ChildIteratorType child_begin(NodeRef N) {
2803     return {N->UserTreeIndices.begin(), N->Container};
2804   }
2805 
2806   static ChildIteratorType child_end(NodeRef N) {
2807     return {N->UserTreeIndices.end(), N->Container};
2808   }
2809 
2810   /// For the node iterator we just need to turn the TreeEntry iterator into a
2811   /// TreeEntry* iterator so that it dereferences to NodeRef.
2812   class nodes_iterator {
2813     using ItTy = ContainerTy::iterator;
2814     ItTy It;
2815 
2816   public:
2817     nodes_iterator(const ItTy &It2) : It(It2) {}
2818     NodeRef operator*() { return It->get(); }
2819     nodes_iterator operator++() {
2820       ++It;
2821       return *this;
2822     }
2823     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2824   };
2825 
2826   static nodes_iterator nodes_begin(BoUpSLP *R) {
2827     return nodes_iterator(R->VectorizableTree.begin());
2828   }
2829 
2830   static nodes_iterator nodes_end(BoUpSLP *R) {
2831     return nodes_iterator(R->VectorizableTree.end());
2832   }
2833 
2834   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2835 };
2836 
2837 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2838   using TreeEntry = BoUpSLP::TreeEntry;
2839 
2840   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2841 
2842   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2843     std::string Str;
2844     raw_string_ostream OS(Str);
2845     if (isSplat(Entry->Scalars))
2846       OS << "<splat> ";
2847     for (auto V : Entry->Scalars) {
2848       OS << *V;
2849       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2850             return EU.Scalar == V;
2851           }))
2852         OS << " <extract>";
2853       OS << "\n";
2854     }
2855     return Str;
2856   }
2857 
2858   static std::string getNodeAttributes(const TreeEntry *Entry,
2859                                        const BoUpSLP *) {
2860     if (Entry->State == TreeEntry::NeedToGather)
2861       return "color=red";
2862     return "";
2863   }
2864 };
2865 
2866 } // end namespace llvm
2867 
2868 BoUpSLP::~BoUpSLP() {
2869   for (const auto &Pair : DeletedInstructions) {
2870     // Replace operands of ignored instructions with Undefs in case if they were
2871     // marked for deletion.
2872     if (Pair.getSecond()) {
2873       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2874       Pair.getFirst()->replaceAllUsesWith(Undef);
2875     }
2876     Pair.getFirst()->dropAllReferences();
2877   }
2878   for (const auto &Pair : DeletedInstructions) {
2879     assert(Pair.getFirst()->use_empty() &&
2880            "trying to erase instruction with users.");
2881     Pair.getFirst()->eraseFromParent();
2882   }
2883 #ifdef EXPENSIVE_CHECKS
2884   // If we could guarantee that this call is not extremely slow, we could
2885   // remove the ifdef limitation (see PR47712).
2886   assert(!verifyFunction(*F, &dbgs()));
2887 #endif
2888 }
2889 
2890 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2891   for (auto *V : AV) {
2892     if (auto *I = dyn_cast<Instruction>(V))
2893       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2894   };
2895 }
2896 
2897 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
2898 /// contains original mask for the scalars reused in the node. Procedure
2899 /// transform this mask in accordance with the given \p Mask.
2900 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
2901   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
2902          "Expected non-empty mask.");
2903   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
2904   Prev.swap(Reuses);
2905   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
2906     if (Mask[I] != UndefMaskElem)
2907       Reuses[Mask[I]] = Prev[I];
2908 }
2909 
2910 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
2911 /// the original order of the scalars. Procedure transforms the provided order
2912 /// in accordance with the given \p Mask. If the resulting \p Order is just an
2913 /// identity order, \p Order is cleared.
2914 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
2915   assert(!Mask.empty() && "Expected non-empty mask.");
2916   SmallVector<int> MaskOrder;
2917   if (Order.empty()) {
2918     MaskOrder.resize(Mask.size());
2919     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
2920   } else {
2921     inversePermutation(Order, MaskOrder);
2922   }
2923   reorderReuses(MaskOrder, Mask);
2924   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
2925     Order.clear();
2926     return;
2927   }
2928   Order.assign(Mask.size(), Mask.size());
2929   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
2930     if (MaskOrder[I] != UndefMaskElem)
2931       Order[MaskOrder[I]] = I;
2932   fixupOrderingIndices(Order);
2933 }
2934 
2935 Optional<BoUpSLP::OrdersType>
2936 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
2937   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
2938   unsigned NumScalars = TE.Scalars.size();
2939   OrdersType CurrentOrder(NumScalars, NumScalars);
2940   SmallVector<int> Positions;
2941   SmallBitVector UsedPositions(NumScalars);
2942   const TreeEntry *STE = nullptr;
2943   // Try to find all gathered scalars that are gets vectorized in other
2944   // vectorize node. Here we can have only one single tree vector node to
2945   // correctly identify order of the gathered scalars.
2946   for (unsigned I = 0; I < NumScalars; ++I) {
2947     Value *V = TE.Scalars[I];
2948     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
2949       continue;
2950     if (const auto *LocalSTE = getTreeEntry(V)) {
2951       if (!STE)
2952         STE = LocalSTE;
2953       else if (STE != LocalSTE)
2954         // Take the order only from the single vector node.
2955         return None;
2956       unsigned Lane =
2957           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
2958       if (Lane >= NumScalars)
2959         return None;
2960       if (CurrentOrder[Lane] != NumScalars) {
2961         if (Lane != I)
2962           continue;
2963         UsedPositions.reset(CurrentOrder[Lane]);
2964       }
2965       // The partial identity (where only some elements of the gather node are
2966       // in the identity order) is good.
2967       CurrentOrder[Lane] = I;
2968       UsedPositions.set(I);
2969     }
2970   }
2971   // Need to keep the order if we have a vector entry and at least 2 scalars or
2972   // the vectorized entry has just 2 scalars.
2973   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
2974     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
2975       for (unsigned I = 0; I < NumScalars; ++I)
2976         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
2977           return false;
2978       return true;
2979     };
2980     if (IsIdentityOrder(CurrentOrder)) {
2981       CurrentOrder.clear();
2982       return CurrentOrder;
2983     }
2984     auto *It = CurrentOrder.begin();
2985     for (unsigned I = 0; I < NumScalars;) {
2986       if (UsedPositions.test(I)) {
2987         ++I;
2988         continue;
2989       }
2990       if (*It == NumScalars) {
2991         *It = I;
2992         ++I;
2993       }
2994       ++It;
2995     }
2996     return CurrentOrder;
2997   }
2998   return None;
2999 }
3000 
3001 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3002                                                          bool TopToBottom) {
3003   // No need to reorder if need to shuffle reuses, still need to shuffle the
3004   // node.
3005   if (!TE.ReuseShuffleIndices.empty())
3006     return None;
3007   if (TE.State == TreeEntry::Vectorize &&
3008       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3009        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3010       !TE.isAltShuffle())
3011     return TE.ReorderIndices;
3012   if (TE.State == TreeEntry::NeedToGather) {
3013     // TODO: add analysis of other gather nodes with extractelement
3014     // instructions and other values/instructions, not only undefs.
3015     if (((TE.getOpcode() == Instruction::ExtractElement &&
3016           !TE.isAltShuffle()) ||
3017          (all_of(TE.Scalars,
3018                  [](Value *V) {
3019                    return isa<UndefValue, ExtractElementInst>(V);
3020                  }) &&
3021           any_of(TE.Scalars,
3022                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3023         all_of(TE.Scalars,
3024                [](Value *V) {
3025                  auto *EE = dyn_cast<ExtractElementInst>(V);
3026                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3027                }) &&
3028         allSameType(TE.Scalars)) {
3029       // Check that gather of extractelements can be represented as
3030       // just a shuffle of a single vector.
3031       OrdersType CurrentOrder;
3032       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3033       if (Reuse || !CurrentOrder.empty()) {
3034         if (!CurrentOrder.empty())
3035           fixupOrderingIndices(CurrentOrder);
3036         return CurrentOrder;
3037       }
3038     }
3039     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3040       return CurrentOrder;
3041   }
3042   return None;
3043 }
3044 
3045 void BoUpSLP::reorderTopToBottom() {
3046   // Maps VF to the graph nodes.
3047   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3048   // ExtractElement gather nodes which can be vectorized and need to handle
3049   // their ordering.
3050   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3051   // Find all reorderable nodes with the given VF.
3052   // Currently the are vectorized stores,loads,extracts + some gathering of
3053   // extracts.
3054   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3055                                  const std::unique_ptr<TreeEntry> &TE) {
3056     if (Optional<OrdersType> CurrentOrder =
3057             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3058       // Do not include ordering for nodes used in the alt opcode vectorization,
3059       // better to reorder them during bottom-to-top stage. If follow the order
3060       // here, it causes reordering of the whole graph though actually it is
3061       // profitable just to reorder the subgraph that starts from the alternate
3062       // opcode vectorization node. Such nodes already end-up with the shuffle
3063       // instruction and it is just enough to change this shuffle rather than
3064       // rotate the scalars for the whole graph.
3065       unsigned Cnt = 0;
3066       const TreeEntry *UserTE = TE.get();
3067       while (UserTE && Cnt < RecursionMaxDepth) {
3068         if (UserTE->UserTreeIndices.size() != 1)
3069           break;
3070         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3071               return EI.UserTE->State == TreeEntry::Vectorize &&
3072                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3073             }))
3074           return;
3075         if (UserTE->UserTreeIndices.empty())
3076           UserTE = nullptr;
3077         else
3078           UserTE = UserTE->UserTreeIndices.back().UserTE;
3079         ++Cnt;
3080       }
3081       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3082       if (TE->State != TreeEntry::Vectorize)
3083         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3084     }
3085   });
3086 
3087   // Reorder the graph nodes according to their vectorization factor.
3088   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3089        VF /= 2) {
3090     auto It = VFToOrderedEntries.find(VF);
3091     if (It == VFToOrderedEntries.end())
3092       continue;
3093     // Try to find the most profitable order. We just are looking for the most
3094     // used order and reorder scalar elements in the nodes according to this
3095     // mostly used order.
3096     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3097     // All operands are reordered and used only in this node - propagate the
3098     // most used order to the user node.
3099     MapVector<OrdersType, unsigned,
3100               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3101         OrdersUses;
3102     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3103     for (const TreeEntry *OpTE : OrderedEntries) {
3104       // No need to reorder this nodes, still need to extend and to use shuffle,
3105       // just need to merge reordering shuffle and the reuse shuffle.
3106       if (!OpTE->ReuseShuffleIndices.empty())
3107         continue;
3108       // Count number of orders uses.
3109       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3110         if (OpTE->State == TreeEntry::NeedToGather)
3111           return GathersToOrders.find(OpTE)->second;
3112         return OpTE->ReorderIndices;
3113       }();
3114       // Stores actually store the mask, not the order, need to invert.
3115       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3116           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3117         SmallVector<int> Mask;
3118         inversePermutation(Order, Mask);
3119         unsigned E = Order.size();
3120         OrdersType CurrentOrder(E, E);
3121         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3122           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3123         });
3124         fixupOrderingIndices(CurrentOrder);
3125         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3126       } else {
3127         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3128       }
3129     }
3130     // Set order of the user node.
3131     if (OrdersUses.empty())
3132       continue;
3133     // Choose the most used order.
3134     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3135     unsigned Cnt = OrdersUses.front().second;
3136     for (const auto &Pair : drop_begin(OrdersUses)) {
3137       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3138         BestOrder = Pair.first;
3139         Cnt = Pair.second;
3140       }
3141     }
3142     // Set order of the user node.
3143     if (BestOrder.empty())
3144       continue;
3145     SmallVector<int> Mask;
3146     inversePermutation(BestOrder, Mask);
3147     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3148     unsigned E = BestOrder.size();
3149     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3150       return I < E ? static_cast<int>(I) : UndefMaskElem;
3151     });
3152     // Do an actual reordering, if profitable.
3153     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3154       // Just do the reordering for the nodes with the given VF.
3155       if (TE->Scalars.size() != VF) {
3156         if (TE->ReuseShuffleIndices.size() == VF) {
3157           // Need to reorder the reuses masks of the operands with smaller VF to
3158           // be able to find the match between the graph nodes and scalar
3159           // operands of the given node during vectorization/cost estimation.
3160           assert(all_of(TE->UserTreeIndices,
3161                         [VF, &TE](const EdgeInfo &EI) {
3162                           return EI.UserTE->Scalars.size() == VF ||
3163                                  EI.UserTE->Scalars.size() ==
3164                                      TE->Scalars.size();
3165                         }) &&
3166                  "All users must be of VF size.");
3167           // Update ordering of the operands with the smaller VF than the given
3168           // one.
3169           reorderReuses(TE->ReuseShuffleIndices, Mask);
3170         }
3171         continue;
3172       }
3173       if (TE->State == TreeEntry::Vectorize &&
3174           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3175               InsertElementInst>(TE->getMainOp()) &&
3176           !TE->isAltShuffle()) {
3177         // Build correct orders for extract{element,value}, loads and
3178         // stores.
3179         reorderOrder(TE->ReorderIndices, Mask);
3180         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3181           TE->reorderOperands(Mask);
3182       } else {
3183         // Reorder the node and its operands.
3184         TE->reorderOperands(Mask);
3185         assert(TE->ReorderIndices.empty() &&
3186                "Expected empty reorder sequence.");
3187         reorderScalars(TE->Scalars, Mask);
3188       }
3189       if (!TE->ReuseShuffleIndices.empty()) {
3190         // Apply reversed order to keep the original ordering of the reused
3191         // elements to avoid extra reorder indices shuffling.
3192         OrdersType CurrentOrder;
3193         reorderOrder(CurrentOrder, MaskOrder);
3194         SmallVector<int> NewReuses;
3195         inversePermutation(CurrentOrder, NewReuses);
3196         addMask(NewReuses, TE->ReuseShuffleIndices);
3197         TE->ReuseShuffleIndices.swap(NewReuses);
3198       }
3199     }
3200   }
3201 }
3202 
3203 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3204   SetVector<TreeEntry *> OrderedEntries;
3205   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3206   // Find all reorderable leaf nodes with the given VF.
3207   // Currently the are vectorized loads,extracts without alternate operands +
3208   // some gathering of extracts.
3209   SmallVector<TreeEntry *> NonVectorized;
3210   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3211                               &NonVectorized](
3212                                  const std::unique_ptr<TreeEntry> &TE) {
3213     if (TE->State != TreeEntry::Vectorize)
3214       NonVectorized.push_back(TE.get());
3215     if (Optional<OrdersType> CurrentOrder =
3216             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3217       OrderedEntries.insert(TE.get());
3218       if (TE->State != TreeEntry::Vectorize)
3219         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3220     }
3221   });
3222 
3223   // Checks if the operands of the users are reordarable and have only single
3224   // use.
3225   auto &&CheckOperands =
3226       [this, &NonVectorized](const auto &Data,
3227                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3228         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3229           if (any_of(Data.second,
3230                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3231                        return OpData.first == I &&
3232                               OpData.second->State == TreeEntry::Vectorize;
3233                      }))
3234             continue;
3235           ArrayRef<Value *> VL = Data.first->getOperand(I);
3236           const TreeEntry *TE = nullptr;
3237           const auto *It = find_if(VL, [this, &TE](Value *V) {
3238             TE = getTreeEntry(V);
3239             return TE;
3240           });
3241           if (It != VL.end() && TE->isSame(VL))
3242             return false;
3243           TreeEntry *Gather = nullptr;
3244           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3245                 assert(TE->State != TreeEntry::Vectorize &&
3246                        "Only non-vectorized nodes are expected.");
3247                 if (TE->isSame(VL)) {
3248                   Gather = TE;
3249                   return true;
3250                 }
3251                 return false;
3252               }) > 1)
3253             return false;
3254           if (Gather)
3255             GatherOps.push_back(Gather);
3256         }
3257         return true;
3258       };
3259   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3260   // I.e., if the node has operands, that are reordered, try to make at least
3261   // one operand order in the natural order and reorder others + reorder the
3262   // user node itself.
3263   SmallPtrSet<const TreeEntry *, 4> Visited;
3264   while (!OrderedEntries.empty()) {
3265     // 1. Filter out only reordered nodes.
3266     // 2. If the entry has multiple uses - skip it and jump to the next node.
3267     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3268     SmallVector<TreeEntry *> Filtered;
3269     for (TreeEntry *TE : OrderedEntries) {
3270       if (!(TE->State == TreeEntry::Vectorize ||
3271             (TE->State == TreeEntry::NeedToGather &&
3272              GathersToOrders.count(TE))) ||
3273           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3274           !all_of(drop_begin(TE->UserTreeIndices),
3275                   [TE](const EdgeInfo &EI) {
3276                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3277                   }) ||
3278           !Visited.insert(TE).second) {
3279         Filtered.push_back(TE);
3280         continue;
3281       }
3282       // Build a map between user nodes and their operands order to speedup
3283       // search. The graph currently does not provide this dependency directly.
3284       for (EdgeInfo &EI : TE->UserTreeIndices) {
3285         TreeEntry *UserTE = EI.UserTE;
3286         auto It = Users.find(UserTE);
3287         if (It == Users.end())
3288           It = Users.insert({UserTE, {}}).first;
3289         It->second.emplace_back(EI.EdgeIdx, TE);
3290       }
3291     }
3292     // Erase filtered entries.
3293     for_each(Filtered,
3294              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3295     for (const auto &Data : Users) {
3296       // Check that operands are used only in the User node.
3297       SmallVector<TreeEntry *> GatherOps;
3298       if (!CheckOperands(Data, GatherOps)) {
3299         for_each(Data.second,
3300                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3301                    OrderedEntries.remove(Op.second);
3302                  });
3303         continue;
3304       }
3305       // All operands are reordered and used only in this node - propagate the
3306       // most used order to the user node.
3307       MapVector<OrdersType, unsigned,
3308                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3309           OrdersUses;
3310       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3311       for (const auto &Op : Data.second) {
3312         TreeEntry *OpTE = Op.second;
3313         if (!OpTE->ReuseShuffleIndices.empty() ||
3314             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3315           continue;
3316         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3317           if (OpTE->State == TreeEntry::NeedToGather)
3318             return GathersToOrders.find(OpTE)->second;
3319           return OpTE->ReorderIndices;
3320         }();
3321         // Stores actually store the mask, not the order, need to invert.
3322         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3323             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3324           SmallVector<int> Mask;
3325           inversePermutation(Order, Mask);
3326           unsigned E = Order.size();
3327           OrdersType CurrentOrder(E, E);
3328           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3329             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3330           });
3331           fixupOrderingIndices(CurrentOrder);
3332           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3333         } else {
3334           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3335         }
3336         if (VisitedOps.insert(OpTE).second)
3337           OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3338               OpTE->UserTreeIndices.size();
3339         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3340         --OrdersUses[{}];
3341       }
3342       // If no orders - skip current nodes and jump to the next one, if any.
3343       if (OrdersUses.empty()) {
3344         for_each(Data.second,
3345                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3346                    OrderedEntries.remove(Op.second);
3347                  });
3348         continue;
3349       }
3350       // Choose the best order.
3351       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3352       unsigned Cnt = OrdersUses.front().second;
3353       for (const auto &Pair : drop_begin(OrdersUses)) {
3354         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3355           BestOrder = Pair.first;
3356           Cnt = Pair.second;
3357         }
3358       }
3359       // Set order of the user node (reordering of operands and user nodes).
3360       if (BestOrder.empty()) {
3361         for_each(Data.second,
3362                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3363                    OrderedEntries.remove(Op.second);
3364                  });
3365         continue;
3366       }
3367       // Erase operands from OrderedEntries list and adjust their orders.
3368       VisitedOps.clear();
3369       SmallVector<int> Mask;
3370       inversePermutation(BestOrder, Mask);
3371       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3372       unsigned E = BestOrder.size();
3373       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3374         return I < E ? static_cast<int>(I) : UndefMaskElem;
3375       });
3376       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3377         TreeEntry *TE = Op.second;
3378         OrderedEntries.remove(TE);
3379         if (!VisitedOps.insert(TE).second)
3380           continue;
3381         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3382           // Just reorder reuses indices.
3383           reorderReuses(TE->ReuseShuffleIndices, Mask);
3384           continue;
3385         }
3386         // Gathers are processed separately.
3387         if (TE->State != TreeEntry::Vectorize)
3388           continue;
3389         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3390                 TE->ReorderIndices.empty()) &&
3391                "Non-matching sizes of user/operand entries.");
3392         reorderOrder(TE->ReorderIndices, Mask);
3393       }
3394       // For gathers just need to reorder its scalars.
3395       for (TreeEntry *Gather : GatherOps) {
3396         assert(Gather->ReorderIndices.empty() &&
3397                "Unexpected reordering of gathers.");
3398         if (!Gather->ReuseShuffleIndices.empty()) {
3399           // Just reorder reuses indices.
3400           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3401           continue;
3402         }
3403         reorderScalars(Gather->Scalars, Mask);
3404         OrderedEntries.remove(Gather);
3405       }
3406       // Reorder operands of the user node and set the ordering for the user
3407       // node itself.
3408       if (Data.first->State != TreeEntry::Vectorize ||
3409           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3410               Data.first->getMainOp()) ||
3411           Data.first->isAltShuffle())
3412         Data.first->reorderOperands(Mask);
3413       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3414           Data.first->isAltShuffle()) {
3415         reorderScalars(Data.first->Scalars, Mask);
3416         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3417         if (Data.first->ReuseShuffleIndices.empty() &&
3418             !Data.first->ReorderIndices.empty() &&
3419             !Data.first->isAltShuffle()) {
3420           // Insert user node to the list to try to sink reordering deeper in
3421           // the graph.
3422           OrderedEntries.insert(Data.first);
3423         }
3424       } else {
3425         reorderOrder(Data.first->ReorderIndices, Mask);
3426       }
3427     }
3428   }
3429   // If the reordering is unnecessary, just remove the reorder.
3430   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3431       VectorizableTree.front()->ReuseShuffleIndices.empty())
3432     VectorizableTree.front()->ReorderIndices.clear();
3433 }
3434 
3435 void BoUpSLP::buildExternalUses(
3436     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3437   // Collect the values that we need to extract from the tree.
3438   for (auto &TEPtr : VectorizableTree) {
3439     TreeEntry *Entry = TEPtr.get();
3440 
3441     // No need to handle users of gathered values.
3442     if (Entry->State == TreeEntry::NeedToGather)
3443       continue;
3444 
3445     // For each lane:
3446     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3447       Value *Scalar = Entry->Scalars[Lane];
3448       int FoundLane = Entry->findLaneForValue(Scalar);
3449 
3450       // Check if the scalar is externally used as an extra arg.
3451       auto ExtI = ExternallyUsedValues.find(Scalar);
3452       if (ExtI != ExternallyUsedValues.end()) {
3453         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3454                           << Lane << " from " << *Scalar << ".\n");
3455         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3456       }
3457       for (User *U : Scalar->users()) {
3458         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3459 
3460         Instruction *UserInst = dyn_cast<Instruction>(U);
3461         if (!UserInst)
3462           continue;
3463 
3464         if (isDeleted(UserInst))
3465           continue;
3466 
3467         // Skip in-tree scalars that become vectors
3468         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3469           Value *UseScalar = UseEntry->Scalars[0];
3470           // Some in-tree scalars will remain as scalar in vectorized
3471           // instructions. If that is the case, the one in Lane 0 will
3472           // be used.
3473           if (UseScalar != U ||
3474               UseEntry->State == TreeEntry::ScatterVectorize ||
3475               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3476             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3477                               << ".\n");
3478             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3479             continue;
3480           }
3481         }
3482 
3483         // Ignore users in the user ignore list.
3484         if (is_contained(UserIgnoreList, UserInst))
3485           continue;
3486 
3487         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3488                           << Lane << " from " << *Scalar << ".\n");
3489         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3490       }
3491     }
3492   }
3493 }
3494 
3495 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3496                         ArrayRef<Value *> UserIgnoreLst) {
3497   deleteTree();
3498   UserIgnoreList = UserIgnoreLst;
3499   if (!allSameType(Roots))
3500     return;
3501   buildTree_rec(Roots, 0, EdgeInfo());
3502 }
3503 
3504 namespace {
3505 /// Tracks the state we can represent the loads in the given sequence.
3506 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3507 } // anonymous namespace
3508 
3509 /// Checks if the given array of loads can be represented as a vectorized,
3510 /// scatter or just simple gather.
3511 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3512                                     const TargetTransformInfo &TTI,
3513                                     const DataLayout &DL, ScalarEvolution &SE,
3514                                     SmallVectorImpl<unsigned> &Order,
3515                                     SmallVectorImpl<Value *> &PointerOps) {
3516   // Check that a vectorized load would load the same memory as a scalar
3517   // load. For example, we don't want to vectorize loads that are smaller
3518   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3519   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3520   // from such a struct, we read/write packed bits disagreeing with the
3521   // unvectorized version.
3522   Type *ScalarTy = VL0->getType();
3523 
3524   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3525     return LoadsState::Gather;
3526 
3527   // Make sure all loads in the bundle are simple - we can't vectorize
3528   // atomic or volatile loads.
3529   PointerOps.clear();
3530   PointerOps.resize(VL.size());
3531   auto *POIter = PointerOps.begin();
3532   for (Value *V : VL) {
3533     auto *L = cast<LoadInst>(V);
3534     if (!L->isSimple())
3535       return LoadsState::Gather;
3536     *POIter = L->getPointerOperand();
3537     ++POIter;
3538   }
3539 
3540   Order.clear();
3541   // Check the order of pointer operands.
3542   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3543     Value *Ptr0;
3544     Value *PtrN;
3545     if (Order.empty()) {
3546       Ptr0 = PointerOps.front();
3547       PtrN = PointerOps.back();
3548     } else {
3549       Ptr0 = PointerOps[Order.front()];
3550       PtrN = PointerOps[Order.back()];
3551     }
3552     Optional<int> Diff =
3553         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3554     // Check that the sorted loads are consecutive.
3555     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3556       return LoadsState::Vectorize;
3557     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3558     for (Value *V : VL)
3559       CommonAlignment =
3560           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3561     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3562                                 CommonAlignment))
3563       return LoadsState::ScatterVectorize;
3564   }
3565 
3566   return LoadsState::Gather;
3567 }
3568 
3569 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3570                             const EdgeInfo &UserTreeIdx) {
3571   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3572 
3573   SmallVector<int> ReuseShuffleIndicies;
3574   SmallVector<Value *> UniqueValues;
3575   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3576                                 &UserTreeIdx,
3577                                 this](const InstructionsState &S) {
3578     // Check that every instruction appears once in this bundle.
3579     DenseMap<Value *, unsigned> UniquePositions;
3580     for (Value *V : VL) {
3581       if (isConstant(V)) {
3582         ReuseShuffleIndicies.emplace_back(
3583             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3584         UniqueValues.emplace_back(V);
3585         continue;
3586       }
3587       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3588       ReuseShuffleIndicies.emplace_back(Res.first->second);
3589       if (Res.second)
3590         UniqueValues.emplace_back(V);
3591     }
3592     size_t NumUniqueScalarValues = UniqueValues.size();
3593     if (NumUniqueScalarValues == VL.size()) {
3594       ReuseShuffleIndicies.clear();
3595     } else {
3596       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3597       if (NumUniqueScalarValues <= 1 ||
3598           (UniquePositions.size() == 1 && all_of(UniqueValues,
3599                                                  [](Value *V) {
3600                                                    return isa<UndefValue>(V) ||
3601                                                           !isConstant(V);
3602                                                  })) ||
3603           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3604         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3605         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3606         return false;
3607       }
3608       VL = UniqueValues;
3609     }
3610     return true;
3611   };
3612 
3613   InstructionsState S = getSameOpcode(VL);
3614   if (Depth == RecursionMaxDepth) {
3615     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3616     if (TryToFindDuplicates(S))
3617       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3618                    ReuseShuffleIndicies);
3619     return;
3620   }
3621 
3622   // Don't handle scalable vectors
3623   if (S.getOpcode() == Instruction::ExtractElement &&
3624       isa<ScalableVectorType>(
3625           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3626     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3627     if (TryToFindDuplicates(S))
3628       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3629                    ReuseShuffleIndicies);
3630     return;
3631   }
3632 
3633   // Don't handle vectors.
3634   if (S.OpValue->getType()->isVectorTy() &&
3635       !isa<InsertElementInst>(S.OpValue)) {
3636     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3637     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3638     return;
3639   }
3640 
3641   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3642     if (SI->getValueOperand()->getType()->isVectorTy()) {
3643       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3644       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3645       return;
3646     }
3647 
3648   // If all of the operands are identical or constant we have a simple solution.
3649   // If we deal with insert/extract instructions, they all must have constant
3650   // indices, otherwise we should gather them, not try to vectorize.
3651   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3652       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3653        !all_of(VL, isVectorLikeInstWithConstOps))) {
3654     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3655     if (TryToFindDuplicates(S))
3656       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3657                    ReuseShuffleIndicies);
3658     return;
3659   }
3660 
3661   // We now know that this is a vector of instructions of the same type from
3662   // the same block.
3663 
3664   // Don't vectorize ephemeral values.
3665   for (Value *V : VL) {
3666     if (EphValues.count(V)) {
3667       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3668                         << ") is ephemeral.\n");
3669       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3670       return;
3671     }
3672   }
3673 
3674   // Check if this is a duplicate of another entry.
3675   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3676     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3677     if (!E->isSame(VL)) {
3678       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3679       if (TryToFindDuplicates(S))
3680         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3681                      ReuseShuffleIndicies);
3682       return;
3683     }
3684     // Record the reuse of the tree node.  FIXME, currently this is only used to
3685     // properly draw the graph rather than for the actual vectorization.
3686     E->UserTreeIndices.push_back(UserTreeIdx);
3687     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3688                       << ".\n");
3689     return;
3690   }
3691 
3692   // Check that none of the instructions in the bundle are already in the tree.
3693   for (Value *V : VL) {
3694     auto *I = dyn_cast<Instruction>(V);
3695     if (!I)
3696       continue;
3697     if (getTreeEntry(I)) {
3698       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3699                         << ") is already in tree.\n");
3700       if (TryToFindDuplicates(S))
3701         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3702                      ReuseShuffleIndicies);
3703       return;
3704     }
3705   }
3706 
3707   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3708   for (Value *V : VL) {
3709     if (is_contained(UserIgnoreList, V)) {
3710       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3711       if (TryToFindDuplicates(S))
3712         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3713                      ReuseShuffleIndicies);
3714       return;
3715     }
3716   }
3717 
3718   // Check that all of the users of the scalars that we want to vectorize are
3719   // schedulable.
3720   auto *VL0 = cast<Instruction>(S.OpValue);
3721   BasicBlock *BB = VL0->getParent();
3722 
3723   if (!DT->isReachableFromEntry(BB)) {
3724     // Don't go into unreachable blocks. They may contain instructions with
3725     // dependency cycles which confuse the final scheduling.
3726     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3727     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3728     return;
3729   }
3730 
3731   // Check that every instruction appears once in this bundle.
3732   if (!TryToFindDuplicates(S))
3733     return;
3734 
3735   auto &BSRef = BlocksSchedules[BB];
3736   if (!BSRef)
3737     BSRef = std::make_unique<BlockScheduling>(BB);
3738 
3739   BlockScheduling &BS = *BSRef.get();
3740 
3741   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3742   if (!Bundle) {
3743     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3744     assert((!BS.getScheduleData(VL0) ||
3745             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3746            "tryScheduleBundle should cancelScheduling on failure");
3747     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3748                  ReuseShuffleIndicies);
3749     return;
3750   }
3751   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3752 
3753   unsigned ShuffleOrOp = S.isAltShuffle() ?
3754                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3755   switch (ShuffleOrOp) {
3756     case Instruction::PHI: {
3757       auto *PH = cast<PHINode>(VL0);
3758 
3759       // Check for terminator values (e.g. invoke).
3760       for (Value *V : VL)
3761         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3762           Instruction *Term = dyn_cast<Instruction>(
3763               cast<PHINode>(V)->getIncomingValueForBlock(
3764                   PH->getIncomingBlock(I)));
3765           if (Term && Term->isTerminator()) {
3766             LLVM_DEBUG(dbgs()
3767                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3768             BS.cancelScheduling(VL, VL0);
3769             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3770                          ReuseShuffleIndicies);
3771             return;
3772           }
3773         }
3774 
3775       TreeEntry *TE =
3776           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3777       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3778 
3779       // Keeps the reordered operands to avoid code duplication.
3780       SmallVector<ValueList, 2> OperandsVec;
3781       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3782         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3783           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3784           TE->setOperand(I, Operands);
3785           OperandsVec.push_back(Operands);
3786           continue;
3787         }
3788         ValueList Operands;
3789         // Prepare the operand vector.
3790         for (Value *V : VL)
3791           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3792               PH->getIncomingBlock(I)));
3793         TE->setOperand(I, Operands);
3794         OperandsVec.push_back(Operands);
3795       }
3796       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3797         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3798       return;
3799     }
3800     case Instruction::ExtractValue:
3801     case Instruction::ExtractElement: {
3802       OrdersType CurrentOrder;
3803       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3804       if (Reuse) {
3805         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3806         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3807                      ReuseShuffleIndicies);
3808         // This is a special case, as it does not gather, but at the same time
3809         // we are not extending buildTree_rec() towards the operands.
3810         ValueList Op0;
3811         Op0.assign(VL.size(), VL0->getOperand(0));
3812         VectorizableTree.back()->setOperand(0, Op0);
3813         return;
3814       }
3815       if (!CurrentOrder.empty()) {
3816         LLVM_DEBUG({
3817           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3818                     "with order";
3819           for (unsigned Idx : CurrentOrder)
3820             dbgs() << " " << Idx;
3821           dbgs() << "\n";
3822         });
3823         fixupOrderingIndices(CurrentOrder);
3824         // Insert new order with initial value 0, if it does not exist,
3825         // otherwise return the iterator to the existing one.
3826         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3827                      ReuseShuffleIndicies, CurrentOrder);
3828         // This is a special case, as it does not gather, but at the same time
3829         // we are not extending buildTree_rec() towards the operands.
3830         ValueList Op0;
3831         Op0.assign(VL.size(), VL0->getOperand(0));
3832         VectorizableTree.back()->setOperand(0, Op0);
3833         return;
3834       }
3835       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3836       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3837                    ReuseShuffleIndicies);
3838       BS.cancelScheduling(VL, VL0);
3839       return;
3840     }
3841     case Instruction::InsertElement: {
3842       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3843 
3844       // Check that we have a buildvector and not a shuffle of 2 or more
3845       // different vectors.
3846       ValueSet SourceVectors;
3847       int MinIdx = std::numeric_limits<int>::max();
3848       for (Value *V : VL) {
3849         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3850         Optional<int> Idx = *getInsertIndex(V, 0);
3851         if (!Idx || *Idx == UndefMaskElem)
3852           continue;
3853         MinIdx = std::min(MinIdx, *Idx);
3854       }
3855 
3856       if (count_if(VL, [&SourceVectors](Value *V) {
3857             return !SourceVectors.contains(V);
3858           }) >= 2) {
3859         // Found 2nd source vector - cancel.
3860         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3861                              "different source vectors.\n");
3862         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3863         BS.cancelScheduling(VL, VL0);
3864         return;
3865       }
3866 
3867       auto OrdCompare = [](const std::pair<int, int> &P1,
3868                            const std::pair<int, int> &P2) {
3869         return P1.first > P2.first;
3870       };
3871       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3872                     decltype(OrdCompare)>
3873           Indices(OrdCompare);
3874       for (int I = 0, E = VL.size(); I < E; ++I) {
3875         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3876         if (!Idx || *Idx == UndefMaskElem)
3877           continue;
3878         Indices.emplace(*Idx, I);
3879       }
3880       OrdersType CurrentOrder(VL.size(), VL.size());
3881       bool IsIdentity = true;
3882       for (int I = 0, E = VL.size(); I < E; ++I) {
3883         CurrentOrder[Indices.top().second] = I;
3884         IsIdentity &= Indices.top().second == I;
3885         Indices.pop();
3886       }
3887       if (IsIdentity)
3888         CurrentOrder.clear();
3889       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3890                                    None, CurrentOrder);
3891       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3892 
3893       constexpr int NumOps = 2;
3894       ValueList VectorOperands[NumOps];
3895       for (int I = 0; I < NumOps; ++I) {
3896         for (Value *V : VL)
3897           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3898 
3899         TE->setOperand(I, VectorOperands[I]);
3900       }
3901       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3902       return;
3903     }
3904     case Instruction::Load: {
3905       // Check that a vectorized load would load the same memory as a scalar
3906       // load. For example, we don't want to vectorize loads that are smaller
3907       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3908       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3909       // from such a struct, we read/write packed bits disagreeing with the
3910       // unvectorized version.
3911       SmallVector<Value *> PointerOps;
3912       OrdersType CurrentOrder;
3913       TreeEntry *TE = nullptr;
3914       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3915                                 PointerOps)) {
3916       case LoadsState::Vectorize:
3917         if (CurrentOrder.empty()) {
3918           // Original loads are consecutive and does not require reordering.
3919           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3920                             ReuseShuffleIndicies);
3921           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3922         } else {
3923           fixupOrderingIndices(CurrentOrder);
3924           // Need to reorder.
3925           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3926                             ReuseShuffleIndicies, CurrentOrder);
3927           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
3928         }
3929         TE->setOperandsInOrder();
3930         break;
3931       case LoadsState::ScatterVectorize:
3932         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3933         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
3934                           UserTreeIdx, ReuseShuffleIndicies);
3935         TE->setOperandsInOrder();
3936         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
3937         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
3938         break;
3939       case LoadsState::Gather:
3940         BS.cancelScheduling(VL, VL0);
3941         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3942                      ReuseShuffleIndicies);
3943 #ifndef NDEBUG
3944         Type *ScalarTy = VL0->getType();
3945         if (DL->getTypeSizeInBits(ScalarTy) !=
3946             DL->getTypeAllocSizeInBits(ScalarTy))
3947           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
3948         else if (any_of(VL, [](Value *V) {
3949                    return !cast<LoadInst>(V)->isSimple();
3950                  }))
3951           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
3952         else
3953           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
3954 #endif // NDEBUG
3955         break;
3956       }
3957       return;
3958     }
3959     case Instruction::ZExt:
3960     case Instruction::SExt:
3961     case Instruction::FPToUI:
3962     case Instruction::FPToSI:
3963     case Instruction::FPExt:
3964     case Instruction::PtrToInt:
3965     case Instruction::IntToPtr:
3966     case Instruction::SIToFP:
3967     case Instruction::UIToFP:
3968     case Instruction::Trunc:
3969     case Instruction::FPTrunc:
3970     case Instruction::BitCast: {
3971       Type *SrcTy = VL0->getOperand(0)->getType();
3972       for (Value *V : VL) {
3973         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
3974         if (Ty != SrcTy || !isValidElementType(Ty)) {
3975           BS.cancelScheduling(VL, VL0);
3976           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3977                        ReuseShuffleIndicies);
3978           LLVM_DEBUG(dbgs()
3979                      << "SLP: Gathering casts with different src types.\n");
3980           return;
3981         }
3982       }
3983       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3984                                    ReuseShuffleIndicies);
3985       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
3986 
3987       TE->setOperandsInOrder();
3988       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3989         ValueList Operands;
3990         // Prepare the operand vector.
3991         for (Value *V : VL)
3992           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3993 
3994         buildTree_rec(Operands, Depth + 1, {TE, i});
3995       }
3996       return;
3997     }
3998     case Instruction::ICmp:
3999     case Instruction::FCmp: {
4000       // Check that all of the compares have the same predicate.
4001       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4002       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4003       Type *ComparedTy = VL0->getOperand(0)->getType();
4004       for (Value *V : VL) {
4005         CmpInst *Cmp = cast<CmpInst>(V);
4006         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4007             Cmp->getOperand(0)->getType() != ComparedTy) {
4008           BS.cancelScheduling(VL, VL0);
4009           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4010                        ReuseShuffleIndicies);
4011           LLVM_DEBUG(dbgs()
4012                      << "SLP: Gathering cmp with different predicate.\n");
4013           return;
4014         }
4015       }
4016 
4017       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4018                                    ReuseShuffleIndicies);
4019       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4020 
4021       ValueList Left, Right;
4022       if (cast<CmpInst>(VL0)->isCommutative()) {
4023         // Commutative predicate - collect + sort operands of the instructions
4024         // so that each side is more likely to have the same opcode.
4025         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4026         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4027       } else {
4028         // Collect operands - commute if it uses the swapped predicate.
4029         for (Value *V : VL) {
4030           auto *Cmp = cast<CmpInst>(V);
4031           Value *LHS = Cmp->getOperand(0);
4032           Value *RHS = Cmp->getOperand(1);
4033           if (Cmp->getPredicate() != P0)
4034             std::swap(LHS, RHS);
4035           Left.push_back(LHS);
4036           Right.push_back(RHS);
4037         }
4038       }
4039       TE->setOperand(0, Left);
4040       TE->setOperand(1, Right);
4041       buildTree_rec(Left, Depth + 1, {TE, 0});
4042       buildTree_rec(Right, Depth + 1, {TE, 1});
4043       return;
4044     }
4045     case Instruction::Select:
4046     case Instruction::FNeg:
4047     case Instruction::Add:
4048     case Instruction::FAdd:
4049     case Instruction::Sub:
4050     case Instruction::FSub:
4051     case Instruction::Mul:
4052     case Instruction::FMul:
4053     case Instruction::UDiv:
4054     case Instruction::SDiv:
4055     case Instruction::FDiv:
4056     case Instruction::URem:
4057     case Instruction::SRem:
4058     case Instruction::FRem:
4059     case Instruction::Shl:
4060     case Instruction::LShr:
4061     case Instruction::AShr:
4062     case Instruction::And:
4063     case Instruction::Or:
4064     case Instruction::Xor: {
4065       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4066                                    ReuseShuffleIndicies);
4067       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4068 
4069       // Sort operands of the instructions so that each side is more likely to
4070       // have the same opcode.
4071       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4072         ValueList Left, Right;
4073         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4074         TE->setOperand(0, Left);
4075         TE->setOperand(1, Right);
4076         buildTree_rec(Left, Depth + 1, {TE, 0});
4077         buildTree_rec(Right, Depth + 1, {TE, 1});
4078         return;
4079       }
4080 
4081       TE->setOperandsInOrder();
4082       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4083         ValueList Operands;
4084         // Prepare the operand vector.
4085         for (Value *V : VL)
4086           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4087 
4088         buildTree_rec(Operands, Depth + 1, {TE, i});
4089       }
4090       return;
4091     }
4092     case Instruction::GetElementPtr: {
4093       // We don't combine GEPs with complicated (nested) indexing.
4094       for (Value *V : VL) {
4095         if (cast<Instruction>(V)->getNumOperands() != 2) {
4096           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4097           BS.cancelScheduling(VL, VL0);
4098           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4099                        ReuseShuffleIndicies);
4100           return;
4101         }
4102       }
4103 
4104       // We can't combine several GEPs into one vector if they operate on
4105       // different types.
4106       Type *Ty0 = VL0->getOperand(0)->getType();
4107       for (Value *V : VL) {
4108         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4109         if (Ty0 != CurTy) {
4110           LLVM_DEBUG(dbgs()
4111                      << "SLP: not-vectorizable GEP (different types).\n");
4112           BS.cancelScheduling(VL, VL0);
4113           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4114                        ReuseShuffleIndicies);
4115           return;
4116         }
4117       }
4118 
4119       // We don't combine GEPs with non-constant indexes.
4120       Type *Ty1 = VL0->getOperand(1)->getType();
4121       for (Value *V : VL) {
4122         auto Op = cast<Instruction>(V)->getOperand(1);
4123         if (!isa<ConstantInt>(Op) ||
4124             (Op->getType() != Ty1 &&
4125              Op->getType()->getScalarSizeInBits() >
4126                  DL->getIndexSizeInBits(
4127                      V->getType()->getPointerAddressSpace()))) {
4128           LLVM_DEBUG(dbgs()
4129                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4130           BS.cancelScheduling(VL, VL0);
4131           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4132                        ReuseShuffleIndicies);
4133           return;
4134         }
4135       }
4136 
4137       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4138                                    ReuseShuffleIndicies);
4139       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4140       SmallVector<ValueList, 2> Operands(2);
4141       // Prepare the operand vector for pointer operands.
4142       for (Value *V : VL)
4143         Operands.front().push_back(
4144             cast<GetElementPtrInst>(V)->getPointerOperand());
4145       TE->setOperand(0, Operands.front());
4146       // Need to cast all indices to the same type before vectorization to
4147       // avoid crash.
4148       // Required to be able to find correct matches between different gather
4149       // nodes and reuse the vectorized values rather than trying to gather them
4150       // again.
4151       int IndexIdx = 1;
4152       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4153       Type *Ty = all_of(VL,
4154                         [VL0Ty, IndexIdx](Value *V) {
4155                           return VL0Ty == cast<GetElementPtrInst>(V)
4156                                               ->getOperand(IndexIdx)
4157                                               ->getType();
4158                         })
4159                      ? VL0Ty
4160                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4161                                             ->getPointerOperandType()
4162                                             ->getScalarType());
4163       // Prepare the operand vector.
4164       for (Value *V : VL) {
4165         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4166         auto *CI = cast<ConstantInt>(Op);
4167         Operands.back().push_back(ConstantExpr::getIntegerCast(
4168             CI, Ty, CI->getValue().isSignBitSet()));
4169       }
4170       TE->setOperand(IndexIdx, Operands.back());
4171 
4172       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4173         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4174       return;
4175     }
4176     case Instruction::Store: {
4177       // Check if the stores are consecutive or if we need to swizzle them.
4178       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4179       // Avoid types that are padded when being allocated as scalars, while
4180       // being packed together in a vector (such as i1).
4181       if (DL->getTypeSizeInBits(ScalarTy) !=
4182           DL->getTypeAllocSizeInBits(ScalarTy)) {
4183         BS.cancelScheduling(VL, VL0);
4184         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4185                      ReuseShuffleIndicies);
4186         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4187         return;
4188       }
4189       // Make sure all stores in the bundle are simple - we can't vectorize
4190       // atomic or volatile stores.
4191       SmallVector<Value *, 4> PointerOps(VL.size());
4192       ValueList Operands(VL.size());
4193       auto POIter = PointerOps.begin();
4194       auto OIter = Operands.begin();
4195       for (Value *V : VL) {
4196         auto *SI = cast<StoreInst>(V);
4197         if (!SI->isSimple()) {
4198           BS.cancelScheduling(VL, VL0);
4199           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4200                        ReuseShuffleIndicies);
4201           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4202           return;
4203         }
4204         *POIter = SI->getPointerOperand();
4205         *OIter = SI->getValueOperand();
4206         ++POIter;
4207         ++OIter;
4208       }
4209 
4210       OrdersType CurrentOrder;
4211       // Check the order of pointer operands.
4212       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4213         Value *Ptr0;
4214         Value *PtrN;
4215         if (CurrentOrder.empty()) {
4216           Ptr0 = PointerOps.front();
4217           PtrN = PointerOps.back();
4218         } else {
4219           Ptr0 = PointerOps[CurrentOrder.front()];
4220           PtrN = PointerOps[CurrentOrder.back()];
4221         }
4222         Optional<int> Dist =
4223             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4224         // Check that the sorted pointer operands are consecutive.
4225         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4226           if (CurrentOrder.empty()) {
4227             // Original stores are consecutive and does not require reordering.
4228             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4229                                          UserTreeIdx, ReuseShuffleIndicies);
4230             TE->setOperandsInOrder();
4231             buildTree_rec(Operands, Depth + 1, {TE, 0});
4232             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4233           } else {
4234             fixupOrderingIndices(CurrentOrder);
4235             TreeEntry *TE =
4236                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4237                              ReuseShuffleIndicies, CurrentOrder);
4238             TE->setOperandsInOrder();
4239             buildTree_rec(Operands, Depth + 1, {TE, 0});
4240             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4241           }
4242           return;
4243         }
4244       }
4245 
4246       BS.cancelScheduling(VL, VL0);
4247       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4248                    ReuseShuffleIndicies);
4249       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4250       return;
4251     }
4252     case Instruction::Call: {
4253       // Check if the calls are all to the same vectorizable intrinsic or
4254       // library function.
4255       CallInst *CI = cast<CallInst>(VL0);
4256       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4257 
4258       VFShape Shape = VFShape::get(
4259           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4260           false /*HasGlobalPred*/);
4261       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4262 
4263       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4264         BS.cancelScheduling(VL, VL0);
4265         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4266                      ReuseShuffleIndicies);
4267         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4268         return;
4269       }
4270       Function *F = CI->getCalledFunction();
4271       unsigned NumArgs = CI->arg_size();
4272       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4273       for (unsigned j = 0; j != NumArgs; ++j)
4274         if (hasVectorInstrinsicScalarOpd(ID, j))
4275           ScalarArgs[j] = CI->getArgOperand(j);
4276       for (Value *V : VL) {
4277         CallInst *CI2 = dyn_cast<CallInst>(V);
4278         if (!CI2 || CI2->getCalledFunction() != F ||
4279             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4280             (VecFunc &&
4281              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4282             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4283           BS.cancelScheduling(VL, VL0);
4284           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4285                        ReuseShuffleIndicies);
4286           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4287                             << "\n");
4288           return;
4289         }
4290         // Some intrinsics have scalar arguments and should be same in order for
4291         // them to be vectorized.
4292         for (unsigned j = 0; j != NumArgs; ++j) {
4293           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4294             Value *A1J = CI2->getArgOperand(j);
4295             if (ScalarArgs[j] != A1J) {
4296               BS.cancelScheduling(VL, VL0);
4297               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4298                            ReuseShuffleIndicies);
4299               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4300                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4301                                 << "\n");
4302               return;
4303             }
4304           }
4305         }
4306         // Verify that the bundle operands are identical between the two calls.
4307         if (CI->hasOperandBundles() &&
4308             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4309                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4310                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4311           BS.cancelScheduling(VL, VL0);
4312           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4313                        ReuseShuffleIndicies);
4314           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4315                             << *CI << "!=" << *V << '\n');
4316           return;
4317         }
4318       }
4319 
4320       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4321                                    ReuseShuffleIndicies);
4322       TE->setOperandsInOrder();
4323       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4324         // For scalar operands no need to to create an entry since no need to
4325         // vectorize it.
4326         if (hasVectorInstrinsicScalarOpd(ID, i))
4327           continue;
4328         ValueList Operands;
4329         // Prepare the operand vector.
4330         for (Value *V : VL) {
4331           auto *CI2 = cast<CallInst>(V);
4332           Operands.push_back(CI2->getArgOperand(i));
4333         }
4334         buildTree_rec(Operands, Depth + 1, {TE, i});
4335       }
4336       return;
4337     }
4338     case Instruction::ShuffleVector: {
4339       // If this is not an alternate sequence of opcode like add-sub
4340       // then do not vectorize this instruction.
4341       if (!S.isAltShuffle()) {
4342         BS.cancelScheduling(VL, VL0);
4343         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4344                      ReuseShuffleIndicies);
4345         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4346         return;
4347       }
4348       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4349                                    ReuseShuffleIndicies);
4350       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4351 
4352       // Reorder operands if reordering would enable vectorization.
4353       if (isa<BinaryOperator>(VL0)) {
4354         ValueList Left, Right;
4355         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4356         TE->setOperand(0, Left);
4357         TE->setOperand(1, Right);
4358         buildTree_rec(Left, Depth + 1, {TE, 0});
4359         buildTree_rec(Right, Depth + 1, {TE, 1});
4360         return;
4361       }
4362 
4363       TE->setOperandsInOrder();
4364       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4365         ValueList Operands;
4366         // Prepare the operand vector.
4367         for (Value *V : VL)
4368           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4369 
4370         buildTree_rec(Operands, Depth + 1, {TE, i});
4371       }
4372       return;
4373     }
4374     default:
4375       BS.cancelScheduling(VL, VL0);
4376       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4377                    ReuseShuffleIndicies);
4378       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4379       return;
4380   }
4381 }
4382 
4383 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4384   unsigned N = 1;
4385   Type *EltTy = T;
4386 
4387   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4388          isa<VectorType>(EltTy)) {
4389     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4390       // Check that struct is homogeneous.
4391       for (const auto *Ty : ST->elements())
4392         if (Ty != *ST->element_begin())
4393           return 0;
4394       N *= ST->getNumElements();
4395       EltTy = *ST->element_begin();
4396     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4397       N *= AT->getNumElements();
4398       EltTy = AT->getElementType();
4399     } else {
4400       auto *VT = cast<FixedVectorType>(EltTy);
4401       N *= VT->getNumElements();
4402       EltTy = VT->getElementType();
4403     }
4404   }
4405 
4406   if (!isValidElementType(EltTy))
4407     return 0;
4408   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4409   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4410     return 0;
4411   return N;
4412 }
4413 
4414 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4415                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4416   const auto *It = find_if(VL, [](Value *V) {
4417     return isa<ExtractElementInst, ExtractValueInst>(V);
4418   });
4419   assert(It != VL.end() && "Expected at least one extract instruction.");
4420   auto *E0 = cast<Instruction>(*It);
4421   assert(all_of(VL,
4422                 [](Value *V) {
4423                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4424                       V);
4425                 }) &&
4426          "Invalid opcode");
4427   // Check if all of the extracts come from the same vector and from the
4428   // correct offset.
4429   Value *Vec = E0->getOperand(0);
4430 
4431   CurrentOrder.clear();
4432 
4433   // We have to extract from a vector/aggregate with the same number of elements.
4434   unsigned NElts;
4435   if (E0->getOpcode() == Instruction::ExtractValue) {
4436     const DataLayout &DL = E0->getModule()->getDataLayout();
4437     NElts = canMapToVector(Vec->getType(), DL);
4438     if (!NElts)
4439       return false;
4440     // Check if load can be rewritten as load of vector.
4441     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4442     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4443       return false;
4444   } else {
4445     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4446   }
4447 
4448   if (NElts != VL.size())
4449     return false;
4450 
4451   // Check that all of the indices extract from the correct offset.
4452   bool ShouldKeepOrder = true;
4453   unsigned E = VL.size();
4454   // Assign to all items the initial value E + 1 so we can check if the extract
4455   // instruction index was used already.
4456   // Also, later we can check that all the indices are used and we have a
4457   // consecutive access in the extract instructions, by checking that no
4458   // element of CurrentOrder still has value E + 1.
4459   CurrentOrder.assign(E, E);
4460   unsigned I = 0;
4461   for (; I < E; ++I) {
4462     auto *Inst = dyn_cast<Instruction>(VL[I]);
4463     if (!Inst)
4464       continue;
4465     if (Inst->getOperand(0) != Vec)
4466       break;
4467     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4468       if (isa<UndefValue>(EE->getIndexOperand()))
4469         continue;
4470     Optional<unsigned> Idx = getExtractIndex(Inst);
4471     if (!Idx)
4472       break;
4473     const unsigned ExtIdx = *Idx;
4474     if (ExtIdx != I) {
4475       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4476         break;
4477       ShouldKeepOrder = false;
4478       CurrentOrder[ExtIdx] = I;
4479     } else {
4480       if (CurrentOrder[I] != E)
4481         break;
4482       CurrentOrder[I] = I;
4483     }
4484   }
4485   if (I < E) {
4486     CurrentOrder.clear();
4487     return false;
4488   }
4489   if (ShouldKeepOrder)
4490     CurrentOrder.clear();
4491 
4492   return ShouldKeepOrder;
4493 }
4494 
4495 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4496                                     ArrayRef<Value *> VectorizedVals) const {
4497   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4498          all_of(I->users(), [this](User *U) {
4499            return ScalarToTreeEntry.count(U) > 0 || MustGather.contains(U);
4500          });
4501 }
4502 
4503 static std::pair<InstructionCost, InstructionCost>
4504 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4505                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4506   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4507 
4508   // Calculate the cost of the scalar and vector calls.
4509   SmallVector<Type *, 4> VecTys;
4510   for (Use &Arg : CI->args())
4511     VecTys.push_back(
4512         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4513   FastMathFlags FMF;
4514   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4515     FMF = FPCI->getFastMathFlags();
4516   SmallVector<const Value *> Arguments(CI->args());
4517   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4518                                     dyn_cast<IntrinsicInst>(CI));
4519   auto IntrinsicCost =
4520     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4521 
4522   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4523                                      VecTy->getNumElements())),
4524                             false /*HasGlobalPred*/);
4525   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4526   auto LibCost = IntrinsicCost;
4527   if (!CI->isNoBuiltin() && VecFunc) {
4528     // Calculate the cost of the vector library call.
4529     // If the corresponding vector call is cheaper, return its cost.
4530     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4531                                     TTI::TCK_RecipThroughput);
4532   }
4533   return {IntrinsicCost, LibCost};
4534 }
4535 
4536 /// Compute the cost of creating a vector of type \p VecTy containing the
4537 /// extracted values from \p VL.
4538 static InstructionCost
4539 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4540                    TargetTransformInfo::ShuffleKind ShuffleKind,
4541                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4542   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4543 
4544   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4545       VecTy->getNumElements() < NumOfParts)
4546     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4547 
4548   bool AllConsecutive = true;
4549   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4550   unsigned Idx = -1;
4551   InstructionCost Cost = 0;
4552 
4553   // Process extracts in blocks of EltsPerVector to check if the source vector
4554   // operand can be re-used directly. If not, add the cost of creating a shuffle
4555   // to extract the values into a vector register.
4556   for (auto *V : VL) {
4557     ++Idx;
4558 
4559     // Need to exclude undefs from analysis.
4560     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4561       continue;
4562 
4563     // Reached the start of a new vector registers.
4564     if (Idx % EltsPerVector == 0) {
4565       AllConsecutive = true;
4566       continue;
4567     }
4568 
4569     // Check all extracts for a vector register on the target directly
4570     // extract values in order.
4571     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4572     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4573       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4574       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4575                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4576     }
4577 
4578     if (AllConsecutive)
4579       continue;
4580 
4581     // Skip all indices, except for the last index per vector block.
4582     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4583       continue;
4584 
4585     // If we have a series of extracts which are not consecutive and hence
4586     // cannot re-use the source vector register directly, compute the shuffle
4587     // cost to extract the a vector with EltsPerVector elements.
4588     Cost += TTI.getShuffleCost(
4589         TargetTransformInfo::SK_PermuteSingleSrc,
4590         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4591   }
4592   return Cost;
4593 }
4594 
4595 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4596 /// operations operands.
4597 static void
4598 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4599                      ArrayRef<int> ReusesIndices,
4600                      const function_ref<bool(Instruction *)> IsAltOp,
4601                      SmallVectorImpl<int> &Mask,
4602                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4603                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4604   unsigned Sz = VL.size();
4605   Mask.assign(Sz, UndefMaskElem);
4606   SmallVector<int> OrderMask;
4607   if (!ReorderIndices.empty())
4608     inversePermutation(ReorderIndices, OrderMask);
4609   for (unsigned I = 0; I < Sz; ++I) {
4610     unsigned Idx = I;
4611     if (!ReorderIndices.empty())
4612       Idx = OrderMask[I];
4613     auto *OpInst = cast<Instruction>(VL[Idx]);
4614     if (IsAltOp(OpInst)) {
4615       Mask[I] = Sz + Idx;
4616       if (AltScalars)
4617         AltScalars->push_back(OpInst);
4618     } else {
4619       Mask[I] = Idx;
4620       if (OpScalars)
4621         OpScalars->push_back(OpInst);
4622     }
4623   }
4624   if (!ReusesIndices.empty()) {
4625     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4626     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4627       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4628     });
4629     Mask.swap(NewMask);
4630   }
4631 }
4632 
4633 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4634                                       ArrayRef<Value *> VectorizedVals) {
4635   ArrayRef<Value*> VL = E->Scalars;
4636 
4637   Type *ScalarTy = VL[0]->getType();
4638   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4639     ScalarTy = SI->getValueOperand()->getType();
4640   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4641     ScalarTy = CI->getOperand(0)->getType();
4642   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4643     ScalarTy = IE->getOperand(1)->getType();
4644   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4645   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4646 
4647   // If we have computed a smaller type for the expression, update VecTy so
4648   // that the costs will be accurate.
4649   if (MinBWs.count(VL[0]))
4650     VecTy = FixedVectorType::get(
4651         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4652   unsigned EntryVF = E->getVectorFactor();
4653   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4654 
4655   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4656   // FIXME: it tries to fix a problem with MSVC buildbots.
4657   TargetTransformInfo &TTIRef = *TTI;
4658   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4659                                VectorizedVals, E](InstructionCost &Cost) {
4660     DenseMap<Value *, int> ExtractVectorsTys;
4661     SmallPtrSet<Value *, 4> CheckedExtracts;
4662     for (auto *V : VL) {
4663       if (isa<UndefValue>(V))
4664         continue;
4665       // If all users of instruction are going to be vectorized and this
4666       // instruction itself is not going to be vectorized, consider this
4667       // instruction as dead and remove its cost from the final cost of the
4668       // vectorized tree.
4669       // Also, avoid adjusting the cost for extractelements with multiple uses
4670       // in different graph entries.
4671       const TreeEntry *VE = getTreeEntry(V);
4672       if (!CheckedExtracts.insert(V).second ||
4673           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4674           (VE && VE != E))
4675         continue;
4676       auto *EE = cast<ExtractElementInst>(V);
4677       Optional<unsigned> EEIdx = getExtractIndex(EE);
4678       if (!EEIdx)
4679         continue;
4680       unsigned Idx = *EEIdx;
4681       if (TTIRef.getNumberOfParts(VecTy) !=
4682           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4683         auto It =
4684             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4685         It->getSecond() = std::min<int>(It->second, Idx);
4686       }
4687       // Take credit for instruction that will become dead.
4688       if (EE->hasOneUse()) {
4689         Instruction *Ext = EE->user_back();
4690         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4691             all_of(Ext->users(),
4692                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4693           // Use getExtractWithExtendCost() to calculate the cost of
4694           // extractelement/ext pair.
4695           Cost -=
4696               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4697                                               EE->getVectorOperandType(), Idx);
4698           // Add back the cost of s|zext which is subtracted separately.
4699           Cost += TTIRef.getCastInstrCost(
4700               Ext->getOpcode(), Ext->getType(), EE->getType(),
4701               TTI::getCastContextHint(Ext), CostKind, Ext);
4702           continue;
4703         }
4704       }
4705       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4706                                         EE->getVectorOperandType(), Idx);
4707     }
4708     // Add a cost for subvector extracts/inserts if required.
4709     for (const auto &Data : ExtractVectorsTys) {
4710       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4711       unsigned NumElts = VecTy->getNumElements();
4712       if (Data.second % NumElts == 0)
4713         continue;
4714       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4715         unsigned Idx = (Data.second / NumElts) * NumElts;
4716         unsigned EENumElts = EEVTy->getNumElements();
4717         if (Idx + NumElts <= EENumElts) {
4718           Cost +=
4719               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4720                                     EEVTy, None, Idx, VecTy);
4721         } else {
4722           // Need to round up the subvector type vectorization factor to avoid a
4723           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4724           // <= EENumElts.
4725           auto *SubVT =
4726               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4727           Cost +=
4728               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4729                                     EEVTy, None, Idx, SubVT);
4730         }
4731       } else {
4732         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4733                                       VecTy, None, 0, EEVTy);
4734       }
4735     }
4736   };
4737   if (E->State == TreeEntry::NeedToGather) {
4738     if (allConstant(VL))
4739       return 0;
4740     if (isa<InsertElementInst>(VL[0]))
4741       return InstructionCost::getInvalid();
4742     SmallVector<int> Mask;
4743     SmallVector<const TreeEntry *> Entries;
4744     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4745         isGatherShuffledEntry(E, Mask, Entries);
4746     if (Shuffle.hasValue()) {
4747       InstructionCost GatherCost = 0;
4748       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4749         // Perfect match in the graph, will reuse the previously vectorized
4750         // node. Cost is 0.
4751         LLVM_DEBUG(
4752             dbgs()
4753             << "SLP: perfect diamond match for gather bundle that starts with "
4754             << *VL.front() << ".\n");
4755         if (NeedToShuffleReuses)
4756           GatherCost =
4757               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4758                                   FinalVecTy, E->ReuseShuffleIndices);
4759       } else {
4760         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4761                           << " entries for bundle that starts with "
4762                           << *VL.front() << ".\n");
4763         // Detected that instead of gather we can emit a shuffle of single/two
4764         // previously vectorized nodes. Add the cost of the permutation rather
4765         // than gather.
4766         ::addMask(Mask, E->ReuseShuffleIndices);
4767         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4768       }
4769       return GatherCost;
4770     }
4771     if ((E->getOpcode() == Instruction::ExtractElement ||
4772          all_of(E->Scalars,
4773                 [](Value *V) {
4774                   return isa<ExtractElementInst, UndefValue>(V);
4775                 })) &&
4776         allSameType(VL)) {
4777       // Check that gather of extractelements can be represented as just a
4778       // shuffle of a single/two vectors the scalars are extracted from.
4779       SmallVector<int> Mask;
4780       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4781           isFixedVectorShuffle(VL, Mask);
4782       if (ShuffleKind.hasValue()) {
4783         // Found the bunch of extractelement instructions that must be gathered
4784         // into a vector and can be represented as a permutation elements in a
4785         // single input vector or of 2 input vectors.
4786         InstructionCost Cost =
4787             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4788         AdjustExtractsCost(Cost);
4789         if (NeedToShuffleReuses)
4790           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4791                                       FinalVecTy, E->ReuseShuffleIndices);
4792         return Cost;
4793       }
4794     }
4795     if (isSplat(VL)) {
4796       // Found the broadcasting of the single scalar, calculate the cost as the
4797       // broadcast.
4798       assert(VecTy == FinalVecTy &&
4799              "No reused scalars expected for broadcast.");
4800       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4801     }
4802     InstructionCost ReuseShuffleCost = 0;
4803     if (NeedToShuffleReuses)
4804       ReuseShuffleCost = TTI->getShuffleCost(
4805           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4806     // Improve gather cost for gather of loads, if we can group some of the
4807     // loads into vector loads.
4808     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4809         !E->isAltShuffle()) {
4810       BoUpSLP::ValueSet VectorizedLoads;
4811       unsigned StartIdx = 0;
4812       unsigned VF = VL.size() / 2;
4813       unsigned VectorizedCnt = 0;
4814       unsigned ScatterVectorizeCnt = 0;
4815       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4816       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4817         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4818              Cnt += VF) {
4819           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4820           if (!VectorizedLoads.count(Slice.front()) &&
4821               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4822             SmallVector<Value *> PointerOps;
4823             OrdersType CurrentOrder;
4824             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4825                                               *SE, CurrentOrder, PointerOps);
4826             switch (LS) {
4827             case LoadsState::Vectorize:
4828             case LoadsState::ScatterVectorize:
4829               // Mark the vectorized loads so that we don't vectorize them
4830               // again.
4831               if (LS == LoadsState::Vectorize)
4832                 ++VectorizedCnt;
4833               else
4834                 ++ScatterVectorizeCnt;
4835               VectorizedLoads.insert(Slice.begin(), Slice.end());
4836               // If we vectorized initial block, no need to try to vectorize it
4837               // again.
4838               if (Cnt == StartIdx)
4839                 StartIdx += VF;
4840               break;
4841             case LoadsState::Gather:
4842               break;
4843             }
4844           }
4845         }
4846         // Check if the whole array was vectorized already - exit.
4847         if (StartIdx >= VL.size())
4848           break;
4849         // Found vectorizable parts - exit.
4850         if (!VectorizedLoads.empty())
4851           break;
4852       }
4853       if (!VectorizedLoads.empty()) {
4854         InstructionCost GatherCost = 0;
4855         unsigned NumParts = TTI->getNumberOfParts(VecTy);
4856         bool NeedInsertSubvectorAnalysis =
4857             !NumParts || (VL.size() / VF) > NumParts;
4858         // Get the cost for gathered loads.
4859         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4860           if (VectorizedLoads.contains(VL[I]))
4861             continue;
4862           GatherCost += getGatherCost(VL.slice(I, VF));
4863         }
4864         // The cost for vectorized loads.
4865         InstructionCost ScalarsCost = 0;
4866         for (Value *V : VectorizedLoads) {
4867           auto *LI = cast<LoadInst>(V);
4868           ScalarsCost += TTI->getMemoryOpCost(
4869               Instruction::Load, LI->getType(), LI->getAlign(),
4870               LI->getPointerAddressSpace(), CostKind, LI);
4871         }
4872         auto *LI = cast<LoadInst>(E->getMainOp());
4873         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4874         Align Alignment = LI->getAlign();
4875         GatherCost +=
4876             VectorizedCnt *
4877             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4878                                  LI->getPointerAddressSpace(), CostKind, LI);
4879         GatherCost += ScatterVectorizeCnt *
4880                       TTI->getGatherScatterOpCost(
4881                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4882                           /*VariableMask=*/false, Alignment, CostKind, LI);
4883         if (NeedInsertSubvectorAnalysis) {
4884           // Add the cost for the subvectors insert.
4885           for (int I = VF, E = VL.size(); I < E; I += VF)
4886             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
4887                                               None, I, LoadTy);
4888         }
4889         return ReuseShuffleCost + GatherCost - ScalarsCost;
4890       }
4891     }
4892     return ReuseShuffleCost + getGatherCost(VL);
4893   }
4894   InstructionCost CommonCost = 0;
4895   SmallVector<int> Mask;
4896   if (!E->ReorderIndices.empty()) {
4897     SmallVector<int> NewMask;
4898     if (E->getOpcode() == Instruction::Store) {
4899       // For stores the order is actually a mask.
4900       NewMask.resize(E->ReorderIndices.size());
4901       copy(E->ReorderIndices, NewMask.begin());
4902     } else {
4903       inversePermutation(E->ReorderIndices, NewMask);
4904     }
4905     ::addMask(Mask, NewMask);
4906   }
4907   if (NeedToShuffleReuses)
4908     ::addMask(Mask, E->ReuseShuffleIndices);
4909   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
4910     CommonCost =
4911         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
4912   assert((E->State == TreeEntry::Vectorize ||
4913           E->State == TreeEntry::ScatterVectorize) &&
4914          "Unhandled state");
4915   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
4916   Instruction *VL0 = E->getMainOp();
4917   unsigned ShuffleOrOp =
4918       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4919   switch (ShuffleOrOp) {
4920     case Instruction::PHI:
4921       return 0;
4922 
4923     case Instruction::ExtractValue:
4924     case Instruction::ExtractElement: {
4925       // The common cost of removal ExtractElement/ExtractValue instructions +
4926       // the cost of shuffles, if required to resuffle the original vector.
4927       if (NeedToShuffleReuses) {
4928         unsigned Idx = 0;
4929         for (unsigned I : E->ReuseShuffleIndices) {
4930           if (ShuffleOrOp == Instruction::ExtractElement) {
4931             auto *EE = cast<ExtractElementInst>(VL[I]);
4932             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4933                                                   EE->getVectorOperandType(),
4934                                                   *getExtractIndex(EE));
4935           } else {
4936             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4937                                                   VecTy, Idx);
4938             ++Idx;
4939           }
4940         }
4941         Idx = EntryVF;
4942         for (Value *V : VL) {
4943           if (ShuffleOrOp == Instruction::ExtractElement) {
4944             auto *EE = cast<ExtractElementInst>(V);
4945             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4946                                                   EE->getVectorOperandType(),
4947                                                   *getExtractIndex(EE));
4948           } else {
4949             --Idx;
4950             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4951                                                   VecTy, Idx);
4952           }
4953         }
4954       }
4955       if (ShuffleOrOp == Instruction::ExtractValue) {
4956         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
4957           auto *EI = cast<Instruction>(VL[I]);
4958           // Take credit for instruction that will become dead.
4959           if (EI->hasOneUse()) {
4960             Instruction *Ext = EI->user_back();
4961             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4962                 all_of(Ext->users(),
4963                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
4964               // Use getExtractWithExtendCost() to calculate the cost of
4965               // extractelement/ext pair.
4966               CommonCost -= TTI->getExtractWithExtendCost(
4967                   Ext->getOpcode(), Ext->getType(), VecTy, I);
4968               // Add back the cost of s|zext which is subtracted separately.
4969               CommonCost += TTI->getCastInstrCost(
4970                   Ext->getOpcode(), Ext->getType(), EI->getType(),
4971                   TTI::getCastContextHint(Ext), CostKind, Ext);
4972               continue;
4973             }
4974           }
4975           CommonCost -=
4976               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
4977         }
4978       } else {
4979         AdjustExtractsCost(CommonCost);
4980       }
4981       return CommonCost;
4982     }
4983     case Instruction::InsertElement: {
4984       assert(E->ReuseShuffleIndices.empty() &&
4985              "Unique insertelements only are expected.");
4986       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
4987 
4988       unsigned const NumElts = SrcVecTy->getNumElements();
4989       unsigned const NumScalars = VL.size();
4990       APInt DemandedElts = APInt::getZero(NumElts);
4991       // TODO: Add support for Instruction::InsertValue.
4992       SmallVector<int> Mask;
4993       if (!E->ReorderIndices.empty()) {
4994         inversePermutation(E->ReorderIndices, Mask);
4995         Mask.append(NumElts - NumScalars, UndefMaskElem);
4996       } else {
4997         Mask.assign(NumElts, UndefMaskElem);
4998         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
4999       }
5000       unsigned Offset = *getInsertIndex(VL0, 0);
5001       bool IsIdentity = true;
5002       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5003       Mask.swap(PrevMask);
5004       for (unsigned I = 0; I < NumScalars; ++I) {
5005         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
5006         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5007           continue;
5008         DemandedElts.setBit(*InsertIdx);
5009         IsIdentity &= *InsertIdx - Offset == I;
5010         Mask[*InsertIdx - Offset] = I;
5011       }
5012       assert(Offset < NumElts && "Failed to find vector index offset");
5013 
5014       InstructionCost Cost = 0;
5015       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5016                                             /*Insert*/ true, /*Extract*/ false);
5017 
5018       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5019         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5020         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5021         Cost += TTI->getShuffleCost(
5022             TargetTransformInfo::SK_PermuteSingleSrc,
5023             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5024       } else if (!IsIdentity) {
5025         auto *FirstInsert =
5026             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5027               return !is_contained(E->Scalars,
5028                                    cast<Instruction>(V)->getOperand(0));
5029             }));
5030         if (isUndefVector(FirstInsert->getOperand(0))) {
5031           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5032         } else {
5033           SmallVector<int> InsertMask(NumElts);
5034           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5035           for (unsigned I = 0; I < NumElts; I++) {
5036             if (Mask[I] != UndefMaskElem)
5037               InsertMask[Offset + I] = NumElts + I;
5038           }
5039           Cost +=
5040               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5041         }
5042       }
5043 
5044       return Cost;
5045     }
5046     case Instruction::ZExt:
5047     case Instruction::SExt:
5048     case Instruction::FPToUI:
5049     case Instruction::FPToSI:
5050     case Instruction::FPExt:
5051     case Instruction::PtrToInt:
5052     case Instruction::IntToPtr:
5053     case Instruction::SIToFP:
5054     case Instruction::UIToFP:
5055     case Instruction::Trunc:
5056     case Instruction::FPTrunc:
5057     case Instruction::BitCast: {
5058       Type *SrcTy = VL0->getOperand(0)->getType();
5059       InstructionCost ScalarEltCost =
5060           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5061                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5062       if (NeedToShuffleReuses) {
5063         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5064       }
5065 
5066       // Calculate the cost of this instruction.
5067       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5068 
5069       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5070       InstructionCost VecCost = 0;
5071       // Check if the values are candidates to demote.
5072       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5073         VecCost = CommonCost + TTI->getCastInstrCost(
5074                                    E->getOpcode(), VecTy, SrcVecTy,
5075                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5076       }
5077       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5078       return VecCost - ScalarCost;
5079     }
5080     case Instruction::FCmp:
5081     case Instruction::ICmp:
5082     case Instruction::Select: {
5083       // Calculate the cost of this instruction.
5084       InstructionCost ScalarEltCost =
5085           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5086                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5087       if (NeedToShuffleReuses) {
5088         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5089       }
5090       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5091       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5092 
5093       // Check if all entries in VL are either compares or selects with compares
5094       // as condition that have the same predicates.
5095       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5096       bool First = true;
5097       for (auto *V : VL) {
5098         CmpInst::Predicate CurrentPred;
5099         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5100         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5101              !match(V, MatchCmp)) ||
5102             (!First && VecPred != CurrentPred)) {
5103           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5104           break;
5105         }
5106         First = false;
5107         VecPred = CurrentPred;
5108       }
5109 
5110       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5111           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5112       // Check if it is possible and profitable to use min/max for selects in
5113       // VL.
5114       //
5115       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5116       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5117         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5118                                           {VecTy, VecTy});
5119         InstructionCost IntrinsicCost =
5120             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5121         // If the selects are the only uses of the compares, they will be dead
5122         // and we can adjust the cost by removing their cost.
5123         if (IntrinsicAndUse.second)
5124           IntrinsicCost -=
5125               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5126                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5127         VecCost = std::min(VecCost, IntrinsicCost);
5128       }
5129       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5130       return CommonCost + VecCost - ScalarCost;
5131     }
5132     case Instruction::FNeg:
5133     case Instruction::Add:
5134     case Instruction::FAdd:
5135     case Instruction::Sub:
5136     case Instruction::FSub:
5137     case Instruction::Mul:
5138     case Instruction::FMul:
5139     case Instruction::UDiv:
5140     case Instruction::SDiv:
5141     case Instruction::FDiv:
5142     case Instruction::URem:
5143     case Instruction::SRem:
5144     case Instruction::FRem:
5145     case Instruction::Shl:
5146     case Instruction::LShr:
5147     case Instruction::AShr:
5148     case Instruction::And:
5149     case Instruction::Or:
5150     case Instruction::Xor: {
5151       // Certain instructions can be cheaper to vectorize if they have a
5152       // constant second vector operand.
5153       TargetTransformInfo::OperandValueKind Op1VK =
5154           TargetTransformInfo::OK_AnyValue;
5155       TargetTransformInfo::OperandValueKind Op2VK =
5156           TargetTransformInfo::OK_UniformConstantValue;
5157       TargetTransformInfo::OperandValueProperties Op1VP =
5158           TargetTransformInfo::OP_None;
5159       TargetTransformInfo::OperandValueProperties Op2VP =
5160           TargetTransformInfo::OP_PowerOf2;
5161 
5162       // If all operands are exactly the same ConstantInt then set the
5163       // operand kind to OK_UniformConstantValue.
5164       // If instead not all operands are constants, then set the operand kind
5165       // to OK_AnyValue. If all operands are constants but not the same,
5166       // then set the operand kind to OK_NonUniformConstantValue.
5167       ConstantInt *CInt0 = nullptr;
5168       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5169         const Instruction *I = cast<Instruction>(VL[i]);
5170         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5171         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5172         if (!CInt) {
5173           Op2VK = TargetTransformInfo::OK_AnyValue;
5174           Op2VP = TargetTransformInfo::OP_None;
5175           break;
5176         }
5177         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5178             !CInt->getValue().isPowerOf2())
5179           Op2VP = TargetTransformInfo::OP_None;
5180         if (i == 0) {
5181           CInt0 = CInt;
5182           continue;
5183         }
5184         if (CInt0 != CInt)
5185           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5186       }
5187 
5188       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5189       InstructionCost ScalarEltCost =
5190           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5191                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5192       if (NeedToShuffleReuses) {
5193         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5194       }
5195       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5196       InstructionCost VecCost =
5197           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5198                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5199       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5200       return CommonCost + VecCost - ScalarCost;
5201     }
5202     case Instruction::GetElementPtr: {
5203       TargetTransformInfo::OperandValueKind Op1VK =
5204           TargetTransformInfo::OK_AnyValue;
5205       TargetTransformInfo::OperandValueKind Op2VK =
5206           TargetTransformInfo::OK_UniformConstantValue;
5207 
5208       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5209           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5210       if (NeedToShuffleReuses) {
5211         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5212       }
5213       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5214       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5215           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5216       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5217       return CommonCost + VecCost - ScalarCost;
5218     }
5219     case Instruction::Load: {
5220       // Cost of wide load - cost of scalar loads.
5221       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5222       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5223           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5224       if (NeedToShuffleReuses) {
5225         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5226       }
5227       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5228       InstructionCost VecLdCost;
5229       if (E->State == TreeEntry::Vectorize) {
5230         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5231                                          CostKind, VL0);
5232       } else {
5233         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5234         Align CommonAlignment = Alignment;
5235         for (Value *V : VL)
5236           CommonAlignment =
5237               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5238         VecLdCost = TTI->getGatherScatterOpCost(
5239             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5240             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5241       }
5242       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5243       return CommonCost + VecLdCost - ScalarLdCost;
5244     }
5245     case Instruction::Store: {
5246       // We know that we can merge the stores. Calculate the cost.
5247       bool IsReorder = !E->ReorderIndices.empty();
5248       auto *SI =
5249           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5250       Align Alignment = SI->getAlign();
5251       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5252           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5253       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5254       InstructionCost VecStCost = TTI->getMemoryOpCost(
5255           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5256       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5257       return CommonCost + VecStCost - ScalarStCost;
5258     }
5259     case Instruction::Call: {
5260       CallInst *CI = cast<CallInst>(VL0);
5261       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5262 
5263       // Calculate the cost of the scalar and vector calls.
5264       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5265       InstructionCost ScalarEltCost =
5266           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5267       if (NeedToShuffleReuses) {
5268         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5269       }
5270       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5271 
5272       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5273       InstructionCost VecCallCost =
5274           std::min(VecCallCosts.first, VecCallCosts.second);
5275 
5276       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5277                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5278                         << " for " << *CI << "\n");
5279 
5280       return CommonCost + VecCallCost - ScalarCallCost;
5281     }
5282     case Instruction::ShuffleVector: {
5283       assert(E->isAltShuffle() &&
5284              ((Instruction::isBinaryOp(E->getOpcode()) &&
5285                Instruction::isBinaryOp(E->getAltOpcode())) ||
5286               (Instruction::isCast(E->getOpcode()) &&
5287                Instruction::isCast(E->getAltOpcode()))) &&
5288              "Invalid Shuffle Vector Operand");
5289       InstructionCost ScalarCost = 0;
5290       if (NeedToShuffleReuses) {
5291         for (unsigned Idx : E->ReuseShuffleIndices) {
5292           Instruction *I = cast<Instruction>(VL[Idx]);
5293           CommonCost -= TTI->getInstructionCost(I, CostKind);
5294         }
5295         for (Value *V : VL) {
5296           Instruction *I = cast<Instruction>(V);
5297           CommonCost += TTI->getInstructionCost(I, CostKind);
5298         }
5299       }
5300       for (Value *V : VL) {
5301         Instruction *I = cast<Instruction>(V);
5302         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5303         ScalarCost += TTI->getInstructionCost(I, CostKind);
5304       }
5305       // VecCost is equal to sum of the cost of creating 2 vectors
5306       // and the cost of creating shuffle.
5307       InstructionCost VecCost = 0;
5308       // Try to find the previous shuffle node with the same operands and same
5309       // main/alternate ops.
5310       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5311         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5312           if (TE.get() == E)
5313             break;
5314           if (TE->isAltShuffle() &&
5315               ((TE->getOpcode() == E->getOpcode() &&
5316                 TE->getAltOpcode() == E->getAltOpcode()) ||
5317                (TE->getOpcode() == E->getAltOpcode() &&
5318                 TE->getAltOpcode() == E->getOpcode())) &&
5319               TE->hasEqualOperands(*E))
5320             return true;
5321         }
5322         return false;
5323       };
5324       if (TryFindNodeWithEqualOperands()) {
5325         LLVM_DEBUG({
5326           dbgs() << "SLP: diamond match for alternate node found.\n";
5327           E->dump();
5328         });
5329         // No need to add new vector costs here since we're going to reuse
5330         // same main/alternate vector ops, just do different shuffling.
5331       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5332         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5333         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5334                                                CostKind);
5335       } else {
5336         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5337         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5338         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5339         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5340         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5341                                         TTI::CastContextHint::None, CostKind);
5342         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5343                                          TTI::CastContextHint::None, CostKind);
5344       }
5345 
5346       SmallVector<int> Mask;
5347       buildSuffleEntryMask(
5348           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5349           [E](Instruction *I) {
5350             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5351             return I->getOpcode() == E->getAltOpcode();
5352           },
5353           Mask);
5354       CommonCost =
5355           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5356       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5357       return CommonCost + VecCost - ScalarCost;
5358     }
5359     default:
5360       llvm_unreachable("Unknown instruction");
5361   }
5362 }
5363 
5364 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5365   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5366                     << VectorizableTree.size() << " is fully vectorizable .\n");
5367 
5368   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5369     SmallVector<int> Mask;
5370     return TE->State == TreeEntry::NeedToGather &&
5371            !any_of(TE->Scalars,
5372                    [this](Value *V) { return EphValues.contains(V); }) &&
5373            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5374             TE->Scalars.size() < Limit ||
5375             ((TE->getOpcode() == Instruction::ExtractElement ||
5376               all_of(TE->Scalars,
5377                      [](Value *V) {
5378                        return isa<ExtractElementInst, UndefValue>(V);
5379                      })) &&
5380              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5381             (TE->State == TreeEntry::NeedToGather &&
5382              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5383   };
5384 
5385   // We only handle trees of heights 1 and 2.
5386   if (VectorizableTree.size() == 1 &&
5387       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5388        (ForReduction &&
5389         AreVectorizableGathers(VectorizableTree[0].get(),
5390                                VectorizableTree[0]->Scalars.size()) &&
5391         VectorizableTree[0]->getVectorFactor() > 2)))
5392     return true;
5393 
5394   if (VectorizableTree.size() != 2)
5395     return false;
5396 
5397   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5398   // with the second gather nodes if they have less scalar operands rather than
5399   // the initial tree element (may be profitable to shuffle the second gather)
5400   // or they are extractelements, which form shuffle.
5401   SmallVector<int> Mask;
5402   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5403       AreVectorizableGathers(VectorizableTree[1].get(),
5404                              VectorizableTree[0]->Scalars.size()))
5405     return true;
5406 
5407   // Gathering cost would be too much for tiny trees.
5408   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5409       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5410        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5411     return false;
5412 
5413   return true;
5414 }
5415 
5416 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5417                                        TargetTransformInfo *TTI,
5418                                        bool MustMatchOrInst) {
5419   // Look past the root to find a source value. Arbitrarily follow the
5420   // path through operand 0 of any 'or'. Also, peek through optional
5421   // shift-left-by-multiple-of-8-bits.
5422   Value *ZextLoad = Root;
5423   const APInt *ShAmtC;
5424   bool FoundOr = false;
5425   while (!isa<ConstantExpr>(ZextLoad) &&
5426          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5427           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5428            ShAmtC->urem(8) == 0))) {
5429     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5430     ZextLoad = BinOp->getOperand(0);
5431     if (BinOp->getOpcode() == Instruction::Or)
5432       FoundOr = true;
5433   }
5434   // Check if the input is an extended load of the required or/shift expression.
5435   Value *Load;
5436   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5437       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5438     return false;
5439 
5440   // Require that the total load bit width is a legal integer type.
5441   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5442   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5443   Type *SrcTy = Load->getType();
5444   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5445   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5446     return false;
5447 
5448   // Everything matched - assume that we can fold the whole sequence using
5449   // load combining.
5450   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5451              << *(cast<Instruction>(Root)) << "\n");
5452 
5453   return true;
5454 }
5455 
5456 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5457   if (RdxKind != RecurKind::Or)
5458     return false;
5459 
5460   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5461   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5462   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5463                                     /* MatchOr */ false);
5464 }
5465 
5466 bool BoUpSLP::isLoadCombineCandidate() const {
5467   // Peek through a final sequence of stores and check if all operations are
5468   // likely to be load-combined.
5469   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5470   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5471     Value *X;
5472     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5473         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5474       return false;
5475   }
5476   return true;
5477 }
5478 
5479 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5480   // No need to vectorize inserts of gathered values.
5481   if (VectorizableTree.size() == 2 &&
5482       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5483       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5484     return true;
5485 
5486   // We can vectorize the tree if its size is greater than or equal to the
5487   // minimum size specified by the MinTreeSize command line option.
5488   if (VectorizableTree.size() >= MinTreeSize)
5489     return false;
5490 
5491   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5492   // can vectorize it if we can prove it fully vectorizable.
5493   if (isFullyVectorizableTinyTree(ForReduction))
5494     return false;
5495 
5496   assert(VectorizableTree.empty()
5497              ? ExternalUses.empty()
5498              : true && "We shouldn't have any external users");
5499 
5500   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5501   // vectorizable.
5502   return true;
5503 }
5504 
5505 InstructionCost BoUpSLP::getSpillCost() const {
5506   // Walk from the bottom of the tree to the top, tracking which values are
5507   // live. When we see a call instruction that is not part of our tree,
5508   // query TTI to see if there is a cost to keeping values live over it
5509   // (for example, if spills and fills are required).
5510   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5511   InstructionCost Cost = 0;
5512 
5513   SmallPtrSet<Instruction*, 4> LiveValues;
5514   Instruction *PrevInst = nullptr;
5515 
5516   // The entries in VectorizableTree are not necessarily ordered by their
5517   // position in basic blocks. Collect them and order them by dominance so later
5518   // instructions are guaranteed to be visited first. For instructions in
5519   // different basic blocks, we only scan to the beginning of the block, so
5520   // their order does not matter, as long as all instructions in a basic block
5521   // are grouped together. Using dominance ensures a deterministic order.
5522   SmallVector<Instruction *, 16> OrderedScalars;
5523   for (const auto &TEPtr : VectorizableTree) {
5524     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5525     if (!Inst)
5526       continue;
5527     OrderedScalars.push_back(Inst);
5528   }
5529   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5530     auto *NodeA = DT->getNode(A->getParent());
5531     auto *NodeB = DT->getNode(B->getParent());
5532     assert(NodeA && "Should only process reachable instructions");
5533     assert(NodeB && "Should only process reachable instructions");
5534     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5535            "Different nodes should have different DFS numbers");
5536     if (NodeA != NodeB)
5537       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5538     return B->comesBefore(A);
5539   });
5540 
5541   for (Instruction *Inst : OrderedScalars) {
5542     if (!PrevInst) {
5543       PrevInst = Inst;
5544       continue;
5545     }
5546 
5547     // Update LiveValues.
5548     LiveValues.erase(PrevInst);
5549     for (auto &J : PrevInst->operands()) {
5550       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5551         LiveValues.insert(cast<Instruction>(&*J));
5552     }
5553 
5554     LLVM_DEBUG({
5555       dbgs() << "SLP: #LV: " << LiveValues.size();
5556       for (auto *X : LiveValues)
5557         dbgs() << " " << X->getName();
5558       dbgs() << ", Looking at ";
5559       Inst->dump();
5560     });
5561 
5562     // Now find the sequence of instructions between PrevInst and Inst.
5563     unsigned NumCalls = 0;
5564     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5565                                  PrevInstIt =
5566                                      PrevInst->getIterator().getReverse();
5567     while (InstIt != PrevInstIt) {
5568       if (PrevInstIt == PrevInst->getParent()->rend()) {
5569         PrevInstIt = Inst->getParent()->rbegin();
5570         continue;
5571       }
5572 
5573       // Debug information does not impact spill cost.
5574       if ((isa<CallInst>(&*PrevInstIt) &&
5575            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5576           &*PrevInstIt != PrevInst)
5577         NumCalls++;
5578 
5579       ++PrevInstIt;
5580     }
5581 
5582     if (NumCalls) {
5583       SmallVector<Type*, 4> V;
5584       for (auto *II : LiveValues) {
5585         auto *ScalarTy = II->getType();
5586         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5587           ScalarTy = VectorTy->getElementType();
5588         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5589       }
5590       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5591     }
5592 
5593     PrevInst = Inst;
5594   }
5595 
5596   return Cost;
5597 }
5598 
5599 /// Check if two insertelement instructions are from the same buildvector.
5600 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5601                                             InsertElementInst *V) {
5602   // Instructions must be from the same basic blocks.
5603   if (VU->getParent() != V->getParent())
5604     return false;
5605   // Checks if 2 insertelements are from the same buildvector.
5606   if (VU->getType() != V->getType())
5607     return false;
5608   // Multiple used inserts are separate nodes.
5609   if (!VU->hasOneUse() && !V->hasOneUse())
5610     return false;
5611   auto *IE1 = VU;
5612   auto *IE2 = V;
5613   // Go through the vector operand of insertelement instructions trying to find
5614   // either VU as the original vector for IE2 or V as the original vector for
5615   // IE1.
5616   do {
5617     if (IE2 == VU || IE1 == V)
5618       return true;
5619     if (IE1) {
5620       if (IE1 != VU && !IE1->hasOneUse())
5621         IE1 = nullptr;
5622       else
5623         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5624     }
5625     if (IE2) {
5626       if (IE2 != V && !IE2->hasOneUse())
5627         IE2 = nullptr;
5628       else
5629         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5630     }
5631   } while (IE1 || IE2);
5632   return false;
5633 }
5634 
5635 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5636   InstructionCost Cost = 0;
5637   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5638                     << VectorizableTree.size() << ".\n");
5639 
5640   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5641 
5642   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5643     TreeEntry &TE = *VectorizableTree[I].get();
5644 
5645     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5646     Cost += C;
5647     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5648                       << " for bundle that starts with " << *TE.Scalars[0]
5649                       << ".\n"
5650                       << "SLP: Current total cost = " << Cost << "\n");
5651   }
5652 
5653   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5654   InstructionCost ExtractCost = 0;
5655   SmallVector<unsigned> VF;
5656   SmallVector<SmallVector<int>> ShuffleMask;
5657   SmallVector<Value *> FirstUsers;
5658   SmallVector<APInt> DemandedElts;
5659   for (ExternalUser &EU : ExternalUses) {
5660     // We only add extract cost once for the same scalar.
5661     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5662         !ExtractCostCalculated.insert(EU.Scalar).second)
5663       continue;
5664 
5665     // Uses by ephemeral values are free (because the ephemeral value will be
5666     // removed prior to code generation, and so the extraction will be
5667     // removed as well).
5668     if (EphValues.count(EU.User))
5669       continue;
5670 
5671     // No extract cost for vector "scalar"
5672     if (isa<FixedVectorType>(EU.Scalar->getType()))
5673       continue;
5674 
5675     // Already counted the cost for external uses when tried to adjust the cost
5676     // for extractelements, no need to add it again.
5677     if (isa<ExtractElementInst>(EU.Scalar))
5678       continue;
5679 
5680     // If found user is an insertelement, do not calculate extract cost but try
5681     // to detect it as a final shuffled/identity match.
5682     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5683       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5684         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5685         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5686           continue;
5687         auto *It = find_if(FirstUsers, [VU](Value *V) {
5688           return areTwoInsertFromSameBuildVector(VU,
5689                                                  cast<InsertElementInst>(V));
5690         });
5691         int VecId = -1;
5692         if (It == FirstUsers.end()) {
5693           VF.push_back(FTy->getNumElements());
5694           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5695           // Find the insertvector, vectorized in tree, if any.
5696           Value *Base = VU;
5697           while (isa<InsertElementInst>(Base)) {
5698             // Build the mask for the vectorized insertelement instructions.
5699             if (const TreeEntry *E = getTreeEntry(Base)) {
5700               VU = cast<InsertElementInst>(Base);
5701               do {
5702                 int Idx = E->findLaneForValue(Base);
5703                 ShuffleMask.back()[Idx] = Idx;
5704                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5705               } while (E == getTreeEntry(Base));
5706               break;
5707             }
5708             Base = cast<InsertElementInst>(Base)->getOperand(0);
5709           }
5710           FirstUsers.push_back(VU);
5711           DemandedElts.push_back(APInt::getZero(VF.back()));
5712           VecId = FirstUsers.size() - 1;
5713         } else {
5714           VecId = std::distance(FirstUsers.begin(), It);
5715         }
5716         int Idx = *InsertIdx;
5717         ShuffleMask[VecId][Idx] = EU.Lane;
5718         DemandedElts[VecId].setBit(Idx);
5719         continue;
5720       }
5721     }
5722 
5723     // If we plan to rewrite the tree in a smaller type, we will need to sign
5724     // extend the extracted value back to the original type. Here, we account
5725     // for the extract and the added cost of the sign extend if needed.
5726     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5727     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5728     if (MinBWs.count(ScalarRoot)) {
5729       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5730       auto Extend =
5731           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5732       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5733       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5734                                                    VecTy, EU.Lane);
5735     } else {
5736       ExtractCost +=
5737           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5738     }
5739   }
5740 
5741   InstructionCost SpillCost = getSpillCost();
5742   Cost += SpillCost + ExtractCost;
5743   if (FirstUsers.size() == 1) {
5744     int Limit = ShuffleMask.front().size() * 2;
5745     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5746         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5747       InstructionCost C = TTI->getShuffleCost(
5748           TTI::SK_PermuteSingleSrc,
5749           cast<FixedVectorType>(FirstUsers.front()->getType()),
5750           ShuffleMask.front());
5751       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5752                         << " for final shuffle of insertelement external users "
5753                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5754                         << "SLP: Current total cost = " << Cost << "\n");
5755       Cost += C;
5756     }
5757     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5758         cast<FixedVectorType>(FirstUsers.front()->getType()),
5759         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5760     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5761                       << " for insertelements gather.\n"
5762                       << "SLP: Current total cost = " << Cost << "\n");
5763     Cost -= InsertCost;
5764   } else if (FirstUsers.size() >= 2) {
5765     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5766     // Combined masks of the first 2 vectors.
5767     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5768     copy(ShuffleMask.front(), CombinedMask.begin());
5769     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5770     auto *VecTy = FixedVectorType::get(
5771         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5772         MaxVF);
5773     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5774       if (ShuffleMask[1][I] != UndefMaskElem) {
5775         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5776         CombinedDemandedElts.setBit(I);
5777       }
5778     }
5779     InstructionCost C =
5780         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5781     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5782                       << " for final shuffle of vector node and external "
5783                          "insertelement users "
5784                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5785                       << "SLP: Current total cost = " << Cost << "\n");
5786     Cost += C;
5787     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5788         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5789     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5790                       << " for insertelements gather.\n"
5791                       << "SLP: Current total cost = " << Cost << "\n");
5792     Cost -= InsertCost;
5793     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5794       // Other elements - permutation of 2 vectors (the initial one and the
5795       // next Ith incoming vector).
5796       unsigned VF = ShuffleMask[I].size();
5797       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5798         int Mask = ShuffleMask[I][Idx];
5799         if (Mask != UndefMaskElem)
5800           CombinedMask[Idx] = MaxVF + Mask;
5801         else if (CombinedMask[Idx] != UndefMaskElem)
5802           CombinedMask[Idx] = Idx;
5803       }
5804       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5805         if (CombinedMask[Idx] != UndefMaskElem)
5806           CombinedMask[Idx] = Idx;
5807       InstructionCost C =
5808           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5809       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5810                         << " for final shuffle of vector node and external "
5811                            "insertelement users "
5812                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5813                         << "SLP: Current total cost = " << Cost << "\n");
5814       Cost += C;
5815       InstructionCost InsertCost = TTI->getScalarizationOverhead(
5816           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5817           /*Insert*/ true, /*Extract*/ false);
5818       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5819                         << " for insertelements gather.\n"
5820                         << "SLP: Current total cost = " << Cost << "\n");
5821       Cost -= InsertCost;
5822     }
5823   }
5824 
5825 #ifndef NDEBUG
5826   SmallString<256> Str;
5827   {
5828     raw_svector_ostream OS(Str);
5829     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5830        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5831        << "SLP: Total Cost = " << Cost << ".\n";
5832   }
5833   LLVM_DEBUG(dbgs() << Str);
5834   if (ViewSLPTree)
5835     ViewGraph(this, "SLP" + F->getName(), false, Str);
5836 #endif
5837 
5838   return Cost;
5839 }
5840 
5841 Optional<TargetTransformInfo::ShuffleKind>
5842 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5843                                SmallVectorImpl<const TreeEntry *> &Entries) {
5844   // TODO: currently checking only for Scalars in the tree entry, need to count
5845   // reused elements too for better cost estimation.
5846   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5847   Entries.clear();
5848   // Build a lists of values to tree entries.
5849   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5850   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5851     if (EntryPtr.get() == TE)
5852       break;
5853     if (EntryPtr->State != TreeEntry::NeedToGather)
5854       continue;
5855     for (Value *V : EntryPtr->Scalars)
5856       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5857   }
5858   // Find all tree entries used by the gathered values. If no common entries
5859   // found - not a shuffle.
5860   // Here we build a set of tree nodes for each gathered value and trying to
5861   // find the intersection between these sets. If we have at least one common
5862   // tree node for each gathered value - we have just a permutation of the
5863   // single vector. If we have 2 different sets, we're in situation where we
5864   // have a permutation of 2 input vectors.
5865   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5866   DenseMap<Value *, int> UsedValuesEntry;
5867   for (Value *V : TE->Scalars) {
5868     if (isa<UndefValue>(V))
5869       continue;
5870     // Build a list of tree entries where V is used.
5871     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5872     auto It = ValueToTEs.find(V);
5873     if (It != ValueToTEs.end())
5874       VToTEs = It->second;
5875     if (const TreeEntry *VTE = getTreeEntry(V))
5876       VToTEs.insert(VTE);
5877     if (VToTEs.empty())
5878       return None;
5879     if (UsedTEs.empty()) {
5880       // The first iteration, just insert the list of nodes to vector.
5881       UsedTEs.push_back(VToTEs);
5882     } else {
5883       // Need to check if there are any previously used tree nodes which use V.
5884       // If there are no such nodes, consider that we have another one input
5885       // vector.
5886       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
5887       unsigned Idx = 0;
5888       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
5889         // Do we have a non-empty intersection of previously listed tree entries
5890         // and tree entries using current V?
5891         set_intersect(VToTEs, Set);
5892         if (!VToTEs.empty()) {
5893           // Yes, write the new subset and continue analysis for the next
5894           // scalar.
5895           Set.swap(VToTEs);
5896           break;
5897         }
5898         VToTEs = SavedVToTEs;
5899         ++Idx;
5900       }
5901       // No non-empty intersection found - need to add a second set of possible
5902       // source vectors.
5903       if (Idx == UsedTEs.size()) {
5904         // If the number of input vectors is greater than 2 - not a permutation,
5905         // fallback to the regular gather.
5906         if (UsedTEs.size() == 2)
5907           return None;
5908         UsedTEs.push_back(SavedVToTEs);
5909         Idx = UsedTEs.size() - 1;
5910       }
5911       UsedValuesEntry.try_emplace(V, Idx);
5912     }
5913   }
5914 
5915   unsigned VF = 0;
5916   if (UsedTEs.size() == 1) {
5917     // Try to find the perfect match in another gather node at first.
5918     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
5919       return EntryPtr->isSame(TE->Scalars);
5920     });
5921     if (It != UsedTEs.front().end()) {
5922       Entries.push_back(*It);
5923       std::iota(Mask.begin(), Mask.end(), 0);
5924       return TargetTransformInfo::SK_PermuteSingleSrc;
5925     }
5926     // No perfect match, just shuffle, so choose the first tree node.
5927     Entries.push_back(*UsedTEs.front().begin());
5928   } else {
5929     // Try to find nodes with the same vector factor.
5930     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
5931     DenseMap<int, const TreeEntry *> VFToTE;
5932     for (const TreeEntry *TE : UsedTEs.front())
5933       VFToTE.try_emplace(TE->getVectorFactor(), TE);
5934     for (const TreeEntry *TE : UsedTEs.back()) {
5935       auto It = VFToTE.find(TE->getVectorFactor());
5936       if (It != VFToTE.end()) {
5937         VF = It->first;
5938         Entries.push_back(It->second);
5939         Entries.push_back(TE);
5940         break;
5941       }
5942     }
5943     // No 2 source vectors with the same vector factor - give up and do regular
5944     // gather.
5945     if (Entries.empty())
5946       return None;
5947   }
5948 
5949   // Build a shuffle mask for better cost estimation and vector emission.
5950   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
5951     Value *V = TE->Scalars[I];
5952     if (isa<UndefValue>(V))
5953       continue;
5954     unsigned Idx = UsedValuesEntry.lookup(V);
5955     const TreeEntry *VTE = Entries[Idx];
5956     int FoundLane = VTE->findLaneForValue(V);
5957     Mask[I] = Idx * VF + FoundLane;
5958     // Extra check required by isSingleSourceMaskImpl function (called by
5959     // ShuffleVectorInst::isSingleSourceMask).
5960     if (Mask[I] >= 2 * E)
5961       return None;
5962   }
5963   switch (Entries.size()) {
5964   case 1:
5965     return TargetTransformInfo::SK_PermuteSingleSrc;
5966   case 2:
5967     return TargetTransformInfo::SK_PermuteTwoSrc;
5968   default:
5969     break;
5970   }
5971   return None;
5972 }
5973 
5974 InstructionCost
5975 BoUpSLP::getGatherCost(FixedVectorType *Ty,
5976                        const DenseSet<unsigned> &ShuffledIndices,
5977                        bool NeedToShuffle) const {
5978   unsigned NumElts = Ty->getNumElements();
5979   APInt DemandedElts = APInt::getZero(NumElts);
5980   for (unsigned I = 0; I < NumElts; ++I)
5981     if (!ShuffledIndices.count(I))
5982       DemandedElts.setBit(I);
5983   InstructionCost Cost =
5984       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
5985                                     /*Extract*/ false);
5986   if (NeedToShuffle)
5987     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
5988   return Cost;
5989 }
5990 
5991 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
5992   // Find the type of the operands in VL.
5993   Type *ScalarTy = VL[0]->getType();
5994   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5995     ScalarTy = SI->getValueOperand()->getType();
5996   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5997   bool DuplicateNonConst = false;
5998   // Find the cost of inserting/extracting values from the vector.
5999   // Check if the same elements are inserted several times and count them as
6000   // shuffle candidates.
6001   DenseSet<unsigned> ShuffledElements;
6002   DenseSet<Value *> UniqueElements;
6003   // Iterate in reverse order to consider insert elements with the high cost.
6004   for (unsigned I = VL.size(); I > 0; --I) {
6005     unsigned Idx = I - 1;
6006     // No need to shuffle duplicates for constants.
6007     if (isConstant(VL[Idx])) {
6008       ShuffledElements.insert(Idx);
6009       continue;
6010     }
6011     if (!UniqueElements.insert(VL[Idx]).second) {
6012       DuplicateNonConst = true;
6013       ShuffledElements.insert(Idx);
6014     }
6015   }
6016   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6017 }
6018 
6019 // Perform operand reordering on the instructions in VL and return the reordered
6020 // operands in Left and Right.
6021 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6022                                              SmallVectorImpl<Value *> &Left,
6023                                              SmallVectorImpl<Value *> &Right,
6024                                              const DataLayout &DL,
6025                                              ScalarEvolution &SE,
6026                                              const BoUpSLP &R) {
6027   if (VL.empty())
6028     return;
6029   VLOperands Ops(VL, DL, SE, R);
6030   // Reorder the operands in place.
6031   Ops.reorder();
6032   Left = Ops.getVL(0);
6033   Right = Ops.getVL(1);
6034 }
6035 
6036 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6037   // Get the basic block this bundle is in. All instructions in the bundle
6038   // should be in this block.
6039   auto *Front = E->getMainOp();
6040   auto *BB = Front->getParent();
6041   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6042     auto *I = cast<Instruction>(V);
6043     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6044   }));
6045 
6046   // The last instruction in the bundle in program order.
6047   Instruction *LastInst = nullptr;
6048 
6049   // Find the last instruction. The common case should be that BB has been
6050   // scheduled, and the last instruction is VL.back(). So we start with
6051   // VL.back() and iterate over schedule data until we reach the end of the
6052   // bundle. The end of the bundle is marked by null ScheduleData.
6053   if (BlocksSchedules.count(BB)) {
6054     auto *Bundle =
6055         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6056     if (Bundle && Bundle->isPartOfBundle())
6057       for (; Bundle; Bundle = Bundle->NextInBundle)
6058         if (Bundle->OpValue == Bundle->Inst)
6059           LastInst = Bundle->Inst;
6060   }
6061 
6062   // LastInst can still be null at this point if there's either not an entry
6063   // for BB in BlocksSchedules or there's no ScheduleData available for
6064   // VL.back(). This can be the case if buildTree_rec aborts for various
6065   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6066   // size is reached, etc.). ScheduleData is initialized in the scheduling
6067   // "dry-run".
6068   //
6069   // If this happens, we can still find the last instruction by brute force. We
6070   // iterate forwards from Front (inclusive) until we either see all
6071   // instructions in the bundle or reach the end of the block. If Front is the
6072   // last instruction in program order, LastInst will be set to Front, and we
6073   // will visit all the remaining instructions in the block.
6074   //
6075   // One of the reasons we exit early from buildTree_rec is to place an upper
6076   // bound on compile-time. Thus, taking an additional compile-time hit here is
6077   // not ideal. However, this should be exceedingly rare since it requires that
6078   // we both exit early from buildTree_rec and that the bundle be out-of-order
6079   // (causing us to iterate all the way to the end of the block).
6080   if (!LastInst) {
6081     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6082     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6083       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6084         LastInst = &I;
6085       if (Bundle.empty())
6086         break;
6087     }
6088   }
6089   assert(LastInst && "Failed to find last instruction in bundle");
6090 
6091   // Set the insertion point after the last instruction in the bundle. Set the
6092   // debug location to Front.
6093   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6094   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6095 }
6096 
6097 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6098   // List of instructions/lanes from current block and/or the blocks which are
6099   // part of the current loop. These instructions will be inserted at the end to
6100   // make it possible to optimize loops and hoist invariant instructions out of
6101   // the loops body with better chances for success.
6102   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6103   SmallSet<int, 4> PostponedIndices;
6104   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6105   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6106     SmallPtrSet<BasicBlock *, 4> Visited;
6107     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6108       InsertBB = InsertBB->getSinglePredecessor();
6109     return InsertBB && InsertBB == InstBB;
6110   };
6111   for (int I = 0, E = VL.size(); I < E; ++I) {
6112     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6113       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6114            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6115           PostponedIndices.insert(I).second)
6116         PostponedInsts.emplace_back(Inst, I);
6117   }
6118 
6119   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6120     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6121     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6122     if (!InsElt)
6123       return Vec;
6124     GatherShuffleSeq.insert(InsElt);
6125     CSEBlocks.insert(InsElt->getParent());
6126     // Add to our 'need-to-extract' list.
6127     if (TreeEntry *Entry = getTreeEntry(V)) {
6128       // Find which lane we need to extract.
6129       unsigned FoundLane = Entry->findLaneForValue(V);
6130       ExternalUses.emplace_back(V, InsElt, FoundLane);
6131     }
6132     return Vec;
6133   };
6134   Value *Val0 =
6135       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6136   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6137   Value *Vec = PoisonValue::get(VecTy);
6138   SmallVector<int> NonConsts;
6139   // Insert constant values at first.
6140   for (int I = 0, E = VL.size(); I < E; ++I) {
6141     if (PostponedIndices.contains(I))
6142       continue;
6143     if (!isConstant(VL[I])) {
6144       NonConsts.push_back(I);
6145       continue;
6146     }
6147     Vec = CreateInsertElement(Vec, VL[I], I);
6148   }
6149   // Insert non-constant values.
6150   for (int I : NonConsts)
6151     Vec = CreateInsertElement(Vec, VL[I], I);
6152   // Append instructions, which are/may be part of the loop, in the end to make
6153   // it possible to hoist non-loop-based instructions.
6154   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6155     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6156 
6157   return Vec;
6158 }
6159 
6160 namespace {
6161 /// Merges shuffle masks and emits final shuffle instruction, if required.
6162 class ShuffleInstructionBuilder {
6163   IRBuilderBase &Builder;
6164   const unsigned VF = 0;
6165   bool IsFinalized = false;
6166   SmallVector<int, 4> Mask;
6167   /// Holds all of the instructions that we gathered.
6168   SetVector<Instruction *> &GatherShuffleSeq;
6169   /// A list of blocks that we are going to CSE.
6170   SetVector<BasicBlock *> &CSEBlocks;
6171 
6172 public:
6173   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6174                             SetVector<Instruction *> &GatherShuffleSeq,
6175                             SetVector<BasicBlock *> &CSEBlocks)
6176       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6177         CSEBlocks(CSEBlocks) {}
6178 
6179   /// Adds a mask, inverting it before applying.
6180   void addInversedMask(ArrayRef<unsigned> SubMask) {
6181     if (SubMask.empty())
6182       return;
6183     SmallVector<int, 4> NewMask;
6184     inversePermutation(SubMask, NewMask);
6185     addMask(NewMask);
6186   }
6187 
6188   /// Functions adds masks, merging them into  single one.
6189   void addMask(ArrayRef<unsigned> SubMask) {
6190     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6191     addMask(NewMask);
6192   }
6193 
6194   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6195 
6196   Value *finalize(Value *V) {
6197     IsFinalized = true;
6198     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6199     if (VF == ValueVF && Mask.empty())
6200       return V;
6201     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6202     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6203     addMask(NormalizedMask);
6204 
6205     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6206       return V;
6207     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6208     if (auto *I = dyn_cast<Instruction>(Vec)) {
6209       GatherShuffleSeq.insert(I);
6210       CSEBlocks.insert(I->getParent());
6211     }
6212     return Vec;
6213   }
6214 
6215   ~ShuffleInstructionBuilder() {
6216     assert((IsFinalized || Mask.empty()) &&
6217            "Shuffle construction must be finalized.");
6218   }
6219 };
6220 } // namespace
6221 
6222 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6223   unsigned VF = VL.size();
6224   InstructionsState S = getSameOpcode(VL);
6225   if (S.getOpcode()) {
6226     if (TreeEntry *E = getTreeEntry(S.OpValue))
6227       if (E->isSame(VL)) {
6228         Value *V = vectorizeTree(E);
6229         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6230           if (!E->ReuseShuffleIndices.empty()) {
6231             // Reshuffle to get only unique values.
6232             // If some of the scalars are duplicated in the vectorization tree
6233             // entry, we do not vectorize them but instead generate a mask for
6234             // the reuses. But if there are several users of the same entry,
6235             // they may have different vectorization factors. This is especially
6236             // important for PHI nodes. In this case, we need to adapt the
6237             // resulting instruction for the user vectorization factor and have
6238             // to reshuffle it again to take only unique elements of the vector.
6239             // Without this code the function incorrectly returns reduced vector
6240             // instruction with the same elements, not with the unique ones.
6241 
6242             // block:
6243             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6244             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6245             // ... (use %2)
6246             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6247             // br %block
6248             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6249             SmallSet<int, 4> UsedIdxs;
6250             int Pos = 0;
6251             int Sz = VL.size();
6252             for (int Idx : E->ReuseShuffleIndices) {
6253               if (Idx != Sz && Idx != UndefMaskElem &&
6254                   UsedIdxs.insert(Idx).second)
6255                 UniqueIdxs[Idx] = Pos;
6256               ++Pos;
6257             }
6258             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6259                                             "less than original vector size.");
6260             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6261             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6262           } else {
6263             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6264                    "Expected vectorization factor less "
6265                    "than original vector size.");
6266             SmallVector<int> UniformMask(VF, 0);
6267             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6268             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6269           }
6270           if (auto *I = dyn_cast<Instruction>(V)) {
6271             GatherShuffleSeq.insert(I);
6272             CSEBlocks.insert(I->getParent());
6273           }
6274         }
6275         return V;
6276       }
6277   }
6278 
6279   // Check that every instruction appears once in this bundle.
6280   SmallVector<int> ReuseShuffleIndicies;
6281   SmallVector<Value *> UniqueValues;
6282   if (VL.size() > 2) {
6283     DenseMap<Value *, unsigned> UniquePositions;
6284     unsigned NumValues =
6285         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6286                                     return !isa<UndefValue>(V);
6287                                   }).base());
6288     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6289     int UniqueVals = 0;
6290     for (Value *V : VL.drop_back(VL.size() - VF)) {
6291       if (isa<UndefValue>(V)) {
6292         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6293         continue;
6294       }
6295       if (isConstant(V)) {
6296         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6297         UniqueValues.emplace_back(V);
6298         continue;
6299       }
6300       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6301       ReuseShuffleIndicies.emplace_back(Res.first->second);
6302       if (Res.second) {
6303         UniqueValues.emplace_back(V);
6304         ++UniqueVals;
6305       }
6306     }
6307     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6308       // Emit pure splat vector.
6309       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6310                                   UndefMaskElem);
6311     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6312       ReuseShuffleIndicies.clear();
6313       UniqueValues.clear();
6314       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6315     }
6316     UniqueValues.append(VF - UniqueValues.size(),
6317                         PoisonValue::get(VL[0]->getType()));
6318     VL = UniqueValues;
6319   }
6320 
6321   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6322                                            CSEBlocks);
6323   Value *Vec = gather(VL);
6324   if (!ReuseShuffleIndicies.empty()) {
6325     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6326     Vec = ShuffleBuilder.finalize(Vec);
6327   }
6328   return Vec;
6329 }
6330 
6331 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6332   IRBuilder<>::InsertPointGuard Guard(Builder);
6333 
6334   if (E->VectorizedValue) {
6335     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6336     return E->VectorizedValue;
6337   }
6338 
6339   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6340   unsigned VF = E->getVectorFactor();
6341   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6342                                            CSEBlocks);
6343   if (E->State == TreeEntry::NeedToGather) {
6344     if (E->getMainOp())
6345       setInsertPointAfterBundle(E);
6346     Value *Vec;
6347     SmallVector<int> Mask;
6348     SmallVector<const TreeEntry *> Entries;
6349     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6350         isGatherShuffledEntry(E, Mask, Entries);
6351     if (Shuffle.hasValue()) {
6352       assert((Entries.size() == 1 || Entries.size() == 2) &&
6353              "Expected shuffle of 1 or 2 entries.");
6354       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6355                                         Entries.back()->VectorizedValue, Mask);
6356       if (auto *I = dyn_cast<Instruction>(Vec)) {
6357         GatherShuffleSeq.insert(I);
6358         CSEBlocks.insert(I->getParent());
6359       }
6360     } else {
6361       Vec = gather(E->Scalars);
6362     }
6363     if (NeedToShuffleReuses) {
6364       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6365       Vec = ShuffleBuilder.finalize(Vec);
6366     }
6367     E->VectorizedValue = Vec;
6368     return Vec;
6369   }
6370 
6371   assert((E->State == TreeEntry::Vectorize ||
6372           E->State == TreeEntry::ScatterVectorize) &&
6373          "Unhandled state");
6374   unsigned ShuffleOrOp =
6375       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6376   Instruction *VL0 = E->getMainOp();
6377   Type *ScalarTy = VL0->getType();
6378   if (auto *Store = dyn_cast<StoreInst>(VL0))
6379     ScalarTy = Store->getValueOperand()->getType();
6380   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6381     ScalarTy = IE->getOperand(1)->getType();
6382   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6383   switch (ShuffleOrOp) {
6384     case Instruction::PHI: {
6385       assert(
6386           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6387           "PHI reordering is free.");
6388       auto *PH = cast<PHINode>(VL0);
6389       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6390       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6391       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6392       Value *V = NewPhi;
6393       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6394       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6395       V = ShuffleBuilder.finalize(V);
6396 
6397       E->VectorizedValue = V;
6398 
6399       // PHINodes may have multiple entries from the same block. We want to
6400       // visit every block once.
6401       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6402 
6403       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6404         ValueList Operands;
6405         BasicBlock *IBB = PH->getIncomingBlock(i);
6406 
6407         if (!VisitedBBs.insert(IBB).second) {
6408           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6409           continue;
6410         }
6411 
6412         Builder.SetInsertPoint(IBB->getTerminator());
6413         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6414         Value *Vec = vectorizeTree(E->getOperand(i));
6415         NewPhi->addIncoming(Vec, IBB);
6416       }
6417 
6418       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6419              "Invalid number of incoming values");
6420       return V;
6421     }
6422 
6423     case Instruction::ExtractElement: {
6424       Value *V = E->getSingleOperand(0);
6425       Builder.SetInsertPoint(VL0);
6426       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6427       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6428       V = ShuffleBuilder.finalize(V);
6429       E->VectorizedValue = V;
6430       return V;
6431     }
6432     case Instruction::ExtractValue: {
6433       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6434       Builder.SetInsertPoint(LI);
6435       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6436       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6437       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6438       Value *NewV = propagateMetadata(V, E->Scalars);
6439       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6440       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6441       NewV = ShuffleBuilder.finalize(NewV);
6442       E->VectorizedValue = NewV;
6443       return NewV;
6444     }
6445     case Instruction::InsertElement: {
6446       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6447       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6448       Value *V = vectorizeTree(E->getOperand(1));
6449 
6450       // Create InsertVector shuffle if necessary
6451       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6452         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6453       }));
6454       const unsigned NumElts =
6455           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6456       const unsigned NumScalars = E->Scalars.size();
6457 
6458       unsigned Offset = *getInsertIndex(VL0, 0);
6459       assert(Offset < NumElts && "Failed to find vector index offset");
6460 
6461       // Create shuffle to resize vector
6462       SmallVector<int> Mask;
6463       if (!E->ReorderIndices.empty()) {
6464         inversePermutation(E->ReorderIndices, Mask);
6465         Mask.append(NumElts - NumScalars, UndefMaskElem);
6466       } else {
6467         Mask.assign(NumElts, UndefMaskElem);
6468         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6469       }
6470       // Create InsertVector shuffle if necessary
6471       bool IsIdentity = true;
6472       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6473       Mask.swap(PrevMask);
6474       for (unsigned I = 0; I < NumScalars; ++I) {
6475         Value *Scalar = E->Scalars[PrevMask[I]];
6476         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6477         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6478           continue;
6479         IsIdentity &= *InsertIdx - Offset == I;
6480         Mask[*InsertIdx - Offset] = I;
6481       }
6482       if (!IsIdentity || NumElts != NumScalars) {
6483         V = Builder.CreateShuffleVector(V, Mask);
6484         if (auto *I = dyn_cast<Instruction>(V)) {
6485           GatherShuffleSeq.insert(I);
6486           CSEBlocks.insert(I->getParent());
6487         }
6488       }
6489 
6490       if ((!IsIdentity || Offset != 0 ||
6491            !isUndefVector(FirstInsert->getOperand(0))) &&
6492           NumElts != NumScalars) {
6493         SmallVector<int> InsertMask(NumElts);
6494         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6495         for (unsigned I = 0; I < NumElts; I++) {
6496           if (Mask[I] != UndefMaskElem)
6497             InsertMask[Offset + I] = NumElts + I;
6498         }
6499 
6500         V = Builder.CreateShuffleVector(
6501             FirstInsert->getOperand(0), V, InsertMask,
6502             cast<Instruction>(E->Scalars.back())->getName());
6503         if (auto *I = dyn_cast<Instruction>(V)) {
6504           GatherShuffleSeq.insert(I);
6505           CSEBlocks.insert(I->getParent());
6506         }
6507       }
6508 
6509       ++NumVectorInstructions;
6510       E->VectorizedValue = V;
6511       return V;
6512     }
6513     case Instruction::ZExt:
6514     case Instruction::SExt:
6515     case Instruction::FPToUI:
6516     case Instruction::FPToSI:
6517     case Instruction::FPExt:
6518     case Instruction::PtrToInt:
6519     case Instruction::IntToPtr:
6520     case Instruction::SIToFP:
6521     case Instruction::UIToFP:
6522     case Instruction::Trunc:
6523     case Instruction::FPTrunc:
6524     case Instruction::BitCast: {
6525       setInsertPointAfterBundle(E);
6526 
6527       Value *InVec = vectorizeTree(E->getOperand(0));
6528 
6529       if (E->VectorizedValue) {
6530         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6531         return E->VectorizedValue;
6532       }
6533 
6534       auto *CI = cast<CastInst>(VL0);
6535       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6536       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6537       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6538       V = ShuffleBuilder.finalize(V);
6539 
6540       E->VectorizedValue = V;
6541       ++NumVectorInstructions;
6542       return V;
6543     }
6544     case Instruction::FCmp:
6545     case Instruction::ICmp: {
6546       setInsertPointAfterBundle(E);
6547 
6548       Value *L = vectorizeTree(E->getOperand(0));
6549       Value *R = vectorizeTree(E->getOperand(1));
6550 
6551       if (E->VectorizedValue) {
6552         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6553         return E->VectorizedValue;
6554       }
6555 
6556       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6557       Value *V = Builder.CreateCmp(P0, L, R);
6558       propagateIRFlags(V, E->Scalars, VL0);
6559       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6560       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6561       V = ShuffleBuilder.finalize(V);
6562 
6563       E->VectorizedValue = V;
6564       ++NumVectorInstructions;
6565       return V;
6566     }
6567     case Instruction::Select: {
6568       setInsertPointAfterBundle(E);
6569 
6570       Value *Cond = vectorizeTree(E->getOperand(0));
6571       Value *True = vectorizeTree(E->getOperand(1));
6572       Value *False = vectorizeTree(E->getOperand(2));
6573 
6574       if (E->VectorizedValue) {
6575         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6576         return E->VectorizedValue;
6577       }
6578 
6579       Value *V = Builder.CreateSelect(Cond, True, False);
6580       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6581       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6582       V = ShuffleBuilder.finalize(V);
6583 
6584       E->VectorizedValue = V;
6585       ++NumVectorInstructions;
6586       return V;
6587     }
6588     case Instruction::FNeg: {
6589       setInsertPointAfterBundle(E);
6590 
6591       Value *Op = vectorizeTree(E->getOperand(0));
6592 
6593       if (E->VectorizedValue) {
6594         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6595         return E->VectorizedValue;
6596       }
6597 
6598       Value *V = Builder.CreateUnOp(
6599           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6600       propagateIRFlags(V, E->Scalars, VL0);
6601       if (auto *I = dyn_cast<Instruction>(V))
6602         V = propagateMetadata(I, E->Scalars);
6603 
6604       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6605       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6606       V = ShuffleBuilder.finalize(V);
6607 
6608       E->VectorizedValue = V;
6609       ++NumVectorInstructions;
6610 
6611       return V;
6612     }
6613     case Instruction::Add:
6614     case Instruction::FAdd:
6615     case Instruction::Sub:
6616     case Instruction::FSub:
6617     case Instruction::Mul:
6618     case Instruction::FMul:
6619     case Instruction::UDiv:
6620     case Instruction::SDiv:
6621     case Instruction::FDiv:
6622     case Instruction::URem:
6623     case Instruction::SRem:
6624     case Instruction::FRem:
6625     case Instruction::Shl:
6626     case Instruction::LShr:
6627     case Instruction::AShr:
6628     case Instruction::And:
6629     case Instruction::Or:
6630     case Instruction::Xor: {
6631       setInsertPointAfterBundle(E);
6632 
6633       Value *LHS = vectorizeTree(E->getOperand(0));
6634       Value *RHS = vectorizeTree(E->getOperand(1));
6635 
6636       if (E->VectorizedValue) {
6637         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6638         return E->VectorizedValue;
6639       }
6640 
6641       Value *V = Builder.CreateBinOp(
6642           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6643           RHS);
6644       propagateIRFlags(V, E->Scalars, VL0);
6645       if (auto *I = dyn_cast<Instruction>(V))
6646         V = propagateMetadata(I, E->Scalars);
6647 
6648       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6649       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6650       V = ShuffleBuilder.finalize(V);
6651 
6652       E->VectorizedValue = V;
6653       ++NumVectorInstructions;
6654 
6655       return V;
6656     }
6657     case Instruction::Load: {
6658       // Loads are inserted at the head of the tree because we don't want to
6659       // sink them all the way down past store instructions.
6660       setInsertPointAfterBundle(E);
6661 
6662       LoadInst *LI = cast<LoadInst>(VL0);
6663       Instruction *NewLI;
6664       unsigned AS = LI->getPointerAddressSpace();
6665       Value *PO = LI->getPointerOperand();
6666       if (E->State == TreeEntry::Vectorize) {
6667 
6668         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6669 
6670         // The pointer operand uses an in-tree scalar so we add the new BitCast
6671         // to ExternalUses list to make sure that an extract will be generated
6672         // in the future.
6673         if (TreeEntry *Entry = getTreeEntry(PO)) {
6674           // Find which lane we need to extract.
6675           unsigned FoundLane = Entry->findLaneForValue(PO);
6676           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6677         }
6678 
6679         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6680       } else {
6681         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6682         Value *VecPtr = vectorizeTree(E->getOperand(0));
6683         // Use the minimum alignment of the gathered loads.
6684         Align CommonAlignment = LI->getAlign();
6685         for (Value *V : E->Scalars)
6686           CommonAlignment =
6687               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6688         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6689       }
6690       Value *V = propagateMetadata(NewLI, E->Scalars);
6691 
6692       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6693       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6694       V = ShuffleBuilder.finalize(V);
6695       E->VectorizedValue = V;
6696       ++NumVectorInstructions;
6697       return V;
6698     }
6699     case Instruction::Store: {
6700       auto *SI = cast<StoreInst>(VL0);
6701       unsigned AS = SI->getPointerAddressSpace();
6702 
6703       setInsertPointAfterBundle(E);
6704 
6705       Value *VecValue = vectorizeTree(E->getOperand(0));
6706       ShuffleBuilder.addMask(E->ReorderIndices);
6707       VecValue = ShuffleBuilder.finalize(VecValue);
6708 
6709       Value *ScalarPtr = SI->getPointerOperand();
6710       Value *VecPtr = Builder.CreateBitCast(
6711           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6712       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6713                                                  SI->getAlign());
6714 
6715       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6716       // ExternalUses to make sure that an extract will be generated in the
6717       // future.
6718       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6719         // Find which lane we need to extract.
6720         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6721         ExternalUses.push_back(
6722             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6723       }
6724 
6725       Value *V = propagateMetadata(ST, E->Scalars);
6726 
6727       E->VectorizedValue = V;
6728       ++NumVectorInstructions;
6729       return V;
6730     }
6731     case Instruction::GetElementPtr: {
6732       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6733       setInsertPointAfterBundle(E);
6734 
6735       Value *Op0 = vectorizeTree(E->getOperand(0));
6736 
6737       SmallVector<Value *> OpVecs;
6738       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6739         Value *OpVec = vectorizeTree(E->getOperand(J));
6740         OpVecs.push_back(OpVec);
6741       }
6742 
6743       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6744       if (Instruction *I = dyn_cast<Instruction>(V))
6745         V = propagateMetadata(I, E->Scalars);
6746 
6747       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6748       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6749       V = ShuffleBuilder.finalize(V);
6750 
6751       E->VectorizedValue = V;
6752       ++NumVectorInstructions;
6753 
6754       return V;
6755     }
6756     case Instruction::Call: {
6757       CallInst *CI = cast<CallInst>(VL0);
6758       setInsertPointAfterBundle(E);
6759 
6760       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6761       if (Function *FI = CI->getCalledFunction())
6762         IID = FI->getIntrinsicID();
6763 
6764       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6765 
6766       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6767       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6768                           VecCallCosts.first <= VecCallCosts.second;
6769 
6770       Value *ScalarArg = nullptr;
6771       std::vector<Value *> OpVecs;
6772       SmallVector<Type *, 2> TysForDecl =
6773           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6774       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6775         ValueList OpVL;
6776         // Some intrinsics have scalar arguments. This argument should not be
6777         // vectorized.
6778         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6779           CallInst *CEI = cast<CallInst>(VL0);
6780           ScalarArg = CEI->getArgOperand(j);
6781           OpVecs.push_back(CEI->getArgOperand(j));
6782           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6783             TysForDecl.push_back(ScalarArg->getType());
6784           continue;
6785         }
6786 
6787         Value *OpVec = vectorizeTree(E->getOperand(j));
6788         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6789         OpVecs.push_back(OpVec);
6790       }
6791 
6792       Function *CF;
6793       if (!UseIntrinsic) {
6794         VFShape Shape =
6795             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6796                                   VecTy->getNumElements())),
6797                          false /*HasGlobalPred*/);
6798         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6799       } else {
6800         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6801       }
6802 
6803       SmallVector<OperandBundleDef, 1> OpBundles;
6804       CI->getOperandBundlesAsDefs(OpBundles);
6805       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6806 
6807       // The scalar argument uses an in-tree scalar so we add the new vectorized
6808       // call to ExternalUses list to make sure that an extract will be
6809       // generated in the future.
6810       if (ScalarArg) {
6811         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6812           // Find which lane we need to extract.
6813           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6814           ExternalUses.push_back(
6815               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6816         }
6817       }
6818 
6819       propagateIRFlags(V, E->Scalars, VL0);
6820       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6821       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6822       V = ShuffleBuilder.finalize(V);
6823 
6824       E->VectorizedValue = V;
6825       ++NumVectorInstructions;
6826       return V;
6827     }
6828     case Instruction::ShuffleVector: {
6829       assert(E->isAltShuffle() &&
6830              ((Instruction::isBinaryOp(E->getOpcode()) &&
6831                Instruction::isBinaryOp(E->getAltOpcode())) ||
6832               (Instruction::isCast(E->getOpcode()) &&
6833                Instruction::isCast(E->getAltOpcode()))) &&
6834              "Invalid Shuffle Vector Operand");
6835 
6836       Value *LHS = nullptr, *RHS = nullptr;
6837       if (Instruction::isBinaryOp(E->getOpcode())) {
6838         setInsertPointAfterBundle(E);
6839         LHS = vectorizeTree(E->getOperand(0));
6840         RHS = vectorizeTree(E->getOperand(1));
6841       } else {
6842         setInsertPointAfterBundle(E);
6843         LHS = vectorizeTree(E->getOperand(0));
6844       }
6845 
6846       if (E->VectorizedValue) {
6847         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6848         return E->VectorizedValue;
6849       }
6850 
6851       Value *V0, *V1;
6852       if (Instruction::isBinaryOp(E->getOpcode())) {
6853         V0 = Builder.CreateBinOp(
6854             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6855         V1 = Builder.CreateBinOp(
6856             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6857       } else {
6858         V0 = Builder.CreateCast(
6859             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6860         V1 = Builder.CreateCast(
6861             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6862       }
6863       // Add V0 and V1 to later analysis to try to find and remove matching
6864       // instruction, if any.
6865       for (Value *V : {V0, V1}) {
6866         if (auto *I = dyn_cast<Instruction>(V)) {
6867           GatherShuffleSeq.insert(I);
6868           CSEBlocks.insert(I->getParent());
6869         }
6870       }
6871 
6872       // Create shuffle to take alternate operations from the vector.
6873       // Also, gather up main and alt scalar ops to propagate IR flags to
6874       // each vector operation.
6875       ValueList OpScalars, AltScalars;
6876       SmallVector<int> Mask;
6877       buildSuffleEntryMask(
6878           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6879           [E](Instruction *I) {
6880             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6881             return I->getOpcode() == E->getAltOpcode();
6882           },
6883           Mask, &OpScalars, &AltScalars);
6884 
6885       propagateIRFlags(V0, OpScalars);
6886       propagateIRFlags(V1, AltScalars);
6887 
6888       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
6889       if (auto *I = dyn_cast<Instruction>(V)) {
6890         V = propagateMetadata(I, E->Scalars);
6891         GatherShuffleSeq.insert(I);
6892         CSEBlocks.insert(I->getParent());
6893       }
6894       V = ShuffleBuilder.finalize(V);
6895 
6896       E->VectorizedValue = V;
6897       ++NumVectorInstructions;
6898 
6899       return V;
6900     }
6901     default:
6902     llvm_unreachable("unknown inst");
6903   }
6904   return nullptr;
6905 }
6906 
6907 Value *BoUpSLP::vectorizeTree() {
6908   ExtraValueToDebugLocsMap ExternallyUsedValues;
6909   return vectorizeTree(ExternallyUsedValues);
6910 }
6911 
6912 Value *
6913 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
6914   // All blocks must be scheduled before any instructions are inserted.
6915   for (auto &BSIter : BlocksSchedules) {
6916     scheduleBlock(BSIter.second.get());
6917   }
6918 
6919   Builder.SetInsertPoint(&F->getEntryBlock().front());
6920   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
6921 
6922   // If the vectorized tree can be rewritten in a smaller type, we truncate the
6923   // vectorized root. InstCombine will then rewrite the entire expression. We
6924   // sign extend the extracted values below.
6925   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6926   if (MinBWs.count(ScalarRoot)) {
6927     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
6928       // If current instr is a phi and not the last phi, insert it after the
6929       // last phi node.
6930       if (isa<PHINode>(I))
6931         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
6932       else
6933         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
6934     }
6935     auto BundleWidth = VectorizableTree[0]->Scalars.size();
6936     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6937     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
6938     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
6939     VectorizableTree[0]->VectorizedValue = Trunc;
6940   }
6941 
6942   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
6943                     << " values .\n");
6944 
6945   // Extract all of the elements with the external uses.
6946   for (const auto &ExternalUse : ExternalUses) {
6947     Value *Scalar = ExternalUse.Scalar;
6948     llvm::User *User = ExternalUse.User;
6949 
6950     // Skip users that we already RAUW. This happens when one instruction
6951     // has multiple uses of the same value.
6952     if (User && !is_contained(Scalar->users(), User))
6953       continue;
6954     TreeEntry *E = getTreeEntry(Scalar);
6955     assert(E && "Invalid scalar");
6956     assert(E->State != TreeEntry::NeedToGather &&
6957            "Extracting from a gather list");
6958 
6959     Value *Vec = E->VectorizedValue;
6960     assert(Vec && "Can't find vectorizable value");
6961 
6962     Value *Lane = Builder.getInt32(ExternalUse.Lane);
6963     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
6964       if (Scalar->getType() != Vec->getType()) {
6965         Value *Ex;
6966         // "Reuse" the existing extract to improve final codegen.
6967         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
6968           Ex = Builder.CreateExtractElement(ES->getOperand(0),
6969                                             ES->getOperand(1));
6970         } else {
6971           Ex = Builder.CreateExtractElement(Vec, Lane);
6972         }
6973         // If necessary, sign-extend or zero-extend ScalarRoot
6974         // to the larger type.
6975         if (!MinBWs.count(ScalarRoot))
6976           return Ex;
6977         if (MinBWs[ScalarRoot].second)
6978           return Builder.CreateSExt(Ex, Scalar->getType());
6979         return Builder.CreateZExt(Ex, Scalar->getType());
6980       }
6981       assert(isa<FixedVectorType>(Scalar->getType()) &&
6982              isa<InsertElementInst>(Scalar) &&
6983              "In-tree scalar of vector type is not insertelement?");
6984       return Vec;
6985     };
6986     // If User == nullptr, the Scalar is used as extra arg. Generate
6987     // ExtractElement instruction and update the record for this scalar in
6988     // ExternallyUsedValues.
6989     if (!User) {
6990       assert(ExternallyUsedValues.count(Scalar) &&
6991              "Scalar with nullptr as an external user must be registered in "
6992              "ExternallyUsedValues map");
6993       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6994         Builder.SetInsertPoint(VecI->getParent(),
6995                                std::next(VecI->getIterator()));
6996       } else {
6997         Builder.SetInsertPoint(&F->getEntryBlock().front());
6998       }
6999       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7000       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7001       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7002       auto It = ExternallyUsedValues.find(Scalar);
7003       assert(It != ExternallyUsedValues.end() &&
7004              "Externally used scalar is not found in ExternallyUsedValues");
7005       NewInstLocs.append(It->second);
7006       ExternallyUsedValues.erase(Scalar);
7007       // Required to update internally referenced instructions.
7008       Scalar->replaceAllUsesWith(NewInst);
7009       continue;
7010     }
7011 
7012     // Generate extracts for out-of-tree users.
7013     // Find the insertion point for the extractelement lane.
7014     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7015       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7016         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7017           if (PH->getIncomingValue(i) == Scalar) {
7018             Instruction *IncomingTerminator =
7019                 PH->getIncomingBlock(i)->getTerminator();
7020             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7021               Builder.SetInsertPoint(VecI->getParent(),
7022                                      std::next(VecI->getIterator()));
7023             } else {
7024               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7025             }
7026             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7027             CSEBlocks.insert(PH->getIncomingBlock(i));
7028             PH->setOperand(i, NewInst);
7029           }
7030         }
7031       } else {
7032         Builder.SetInsertPoint(cast<Instruction>(User));
7033         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7034         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7035         User->replaceUsesOfWith(Scalar, NewInst);
7036       }
7037     } else {
7038       Builder.SetInsertPoint(&F->getEntryBlock().front());
7039       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7040       CSEBlocks.insert(&F->getEntryBlock());
7041       User->replaceUsesOfWith(Scalar, NewInst);
7042     }
7043 
7044     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7045   }
7046 
7047   // For each vectorized value:
7048   for (auto &TEPtr : VectorizableTree) {
7049     TreeEntry *Entry = TEPtr.get();
7050 
7051     // No need to handle users of gathered values.
7052     if (Entry->State == TreeEntry::NeedToGather)
7053       continue;
7054 
7055     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7056 
7057     // For each lane:
7058     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7059       Value *Scalar = Entry->Scalars[Lane];
7060 
7061 #ifndef NDEBUG
7062       Type *Ty = Scalar->getType();
7063       if (!Ty->isVoidTy()) {
7064         for (User *U : Scalar->users()) {
7065           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7066 
7067           // It is legal to delete users in the ignorelist.
7068           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7069                   (isa_and_nonnull<Instruction>(U) &&
7070                    isDeleted(cast<Instruction>(U)))) &&
7071                  "Deleting out-of-tree value");
7072         }
7073       }
7074 #endif
7075       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7076       eraseInstruction(cast<Instruction>(Scalar));
7077     }
7078   }
7079 
7080   Builder.ClearInsertionPoint();
7081   InstrElementSize.clear();
7082 
7083   return VectorizableTree[0]->VectorizedValue;
7084 }
7085 
7086 void BoUpSLP::optimizeGatherSequence() {
7087   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7088                     << " gather sequences instructions.\n");
7089   // LICM InsertElementInst sequences.
7090   for (Instruction *I : GatherShuffleSeq) {
7091     if (isDeleted(I))
7092       continue;
7093 
7094     // Check if this block is inside a loop.
7095     Loop *L = LI->getLoopFor(I->getParent());
7096     if (!L)
7097       continue;
7098 
7099     // Check if it has a preheader.
7100     BasicBlock *PreHeader = L->getLoopPreheader();
7101     if (!PreHeader)
7102       continue;
7103 
7104     // If the vector or the element that we insert into it are
7105     // instructions that are defined in this basic block then we can't
7106     // hoist this instruction.
7107     if (any_of(I->operands(), [L](Value *V) {
7108           auto *OpI = dyn_cast<Instruction>(V);
7109           return OpI && L->contains(OpI);
7110         }))
7111       continue;
7112 
7113     // We can hoist this instruction. Move it to the pre-header.
7114     I->moveBefore(PreHeader->getTerminator());
7115   }
7116 
7117   // Make a list of all reachable blocks in our CSE queue.
7118   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7119   CSEWorkList.reserve(CSEBlocks.size());
7120   for (BasicBlock *BB : CSEBlocks)
7121     if (DomTreeNode *N = DT->getNode(BB)) {
7122       assert(DT->isReachableFromEntry(N));
7123       CSEWorkList.push_back(N);
7124     }
7125 
7126   // Sort blocks by domination. This ensures we visit a block after all blocks
7127   // dominating it are visited.
7128   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7129     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7130            "Different nodes should have different DFS numbers");
7131     return A->getDFSNumIn() < B->getDFSNumIn();
7132   });
7133 
7134   // Less defined shuffles can be replaced by the more defined copies.
7135   // Between two shuffles one is less defined if it has the same vector operands
7136   // and its mask indeces are the same as in the first one or undefs. E.g.
7137   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7138   // poison, <0, 0, 0, 0>.
7139   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7140                                            SmallVectorImpl<int> &NewMask) {
7141     if (I1->getType() != I2->getType())
7142       return false;
7143     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7144     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7145     if (!SI1 || !SI2)
7146       return I1->isIdenticalTo(I2);
7147     if (SI1->isIdenticalTo(SI2))
7148       return true;
7149     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7150       if (SI1->getOperand(I) != SI2->getOperand(I))
7151         return false;
7152     // Check if the second instruction is more defined than the first one.
7153     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7154     ArrayRef<int> SM1 = SI1->getShuffleMask();
7155     // Count trailing undefs in the mask to check the final number of used
7156     // registers.
7157     unsigned LastUndefsCnt = 0;
7158     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7159       if (SM1[I] == UndefMaskElem)
7160         ++LastUndefsCnt;
7161       else
7162         LastUndefsCnt = 0;
7163       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7164           NewMask[I] != SM1[I])
7165         return false;
7166       if (NewMask[I] == UndefMaskElem)
7167         NewMask[I] = SM1[I];
7168     }
7169     // Check if the last undefs actually change the final number of used vector
7170     // registers.
7171     return SM1.size() - LastUndefsCnt > 1 &&
7172            TTI->getNumberOfParts(SI1->getType()) ==
7173                TTI->getNumberOfParts(
7174                    FixedVectorType::get(SI1->getType()->getElementType(),
7175                                         SM1.size() - LastUndefsCnt));
7176   };
7177   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7178   // instructions. TODO: We can further optimize this scan if we split the
7179   // instructions into different buckets based on the insert lane.
7180   SmallVector<Instruction *, 16> Visited;
7181   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7182     assert(*I &&
7183            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7184            "Worklist not sorted properly!");
7185     BasicBlock *BB = (*I)->getBlock();
7186     // For all instructions in blocks containing gather sequences:
7187     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7188       if (isDeleted(&In))
7189         continue;
7190       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7191           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7192         continue;
7193 
7194       // Check if we can replace this instruction with any of the
7195       // visited instructions.
7196       bool Replaced = false;
7197       for (Instruction *&V : Visited) {
7198         SmallVector<int> NewMask;
7199         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7200             DT->dominates(V->getParent(), In.getParent())) {
7201           In.replaceAllUsesWith(V);
7202           eraseInstruction(&In);
7203           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7204             if (!NewMask.empty())
7205               SI->setShuffleMask(NewMask);
7206           Replaced = true;
7207           break;
7208         }
7209         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7210             GatherShuffleSeq.contains(V) &&
7211             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7212             DT->dominates(In.getParent(), V->getParent())) {
7213           In.moveAfter(V);
7214           V->replaceAllUsesWith(&In);
7215           eraseInstruction(V);
7216           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7217             if (!NewMask.empty())
7218               SI->setShuffleMask(NewMask);
7219           V = &In;
7220           Replaced = true;
7221           break;
7222         }
7223       }
7224       if (!Replaced) {
7225         assert(!is_contained(Visited, &In));
7226         Visited.push_back(&In);
7227       }
7228     }
7229   }
7230   CSEBlocks.clear();
7231   GatherShuffleSeq.clear();
7232 }
7233 
7234 BoUpSLP::ScheduleData *
7235 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7236   ScheduleData *Bundle = nullptr;
7237   ScheduleData *PrevInBundle = nullptr;
7238   for (Value *V : VL) {
7239     ScheduleData *BundleMember = getScheduleData(V);
7240     assert(BundleMember &&
7241            "no ScheduleData for bundle member "
7242            "(maybe not in same basic block)");
7243     assert(BundleMember->isSchedulingEntity() &&
7244            "bundle member already part of other bundle");
7245     if (PrevInBundle) {
7246       PrevInBundle->NextInBundle = BundleMember;
7247     } else {
7248       Bundle = BundleMember;
7249     }
7250     BundleMember->UnscheduledDepsInBundle = 0;
7251     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7252 
7253     // Group the instructions to a bundle.
7254     BundleMember->FirstInBundle = Bundle;
7255     PrevInBundle = BundleMember;
7256   }
7257   assert(Bundle && "Failed to find schedule bundle");
7258   return Bundle;
7259 }
7260 
7261 // Groups the instructions to a bundle (which is then a single scheduling entity)
7262 // and schedules instructions until the bundle gets ready.
7263 Optional<BoUpSLP::ScheduleData *>
7264 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7265                                             const InstructionsState &S) {
7266   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7267   // instructions.
7268   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7269     return nullptr;
7270 
7271   // Initialize the instruction bundle.
7272   Instruction *OldScheduleEnd = ScheduleEnd;
7273   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7274 
7275   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7276                                                          ScheduleData *Bundle) {
7277     // The scheduling region got new instructions at the lower end (or it is a
7278     // new region for the first bundle). This makes it necessary to
7279     // recalculate all dependencies.
7280     // It is seldom that this needs to be done a second time after adding the
7281     // initial bundle to the region.
7282     if (ScheduleEnd != OldScheduleEnd) {
7283       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7284         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7285       ReSchedule = true;
7286     }
7287     if (ReSchedule) {
7288       resetSchedule();
7289       initialFillReadyList(ReadyInsts);
7290     }
7291     if (Bundle) {
7292       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7293                         << " in block " << BB->getName() << "\n");
7294       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7295     }
7296 
7297     // Now try to schedule the new bundle or (if no bundle) just calculate
7298     // dependencies. As soon as the bundle is "ready" it means that there are no
7299     // cyclic dependencies and we can schedule it. Note that's important that we
7300     // don't "schedule" the bundle yet (see cancelScheduling).
7301     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7302            !ReadyInsts.empty()) {
7303       ScheduleData *Picked = ReadyInsts.pop_back_val();
7304       if (Picked->isSchedulingEntity() && Picked->isReady())
7305         schedule(Picked, ReadyInsts);
7306     }
7307   };
7308 
7309   // Make sure that the scheduling region contains all
7310   // instructions of the bundle.
7311   for (Value *V : VL) {
7312     if (!extendSchedulingRegion(V, S)) {
7313       // If the scheduling region got new instructions at the lower end (or it
7314       // is a new region for the first bundle). This makes it necessary to
7315       // recalculate all dependencies.
7316       // Otherwise the compiler may crash trying to incorrectly calculate
7317       // dependencies and emit instruction in the wrong order at the actual
7318       // scheduling.
7319       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7320       return None;
7321     }
7322   }
7323 
7324   bool ReSchedule = false;
7325   for (Value *V : VL) {
7326     ScheduleData *BundleMember = getScheduleData(V);
7327     assert(BundleMember &&
7328            "no ScheduleData for bundle member (maybe not in same basic block)");
7329     if (!BundleMember->IsScheduled)
7330       continue;
7331     // A bundle member was scheduled as single instruction before and now
7332     // needs to be scheduled as part of the bundle. We just get rid of the
7333     // existing schedule.
7334     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7335                       << " was already scheduled\n");
7336     ReSchedule = true;
7337   }
7338 
7339   auto *Bundle = buildBundle(VL);
7340   TryScheduleBundleImpl(ReSchedule, Bundle);
7341   if (!Bundle->isReady()) {
7342     cancelScheduling(VL, S.OpValue);
7343     return None;
7344   }
7345   return Bundle;
7346 }
7347 
7348 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7349                                                 Value *OpValue) {
7350   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7351     return;
7352 
7353   ScheduleData *Bundle = getScheduleData(OpValue);
7354   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7355   assert(!Bundle->IsScheduled &&
7356          "Can't cancel bundle which is already scheduled");
7357   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7358          "tried to unbundle something which is not a bundle");
7359 
7360   // Un-bundle: make single instructions out of the bundle.
7361   ScheduleData *BundleMember = Bundle;
7362   while (BundleMember) {
7363     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7364     BundleMember->FirstInBundle = BundleMember;
7365     ScheduleData *Next = BundleMember->NextInBundle;
7366     BundleMember->NextInBundle = nullptr;
7367     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7368     if (BundleMember->UnscheduledDepsInBundle == 0) {
7369       ReadyInsts.insert(BundleMember);
7370     }
7371     BundleMember = Next;
7372   }
7373 }
7374 
7375 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7376   // Allocate a new ScheduleData for the instruction.
7377   if (ChunkPos >= ChunkSize) {
7378     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7379     ChunkPos = 0;
7380   }
7381   return &(ScheduleDataChunks.back()[ChunkPos++]);
7382 }
7383 
7384 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7385                                                       const InstructionsState &S) {
7386   if (getScheduleData(V, isOneOf(S, V)))
7387     return true;
7388   Instruction *I = dyn_cast<Instruction>(V);
7389   assert(I && "bundle member must be an instruction");
7390   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7391          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7392          "be scheduled");
7393   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7394     ScheduleData *ISD = getScheduleData(I);
7395     if (!ISD)
7396       return false;
7397     assert(isInSchedulingRegion(ISD) &&
7398            "ScheduleData not in scheduling region");
7399     ScheduleData *SD = allocateScheduleDataChunks();
7400     SD->Inst = I;
7401     SD->init(SchedulingRegionID, S.OpValue);
7402     ExtraScheduleDataMap[I][S.OpValue] = SD;
7403     return true;
7404   };
7405   if (CheckSheduleForI(I))
7406     return true;
7407   if (!ScheduleStart) {
7408     // It's the first instruction in the new region.
7409     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7410     ScheduleStart = I;
7411     ScheduleEnd = I->getNextNode();
7412     if (isOneOf(S, I) != I)
7413       CheckSheduleForI(I);
7414     assert(ScheduleEnd && "tried to vectorize a terminator?");
7415     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7416     return true;
7417   }
7418   // Search up and down at the same time, because we don't know if the new
7419   // instruction is above or below the existing scheduling region.
7420   BasicBlock::reverse_iterator UpIter =
7421       ++ScheduleStart->getIterator().getReverse();
7422   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7423   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7424   BasicBlock::iterator LowerEnd = BB->end();
7425   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7426          &*DownIter != I) {
7427     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7428       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7429       return false;
7430     }
7431 
7432     ++UpIter;
7433     ++DownIter;
7434   }
7435   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7436     assert(I->getParent() == ScheduleStart->getParent() &&
7437            "Instruction is in wrong basic block.");
7438     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7439     ScheduleStart = I;
7440     if (isOneOf(S, I) != I)
7441       CheckSheduleForI(I);
7442     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7443                       << "\n");
7444     return true;
7445   }
7446   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7447          "Expected to reach top of the basic block or instruction down the "
7448          "lower end.");
7449   assert(I->getParent() == ScheduleEnd->getParent() &&
7450          "Instruction is in wrong basic block.");
7451   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7452                    nullptr);
7453   ScheduleEnd = I->getNextNode();
7454   if (isOneOf(S, I) != I)
7455     CheckSheduleForI(I);
7456   assert(ScheduleEnd && "tried to vectorize a terminator?");
7457   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7458   return true;
7459 }
7460 
7461 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7462                                                 Instruction *ToI,
7463                                                 ScheduleData *PrevLoadStore,
7464                                                 ScheduleData *NextLoadStore) {
7465   ScheduleData *CurrentLoadStore = PrevLoadStore;
7466   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7467     ScheduleData *SD = ScheduleDataMap[I];
7468     if (!SD) {
7469       SD = allocateScheduleDataChunks();
7470       ScheduleDataMap[I] = SD;
7471       SD->Inst = I;
7472     }
7473     assert(!isInSchedulingRegion(SD) &&
7474            "new ScheduleData already in scheduling region");
7475     SD->init(SchedulingRegionID, I);
7476 
7477     if (I->mayReadOrWriteMemory() &&
7478         (!isa<IntrinsicInst>(I) ||
7479          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7480           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7481               Intrinsic::pseudoprobe))) {
7482       // Update the linked list of memory accessing instructions.
7483       if (CurrentLoadStore) {
7484         CurrentLoadStore->NextLoadStore = SD;
7485       } else {
7486         FirstLoadStoreInRegion = SD;
7487       }
7488       CurrentLoadStore = SD;
7489     }
7490   }
7491   if (NextLoadStore) {
7492     if (CurrentLoadStore)
7493       CurrentLoadStore->NextLoadStore = NextLoadStore;
7494   } else {
7495     LastLoadStoreInRegion = CurrentLoadStore;
7496   }
7497 }
7498 
7499 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7500                                                      bool InsertInReadyList,
7501                                                      BoUpSLP *SLP) {
7502   assert(SD->isSchedulingEntity());
7503 
7504   SmallVector<ScheduleData *, 10> WorkList;
7505   WorkList.push_back(SD);
7506 
7507   while (!WorkList.empty()) {
7508     ScheduleData *SD = WorkList.pop_back_val();
7509     for (ScheduleData *BundleMember = SD; BundleMember;
7510          BundleMember = BundleMember->NextInBundle) {
7511       assert(isInSchedulingRegion(BundleMember));
7512       if (BundleMember->hasValidDependencies())
7513         continue;
7514 
7515       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7516                  << "\n");
7517       BundleMember->Dependencies = 0;
7518       BundleMember->resetUnscheduledDeps();
7519 
7520       // Handle def-use chain dependencies.
7521       if (BundleMember->OpValue != BundleMember->Inst) {
7522         ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7523         if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7524           BundleMember->Dependencies++;
7525           ScheduleData *DestBundle = UseSD->FirstInBundle;
7526           if (!DestBundle->IsScheduled)
7527             BundleMember->incrementUnscheduledDeps(1);
7528           if (!DestBundle->hasValidDependencies())
7529             WorkList.push_back(DestBundle);
7530         }
7531       } else {
7532         for (User *U : BundleMember->Inst->users()) {
7533           assert(isa<Instruction>(U) &&
7534                  "user of instruction must be instruction");
7535           ScheduleData *UseSD = getScheduleData(U);
7536           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7537             BundleMember->Dependencies++;
7538             ScheduleData *DestBundle = UseSD->FirstInBundle;
7539             if (!DestBundle->IsScheduled)
7540               BundleMember->incrementUnscheduledDeps(1);
7541             if (!DestBundle->hasValidDependencies())
7542               WorkList.push_back(DestBundle);
7543           }
7544         }
7545       }
7546 
7547       // Handle the memory dependencies (if any).
7548       ScheduleData *DepDest = BundleMember->NextLoadStore;
7549       if (!DepDest)
7550         continue;
7551       Instruction *SrcInst = BundleMember->Inst;
7552       assert(SrcInst->mayReadOrWriteMemory() &&
7553              "NextLoadStore list for non memory effecting bundle?");
7554       MemoryLocation SrcLoc = getLocation(SrcInst);
7555       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7556       unsigned numAliased = 0;
7557       unsigned DistToSrc = 1;
7558 
7559       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7560         assert(isInSchedulingRegion(DepDest));
7561 
7562         // We have two limits to reduce the complexity:
7563         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7564         //    SLP->isAliased (which is the expensive part in this loop).
7565         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7566         //    the whole loop (even if the loop is fast, it's quadratic).
7567         //    It's important for the loop break condition (see below) to
7568         //    check this limit even between two read-only instructions.
7569         if (DistToSrc >= MaxMemDepDistance ||
7570             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7571              (numAliased >= AliasedCheckLimit ||
7572               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7573 
7574           // We increment the counter only if the locations are aliased
7575           // (instead of counting all alias checks). This gives a better
7576           // balance between reduced runtime and accurate dependencies.
7577           numAliased++;
7578 
7579           DepDest->MemoryDependencies.push_back(BundleMember);
7580           BundleMember->Dependencies++;
7581           ScheduleData *DestBundle = DepDest->FirstInBundle;
7582           if (!DestBundle->IsScheduled) {
7583             BundleMember->incrementUnscheduledDeps(1);
7584           }
7585           if (!DestBundle->hasValidDependencies()) {
7586             WorkList.push_back(DestBundle);
7587           }
7588         }
7589 
7590         // Example, explaining the loop break condition: Let's assume our
7591         // starting instruction is i0 and MaxMemDepDistance = 3.
7592         //
7593         //                      +--------v--v--v
7594         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7595         //             +--------^--^--^
7596         //
7597         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7598         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7599         // Previously we already added dependencies from i3 to i6,i7,i8
7600         // (because of MaxMemDepDistance). As we added a dependency from
7601         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7602         // and we can abort this loop at i6.
7603         if (DistToSrc >= 2 * MaxMemDepDistance)
7604           break;
7605         DistToSrc++;
7606       }
7607     }
7608     if (InsertInReadyList && SD->isReady()) {
7609       ReadyInsts.push_back(SD);
7610       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7611                         << "\n");
7612     }
7613   }
7614 }
7615 
7616 void BoUpSLP::BlockScheduling::resetSchedule() {
7617   assert(ScheduleStart &&
7618          "tried to reset schedule on block which has not been scheduled");
7619   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7620     doForAllOpcodes(I, [&](ScheduleData *SD) {
7621       assert(isInSchedulingRegion(SD) &&
7622              "ScheduleData not in scheduling region");
7623       SD->IsScheduled = false;
7624       SD->resetUnscheduledDeps();
7625     });
7626   }
7627   ReadyInsts.clear();
7628 }
7629 
7630 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7631   if (!BS->ScheduleStart)
7632     return;
7633 
7634   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7635 
7636   BS->resetSchedule();
7637 
7638   // For the real scheduling we use a more sophisticated ready-list: it is
7639   // sorted by the original instruction location. This lets the final schedule
7640   // be as  close as possible to the original instruction order.
7641   struct ScheduleDataCompare {
7642     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7643       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7644     }
7645   };
7646   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7647 
7648   // Ensure that all dependency data is updated and fill the ready-list with
7649   // initial instructions.
7650   int Idx = 0;
7651   int NumToSchedule = 0;
7652   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7653        I = I->getNextNode()) {
7654     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7655       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7656               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7657              "scheduler and vectorizer bundle mismatch");
7658       SD->FirstInBundle->SchedulingPriority = Idx++;
7659       if (SD->isSchedulingEntity()) {
7660         BS->calculateDependencies(SD, false, this);
7661         NumToSchedule++;
7662       }
7663     });
7664   }
7665   BS->initialFillReadyList(ReadyInsts);
7666 
7667   Instruction *LastScheduledInst = BS->ScheduleEnd;
7668 
7669   // Do the "real" scheduling.
7670   while (!ReadyInsts.empty()) {
7671     ScheduleData *picked = *ReadyInsts.begin();
7672     ReadyInsts.erase(ReadyInsts.begin());
7673 
7674     // Move the scheduled instruction(s) to their dedicated places, if not
7675     // there yet.
7676     for (ScheduleData *BundleMember = picked; BundleMember;
7677          BundleMember = BundleMember->NextInBundle) {
7678       Instruction *pickedInst = BundleMember->Inst;
7679       if (pickedInst->getNextNode() != LastScheduledInst) {
7680         BS->BB->getInstList().remove(pickedInst);
7681         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
7682                                      pickedInst);
7683       }
7684       LastScheduledInst = pickedInst;
7685     }
7686 
7687     BS->schedule(picked, ReadyInsts);
7688     NumToSchedule--;
7689   }
7690   assert(NumToSchedule == 0 && "could not schedule all instructions");
7691 
7692   // Avoid duplicate scheduling of the block.
7693   BS->ScheduleStart = nullptr;
7694 }
7695 
7696 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7697   // If V is a store, just return the width of the stored value (or value
7698   // truncated just before storing) without traversing the expression tree.
7699   // This is the common case.
7700   if (auto *Store = dyn_cast<StoreInst>(V)) {
7701     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7702       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7703     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7704   }
7705 
7706   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7707     return getVectorElementSize(IEI->getOperand(1));
7708 
7709   auto E = InstrElementSize.find(V);
7710   if (E != InstrElementSize.end())
7711     return E->second;
7712 
7713   // If V is not a store, we can traverse the expression tree to find loads
7714   // that feed it. The type of the loaded value may indicate a more suitable
7715   // width than V's type. We want to base the vector element size on the width
7716   // of memory operations where possible.
7717   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7718   SmallPtrSet<Instruction *, 16> Visited;
7719   if (auto *I = dyn_cast<Instruction>(V)) {
7720     Worklist.emplace_back(I, I->getParent());
7721     Visited.insert(I);
7722   }
7723 
7724   // Traverse the expression tree in bottom-up order looking for loads. If we
7725   // encounter an instruction we don't yet handle, we give up.
7726   auto Width = 0u;
7727   while (!Worklist.empty()) {
7728     Instruction *I;
7729     BasicBlock *Parent;
7730     std::tie(I, Parent) = Worklist.pop_back_val();
7731 
7732     // We should only be looking at scalar instructions here. If the current
7733     // instruction has a vector type, skip.
7734     auto *Ty = I->getType();
7735     if (isa<VectorType>(Ty))
7736       continue;
7737 
7738     // If the current instruction is a load, update MaxWidth to reflect the
7739     // width of the loaded value.
7740     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7741         isa<ExtractValueInst>(I))
7742       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7743 
7744     // Otherwise, we need to visit the operands of the instruction. We only
7745     // handle the interesting cases from buildTree here. If an operand is an
7746     // instruction we haven't yet visited and from the same basic block as the
7747     // user or the use is a PHI node, we add it to the worklist.
7748     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7749              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7750              isa<UnaryOperator>(I)) {
7751       for (Use &U : I->operands())
7752         if (auto *J = dyn_cast<Instruction>(U.get()))
7753           if (Visited.insert(J).second &&
7754               (isa<PHINode>(I) || J->getParent() == Parent))
7755             Worklist.emplace_back(J, J->getParent());
7756     } else {
7757       break;
7758     }
7759   }
7760 
7761   // If we didn't encounter a memory access in the expression tree, or if we
7762   // gave up for some reason, just return the width of V. Otherwise, return the
7763   // maximum width we found.
7764   if (!Width) {
7765     if (auto *CI = dyn_cast<CmpInst>(V))
7766       V = CI->getOperand(0);
7767     Width = DL->getTypeSizeInBits(V->getType());
7768   }
7769 
7770   for (Instruction *I : Visited)
7771     InstrElementSize[I] = Width;
7772 
7773   return Width;
7774 }
7775 
7776 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7777 // smaller type with a truncation. We collect the values that will be demoted
7778 // in ToDemote and additional roots that require investigating in Roots.
7779 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7780                                   SmallVectorImpl<Value *> &ToDemote,
7781                                   SmallVectorImpl<Value *> &Roots) {
7782   // We can always demote constants.
7783   if (isa<Constant>(V)) {
7784     ToDemote.push_back(V);
7785     return true;
7786   }
7787 
7788   // If the value is not an instruction in the expression with only one use, it
7789   // cannot be demoted.
7790   auto *I = dyn_cast<Instruction>(V);
7791   if (!I || !I->hasOneUse() || !Expr.count(I))
7792     return false;
7793 
7794   switch (I->getOpcode()) {
7795 
7796   // We can always demote truncations and extensions. Since truncations can
7797   // seed additional demotion, we save the truncated value.
7798   case Instruction::Trunc:
7799     Roots.push_back(I->getOperand(0));
7800     break;
7801   case Instruction::ZExt:
7802   case Instruction::SExt:
7803     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7804         isa<InsertElementInst>(I->getOperand(0)))
7805       return false;
7806     break;
7807 
7808   // We can demote certain binary operations if we can demote both of their
7809   // operands.
7810   case Instruction::Add:
7811   case Instruction::Sub:
7812   case Instruction::Mul:
7813   case Instruction::And:
7814   case Instruction::Or:
7815   case Instruction::Xor:
7816     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7817         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7818       return false;
7819     break;
7820 
7821   // We can demote selects if we can demote their true and false values.
7822   case Instruction::Select: {
7823     SelectInst *SI = cast<SelectInst>(I);
7824     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7825         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7826       return false;
7827     break;
7828   }
7829 
7830   // We can demote phis if we can demote all their incoming operands. Note that
7831   // we don't need to worry about cycles since we ensure single use above.
7832   case Instruction::PHI: {
7833     PHINode *PN = cast<PHINode>(I);
7834     for (Value *IncValue : PN->incoming_values())
7835       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7836         return false;
7837     break;
7838   }
7839 
7840   // Otherwise, conservatively give up.
7841   default:
7842     return false;
7843   }
7844 
7845   // Record the value that we can demote.
7846   ToDemote.push_back(V);
7847   return true;
7848 }
7849 
7850 void BoUpSLP::computeMinimumValueSizes() {
7851   // If there are no external uses, the expression tree must be rooted by a
7852   // store. We can't demote in-memory values, so there is nothing to do here.
7853   if (ExternalUses.empty())
7854     return;
7855 
7856   // We only attempt to truncate integer expressions.
7857   auto &TreeRoot = VectorizableTree[0]->Scalars;
7858   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
7859   if (!TreeRootIT)
7860     return;
7861 
7862   // If the expression is not rooted by a store, these roots should have
7863   // external uses. We will rely on InstCombine to rewrite the expression in
7864   // the narrower type. However, InstCombine only rewrites single-use values.
7865   // This means that if a tree entry other than a root is used externally, it
7866   // must have multiple uses and InstCombine will not rewrite it. The code
7867   // below ensures that only the roots are used externally.
7868   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
7869   for (auto &EU : ExternalUses)
7870     if (!Expr.erase(EU.Scalar))
7871       return;
7872   if (!Expr.empty())
7873     return;
7874 
7875   // Collect the scalar values of the vectorizable expression. We will use this
7876   // context to determine which values can be demoted. If we see a truncation,
7877   // we mark it as seeding another demotion.
7878   for (auto &EntryPtr : VectorizableTree)
7879     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
7880 
7881   // Ensure the roots of the vectorizable tree don't form a cycle. They must
7882   // have a single external user that is not in the vectorizable tree.
7883   for (auto *Root : TreeRoot)
7884     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
7885       return;
7886 
7887   // Conservatively determine if we can actually truncate the roots of the
7888   // expression. Collect the values that can be demoted in ToDemote and
7889   // additional roots that require investigating in Roots.
7890   SmallVector<Value *, 32> ToDemote;
7891   SmallVector<Value *, 4> Roots;
7892   for (auto *Root : TreeRoot)
7893     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
7894       return;
7895 
7896   // The maximum bit width required to represent all the values that can be
7897   // demoted without loss of precision. It would be safe to truncate the roots
7898   // of the expression to this width.
7899   auto MaxBitWidth = 8u;
7900 
7901   // We first check if all the bits of the roots are demanded. If they're not,
7902   // we can truncate the roots to this narrower type.
7903   for (auto *Root : TreeRoot) {
7904     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
7905     MaxBitWidth = std::max<unsigned>(
7906         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
7907   }
7908 
7909   // True if the roots can be zero-extended back to their original type, rather
7910   // than sign-extended. We know that if the leading bits are not demanded, we
7911   // can safely zero-extend. So we initialize IsKnownPositive to True.
7912   bool IsKnownPositive = true;
7913 
7914   // If all the bits of the roots are demanded, we can try a little harder to
7915   // compute a narrower type. This can happen, for example, if the roots are
7916   // getelementptr indices. InstCombine promotes these indices to the pointer
7917   // width. Thus, all their bits are technically demanded even though the
7918   // address computation might be vectorized in a smaller type.
7919   //
7920   // We start by looking at each entry that can be demoted. We compute the
7921   // maximum bit width required to store the scalar by using ValueTracking to
7922   // compute the number of high-order bits we can truncate.
7923   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
7924       llvm::all_of(TreeRoot, [](Value *R) {
7925         assert(R->hasOneUse() && "Root should have only one use!");
7926         return isa<GetElementPtrInst>(R->user_back());
7927       })) {
7928     MaxBitWidth = 8u;
7929 
7930     // Determine if the sign bit of all the roots is known to be zero. If not,
7931     // IsKnownPositive is set to False.
7932     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
7933       KnownBits Known = computeKnownBits(R, *DL);
7934       return Known.isNonNegative();
7935     });
7936 
7937     // Determine the maximum number of bits required to store the scalar
7938     // values.
7939     for (auto *Scalar : ToDemote) {
7940       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
7941       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
7942       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
7943     }
7944 
7945     // If we can't prove that the sign bit is zero, we must add one to the
7946     // maximum bit width to account for the unknown sign bit. This preserves
7947     // the existing sign bit so we can safely sign-extend the root back to the
7948     // original type. Otherwise, if we know the sign bit is zero, we will
7949     // zero-extend the root instead.
7950     //
7951     // FIXME: This is somewhat suboptimal, as there will be cases where adding
7952     //        one to the maximum bit width will yield a larger-than-necessary
7953     //        type. In general, we need to add an extra bit only if we can't
7954     //        prove that the upper bit of the original type is equal to the
7955     //        upper bit of the proposed smaller type. If these two bits are the
7956     //        same (either zero or one) we know that sign-extending from the
7957     //        smaller type will result in the same value. Here, since we can't
7958     //        yet prove this, we are just making the proposed smaller type
7959     //        larger to ensure correctness.
7960     if (!IsKnownPositive)
7961       ++MaxBitWidth;
7962   }
7963 
7964   // Round MaxBitWidth up to the next power-of-two.
7965   if (!isPowerOf2_64(MaxBitWidth))
7966     MaxBitWidth = NextPowerOf2(MaxBitWidth);
7967 
7968   // If the maximum bit width we compute is less than the with of the roots'
7969   // type, we can proceed with the narrowing. Otherwise, do nothing.
7970   if (MaxBitWidth >= TreeRootIT->getBitWidth())
7971     return;
7972 
7973   // If we can truncate the root, we must collect additional values that might
7974   // be demoted as a result. That is, those seeded by truncations we will
7975   // modify.
7976   while (!Roots.empty())
7977     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
7978 
7979   // Finally, map the values we can demote to the maximum bit with we computed.
7980   for (auto *Scalar : ToDemote)
7981     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
7982 }
7983 
7984 namespace {
7985 
7986 /// The SLPVectorizer Pass.
7987 struct SLPVectorizer : public FunctionPass {
7988   SLPVectorizerPass Impl;
7989 
7990   /// Pass identification, replacement for typeid
7991   static char ID;
7992 
7993   explicit SLPVectorizer() : FunctionPass(ID) {
7994     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
7995   }
7996 
7997   bool doInitialization(Module &M) override { return false; }
7998 
7999   bool runOnFunction(Function &F) override {
8000     if (skipFunction(F))
8001       return false;
8002 
8003     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8004     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8005     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8006     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8007     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8008     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8009     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8010     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8011     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8012     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8013 
8014     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8015   }
8016 
8017   void getAnalysisUsage(AnalysisUsage &AU) const override {
8018     FunctionPass::getAnalysisUsage(AU);
8019     AU.addRequired<AssumptionCacheTracker>();
8020     AU.addRequired<ScalarEvolutionWrapperPass>();
8021     AU.addRequired<AAResultsWrapperPass>();
8022     AU.addRequired<TargetTransformInfoWrapperPass>();
8023     AU.addRequired<LoopInfoWrapperPass>();
8024     AU.addRequired<DominatorTreeWrapperPass>();
8025     AU.addRequired<DemandedBitsWrapperPass>();
8026     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8027     AU.addRequired<InjectTLIMappingsLegacy>();
8028     AU.addPreserved<LoopInfoWrapperPass>();
8029     AU.addPreserved<DominatorTreeWrapperPass>();
8030     AU.addPreserved<AAResultsWrapperPass>();
8031     AU.addPreserved<GlobalsAAWrapperPass>();
8032     AU.setPreservesCFG();
8033   }
8034 };
8035 
8036 } // end anonymous namespace
8037 
8038 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8039   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8040   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8041   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8042   auto *AA = &AM.getResult<AAManager>(F);
8043   auto *LI = &AM.getResult<LoopAnalysis>(F);
8044   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8045   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8046   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8047   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8048 
8049   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8050   if (!Changed)
8051     return PreservedAnalyses::all();
8052 
8053   PreservedAnalyses PA;
8054   PA.preserveSet<CFGAnalyses>();
8055   return PA;
8056 }
8057 
8058 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8059                                 TargetTransformInfo *TTI_,
8060                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8061                                 LoopInfo *LI_, DominatorTree *DT_,
8062                                 AssumptionCache *AC_, DemandedBits *DB_,
8063                                 OptimizationRemarkEmitter *ORE_) {
8064   if (!RunSLPVectorization)
8065     return false;
8066   SE = SE_;
8067   TTI = TTI_;
8068   TLI = TLI_;
8069   AA = AA_;
8070   LI = LI_;
8071   DT = DT_;
8072   AC = AC_;
8073   DB = DB_;
8074   DL = &F.getParent()->getDataLayout();
8075 
8076   Stores.clear();
8077   GEPs.clear();
8078   bool Changed = false;
8079 
8080   // If the target claims to have no vector registers don't attempt
8081   // vectorization.
8082   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8083     LLVM_DEBUG(
8084         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8085     return false;
8086   }
8087 
8088   // Don't vectorize when the attribute NoImplicitFloat is used.
8089   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8090     return false;
8091 
8092   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8093 
8094   // Use the bottom up slp vectorizer to construct chains that start with
8095   // store instructions.
8096   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8097 
8098   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8099   // delete instructions.
8100 
8101   // Update DFS numbers now so that we can use them for ordering.
8102   DT->updateDFSNumbers();
8103 
8104   // Scan the blocks in the function in post order.
8105   for (auto BB : post_order(&F.getEntryBlock())) {
8106     collectSeedInstructions(BB);
8107 
8108     // Vectorize trees that end at stores.
8109     if (!Stores.empty()) {
8110       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8111                         << " underlying objects.\n");
8112       Changed |= vectorizeStoreChains(R);
8113     }
8114 
8115     // Vectorize trees that end at reductions.
8116     Changed |= vectorizeChainsInBlock(BB, R);
8117 
8118     // Vectorize the index computations of getelementptr instructions. This
8119     // is primarily intended to catch gather-like idioms ending at
8120     // non-consecutive loads.
8121     if (!GEPs.empty()) {
8122       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8123                         << " underlying objects.\n");
8124       Changed |= vectorizeGEPIndices(BB, R);
8125     }
8126   }
8127 
8128   if (Changed) {
8129     R.optimizeGatherSequence();
8130     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8131   }
8132   return Changed;
8133 }
8134 
8135 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8136                                             unsigned Idx) {
8137   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8138                     << "\n");
8139   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8140   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8141   unsigned VF = Chain.size();
8142 
8143   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8144     return false;
8145 
8146   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8147                     << "\n");
8148 
8149   R.buildTree(Chain);
8150   if (R.isTreeTinyAndNotFullyVectorizable())
8151     return false;
8152   if (R.isLoadCombineCandidate())
8153     return false;
8154   R.reorderTopToBottom();
8155   R.reorderBottomToTop();
8156   R.buildExternalUses();
8157 
8158   R.computeMinimumValueSizes();
8159 
8160   InstructionCost Cost = R.getTreeCost();
8161 
8162   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8163   if (Cost < -SLPCostThreshold) {
8164     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8165 
8166     using namespace ore;
8167 
8168     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8169                                         cast<StoreInst>(Chain[0]))
8170                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8171                      << " and with tree size "
8172                      << NV("TreeSize", R.getTreeSize()));
8173 
8174     R.vectorizeTree();
8175     return true;
8176   }
8177 
8178   return false;
8179 }
8180 
8181 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8182                                         BoUpSLP &R) {
8183   // We may run into multiple chains that merge into a single chain. We mark the
8184   // stores that we vectorized so that we don't visit the same store twice.
8185   BoUpSLP::ValueSet VectorizedStores;
8186   bool Changed = false;
8187 
8188   int E = Stores.size();
8189   SmallBitVector Tails(E, false);
8190   int MaxIter = MaxStoreLookup.getValue();
8191   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8192       E, std::make_pair(E, INT_MAX));
8193   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8194   int IterCnt;
8195   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8196                                   &CheckedPairs,
8197                                   &ConsecutiveChain](int K, int Idx) {
8198     if (IterCnt >= MaxIter)
8199       return true;
8200     if (CheckedPairs[Idx].test(K))
8201       return ConsecutiveChain[K].second == 1 &&
8202              ConsecutiveChain[K].first == Idx;
8203     ++IterCnt;
8204     CheckedPairs[Idx].set(K);
8205     CheckedPairs[K].set(Idx);
8206     Optional<int> Diff = getPointersDiff(
8207         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8208         Stores[Idx]->getValueOperand()->getType(),
8209         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8210     if (!Diff || *Diff == 0)
8211       return false;
8212     int Val = *Diff;
8213     if (Val < 0) {
8214       if (ConsecutiveChain[Idx].second > -Val) {
8215         Tails.set(K);
8216         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8217       }
8218       return false;
8219     }
8220     if (ConsecutiveChain[K].second <= Val)
8221       return false;
8222 
8223     Tails.set(Idx);
8224     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8225     return Val == 1;
8226   };
8227   // Do a quadratic search on all of the given stores in reverse order and find
8228   // all of the pairs of stores that follow each other.
8229   for (int Idx = E - 1; Idx >= 0; --Idx) {
8230     // If a store has multiple consecutive store candidates, search according
8231     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8232     // This is because usually pairing with immediate succeeding or preceding
8233     // candidate create the best chance to find slp vectorization opportunity.
8234     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8235     IterCnt = 0;
8236     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8237       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8238           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8239         break;
8240   }
8241 
8242   // Tracks if we tried to vectorize stores starting from the given tail
8243   // already.
8244   SmallBitVector TriedTails(E, false);
8245   // For stores that start but don't end a link in the chain:
8246   for (int Cnt = E; Cnt > 0; --Cnt) {
8247     int I = Cnt - 1;
8248     if (ConsecutiveChain[I].first == E || Tails.test(I))
8249       continue;
8250     // We found a store instr that starts a chain. Now follow the chain and try
8251     // to vectorize it.
8252     BoUpSLP::ValueList Operands;
8253     // Collect the chain into a list.
8254     while (I != E && !VectorizedStores.count(Stores[I])) {
8255       Operands.push_back(Stores[I]);
8256       Tails.set(I);
8257       if (ConsecutiveChain[I].second != 1) {
8258         // Mark the new end in the chain and go back, if required. It might be
8259         // required if the original stores come in reversed order, for example.
8260         if (ConsecutiveChain[I].first != E &&
8261             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8262             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8263           TriedTails.set(I);
8264           Tails.reset(ConsecutiveChain[I].first);
8265           if (Cnt < ConsecutiveChain[I].first + 2)
8266             Cnt = ConsecutiveChain[I].first + 2;
8267         }
8268         break;
8269       }
8270       // Move to the next value in the chain.
8271       I = ConsecutiveChain[I].first;
8272     }
8273     assert(!Operands.empty() && "Expected non-empty list of stores.");
8274 
8275     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8276     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8277     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8278 
8279     unsigned MinVF = R.getMinVF(EltSize);
8280     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8281                               MaxElts);
8282 
8283     // FIXME: Is division-by-2 the correct step? Should we assert that the
8284     // register size is a power-of-2?
8285     unsigned StartIdx = 0;
8286     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8287       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8288         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8289         if (!VectorizedStores.count(Slice.front()) &&
8290             !VectorizedStores.count(Slice.back()) &&
8291             vectorizeStoreChain(Slice, R, Cnt)) {
8292           // Mark the vectorized stores so that we don't vectorize them again.
8293           VectorizedStores.insert(Slice.begin(), Slice.end());
8294           Changed = true;
8295           // If we vectorized initial block, no need to try to vectorize it
8296           // again.
8297           if (Cnt == StartIdx)
8298             StartIdx += Size;
8299           Cnt += Size;
8300           continue;
8301         }
8302         ++Cnt;
8303       }
8304       // Check if the whole array was vectorized already - exit.
8305       if (StartIdx >= Operands.size())
8306         break;
8307     }
8308   }
8309 
8310   return Changed;
8311 }
8312 
8313 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8314   // Initialize the collections. We will make a single pass over the block.
8315   Stores.clear();
8316   GEPs.clear();
8317 
8318   // Visit the store and getelementptr instructions in BB and organize them in
8319   // Stores and GEPs according to the underlying objects of their pointer
8320   // operands.
8321   for (Instruction &I : *BB) {
8322     // Ignore store instructions that are volatile or have a pointer operand
8323     // that doesn't point to a scalar type.
8324     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8325       if (!SI->isSimple())
8326         continue;
8327       if (!isValidElementType(SI->getValueOperand()->getType()))
8328         continue;
8329       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8330     }
8331 
8332     // Ignore getelementptr instructions that have more than one index, a
8333     // constant index, or a pointer operand that doesn't point to a scalar
8334     // type.
8335     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8336       auto Idx = GEP->idx_begin()->get();
8337       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8338         continue;
8339       if (!isValidElementType(Idx->getType()))
8340         continue;
8341       if (GEP->getType()->isVectorTy())
8342         continue;
8343       GEPs[GEP->getPointerOperand()].push_back(GEP);
8344     }
8345   }
8346 }
8347 
8348 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8349   if (!A || !B)
8350     return false;
8351   Value *VL[] = {A, B};
8352   return tryToVectorizeList(VL, R);
8353 }
8354 
8355 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8356                                            bool LimitForRegisterSize) {
8357   if (VL.size() < 2)
8358     return false;
8359 
8360   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8361                     << VL.size() << ".\n");
8362 
8363   // Check that all of the parts are instructions of the same type,
8364   // we permit an alternate opcode via InstructionsState.
8365   InstructionsState S = getSameOpcode(VL);
8366   if (!S.getOpcode())
8367     return false;
8368 
8369   Instruction *I0 = cast<Instruction>(S.OpValue);
8370   // Make sure invalid types (including vector type) are rejected before
8371   // determining vectorization factor for scalar instructions.
8372   for (Value *V : VL) {
8373     Type *Ty = V->getType();
8374     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8375       // NOTE: the following will give user internal llvm type name, which may
8376       // not be useful.
8377       R.getORE()->emit([&]() {
8378         std::string type_str;
8379         llvm::raw_string_ostream rso(type_str);
8380         Ty->print(rso);
8381         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8382                << "Cannot SLP vectorize list: type "
8383                << rso.str() + " is unsupported by vectorizer";
8384       });
8385       return false;
8386     }
8387   }
8388 
8389   unsigned Sz = R.getVectorElementSize(I0);
8390   unsigned MinVF = R.getMinVF(Sz);
8391   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8392   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8393   if (MaxVF < 2) {
8394     R.getORE()->emit([&]() {
8395       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8396              << "Cannot SLP vectorize list: vectorization factor "
8397              << "less than 2 is not supported";
8398     });
8399     return false;
8400   }
8401 
8402   bool Changed = false;
8403   bool CandidateFound = false;
8404   InstructionCost MinCost = SLPCostThreshold.getValue();
8405   Type *ScalarTy = VL[0]->getType();
8406   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8407     ScalarTy = IE->getOperand(1)->getType();
8408 
8409   unsigned NextInst = 0, MaxInst = VL.size();
8410   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8411     // No actual vectorization should happen, if number of parts is the same as
8412     // provided vectorization factor (i.e. the scalar type is used for vector
8413     // code during codegen).
8414     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8415     if (TTI->getNumberOfParts(VecTy) == VF)
8416       continue;
8417     for (unsigned I = NextInst; I < MaxInst; ++I) {
8418       unsigned OpsWidth = 0;
8419 
8420       if (I + VF > MaxInst)
8421         OpsWidth = MaxInst - I;
8422       else
8423         OpsWidth = VF;
8424 
8425       if (!isPowerOf2_32(OpsWidth))
8426         continue;
8427 
8428       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8429           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8430         break;
8431 
8432       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8433       // Check that a previous iteration of this loop did not delete the Value.
8434       if (llvm::any_of(Ops, [&R](Value *V) {
8435             auto *I = dyn_cast<Instruction>(V);
8436             return I && R.isDeleted(I);
8437           }))
8438         continue;
8439 
8440       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8441                         << "\n");
8442 
8443       R.buildTree(Ops);
8444       if (R.isTreeTinyAndNotFullyVectorizable())
8445         continue;
8446       R.reorderTopToBottom();
8447       R.reorderBottomToTop();
8448       R.buildExternalUses();
8449 
8450       R.computeMinimumValueSizes();
8451       InstructionCost Cost = R.getTreeCost();
8452       CandidateFound = true;
8453       MinCost = std::min(MinCost, Cost);
8454 
8455       if (Cost < -SLPCostThreshold) {
8456         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8457         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8458                                                     cast<Instruction>(Ops[0]))
8459                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8460                                  << " and with tree size "
8461                                  << ore::NV("TreeSize", R.getTreeSize()));
8462 
8463         R.vectorizeTree();
8464         // Move to the next bundle.
8465         I += VF - 1;
8466         NextInst = I + 1;
8467         Changed = true;
8468       }
8469     }
8470   }
8471 
8472   if (!Changed && CandidateFound) {
8473     R.getORE()->emit([&]() {
8474       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8475              << "List vectorization was possible but not beneficial with cost "
8476              << ore::NV("Cost", MinCost) << " >= "
8477              << ore::NV("Treshold", -SLPCostThreshold);
8478     });
8479   } else if (!Changed) {
8480     R.getORE()->emit([&]() {
8481       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8482              << "Cannot SLP vectorize list: vectorization was impossible"
8483              << " with available vectorization factors";
8484     });
8485   }
8486   return Changed;
8487 }
8488 
8489 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8490   if (!I)
8491     return false;
8492 
8493   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8494     return false;
8495 
8496   Value *P = I->getParent();
8497 
8498   // Vectorize in current basic block only.
8499   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8500   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8501   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8502     return false;
8503 
8504   // Try to vectorize V.
8505   if (tryToVectorizePair(Op0, Op1, R))
8506     return true;
8507 
8508   auto *A = dyn_cast<BinaryOperator>(Op0);
8509   auto *B = dyn_cast<BinaryOperator>(Op1);
8510   // Try to skip B.
8511   if (B && B->hasOneUse()) {
8512     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8513     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8514     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8515       return true;
8516     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8517       return true;
8518   }
8519 
8520   // Try to skip A.
8521   if (A && A->hasOneUse()) {
8522     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8523     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8524     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8525       return true;
8526     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8527       return true;
8528   }
8529   return false;
8530 }
8531 
8532 namespace {
8533 
8534 /// Model horizontal reductions.
8535 ///
8536 /// A horizontal reduction is a tree of reduction instructions that has values
8537 /// that can be put into a vector as its leaves. For example:
8538 ///
8539 /// mul mul mul mul
8540 ///  \  /    \  /
8541 ///   +       +
8542 ///    \     /
8543 ///       +
8544 /// This tree has "mul" as its leaf values and "+" as its reduction
8545 /// instructions. A reduction can feed into a store or a binary operation
8546 /// feeding a phi.
8547 ///    ...
8548 ///    \  /
8549 ///     +
8550 ///     |
8551 ///  phi +=
8552 ///
8553 ///  Or:
8554 ///    ...
8555 ///    \  /
8556 ///     +
8557 ///     |
8558 ///   *p =
8559 ///
8560 class HorizontalReduction {
8561   using ReductionOpsType = SmallVector<Value *, 16>;
8562   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8563   ReductionOpsListType ReductionOps;
8564   SmallVector<Value *, 32> ReducedVals;
8565   // Use map vector to make stable output.
8566   MapVector<Instruction *, Value *> ExtraArgs;
8567   WeakTrackingVH ReductionRoot;
8568   /// The type of reduction operation.
8569   RecurKind RdxKind;
8570 
8571   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8572 
8573   static bool isCmpSelMinMax(Instruction *I) {
8574     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8575            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8576   }
8577 
8578   // And/or are potentially poison-safe logical patterns like:
8579   // select x, y, false
8580   // select x, true, y
8581   static bool isBoolLogicOp(Instruction *I) {
8582     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8583            match(I, m_LogicalOr(m_Value(), m_Value()));
8584   }
8585 
8586   /// Checks if instruction is associative and can be vectorized.
8587   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8588     if (Kind == RecurKind::None)
8589       return false;
8590 
8591     // Integer ops that map to select instructions or intrinsics are fine.
8592     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8593         isBoolLogicOp(I))
8594       return true;
8595 
8596     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8597       // FP min/max are associative except for NaN and -0.0. We do not
8598       // have to rule out -0.0 here because the intrinsic semantics do not
8599       // specify a fixed result for it.
8600       return I->getFastMathFlags().noNaNs();
8601     }
8602 
8603     return I->isAssociative();
8604   }
8605 
8606   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8607     // Poison-safe 'or' takes the form: select X, true, Y
8608     // To make that work with the normal operand processing, we skip the
8609     // true value operand.
8610     // TODO: Change the code and data structures to handle this without a hack.
8611     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8612       return I->getOperand(2);
8613     return I->getOperand(Index);
8614   }
8615 
8616   /// Checks if the ParentStackElem.first should be marked as a reduction
8617   /// operation with an extra argument or as extra argument itself.
8618   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8619                     Value *ExtraArg) {
8620     if (ExtraArgs.count(ParentStackElem.first)) {
8621       ExtraArgs[ParentStackElem.first] = nullptr;
8622       // We ran into something like:
8623       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8624       // The whole ParentStackElem.first should be considered as an extra value
8625       // in this case.
8626       // Do not perform analysis of remaining operands of ParentStackElem.first
8627       // instruction, this whole instruction is an extra argument.
8628       ParentStackElem.second = INVALID_OPERAND_INDEX;
8629     } else {
8630       // We ran into something like:
8631       // ParentStackElem.first += ... + ExtraArg + ...
8632       ExtraArgs[ParentStackElem.first] = ExtraArg;
8633     }
8634   }
8635 
8636   /// Creates reduction operation with the current opcode.
8637   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8638                          Value *RHS, const Twine &Name, bool UseSelect) {
8639     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8640     switch (Kind) {
8641     case RecurKind::Or:
8642       if (UseSelect &&
8643           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8644         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8645       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8646                                  Name);
8647     case RecurKind::And:
8648       if (UseSelect &&
8649           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8650         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8651       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8652                                  Name);
8653     case RecurKind::Add:
8654     case RecurKind::Mul:
8655     case RecurKind::Xor:
8656     case RecurKind::FAdd:
8657     case RecurKind::FMul:
8658       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8659                                  Name);
8660     case RecurKind::FMax:
8661       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8662     case RecurKind::FMin:
8663       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8664     case RecurKind::SMax:
8665       if (UseSelect) {
8666         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8667         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8668       }
8669       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8670     case RecurKind::SMin:
8671       if (UseSelect) {
8672         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8673         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8674       }
8675       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8676     case RecurKind::UMax:
8677       if (UseSelect) {
8678         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8679         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8680       }
8681       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8682     case RecurKind::UMin:
8683       if (UseSelect) {
8684         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8685         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8686       }
8687       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8688     default:
8689       llvm_unreachable("Unknown reduction operation.");
8690     }
8691   }
8692 
8693   /// Creates reduction operation with the current opcode with the IR flags
8694   /// from \p ReductionOps.
8695   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8696                          Value *RHS, const Twine &Name,
8697                          const ReductionOpsListType &ReductionOps) {
8698     bool UseSelect = ReductionOps.size() == 2 ||
8699                      // Logical or/and.
8700                      (ReductionOps.size() == 1 &&
8701                       isa<SelectInst>(ReductionOps.front().front()));
8702     assert((!UseSelect || ReductionOps.size() != 2 ||
8703             isa<SelectInst>(ReductionOps[1][0])) &&
8704            "Expected cmp + select pairs for reduction");
8705     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8706     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8707       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8708         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8709         propagateIRFlags(Op, ReductionOps[1]);
8710         return Op;
8711       }
8712     }
8713     propagateIRFlags(Op, ReductionOps[0]);
8714     return Op;
8715   }
8716 
8717   /// Creates reduction operation with the current opcode with the IR flags
8718   /// from \p I.
8719   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8720                          Value *RHS, const Twine &Name, Instruction *I) {
8721     auto *SelI = dyn_cast<SelectInst>(I);
8722     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8723     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8724       if (auto *Sel = dyn_cast<SelectInst>(Op))
8725         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8726     }
8727     propagateIRFlags(Op, I);
8728     return Op;
8729   }
8730 
8731   static RecurKind getRdxKind(Instruction *I) {
8732     assert(I && "Expected instruction for reduction matching");
8733     if (match(I, m_Add(m_Value(), m_Value())))
8734       return RecurKind::Add;
8735     if (match(I, m_Mul(m_Value(), m_Value())))
8736       return RecurKind::Mul;
8737     if (match(I, m_And(m_Value(), m_Value())) ||
8738         match(I, m_LogicalAnd(m_Value(), m_Value())))
8739       return RecurKind::And;
8740     if (match(I, m_Or(m_Value(), m_Value())) ||
8741         match(I, m_LogicalOr(m_Value(), m_Value())))
8742       return RecurKind::Or;
8743     if (match(I, m_Xor(m_Value(), m_Value())))
8744       return RecurKind::Xor;
8745     if (match(I, m_FAdd(m_Value(), m_Value())))
8746       return RecurKind::FAdd;
8747     if (match(I, m_FMul(m_Value(), m_Value())))
8748       return RecurKind::FMul;
8749 
8750     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8751       return RecurKind::FMax;
8752     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8753       return RecurKind::FMin;
8754 
8755     // This matches either cmp+select or intrinsics. SLP is expected to handle
8756     // either form.
8757     // TODO: If we are canonicalizing to intrinsics, we can remove several
8758     //       special-case paths that deal with selects.
8759     if (match(I, m_SMax(m_Value(), m_Value())))
8760       return RecurKind::SMax;
8761     if (match(I, m_SMin(m_Value(), m_Value())))
8762       return RecurKind::SMin;
8763     if (match(I, m_UMax(m_Value(), m_Value())))
8764       return RecurKind::UMax;
8765     if (match(I, m_UMin(m_Value(), m_Value())))
8766       return RecurKind::UMin;
8767 
8768     if (auto *Select = dyn_cast<SelectInst>(I)) {
8769       // Try harder: look for min/max pattern based on instructions producing
8770       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8771       // During the intermediate stages of SLP, it's very common to have
8772       // pattern like this (since optimizeGatherSequence is run only once
8773       // at the end):
8774       // %1 = extractelement <2 x i32> %a, i32 0
8775       // %2 = extractelement <2 x i32> %a, i32 1
8776       // %cond = icmp sgt i32 %1, %2
8777       // %3 = extractelement <2 x i32> %a, i32 0
8778       // %4 = extractelement <2 x i32> %a, i32 1
8779       // %select = select i1 %cond, i32 %3, i32 %4
8780       CmpInst::Predicate Pred;
8781       Instruction *L1;
8782       Instruction *L2;
8783 
8784       Value *LHS = Select->getTrueValue();
8785       Value *RHS = Select->getFalseValue();
8786       Value *Cond = Select->getCondition();
8787 
8788       // TODO: Support inverse predicates.
8789       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8790         if (!isa<ExtractElementInst>(RHS) ||
8791             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8792           return RecurKind::None;
8793       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8794         if (!isa<ExtractElementInst>(LHS) ||
8795             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8796           return RecurKind::None;
8797       } else {
8798         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8799           return RecurKind::None;
8800         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8801             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8802             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8803           return RecurKind::None;
8804       }
8805 
8806       switch (Pred) {
8807       default:
8808         return RecurKind::None;
8809       case CmpInst::ICMP_SGT:
8810       case CmpInst::ICMP_SGE:
8811         return RecurKind::SMax;
8812       case CmpInst::ICMP_SLT:
8813       case CmpInst::ICMP_SLE:
8814         return RecurKind::SMin;
8815       case CmpInst::ICMP_UGT:
8816       case CmpInst::ICMP_UGE:
8817         return RecurKind::UMax;
8818       case CmpInst::ICMP_ULT:
8819       case CmpInst::ICMP_ULE:
8820         return RecurKind::UMin;
8821       }
8822     }
8823     return RecurKind::None;
8824   }
8825 
8826   /// Get the index of the first operand.
8827   static unsigned getFirstOperandIndex(Instruction *I) {
8828     return isCmpSelMinMax(I) ? 1 : 0;
8829   }
8830 
8831   /// Total number of operands in the reduction operation.
8832   static unsigned getNumberOfOperands(Instruction *I) {
8833     return isCmpSelMinMax(I) ? 3 : 2;
8834   }
8835 
8836   /// Checks if the instruction is in basic block \p BB.
8837   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8838   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8839     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
8840       auto *Sel = cast<SelectInst>(I);
8841       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
8842       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
8843     }
8844     return I->getParent() == BB;
8845   }
8846 
8847   /// Expected number of uses for reduction operations/reduced values.
8848   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
8849     if (IsCmpSelMinMax) {
8850       // SelectInst must be used twice while the condition op must have single
8851       // use only.
8852       if (auto *Sel = dyn_cast<SelectInst>(I))
8853         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
8854       return I->hasNUses(2);
8855     }
8856 
8857     // Arithmetic reduction operation must be used once only.
8858     return I->hasOneUse();
8859   }
8860 
8861   /// Initializes the list of reduction operations.
8862   void initReductionOps(Instruction *I) {
8863     if (isCmpSelMinMax(I))
8864       ReductionOps.assign(2, ReductionOpsType());
8865     else
8866       ReductionOps.assign(1, ReductionOpsType());
8867   }
8868 
8869   /// Add all reduction operations for the reduction instruction \p I.
8870   void addReductionOps(Instruction *I) {
8871     if (isCmpSelMinMax(I)) {
8872       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
8873       ReductionOps[1].emplace_back(I);
8874     } else {
8875       ReductionOps[0].emplace_back(I);
8876     }
8877   }
8878 
8879   static Value *getLHS(RecurKind Kind, Instruction *I) {
8880     if (Kind == RecurKind::None)
8881       return nullptr;
8882     return I->getOperand(getFirstOperandIndex(I));
8883   }
8884   static Value *getRHS(RecurKind Kind, Instruction *I) {
8885     if (Kind == RecurKind::None)
8886       return nullptr;
8887     return I->getOperand(getFirstOperandIndex(I) + 1);
8888   }
8889 
8890 public:
8891   HorizontalReduction() = default;
8892 
8893   /// Try to find a reduction tree.
8894   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
8895     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
8896            "Phi needs to use the binary operator");
8897     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
8898             isa<IntrinsicInst>(Inst)) &&
8899            "Expected binop, select, or intrinsic for reduction matching");
8900     RdxKind = getRdxKind(Inst);
8901 
8902     // We could have a initial reductions that is not an add.
8903     //  r *= v1 + v2 + v3 + v4
8904     // In such a case start looking for a tree rooted in the first '+'.
8905     if (Phi) {
8906       if (getLHS(RdxKind, Inst) == Phi) {
8907         Phi = nullptr;
8908         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
8909         if (!Inst)
8910           return false;
8911         RdxKind = getRdxKind(Inst);
8912       } else if (getRHS(RdxKind, Inst) == Phi) {
8913         Phi = nullptr;
8914         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
8915         if (!Inst)
8916           return false;
8917         RdxKind = getRdxKind(Inst);
8918       }
8919     }
8920 
8921     if (!isVectorizable(RdxKind, Inst))
8922       return false;
8923 
8924     // Analyze "regular" integer/FP types for reductions - no target-specific
8925     // types or pointers.
8926     Type *Ty = Inst->getType();
8927     if (!isValidElementType(Ty) || Ty->isPointerTy())
8928       return false;
8929 
8930     // Though the ultimate reduction may have multiple uses, its condition must
8931     // have only single use.
8932     if (auto *Sel = dyn_cast<SelectInst>(Inst))
8933       if (!Sel->getCondition()->hasOneUse())
8934         return false;
8935 
8936     ReductionRoot = Inst;
8937 
8938     // The opcode for leaf values that we perform a reduction on.
8939     // For example: load(x) + load(y) + load(z) + fptoui(w)
8940     // The leaf opcode for 'w' does not match, so we don't include it as a
8941     // potential candidate for the reduction.
8942     unsigned LeafOpcode = 0;
8943 
8944     // Post-order traverse the reduction tree starting at Inst. We only handle
8945     // true trees containing binary operators or selects.
8946     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
8947     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
8948     initReductionOps(Inst);
8949     while (!Stack.empty()) {
8950       Instruction *TreeN = Stack.back().first;
8951       unsigned EdgeToVisit = Stack.back().second++;
8952       const RecurKind TreeRdxKind = getRdxKind(TreeN);
8953       bool IsReducedValue = TreeRdxKind != RdxKind;
8954 
8955       // Postorder visit.
8956       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
8957         if (IsReducedValue)
8958           ReducedVals.push_back(TreeN);
8959         else {
8960           auto ExtraArgsIter = ExtraArgs.find(TreeN);
8961           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
8962             // Check if TreeN is an extra argument of its parent operation.
8963             if (Stack.size() <= 1) {
8964               // TreeN can't be an extra argument as it is a root reduction
8965               // operation.
8966               return false;
8967             }
8968             // Yes, TreeN is an extra argument, do not add it to a list of
8969             // reduction operations.
8970             // Stack[Stack.size() - 2] always points to the parent operation.
8971             markExtraArg(Stack[Stack.size() - 2], TreeN);
8972             ExtraArgs.erase(TreeN);
8973           } else
8974             addReductionOps(TreeN);
8975         }
8976         // Retract.
8977         Stack.pop_back();
8978         continue;
8979       }
8980 
8981       // Visit operands.
8982       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
8983       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
8984       if (!EdgeInst) {
8985         // Edge value is not a reduction instruction or a leaf instruction.
8986         // (It may be a constant, function argument, or something else.)
8987         markExtraArg(Stack.back(), EdgeVal);
8988         continue;
8989       }
8990       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
8991       // Continue analysis if the next operand is a reduction operation or
8992       // (possibly) a leaf value. If the leaf value opcode is not set,
8993       // the first met operation != reduction operation is considered as the
8994       // leaf opcode.
8995       // Only handle trees in the current basic block.
8996       // Each tree node needs to have minimal number of users except for the
8997       // ultimate reduction.
8998       const bool IsRdxInst = EdgeRdxKind == RdxKind;
8999       if (EdgeInst != Phi && EdgeInst != Inst &&
9000           hasSameParent(EdgeInst, Inst->getParent()) &&
9001           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9002           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9003         if (IsRdxInst) {
9004           // We need to be able to reassociate the reduction operations.
9005           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9006             // I is an extra argument for TreeN (its parent operation).
9007             markExtraArg(Stack.back(), EdgeInst);
9008             continue;
9009           }
9010         } else if (!LeafOpcode) {
9011           LeafOpcode = EdgeInst->getOpcode();
9012         }
9013         Stack.push_back(
9014             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9015         continue;
9016       }
9017       // I is an extra argument for TreeN (its parent operation).
9018       markExtraArg(Stack.back(), EdgeInst);
9019     }
9020     return true;
9021   }
9022 
9023   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9024   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9025     // If there are a sufficient number of reduction values, reduce
9026     // to a nearby power-of-2. We can safely generate oversized
9027     // vectors and rely on the backend to split them to legal sizes.
9028     unsigned NumReducedVals = ReducedVals.size();
9029     if (NumReducedVals < 4)
9030       return nullptr;
9031 
9032     // Intersect the fast-math-flags from all reduction operations.
9033     FastMathFlags RdxFMF;
9034     RdxFMF.set();
9035     for (ReductionOpsType &RdxOp : ReductionOps) {
9036       for (Value *RdxVal : RdxOp) {
9037         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9038           RdxFMF &= FPMO->getFastMathFlags();
9039       }
9040     }
9041 
9042     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9043     Builder.setFastMathFlags(RdxFMF);
9044 
9045     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9046     // The same extra argument may be used several times, so log each attempt
9047     // to use it.
9048     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9049       assert(Pair.first && "DebugLoc must be set.");
9050       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9051     }
9052 
9053     // The compare instruction of a min/max is the insertion point for new
9054     // instructions and may be replaced with a new compare instruction.
9055     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9056       assert(isa<SelectInst>(RdxRootInst) &&
9057              "Expected min/max reduction to have select root instruction");
9058       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9059       assert(isa<Instruction>(ScalarCond) &&
9060              "Expected min/max reduction to have compare condition");
9061       return cast<Instruction>(ScalarCond);
9062     };
9063 
9064     // The reduction root is used as the insertion point for new instructions,
9065     // so set it as externally used to prevent it from being deleted.
9066     ExternallyUsedValues[ReductionRoot];
9067     SmallVector<Value *, 16> IgnoreList;
9068     for (ReductionOpsType &RdxOp : ReductionOps)
9069       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9070 
9071     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9072     if (NumReducedVals > ReduxWidth) {
9073       // In the loop below, we are building a tree based on a window of
9074       // 'ReduxWidth' values.
9075       // If the operands of those values have common traits (compare predicate,
9076       // constant operand, etc), then we want to group those together to
9077       // minimize the cost of the reduction.
9078 
9079       // TODO: This should be extended to count common operands for
9080       //       compares and binops.
9081 
9082       // Step 1: Count the number of times each compare predicate occurs.
9083       SmallDenseMap<unsigned, unsigned> PredCountMap;
9084       for (Value *RdxVal : ReducedVals) {
9085         CmpInst::Predicate Pred;
9086         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9087           ++PredCountMap[Pred];
9088       }
9089       // Step 2: Sort the values so the most common predicates come first.
9090       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9091         CmpInst::Predicate PredA, PredB;
9092         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9093             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9094           return PredCountMap[PredA] > PredCountMap[PredB];
9095         }
9096         return false;
9097       });
9098     }
9099 
9100     Value *VectorizedTree = nullptr;
9101     unsigned i = 0;
9102     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9103       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9104       V.buildTree(VL, IgnoreList);
9105       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9106         break;
9107       if (V.isLoadCombineReductionCandidate(RdxKind))
9108         break;
9109       V.reorderTopToBottom();
9110       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9111       V.buildExternalUses(ExternallyUsedValues);
9112 
9113       // For a poison-safe boolean logic reduction, do not replace select
9114       // instructions with logic ops. All reduced values will be frozen (see
9115       // below) to prevent leaking poison.
9116       if (isa<SelectInst>(ReductionRoot) &&
9117           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9118           NumReducedVals != ReduxWidth)
9119         break;
9120 
9121       V.computeMinimumValueSizes();
9122 
9123       // Estimate cost.
9124       InstructionCost TreeCost =
9125           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9126       InstructionCost ReductionCost =
9127           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9128       InstructionCost Cost = TreeCost + ReductionCost;
9129       if (!Cost.isValid()) {
9130         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9131         return nullptr;
9132       }
9133       if (Cost >= -SLPCostThreshold) {
9134         V.getORE()->emit([&]() {
9135           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9136                                           cast<Instruction>(VL[0]))
9137                  << "Vectorizing horizontal reduction is possible"
9138                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9139                  << " and threshold "
9140                  << ore::NV("Threshold", -SLPCostThreshold);
9141         });
9142         break;
9143       }
9144 
9145       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9146                         << Cost << ". (HorRdx)\n");
9147       V.getORE()->emit([&]() {
9148         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9149                                   cast<Instruction>(VL[0]))
9150                << "Vectorized horizontal reduction with cost "
9151                << ore::NV("Cost", Cost) << " and with tree size "
9152                << ore::NV("TreeSize", V.getTreeSize());
9153       });
9154 
9155       // Vectorize a tree.
9156       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9157       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9158 
9159       // Emit a reduction. If the root is a select (min/max idiom), the insert
9160       // point is the compare condition of that select.
9161       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9162       if (isCmpSelMinMax(RdxRootInst))
9163         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9164       else
9165         Builder.SetInsertPoint(RdxRootInst);
9166 
9167       // To prevent poison from leaking across what used to be sequential, safe,
9168       // scalar boolean logic operations, the reduction operand must be frozen.
9169       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9170         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9171 
9172       Value *ReducedSubTree =
9173           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9174 
9175       if (!VectorizedTree) {
9176         // Initialize the final value in the reduction.
9177         VectorizedTree = ReducedSubTree;
9178       } else {
9179         // Update the final value in the reduction.
9180         Builder.SetCurrentDebugLocation(Loc);
9181         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9182                                   ReducedSubTree, "op.rdx", ReductionOps);
9183       }
9184       i += ReduxWidth;
9185       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9186     }
9187 
9188     if (VectorizedTree) {
9189       // Finish the reduction.
9190       for (; i < NumReducedVals; ++i) {
9191         auto *I = cast<Instruction>(ReducedVals[i]);
9192         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9193         VectorizedTree =
9194             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9195       }
9196       for (auto &Pair : ExternallyUsedValues) {
9197         // Add each externally used value to the final reduction.
9198         for (auto *I : Pair.second) {
9199           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9200           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9201                                     Pair.first, "op.extra", I);
9202         }
9203       }
9204 
9205       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9206 
9207       // Mark all scalar reduction ops for deletion, they are replaced by the
9208       // vector reductions.
9209       V.eraseInstructions(IgnoreList);
9210     }
9211     return VectorizedTree;
9212   }
9213 
9214   unsigned numReductionValues() const { return ReducedVals.size(); }
9215 
9216 private:
9217   /// Calculate the cost of a reduction.
9218   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9219                                    Value *FirstReducedVal, unsigned ReduxWidth,
9220                                    FastMathFlags FMF) {
9221     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9222     Type *ScalarTy = FirstReducedVal->getType();
9223     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9224     InstructionCost VectorCost, ScalarCost;
9225     switch (RdxKind) {
9226     case RecurKind::Add:
9227     case RecurKind::Mul:
9228     case RecurKind::Or:
9229     case RecurKind::And:
9230     case RecurKind::Xor:
9231     case RecurKind::FAdd:
9232     case RecurKind::FMul: {
9233       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9234       VectorCost =
9235           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9236       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9237       break;
9238     }
9239     case RecurKind::FMax:
9240     case RecurKind::FMin: {
9241       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9242       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9243       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9244                                                /*IsUnsigned=*/false, CostKind);
9245       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9246       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9247                                            SclCondTy, RdxPred, CostKind) +
9248                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9249                                            SclCondTy, RdxPred, CostKind);
9250       break;
9251     }
9252     case RecurKind::SMax:
9253     case RecurKind::SMin:
9254     case RecurKind::UMax:
9255     case RecurKind::UMin: {
9256       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9257       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9258       bool IsUnsigned =
9259           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9260       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9261                                                CostKind);
9262       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9263       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9264                                            SclCondTy, RdxPred, CostKind) +
9265                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9266                                            SclCondTy, RdxPred, CostKind);
9267       break;
9268     }
9269     default:
9270       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9271     }
9272 
9273     // Scalar cost is repeated for N-1 elements.
9274     ScalarCost *= (ReduxWidth - 1);
9275     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9276                       << " for reduction that starts with " << *FirstReducedVal
9277                       << " (It is a splitting reduction)\n");
9278     return VectorCost - ScalarCost;
9279   }
9280 
9281   /// Emit a horizontal reduction of the vectorized value.
9282   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9283                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9284     assert(VectorizedValue && "Need to have a vectorized tree node");
9285     assert(isPowerOf2_32(ReduxWidth) &&
9286            "We only handle power-of-two reductions for now");
9287     assert(RdxKind != RecurKind::FMulAdd &&
9288            "A call to the llvm.fmuladd intrinsic is not handled yet");
9289 
9290     ++NumVectorInstructions;
9291     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9292   }
9293 };
9294 
9295 } // end anonymous namespace
9296 
9297 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9298   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9299     return cast<FixedVectorType>(IE->getType())->getNumElements();
9300 
9301   unsigned AggregateSize = 1;
9302   auto *IV = cast<InsertValueInst>(InsertInst);
9303   Type *CurrentType = IV->getType();
9304   do {
9305     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9306       for (auto *Elt : ST->elements())
9307         if (Elt != ST->getElementType(0)) // check homogeneity
9308           return None;
9309       AggregateSize *= ST->getNumElements();
9310       CurrentType = ST->getElementType(0);
9311     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9312       AggregateSize *= AT->getNumElements();
9313       CurrentType = AT->getElementType();
9314     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9315       AggregateSize *= VT->getNumElements();
9316       return AggregateSize;
9317     } else if (CurrentType->isSingleValueType()) {
9318       return AggregateSize;
9319     } else {
9320       return None;
9321     }
9322   } while (true);
9323 }
9324 
9325 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9326                                    TargetTransformInfo *TTI,
9327                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9328                                    SmallVectorImpl<Value *> &InsertElts,
9329                                    unsigned OperandOffset) {
9330   do {
9331     Value *InsertedOperand = LastInsertInst->getOperand(1);
9332     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9333     if (!OperandIndex)
9334       return false;
9335     if (isa<InsertElementInst>(InsertedOperand) ||
9336         isa<InsertValueInst>(InsertedOperand)) {
9337       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9338                                   BuildVectorOpds, InsertElts, *OperandIndex))
9339         return false;
9340     } else {
9341       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9342       InsertElts[*OperandIndex] = LastInsertInst;
9343     }
9344     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9345   } while (LastInsertInst != nullptr &&
9346            (isa<InsertValueInst>(LastInsertInst) ||
9347             isa<InsertElementInst>(LastInsertInst)) &&
9348            LastInsertInst->hasOneUse());
9349   return true;
9350 }
9351 
9352 /// Recognize construction of vectors like
9353 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9354 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9355 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9356 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9357 ///  starting from the last insertelement or insertvalue instruction.
9358 ///
9359 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9360 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9361 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9362 ///
9363 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9364 ///
9365 /// \return true if it matches.
9366 static bool findBuildAggregate(Instruction *LastInsertInst,
9367                                TargetTransformInfo *TTI,
9368                                SmallVectorImpl<Value *> &BuildVectorOpds,
9369                                SmallVectorImpl<Value *> &InsertElts) {
9370 
9371   assert((isa<InsertElementInst>(LastInsertInst) ||
9372           isa<InsertValueInst>(LastInsertInst)) &&
9373          "Expected insertelement or insertvalue instruction!");
9374 
9375   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9376          "Expected empty result vectors!");
9377 
9378   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9379   if (!AggregateSize)
9380     return false;
9381   BuildVectorOpds.resize(*AggregateSize);
9382   InsertElts.resize(*AggregateSize);
9383 
9384   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9385                              0)) {
9386     llvm::erase_value(BuildVectorOpds, nullptr);
9387     llvm::erase_value(InsertElts, nullptr);
9388     if (BuildVectorOpds.size() >= 2)
9389       return true;
9390   }
9391 
9392   return false;
9393 }
9394 
9395 /// Try and get a reduction value from a phi node.
9396 ///
9397 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9398 /// if they come from either \p ParentBB or a containing loop latch.
9399 ///
9400 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9401 /// if not possible.
9402 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9403                                 BasicBlock *ParentBB, LoopInfo *LI) {
9404   // There are situations where the reduction value is not dominated by the
9405   // reduction phi. Vectorizing such cases has been reported to cause
9406   // miscompiles. See PR25787.
9407   auto DominatedReduxValue = [&](Value *R) {
9408     return isa<Instruction>(R) &&
9409            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9410   };
9411 
9412   Value *Rdx = nullptr;
9413 
9414   // Return the incoming value if it comes from the same BB as the phi node.
9415   if (P->getIncomingBlock(0) == ParentBB) {
9416     Rdx = P->getIncomingValue(0);
9417   } else if (P->getIncomingBlock(1) == ParentBB) {
9418     Rdx = P->getIncomingValue(1);
9419   }
9420 
9421   if (Rdx && DominatedReduxValue(Rdx))
9422     return Rdx;
9423 
9424   // Otherwise, check whether we have a loop latch to look at.
9425   Loop *BBL = LI->getLoopFor(ParentBB);
9426   if (!BBL)
9427     return nullptr;
9428   BasicBlock *BBLatch = BBL->getLoopLatch();
9429   if (!BBLatch)
9430     return nullptr;
9431 
9432   // There is a loop latch, return the incoming value if it comes from
9433   // that. This reduction pattern occasionally turns up.
9434   if (P->getIncomingBlock(0) == BBLatch) {
9435     Rdx = P->getIncomingValue(0);
9436   } else if (P->getIncomingBlock(1) == BBLatch) {
9437     Rdx = P->getIncomingValue(1);
9438   }
9439 
9440   if (Rdx && DominatedReduxValue(Rdx))
9441     return Rdx;
9442 
9443   return nullptr;
9444 }
9445 
9446 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9447   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9448     return true;
9449   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9450     return true;
9451   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9452     return true;
9453   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9454     return true;
9455   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9456     return true;
9457   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9458     return true;
9459   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9460     return true;
9461   return false;
9462 }
9463 
9464 /// Attempt to reduce a horizontal reduction.
9465 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9466 /// with reduction operators \a Root (or one of its operands) in a basic block
9467 /// \a BB, then check if it can be done. If horizontal reduction is not found
9468 /// and root instruction is a binary operation, vectorization of the operands is
9469 /// attempted.
9470 /// \returns true if a horizontal reduction was matched and reduced or operands
9471 /// of one of the binary instruction were vectorized.
9472 /// \returns false if a horizontal reduction was not matched (or not possible)
9473 /// or no vectorization of any binary operation feeding \a Root instruction was
9474 /// performed.
9475 static bool tryToVectorizeHorReductionOrInstOperands(
9476     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9477     TargetTransformInfo *TTI,
9478     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9479   if (!ShouldVectorizeHor)
9480     return false;
9481 
9482   if (!Root)
9483     return false;
9484 
9485   if (Root->getParent() != BB || isa<PHINode>(Root))
9486     return false;
9487   // Start analysis starting from Root instruction. If horizontal reduction is
9488   // found, try to vectorize it. If it is not a horizontal reduction or
9489   // vectorization is not possible or not effective, and currently analyzed
9490   // instruction is a binary operation, try to vectorize the operands, using
9491   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9492   // the same procedure considering each operand as a possible root of the
9493   // horizontal reduction.
9494   // Interrupt the process if the Root instruction itself was vectorized or all
9495   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9496   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9497   // CmpInsts so we can skip extra attempts in
9498   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9499   std::queue<std::pair<Instruction *, unsigned>> Stack;
9500   Stack.emplace(Root, 0);
9501   SmallPtrSet<Value *, 8> VisitedInstrs;
9502   SmallVector<WeakTrackingVH> PostponedInsts;
9503   bool Res = false;
9504   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9505                                      Value *&B1) -> Value * {
9506     bool IsBinop = matchRdxBop(Inst, B0, B1);
9507     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9508     if (IsBinop || IsSelect) {
9509       HorizontalReduction HorRdx;
9510       if (HorRdx.matchAssociativeReduction(P, Inst))
9511         return HorRdx.tryToReduce(R, TTI);
9512     }
9513     return nullptr;
9514   };
9515   while (!Stack.empty()) {
9516     Instruction *Inst;
9517     unsigned Level;
9518     std::tie(Inst, Level) = Stack.front();
9519     Stack.pop();
9520     // Do not try to analyze instruction that has already been vectorized.
9521     // This may happen when we vectorize instruction operands on a previous
9522     // iteration while stack was populated before that happened.
9523     if (R.isDeleted(Inst))
9524       continue;
9525     Value *B0 = nullptr, *B1 = nullptr;
9526     if (Value *V = TryToReduce(Inst, B0, B1)) {
9527       Res = true;
9528       // Set P to nullptr to avoid re-analysis of phi node in
9529       // matchAssociativeReduction function unless this is the root node.
9530       P = nullptr;
9531       if (auto *I = dyn_cast<Instruction>(V)) {
9532         // Try to find another reduction.
9533         Stack.emplace(I, Level);
9534         continue;
9535       }
9536     } else {
9537       bool IsBinop = B0 && B1;
9538       if (P && IsBinop) {
9539         Inst = dyn_cast<Instruction>(B0);
9540         if (Inst == P)
9541           Inst = dyn_cast<Instruction>(B1);
9542         if (!Inst) {
9543           // Set P to nullptr to avoid re-analysis of phi node in
9544           // matchAssociativeReduction function unless this is the root node.
9545           P = nullptr;
9546           continue;
9547         }
9548       }
9549       // Set P to nullptr to avoid re-analysis of phi node in
9550       // matchAssociativeReduction function unless this is the root node.
9551       P = nullptr;
9552       // Do not try to vectorize CmpInst operands, this is done separately.
9553       // Final attempt for binop args vectorization should happen after the loop
9554       // to try to find reductions.
9555       if (!isa<CmpInst>(Inst))
9556         PostponedInsts.push_back(Inst);
9557     }
9558 
9559     // Try to vectorize operands.
9560     // Continue analysis for the instruction from the same basic block only to
9561     // save compile time.
9562     if (++Level < RecursionMaxDepth)
9563       for (auto *Op : Inst->operand_values())
9564         if (VisitedInstrs.insert(Op).second)
9565           if (auto *I = dyn_cast<Instruction>(Op))
9566             // Do not try to vectorize CmpInst operands,  this is done
9567             // separately.
9568             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9569                 I->getParent() == BB)
9570               Stack.emplace(I, Level);
9571   }
9572   // Try to vectorized binops where reductions were not found.
9573   for (Value *V : PostponedInsts)
9574     if (auto *Inst = dyn_cast<Instruction>(V))
9575       if (!R.isDeleted(Inst))
9576         Res |= Vectorize(Inst, R);
9577   return Res;
9578 }
9579 
9580 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9581                                                  BasicBlock *BB, BoUpSLP &R,
9582                                                  TargetTransformInfo *TTI) {
9583   auto *I = dyn_cast_or_null<Instruction>(V);
9584   if (!I)
9585     return false;
9586 
9587   if (!isa<BinaryOperator>(I))
9588     P = nullptr;
9589   // Try to match and vectorize a horizontal reduction.
9590   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9591     return tryToVectorize(I, R);
9592   };
9593   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9594                                                   ExtraVectorization);
9595 }
9596 
9597 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9598                                                  BasicBlock *BB, BoUpSLP &R) {
9599   const DataLayout &DL = BB->getModule()->getDataLayout();
9600   if (!R.canMapToVector(IVI->getType(), DL))
9601     return false;
9602 
9603   SmallVector<Value *, 16> BuildVectorOpds;
9604   SmallVector<Value *, 16> BuildVectorInsts;
9605   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9606     return false;
9607 
9608   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9609   // Aggregate value is unlikely to be processed in vector register.
9610   return tryToVectorizeList(BuildVectorOpds, R);
9611 }
9612 
9613 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9614                                                    BasicBlock *BB, BoUpSLP &R) {
9615   SmallVector<Value *, 16> BuildVectorInsts;
9616   SmallVector<Value *, 16> BuildVectorOpds;
9617   SmallVector<int> Mask;
9618   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9619       (llvm::all_of(
9620            BuildVectorOpds,
9621            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9622        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9623     return false;
9624 
9625   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9626   return tryToVectorizeList(BuildVectorInsts, R);
9627 }
9628 
9629 template <typename T>
9630 static bool
9631 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9632                        function_ref<unsigned(T *)> Limit,
9633                        function_ref<bool(T *, T *)> Comparator,
9634                        function_ref<bool(T *, T *)> AreCompatible,
9635                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9636                        bool LimitForRegisterSize) {
9637   bool Changed = false;
9638   // Sort by type, parent, operands.
9639   stable_sort(Incoming, Comparator);
9640 
9641   // Try to vectorize elements base on their type.
9642   SmallVector<T *> Candidates;
9643   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9644     // Look for the next elements with the same type, parent and operand
9645     // kinds.
9646     auto *SameTypeIt = IncIt;
9647     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9648       ++SameTypeIt;
9649 
9650     // Try to vectorize them.
9651     unsigned NumElts = (SameTypeIt - IncIt);
9652     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9653                       << NumElts << ")\n");
9654     // The vectorization is a 3-state attempt:
9655     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9656     // size of maximal register at first.
9657     // 2. Try to vectorize remaining instructions with the same type, if
9658     // possible. This may result in the better vectorization results rather than
9659     // if we try just to vectorize instructions with the same/alternate opcodes.
9660     // 3. Final attempt to try to vectorize all instructions with the
9661     // same/alternate ops only, this may result in some extra final
9662     // vectorization.
9663     if (NumElts > 1 &&
9664         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9665       // Success start over because instructions might have been changed.
9666       Changed = true;
9667     } else if (NumElts < Limit(*IncIt) &&
9668                (Candidates.empty() ||
9669                 Candidates.front()->getType() == (*IncIt)->getType())) {
9670       Candidates.append(IncIt, std::next(IncIt, NumElts));
9671     }
9672     // Final attempt to vectorize instructions with the same types.
9673     if (Candidates.size() > 1 &&
9674         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9675       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
9676         // Success start over because instructions might have been changed.
9677         Changed = true;
9678       } else if (LimitForRegisterSize) {
9679         // Try to vectorize using small vectors.
9680         for (auto *It = Candidates.begin(), *End = Candidates.end();
9681              It != End;) {
9682           auto *SameTypeIt = It;
9683           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9684             ++SameTypeIt;
9685           unsigned NumElts = (SameTypeIt - It);
9686           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
9687                                             /*LimitForRegisterSize=*/false))
9688             Changed = true;
9689           It = SameTypeIt;
9690         }
9691       }
9692       Candidates.clear();
9693     }
9694 
9695     // Start over at the next instruction of a different type (or the end).
9696     IncIt = SameTypeIt;
9697   }
9698   return Changed;
9699 }
9700 
9701 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9702 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9703 /// operands. If IsCompatibility is false, function implements strict weak
9704 /// ordering relation between two cmp instructions, returning true if the first
9705 /// instruction is "less" than the second, i.e. its predicate is less than the
9706 /// predicate of the second or the operands IDs are less than the operands IDs
9707 /// of the second cmp instruction.
9708 template <bool IsCompatibility>
9709 static bool compareCmp(Value *V, Value *V2,
9710                        function_ref<bool(Instruction *)> IsDeleted) {
9711   auto *CI1 = cast<CmpInst>(V);
9712   auto *CI2 = cast<CmpInst>(V2);
9713   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9714     return false;
9715   if (CI1->getOperand(0)->getType()->getTypeID() <
9716       CI2->getOperand(0)->getType()->getTypeID())
9717     return !IsCompatibility;
9718   if (CI1->getOperand(0)->getType()->getTypeID() >
9719       CI2->getOperand(0)->getType()->getTypeID())
9720     return false;
9721   CmpInst::Predicate Pred1 = CI1->getPredicate();
9722   CmpInst::Predicate Pred2 = CI2->getPredicate();
9723   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9724   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9725   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9726   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9727   if (BasePred1 < BasePred2)
9728     return !IsCompatibility;
9729   if (BasePred1 > BasePred2)
9730     return false;
9731   // Compare operands.
9732   bool LEPreds = Pred1 <= Pred2;
9733   bool GEPreds = Pred1 >= Pred2;
9734   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
9735     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
9736     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
9737     if (Op1->getValueID() < Op2->getValueID())
9738       return !IsCompatibility;
9739     if (Op1->getValueID() > Op2->getValueID())
9740       return false;
9741     if (auto *I1 = dyn_cast<Instruction>(Op1))
9742       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
9743         if (I1->getParent() != I2->getParent())
9744           return false;
9745         InstructionsState S = getSameOpcode({I1, I2});
9746         if (S.getOpcode())
9747           continue;
9748         return false;
9749       }
9750   }
9751   return IsCompatibility;
9752 }
9753 
9754 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9755     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9756     bool AtTerminator) {
9757   bool OpsChanged = false;
9758   SmallVector<Instruction *, 4> PostponedCmps;
9759   for (auto *I : reverse(Instructions)) {
9760     if (R.isDeleted(I))
9761       continue;
9762     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9763       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9764     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9765       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9766     else if (isa<CmpInst>(I))
9767       PostponedCmps.push_back(I);
9768   }
9769   if (AtTerminator) {
9770     // Try to find reductions first.
9771     for (Instruction *I : PostponedCmps) {
9772       if (R.isDeleted(I))
9773         continue;
9774       for (Value *Op : I->operands())
9775         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9776     }
9777     // Try to vectorize operands as vector bundles.
9778     for (Instruction *I : PostponedCmps) {
9779       if (R.isDeleted(I))
9780         continue;
9781       OpsChanged |= tryToVectorize(I, R);
9782     }
9783     // Try to vectorize list of compares.
9784     // Sort by type, compare predicate, etc.
9785     auto &&CompareSorter = [&R](Value *V, Value *V2) {
9786       return compareCmp<false>(V, V2,
9787                                [&R](Instruction *I) { return R.isDeleted(I); });
9788     };
9789 
9790     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
9791       if (V1 == V2)
9792         return true;
9793       return compareCmp<true>(V1, V2,
9794                               [&R](Instruction *I) { return R.isDeleted(I); });
9795     };
9796     auto Limit = [&R](Value *V) {
9797       unsigned EltSize = R.getVectorElementSize(V);
9798       return std::max(2U, R.getMaxVecRegSize() / EltSize);
9799     };
9800 
9801     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
9802     OpsChanged |= tryToVectorizeSequence<Value>(
9803         Vals, Limit, CompareSorter, AreCompatibleCompares,
9804         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9805           // Exclude possible reductions from other blocks.
9806           bool ArePossiblyReducedInOtherBlock =
9807               any_of(Candidates, [](Value *V) {
9808                 return any_of(V->users(), [V](User *U) {
9809                   return isa<SelectInst>(U) &&
9810                          cast<SelectInst>(U)->getParent() !=
9811                              cast<Instruction>(V)->getParent();
9812                 });
9813               });
9814           if (ArePossiblyReducedInOtherBlock)
9815             return false;
9816           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9817         },
9818         /*LimitForRegisterSize=*/true);
9819     Instructions.clear();
9820   } else {
9821     // Insert in reverse order since the PostponedCmps vector was filled in
9822     // reverse order.
9823     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9824   }
9825   return OpsChanged;
9826 }
9827 
9828 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9829   bool Changed = false;
9830   SmallVector<Value *, 4> Incoming;
9831   SmallPtrSet<Value *, 16> VisitedInstrs;
9832   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9833   // node. Allows better to identify the chains that can be vectorized in the
9834   // better way.
9835   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9836   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9837     assert(isValidElementType(V1->getType()) &&
9838            isValidElementType(V2->getType()) &&
9839            "Expected vectorizable types only.");
9840     // It is fine to compare type IDs here, since we expect only vectorizable
9841     // types, like ints, floats and pointers, we don't care about other type.
9842     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9843       return true;
9844     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
9845       return false;
9846     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9847     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9848     if (Opcodes1.size() < Opcodes2.size())
9849       return true;
9850     if (Opcodes1.size() > Opcodes2.size())
9851       return false;
9852     Optional<bool> ConstOrder;
9853     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9854       // Undefs are compatible with any other value.
9855       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
9856         if (!ConstOrder)
9857           ConstOrder =
9858               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
9859         continue;
9860       }
9861       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9862         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9863           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
9864           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
9865           if (!NodeI1)
9866             return NodeI2 != nullptr;
9867           if (!NodeI2)
9868             return false;
9869           assert((NodeI1 == NodeI2) ==
9870                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9871                  "Different nodes should have different DFS numbers");
9872           if (NodeI1 != NodeI2)
9873             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9874           InstructionsState S = getSameOpcode({I1, I2});
9875           if (S.getOpcode())
9876             continue;
9877           return I1->getOpcode() < I2->getOpcode();
9878         }
9879       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
9880         if (!ConstOrder)
9881           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
9882         continue;
9883       }
9884       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
9885         return true;
9886       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
9887         return false;
9888     }
9889     return ConstOrder && *ConstOrder;
9890   };
9891   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
9892     if (V1 == V2)
9893       return true;
9894     if (V1->getType() != V2->getType())
9895       return false;
9896     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9897     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9898     if (Opcodes1.size() != Opcodes2.size())
9899       return false;
9900     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9901       // Undefs are compatible with any other value.
9902       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9903         continue;
9904       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9905         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9906           if (I1->getParent() != I2->getParent())
9907             return false;
9908           InstructionsState S = getSameOpcode({I1, I2});
9909           if (S.getOpcode())
9910             continue;
9911           return false;
9912         }
9913       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9914         continue;
9915       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
9916         return false;
9917     }
9918     return true;
9919   };
9920   auto Limit = [&R](Value *V) {
9921     unsigned EltSize = R.getVectorElementSize(V);
9922     return std::max(2U, R.getMaxVecRegSize() / EltSize);
9923   };
9924 
9925   bool HaveVectorizedPhiNodes = false;
9926   do {
9927     // Collect the incoming values from the PHIs.
9928     Incoming.clear();
9929     for (Instruction &I : *BB) {
9930       PHINode *P = dyn_cast<PHINode>(&I);
9931       if (!P)
9932         break;
9933 
9934       // No need to analyze deleted, vectorized and non-vectorizable
9935       // instructions.
9936       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
9937           isValidElementType(P->getType()))
9938         Incoming.push_back(P);
9939     }
9940 
9941     // Find the corresponding non-phi nodes for better matching when trying to
9942     // build the tree.
9943     for (Value *V : Incoming) {
9944       SmallVectorImpl<Value *> &Opcodes =
9945           PHIToOpcodes.try_emplace(V).first->getSecond();
9946       if (!Opcodes.empty())
9947         continue;
9948       SmallVector<Value *, 4> Nodes(1, V);
9949       SmallPtrSet<Value *, 4> Visited;
9950       while (!Nodes.empty()) {
9951         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
9952         if (!Visited.insert(PHI).second)
9953           continue;
9954         for (Value *V : PHI->incoming_values()) {
9955           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
9956             Nodes.push_back(PHI1);
9957             continue;
9958           }
9959           Opcodes.emplace_back(V);
9960         }
9961       }
9962     }
9963 
9964     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
9965         Incoming, Limit, PHICompare, AreCompatiblePHIs,
9966         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9967           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9968         },
9969         /*LimitForRegisterSize=*/true);
9970     Changed |= HaveVectorizedPhiNodes;
9971     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
9972   } while (HaveVectorizedPhiNodes);
9973 
9974   VisitedInstrs.clear();
9975 
9976   SmallVector<Instruction *, 8> PostProcessInstructions;
9977   SmallDenseSet<Instruction *, 4> KeyNodes;
9978   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
9979     // Skip instructions with scalable type. The num of elements is unknown at
9980     // compile-time for scalable type.
9981     if (isa<ScalableVectorType>(it->getType()))
9982       continue;
9983 
9984     // Skip instructions marked for the deletion.
9985     if (R.isDeleted(&*it))
9986       continue;
9987     // We may go through BB multiple times so skip the one we have checked.
9988     if (!VisitedInstrs.insert(&*it).second) {
9989       if (it->use_empty() && KeyNodes.contains(&*it) &&
9990           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9991                                       it->isTerminator())) {
9992         // We would like to start over since some instructions are deleted
9993         // and the iterator may become invalid value.
9994         Changed = true;
9995         it = BB->begin();
9996         e = BB->end();
9997       }
9998       continue;
9999     }
10000 
10001     if (isa<DbgInfoIntrinsic>(it))
10002       continue;
10003 
10004     // Try to vectorize reductions that use PHINodes.
10005     if (PHINode *P = dyn_cast<PHINode>(it)) {
10006       // Check that the PHI is a reduction PHI.
10007       if (P->getNumIncomingValues() == 2) {
10008         // Try to match and vectorize a horizontal reduction.
10009         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10010                                      TTI)) {
10011           Changed = true;
10012           it = BB->begin();
10013           e = BB->end();
10014           continue;
10015         }
10016       }
10017       // Try to vectorize the incoming values of the PHI, to catch reductions
10018       // that feed into PHIs.
10019       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10020         // Skip if the incoming block is the current BB for now. Also, bypass
10021         // unreachable IR for efficiency and to avoid crashing.
10022         // TODO: Collect the skipped incoming values and try to vectorize them
10023         // after processing BB.
10024         if (BB == P->getIncomingBlock(I) ||
10025             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10026           continue;
10027 
10028         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10029                                             P->getIncomingBlock(I), R, TTI);
10030       }
10031       continue;
10032     }
10033 
10034     // Ran into an instruction without users, like terminator, or function call
10035     // with ignored return value, store. Ignore unused instructions (basing on
10036     // instruction type, except for CallInst and InvokeInst).
10037     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10038                             isa<InvokeInst>(it))) {
10039       KeyNodes.insert(&*it);
10040       bool OpsChanged = false;
10041       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10042         for (auto *V : it->operand_values()) {
10043           // Try to match and vectorize a horizontal reduction.
10044           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10045         }
10046       }
10047       // Start vectorization of post-process list of instructions from the
10048       // top-tree instructions to try to vectorize as many instructions as
10049       // possible.
10050       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10051                                                 it->isTerminator());
10052       if (OpsChanged) {
10053         // We would like to start over since some instructions are deleted
10054         // and the iterator may become invalid value.
10055         Changed = true;
10056         it = BB->begin();
10057         e = BB->end();
10058         continue;
10059       }
10060     }
10061 
10062     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10063         isa<InsertValueInst>(it))
10064       PostProcessInstructions.push_back(&*it);
10065   }
10066 
10067   return Changed;
10068 }
10069 
10070 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10071   auto Changed = false;
10072   for (auto &Entry : GEPs) {
10073     // If the getelementptr list has fewer than two elements, there's nothing
10074     // to do.
10075     if (Entry.second.size() < 2)
10076       continue;
10077 
10078     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10079                       << Entry.second.size() << ".\n");
10080 
10081     // Process the GEP list in chunks suitable for the target's supported
10082     // vector size. If a vector register can't hold 1 element, we are done. We
10083     // are trying to vectorize the index computations, so the maximum number of
10084     // elements is based on the size of the index expression, rather than the
10085     // size of the GEP itself (the target's pointer size).
10086     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10087     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10088     if (MaxVecRegSize < EltSize)
10089       continue;
10090 
10091     unsigned MaxElts = MaxVecRegSize / EltSize;
10092     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10093       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10094       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10095 
10096       // Initialize a set a candidate getelementptrs. Note that we use a
10097       // SetVector here to preserve program order. If the index computations
10098       // are vectorizable and begin with loads, we want to minimize the chance
10099       // of having to reorder them later.
10100       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10101 
10102       // Some of the candidates may have already been vectorized after we
10103       // initially collected them. If so, they are marked as deleted, so remove
10104       // them from the set of candidates.
10105       Candidates.remove_if(
10106           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10107 
10108       // Remove from the set of candidates all pairs of getelementptrs with
10109       // constant differences. Such getelementptrs are likely not good
10110       // candidates for vectorization in a bottom-up phase since one can be
10111       // computed from the other. We also ensure all candidate getelementptr
10112       // indices are unique.
10113       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10114         auto *GEPI = GEPList[I];
10115         if (!Candidates.count(GEPI))
10116           continue;
10117         auto *SCEVI = SE->getSCEV(GEPList[I]);
10118         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10119           auto *GEPJ = GEPList[J];
10120           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10121           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10122             Candidates.remove(GEPI);
10123             Candidates.remove(GEPJ);
10124           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10125             Candidates.remove(GEPJ);
10126           }
10127         }
10128       }
10129 
10130       // We break out of the above computation as soon as we know there are
10131       // fewer than two candidates remaining.
10132       if (Candidates.size() < 2)
10133         continue;
10134 
10135       // Add the single, non-constant index of each candidate to the bundle. We
10136       // ensured the indices met these constraints when we originally collected
10137       // the getelementptrs.
10138       SmallVector<Value *, 16> Bundle(Candidates.size());
10139       auto BundleIndex = 0u;
10140       for (auto *V : Candidates) {
10141         auto *GEP = cast<GetElementPtrInst>(V);
10142         auto *GEPIdx = GEP->idx_begin()->get();
10143         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10144         Bundle[BundleIndex++] = GEPIdx;
10145       }
10146 
10147       // Try and vectorize the indices. We are currently only interested in
10148       // gather-like cases of the form:
10149       //
10150       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10151       //
10152       // where the loads of "a", the loads of "b", and the subtractions can be
10153       // performed in parallel. It's likely that detecting this pattern in a
10154       // bottom-up phase will be simpler and less costly than building a
10155       // full-blown top-down phase beginning at the consecutive loads.
10156       Changed |= tryToVectorizeList(Bundle, R);
10157     }
10158   }
10159   return Changed;
10160 }
10161 
10162 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10163   bool Changed = false;
10164   // Sort by type, base pointers and values operand. Value operands must be
10165   // compatible (have the same opcode, same parent), otherwise it is
10166   // definitely not profitable to try to vectorize them.
10167   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10168     if (V->getPointerOperandType()->getTypeID() <
10169         V2->getPointerOperandType()->getTypeID())
10170       return true;
10171     if (V->getPointerOperandType()->getTypeID() >
10172         V2->getPointerOperandType()->getTypeID())
10173       return false;
10174     // UndefValues are compatible with all other values.
10175     if (isa<UndefValue>(V->getValueOperand()) ||
10176         isa<UndefValue>(V2->getValueOperand()))
10177       return false;
10178     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10179       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10180         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10181             DT->getNode(I1->getParent());
10182         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10183             DT->getNode(I2->getParent());
10184         assert(NodeI1 && "Should only process reachable instructions");
10185         assert(NodeI1 && "Should only process reachable instructions");
10186         assert((NodeI1 == NodeI2) ==
10187                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10188                "Different nodes should have different DFS numbers");
10189         if (NodeI1 != NodeI2)
10190           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10191         InstructionsState S = getSameOpcode({I1, I2});
10192         if (S.getOpcode())
10193           return false;
10194         return I1->getOpcode() < I2->getOpcode();
10195       }
10196     if (isa<Constant>(V->getValueOperand()) &&
10197         isa<Constant>(V2->getValueOperand()))
10198       return false;
10199     return V->getValueOperand()->getValueID() <
10200            V2->getValueOperand()->getValueID();
10201   };
10202 
10203   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10204     if (V1 == V2)
10205       return true;
10206     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10207       return false;
10208     // Undefs are compatible with any other value.
10209     if (isa<UndefValue>(V1->getValueOperand()) ||
10210         isa<UndefValue>(V2->getValueOperand()))
10211       return true;
10212     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10213       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10214         if (I1->getParent() != I2->getParent())
10215           return false;
10216         InstructionsState S = getSameOpcode({I1, I2});
10217         return S.getOpcode() > 0;
10218       }
10219     if (isa<Constant>(V1->getValueOperand()) &&
10220         isa<Constant>(V2->getValueOperand()))
10221       return true;
10222     return V1->getValueOperand()->getValueID() ==
10223            V2->getValueOperand()->getValueID();
10224   };
10225   auto Limit = [&R, this](StoreInst *SI) {
10226     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10227     return R.getMinVF(EltSize);
10228   };
10229 
10230   // Attempt to sort and vectorize each of the store-groups.
10231   for (auto &Pair : Stores) {
10232     if (Pair.second.size() < 2)
10233       continue;
10234 
10235     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10236                       << Pair.second.size() << ".\n");
10237 
10238     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10239       continue;
10240 
10241     Changed |= tryToVectorizeSequence<StoreInst>(
10242         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10243         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10244           return vectorizeStores(Candidates, R);
10245         },
10246         /*LimitForRegisterSize=*/false);
10247   }
10248   return Changed;
10249 }
10250 
10251 char SLPVectorizer::ID = 0;
10252 
10253 static const char lv_name[] = "SLP Vectorizer";
10254 
10255 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10256 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10257 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10258 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10259 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10260 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10261 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10262 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10263 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10264 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10265 
10266 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10267