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