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