1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The Look-ahead heuristic goes through the users of the bundle to calculate
168 // the users cost in getExternalUsesCost(). To avoid compilation time increase
169 // we limit the number of users visited to this value.
170 static cl::opt<unsigned> LookAheadUsersBudget(
171     "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
172     cl::desc("The maximum number of users to visit while visiting the "
173              "predecessors. This prevents compilation time increase."));
174 
175 static cl::opt<bool>
176     ViewSLPTree("view-slp-tree", cl::Hidden,
177                 cl::desc("Display the SLP trees with Graphviz"));
178 
179 // Limit the number of alias checks. The limit is chosen so that
180 // it has no negative effect on the llvm benchmarks.
181 static const unsigned AliasedCheckLimit = 10;
182 
183 // Another limit for the alias checks: The maximum distance between load/store
184 // instructions where alias checks are done.
185 // This limit is useful for very large basic blocks.
186 static const unsigned MaxMemDepDistance = 160;
187 
188 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
189 /// regions to be handled.
190 static const int MinScheduleRegionSize = 16;
191 
192 /// Predicate for the element types that the SLP vectorizer supports.
193 ///
194 /// The most important thing to filter here are types which are invalid in LLVM
195 /// vectors. We also filter target specific types which have absolutely no
196 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
197 /// avoids spending time checking the cost model and realizing that they will
198 /// be inevitably scalarized.
199 static bool isValidElementType(Type *Ty) {
200   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
201          !Ty->isPPC_FP128Ty();
202 }
203 
204 /// \returns True if the value is a constant (but not globals/constant
205 /// expressions).
206 static bool isConstant(Value *V) {
207   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
208 }
209 
210 /// Checks if \p V is one of vector-like instructions, i.e. undef,
211 /// insertelement/extractelement with constant indices for fixed vector type or
212 /// extractvalue instruction.
213 static bool isVectorLikeInstWithConstOps(Value *V) {
214   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
215       !isa<ExtractValueInst, UndefValue>(V))
216     return false;
217   auto *I = dyn_cast<Instruction>(V);
218   if (!I || isa<ExtractValueInst>(I))
219     return true;
220   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
221     return false;
222   if (isa<ExtractElementInst>(I))
223     return isConstant(I->getOperand(1));
224   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
225   return isConstant(I->getOperand(2));
226 }
227 
228 /// \returns true if all of the instructions in \p VL are in the same block or
229 /// false otherwise.
230 static bool allSameBlock(ArrayRef<Value *> VL) {
231   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
232   if (!I0)
233     return false;
234   if (all_of(VL, isVectorLikeInstWithConstOps))
235     return true;
236 
237   BasicBlock *BB = I0->getParent();
238   for (int I = 1, E = VL.size(); I < E; I++) {
239     auto *II = dyn_cast<Instruction>(VL[I]);
240     if (!II)
241       return false;
242 
243     if (BB != II->getParent())
244       return false;
245   }
246   return true;
247 }
248 
249 /// \returns True if all of the values in \p VL are constants (but not
250 /// globals/constant expressions).
251 static bool allConstant(ArrayRef<Value *> VL) {
252   // Constant expressions and globals can't be vectorized like normal integer/FP
253   // constants.
254   return all_of(VL, isConstant);
255 }
256 
257 /// \returns True if all of the values in \p VL are identical or some of them
258 /// are UndefValue.
259 static bool isSplat(ArrayRef<Value *> VL) {
260   Value *FirstNonUndef = nullptr;
261   for (Value *V : VL) {
262     if (isa<UndefValue>(V))
263       continue;
264     if (!FirstNonUndef) {
265       FirstNonUndef = V;
266       continue;
267     }
268     if (V != FirstNonUndef)
269       return false;
270   }
271   return FirstNonUndef != nullptr;
272 }
273 
274 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
275 static bool isCommutative(Instruction *I) {
276   if (auto *Cmp = dyn_cast<CmpInst>(I))
277     return Cmp->isCommutative();
278   if (auto *BO = dyn_cast<BinaryOperator>(I))
279     return BO->isCommutative();
280   // TODO: This should check for generic Instruction::isCommutative(), but
281   //       we need to confirm that the caller code correctly handles Intrinsics
282   //       for example (does not have 2 operands).
283   return false;
284 }
285 
286 /// Checks if the given value is actually an undefined constant vector.
287 static bool isUndefVector(const Value *V) {
288   if (isa<UndefValue>(V))
289     return true;
290   auto *C = dyn_cast<Constant>(V);
291   if (!C)
292     return false;
293   if (!C->containsUndefOrPoisonElement())
294     return false;
295   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
296   if (!VecTy)
297     return false;
298   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
299     if (Constant *Elem = C->getAggregateElement(I))
300       if (!isa<UndefValue>(Elem))
301         return false;
302   }
303   return true;
304 }
305 
306 /// Checks if the vector of instructions can be represented as a shuffle, like:
307 /// %x0 = extractelement <4 x i8> %x, i32 0
308 /// %x3 = extractelement <4 x i8> %x, i32 3
309 /// %y1 = extractelement <4 x i8> %y, i32 1
310 /// %y2 = extractelement <4 x i8> %y, i32 2
311 /// %x0x0 = mul i8 %x0, %x0
312 /// %x3x3 = mul i8 %x3, %x3
313 /// %y1y1 = mul i8 %y1, %y1
314 /// %y2y2 = mul i8 %y2, %y2
315 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
316 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
317 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
318 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
319 /// ret <4 x i8> %ins4
320 /// can be transformed into:
321 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
322 ///                                                         i32 6>
323 /// %2 = mul <4 x i8> %1, %1
324 /// ret <4 x i8> %2
325 /// We convert this initially to something like:
326 /// %x0 = extractelement <4 x i8> %x, i32 0
327 /// %x3 = extractelement <4 x i8> %x, i32 3
328 /// %y1 = extractelement <4 x i8> %y, i32 1
329 /// %y2 = extractelement <4 x i8> %y, i32 2
330 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
331 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
332 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
333 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
334 /// %5 = mul <4 x i8> %4, %4
335 /// %6 = extractelement <4 x i8> %5, i32 0
336 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
337 /// %7 = extractelement <4 x i8> %5, i32 1
338 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
339 /// %8 = extractelement <4 x i8> %5, i32 2
340 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
341 /// %9 = extractelement <4 x i8> %5, i32 3
342 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
343 /// ret <4 x i8> %ins4
344 /// InstCombiner transforms this into a shuffle and vector mul
345 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
346 /// TODO: Can we split off and reuse the shuffle mask detection from
347 /// TargetTransformInfo::getInstructionThroughput?
348 static Optional<TargetTransformInfo::ShuffleKind>
349 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
350   const auto *It =
351       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
352   if (It == VL.end())
353     return None;
354   auto *EI0 = cast<ExtractElementInst>(*It);
355   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
356     return None;
357   unsigned Size =
358       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
359   Value *Vec1 = nullptr;
360   Value *Vec2 = nullptr;
361   enum ShuffleMode { Unknown, Select, Permute };
362   ShuffleMode CommonShuffleMode = Unknown;
363   Mask.assign(VL.size(), UndefMaskElem);
364   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
365     // Undef can be represented as an undef element in a vector.
366     if (isa<UndefValue>(VL[I]))
367       continue;
368     auto *EI = cast<ExtractElementInst>(VL[I]);
369     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
370       return None;
371     auto *Vec = EI->getVectorOperand();
372     // We can extractelement from undef or poison vector.
373     if (isUndefVector(Vec))
374       continue;
375     // All vector operands must have the same number of vector elements.
376     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
377       return None;
378     if (isa<UndefValue>(EI->getIndexOperand()))
379       continue;
380     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
381     if (!Idx)
382       return None;
383     // Undefined behavior if Idx is negative or >= Size.
384     if (Idx->getValue().uge(Size))
385       continue;
386     unsigned IntIdx = Idx->getValue().getZExtValue();
387     Mask[I] = IntIdx;
388     // For correct shuffling we have to have at most 2 different vector operands
389     // in all extractelement instructions.
390     if (!Vec1 || Vec1 == Vec) {
391       Vec1 = Vec;
392     } else if (!Vec2 || Vec2 == Vec) {
393       Vec2 = Vec;
394       Mask[I] += Size;
395     } else {
396       return None;
397     }
398     if (CommonShuffleMode == Permute)
399       continue;
400     // If the extract index is not the same as the operation number, it is a
401     // permutation.
402     if (IntIdx != I) {
403       CommonShuffleMode = Permute;
404       continue;
405     }
406     CommonShuffleMode = Select;
407   }
408   // If we're not crossing lanes in different vectors, consider it as blending.
409   if (CommonShuffleMode == Select && Vec2)
410     return TargetTransformInfo::SK_Select;
411   // If Vec2 was never used, we have a permutation of a single vector, otherwise
412   // we have permutation of 2 vectors.
413   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
414               : TargetTransformInfo::SK_PermuteSingleSrc;
415 }
416 
417 namespace {
418 
419 /// Main data required for vectorization of instructions.
420 struct InstructionsState {
421   /// The very first instruction in the list with the main opcode.
422   Value *OpValue = nullptr;
423 
424   /// The main/alternate instruction.
425   Instruction *MainOp = nullptr;
426   Instruction *AltOp = nullptr;
427 
428   /// The main/alternate opcodes for the list of instructions.
429   unsigned getOpcode() const {
430     return MainOp ? MainOp->getOpcode() : 0;
431   }
432 
433   unsigned getAltOpcode() const {
434     return AltOp ? AltOp->getOpcode() : 0;
435   }
436 
437   /// Some of the instructions in the list have alternate opcodes.
438   bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
439 
440   bool isOpcodeOrAlt(Instruction *I) const {
441     unsigned CheckedOpcode = I->getOpcode();
442     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
443   }
444 
445   InstructionsState() = delete;
446   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
447       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
448 };
449 
450 } // end anonymous namespace
451 
452 /// Chooses the correct key for scheduling data. If \p Op has the same (or
453 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
454 /// OpValue.
455 static Value *isOneOf(const InstructionsState &S, Value *Op) {
456   auto *I = dyn_cast<Instruction>(Op);
457   if (I && S.isOpcodeOrAlt(I))
458     return Op;
459   return S.OpValue;
460 }
461 
462 /// \returns true if \p Opcode is allowed as part of of the main/alternate
463 /// instruction for SLP vectorization.
464 ///
465 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
466 /// "shuffled out" lane would result in division by zero.
467 static bool isValidForAlternation(unsigned Opcode) {
468   if (Instruction::isIntDivRem(Opcode))
469     return false;
470 
471   return true;
472 }
473 
474 /// \returns analysis of the Instructions in \p VL described in
475 /// InstructionsState, the Opcode that we suppose the whole list
476 /// could be vectorized even if its structure is diverse.
477 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
478                                        unsigned BaseIndex = 0) {
479   // Make sure these are all Instructions.
480   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
481     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
482 
483   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
484   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
485   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
486   unsigned AltOpcode = Opcode;
487   unsigned AltIndex = BaseIndex;
488 
489   // Check for one alternate opcode from another BinaryOperator.
490   // TODO - generalize to support all operators (types, calls etc.).
491   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
492     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
493     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
494       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
495         continue;
496       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
497           isValidForAlternation(Opcode)) {
498         AltOpcode = InstOpcode;
499         AltIndex = Cnt;
500         continue;
501       }
502     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
503       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
504       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
505       if (Ty0 == Ty1) {
506         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
507           continue;
508         if (Opcode == AltOpcode) {
509           assert(isValidForAlternation(Opcode) &&
510                  isValidForAlternation(InstOpcode) &&
511                  "Cast isn't safe for alternation, logic needs to be updated!");
512           AltOpcode = InstOpcode;
513           AltIndex = Cnt;
514           continue;
515         }
516       }
517     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518       continue;
519     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
520   }
521 
522   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
523                            cast<Instruction>(VL[AltIndex]));
524 }
525 
526 /// \returns true if all of the values in \p VL have the same type or false
527 /// otherwise.
528 static bool allSameType(ArrayRef<Value *> VL) {
529   Type *Ty = VL[0]->getType();
530   for (int i = 1, e = VL.size(); i < e; i++)
531     if (VL[i]->getType() != Ty)
532       return false;
533 
534   return true;
535 }
536 
537 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
538 static Optional<unsigned> getExtractIndex(Instruction *E) {
539   unsigned Opcode = E->getOpcode();
540   assert((Opcode == Instruction::ExtractElement ||
541           Opcode == Instruction::ExtractValue) &&
542          "Expected extractelement or extractvalue instruction.");
543   if (Opcode == Instruction::ExtractElement) {
544     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
545     if (!CI)
546       return None;
547     return CI->getZExtValue();
548   }
549   ExtractValueInst *EI = cast<ExtractValueInst>(E);
550   if (EI->getNumIndices() != 1)
551     return None;
552   return *EI->idx_begin();
553 }
554 
555 /// \returns True if in-tree use also needs extract. This refers to
556 /// possible scalar operand in vectorized instruction.
557 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
558                                     TargetLibraryInfo *TLI) {
559   unsigned Opcode = UserInst->getOpcode();
560   switch (Opcode) {
561   case Instruction::Load: {
562     LoadInst *LI = cast<LoadInst>(UserInst);
563     return (LI->getPointerOperand() == Scalar);
564   }
565   case Instruction::Store: {
566     StoreInst *SI = cast<StoreInst>(UserInst);
567     return (SI->getPointerOperand() == Scalar);
568   }
569   case Instruction::Call: {
570     CallInst *CI = cast<CallInst>(UserInst);
571     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
572     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
573       if (hasVectorInstrinsicScalarOpd(ID, i))
574         return (CI->getArgOperand(i) == Scalar);
575     }
576     LLVM_FALLTHROUGH;
577   }
578   default:
579     return false;
580   }
581 }
582 
583 /// \returns the AA location that is being access by the instruction.
584 static MemoryLocation getLocation(Instruction *I, AAResults *AA) {
585   if (StoreInst *SI = dyn_cast<StoreInst>(I))
586     return MemoryLocation::get(SI);
587   if (LoadInst *LI = dyn_cast<LoadInst>(I))
588     return MemoryLocation::get(LI);
589   return MemoryLocation();
590 }
591 
592 /// \returns True if the instruction is not a volatile or atomic load/store.
593 static bool isSimple(Instruction *I) {
594   if (LoadInst *LI = dyn_cast<LoadInst>(I))
595     return LI->isSimple();
596   if (StoreInst *SI = dyn_cast<StoreInst>(I))
597     return SI->isSimple();
598   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
599     return !MI->isVolatile();
600   return true;
601 }
602 
603 /// Shuffles \p Mask in accordance with the given \p SubMask.
604 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
605   if (SubMask.empty())
606     return;
607   if (Mask.empty()) {
608     Mask.append(SubMask.begin(), SubMask.end());
609     return;
610   }
611   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
612   int TermValue = std::min(Mask.size(), SubMask.size());
613   for (int I = 0, E = SubMask.size(); I < E; ++I) {
614     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
615         Mask[SubMask[I]] >= TermValue)
616       continue;
617     NewMask[I] = Mask[SubMask[I]];
618   }
619   Mask.swap(NewMask);
620 }
621 
622 /// Order may have elements assigned special value (size) which is out of
623 /// bounds. Such indices only appear on places which correspond to undef values
624 /// (see canReuseExtract for details) and used in order to avoid undef values
625 /// have effect on operands ordering.
626 /// The first loop below simply finds all unused indices and then the next loop
627 /// nest assigns these indices for undef values positions.
628 /// As an example below Order has two undef positions and they have assigned
629 /// values 3 and 7 respectively:
630 /// before:  6 9 5 4 9 2 1 0
631 /// after:   6 3 5 4 7 2 1 0
632 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
633   const unsigned Sz = Order.size();
634   SmallBitVector UnusedIndices(Sz, /*t=*/true);
635   SmallBitVector MaskedIndices(Sz);
636   for (unsigned I = 0; I < Sz; ++I) {
637     if (Order[I] < Sz)
638       UnusedIndices.reset(Order[I]);
639     else
640       MaskedIndices.set(I);
641   }
642   if (MaskedIndices.none())
643     return;
644   assert(UnusedIndices.count() == MaskedIndices.count() &&
645          "Non-synced masked/available indices.");
646   int Idx = UnusedIndices.find_first();
647   int MIdx = MaskedIndices.find_first();
648   while (MIdx >= 0) {
649     assert(Idx >= 0 && "Indices must be synced.");
650     Order[MIdx] = Idx;
651     Idx = UnusedIndices.find_next(Idx);
652     MIdx = MaskedIndices.find_next(MIdx);
653   }
654 }
655 
656 namespace llvm {
657 
658 static void inversePermutation(ArrayRef<unsigned> Indices,
659                                SmallVectorImpl<int> &Mask) {
660   Mask.clear();
661   const unsigned E = Indices.size();
662   Mask.resize(E, UndefMaskElem);
663   for (unsigned I = 0; I < E; ++I)
664     Mask[Indices[I]] = I;
665 }
666 
667 /// \returns inserting index of InsertElement or InsertValue instruction,
668 /// using Offset as base offset for index.
669 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
670   int Index = Offset;
671   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
672     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
673       auto *VT = cast<FixedVectorType>(IE->getType());
674       if (CI->getValue().uge(VT->getNumElements()))
675         return UndefMaskElem;
676       Index *= VT->getNumElements();
677       Index += CI->getZExtValue();
678       return Index;
679     }
680     if (isa<UndefValue>(IE->getOperand(2)))
681       return UndefMaskElem;
682     return None;
683   }
684 
685   auto *IV = cast<InsertValueInst>(InsertInst);
686   Type *CurrentType = IV->getType();
687   for (unsigned I : IV->indices()) {
688     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
689       Index *= ST->getNumElements();
690       CurrentType = ST->getElementType(I);
691     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
692       Index *= AT->getNumElements();
693       CurrentType = AT->getElementType();
694     } else {
695       return None;
696     }
697     Index += I;
698   }
699   return Index;
700 }
701 
702 /// Reorders the list of scalars in accordance with the given \p Order and then
703 /// the \p Mask. \p Order - is the original order of the scalars, need to
704 /// reorder scalars into an unordered state at first according to the given
705 /// order. Then the ordered scalars are shuffled once again in accordance with
706 /// the provided mask.
707 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
708                            ArrayRef<int> Mask) {
709   assert(!Mask.empty() && "Expected non-empty mask.");
710   SmallVector<Value *> Prev(Scalars.size(),
711                             UndefValue::get(Scalars.front()->getType()));
712   Prev.swap(Scalars);
713   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
714     if (Mask[I] != UndefMaskElem)
715       Scalars[Mask[I]] = Prev[I];
716 }
717 
718 namespace slpvectorizer {
719 
720 /// Bottom Up SLP Vectorizer.
721 class BoUpSLP {
722   struct TreeEntry;
723   struct ScheduleData;
724 
725 public:
726   using ValueList = SmallVector<Value *, 8>;
727   using InstrList = SmallVector<Instruction *, 16>;
728   using ValueSet = SmallPtrSet<Value *, 16>;
729   using StoreList = SmallVector<StoreInst *, 8>;
730   using ExtraValueToDebugLocsMap =
731       MapVector<Value *, SmallVector<Instruction *, 2>>;
732   using OrdersType = SmallVector<unsigned, 4>;
733 
734   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
735           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
736           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
737           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
738       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
739         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
740     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
741     // Use the vector register size specified by the target unless overridden
742     // by a command-line option.
743     // TODO: It would be better to limit the vectorization factor based on
744     //       data type rather than just register size. For example, x86 AVX has
745     //       256-bit registers, but it does not support integer operations
746     //       at that width (that requires AVX2).
747     if (MaxVectorRegSizeOption.getNumOccurrences())
748       MaxVecRegSize = MaxVectorRegSizeOption;
749     else
750       MaxVecRegSize =
751           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
752               .getFixedSize();
753 
754     if (MinVectorRegSizeOption.getNumOccurrences())
755       MinVecRegSize = MinVectorRegSizeOption;
756     else
757       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
758   }
759 
760   /// Vectorize the tree that starts with the elements in \p VL.
761   /// Returns the vectorized root.
762   Value *vectorizeTree();
763 
764   /// Vectorize the tree but with the list of externally used values \p
765   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
766   /// generated extractvalue instructions.
767   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
768 
769   /// \returns the cost incurred by unwanted spills and fills, caused by
770   /// holding live values over call sites.
771   InstructionCost getSpillCost() const;
772 
773   /// \returns the vectorization cost of the subtree that starts at \p VL.
774   /// A negative number means that this is profitable.
775   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
776 
777   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
778   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
779   void buildTree(ArrayRef<Value *> Roots,
780                  ArrayRef<Value *> UserIgnoreLst = None);
781 
782   /// Builds external uses of the vectorized scalars, i.e. the list of
783   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
784   /// ExternallyUsedValues contains additional list of external uses to handle
785   /// vectorization of reductions.
786   void
787   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
788 
789   /// Clear the internal data structures that are created by 'buildTree'.
790   void deleteTree() {
791     VectorizableTree.clear();
792     ScalarToTreeEntry.clear();
793     MustGather.clear();
794     ExternalUses.clear();
795     for (auto &Iter : BlocksSchedules) {
796       BlockScheduling *BS = Iter.second.get();
797       BS->clear();
798     }
799     MinBWs.clear();
800     InstrElementSize.clear();
801   }
802 
803   unsigned getTreeSize() const { return VectorizableTree.size(); }
804 
805   /// Perform LICM and CSE on the newly generated gather sequences.
806   void optimizeGatherSequence();
807 
808   /// Checks if the specified gather tree entry \p TE can be represented as a
809   /// shuffled vector entry + (possibly) permutation with other gathers. It
810   /// implements the checks only for possibly ordered scalars (Loads,
811   /// ExtractElement, ExtractValue), which can be part of the graph.
812   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
813 
814   /// Gets reordering data for the given tree entry. If the entry is vectorized
815   /// - just return ReorderIndices, otherwise check if the scalars can be
816   /// reordered and return the most optimal order.
817   /// \param TopToBottom If true, include the order of vectorized stores and
818   /// insertelement nodes, otherwise skip them.
819   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
820 
821   /// Reorders the current graph to the most profitable order starting from the
822   /// root node to the leaf nodes. The best order is chosen only from the nodes
823   /// of the same size (vectorization factor). Smaller nodes are considered
824   /// parts of subgraph with smaller VF and they are reordered independently. We
825   /// can make it because we still need to extend smaller nodes to the wider VF
826   /// and we can merge reordering shuffles with the widening shuffles.
827   void reorderTopToBottom();
828 
829   /// Reorders the current graph to the most profitable order starting from
830   /// leaves to the root. It allows to rotate small subgraphs and reduce the
831   /// number of reshuffles if the leaf nodes use the same order. In this case we
832   /// can merge the orders and just shuffle user node instead of shuffling its
833   /// operands. Plus, even the leaf nodes have different orders, it allows to
834   /// sink reordering in the graph closer to the root node and merge it later
835   /// during analysis.
836   void reorderBottomToTop(bool IgnoreReorder = false);
837 
838   /// \return The vector element size in bits to use when vectorizing the
839   /// expression tree ending at \p V. If V is a store, the size is the width of
840   /// the stored value. Otherwise, the size is the width of the largest loaded
841   /// value reaching V. This method is used by the vectorizer to calculate
842   /// vectorization factors.
843   unsigned getVectorElementSize(Value *V);
844 
845   /// Compute the minimum type sizes required to represent the entries in a
846   /// vectorizable tree.
847   void computeMinimumValueSizes();
848 
849   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
850   unsigned getMaxVecRegSize() const {
851     return MaxVecRegSize;
852   }
853 
854   // \returns minimum vector register size as set by cl::opt.
855   unsigned getMinVecRegSize() const {
856     return MinVecRegSize;
857   }
858 
859   unsigned getMinVF(unsigned Sz) const {
860     return std::max(2U, getMinVecRegSize() / Sz);
861   }
862 
863   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
864     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
865       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
866     return MaxVF ? MaxVF : UINT_MAX;
867   }
868 
869   /// Check if homogeneous aggregate is isomorphic to some VectorType.
870   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
871   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
872   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
873   ///
874   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
875   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
876 
877   /// \returns True if the VectorizableTree is both tiny and not fully
878   /// vectorizable. We do not vectorize such trees.
879   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
880 
881   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
882   /// can be load combined in the backend. Load combining may not be allowed in
883   /// the IR optimizer, so we do not want to alter the pattern. For example,
884   /// partially transforming a scalar bswap() pattern into vector code is
885   /// effectively impossible for the backend to undo.
886   /// TODO: If load combining is allowed in the IR optimizer, this analysis
887   ///       may not be necessary.
888   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
889 
890   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
891   /// can be load combined in the backend. Load combining may not be allowed in
892   /// the IR optimizer, so we do not want to alter the pattern. For example,
893   /// partially transforming a scalar bswap() pattern into vector code is
894   /// effectively impossible for the backend to undo.
895   /// TODO: If load combining is allowed in the IR optimizer, this analysis
896   ///       may not be necessary.
897   bool isLoadCombineCandidate() const;
898 
899   OptimizationRemarkEmitter *getORE() { return ORE; }
900 
901   /// This structure holds any data we need about the edges being traversed
902   /// during buildTree_rec(). We keep track of:
903   /// (i) the user TreeEntry index, and
904   /// (ii) the index of the edge.
905   struct EdgeInfo {
906     EdgeInfo() = default;
907     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
908         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
909     /// The user TreeEntry.
910     TreeEntry *UserTE = nullptr;
911     /// The operand index of the use.
912     unsigned EdgeIdx = UINT_MAX;
913 #ifndef NDEBUG
914     friend inline raw_ostream &operator<<(raw_ostream &OS,
915                                           const BoUpSLP::EdgeInfo &EI) {
916       EI.dump(OS);
917       return OS;
918     }
919     /// Debug print.
920     void dump(raw_ostream &OS) const {
921       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
922          << " EdgeIdx:" << EdgeIdx << "}";
923     }
924     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
925 #endif
926   };
927 
928   /// A helper data structure to hold the operands of a vector of instructions.
929   /// This supports a fixed vector length for all operand vectors.
930   class VLOperands {
931     /// For each operand we need (i) the value, and (ii) the opcode that it
932     /// would be attached to if the expression was in a left-linearized form.
933     /// This is required to avoid illegal operand reordering.
934     /// For example:
935     /// \verbatim
936     ///                         0 Op1
937     ///                         |/
938     /// Op1 Op2   Linearized    + Op2
939     ///   \ /     ---------->   |/
940     ///    -                    -
941     ///
942     /// Op1 - Op2            (0 + Op1) - Op2
943     /// \endverbatim
944     ///
945     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
946     ///
947     /// Another way to think of this is to track all the operations across the
948     /// path from the operand all the way to the root of the tree and to
949     /// calculate the operation that corresponds to this path. For example, the
950     /// path from Op2 to the root crosses the RHS of the '-', therefore the
951     /// corresponding operation is a '-' (which matches the one in the
952     /// linearized tree, as shown above).
953     ///
954     /// For lack of a better term, we refer to this operation as Accumulated
955     /// Path Operation (APO).
956     struct OperandData {
957       OperandData() = default;
958       OperandData(Value *V, bool APO, bool IsUsed)
959           : V(V), APO(APO), IsUsed(IsUsed) {}
960       /// The operand value.
961       Value *V = nullptr;
962       /// TreeEntries only allow a single opcode, or an alternate sequence of
963       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
964       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
965       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
966       /// (e.g., Add/Mul)
967       bool APO = false;
968       /// Helper data for the reordering function.
969       bool IsUsed = false;
970     };
971 
972     /// During operand reordering, we are trying to select the operand at lane
973     /// that matches best with the operand at the neighboring lane. Our
974     /// selection is based on the type of value we are looking for. For example,
975     /// if the neighboring lane has a load, we need to look for a load that is
976     /// accessing a consecutive address. These strategies are summarized in the
977     /// 'ReorderingMode' enumerator.
978     enum class ReorderingMode {
979       Load,     ///< Matching loads to consecutive memory addresses
980       Opcode,   ///< Matching instructions based on opcode (same or alternate)
981       Constant, ///< Matching constants
982       Splat,    ///< Matching the same instruction multiple times (broadcast)
983       Failed,   ///< We failed to create a vectorizable group
984     };
985 
986     using OperandDataVec = SmallVector<OperandData, 2>;
987 
988     /// A vector of operand vectors.
989     SmallVector<OperandDataVec, 4> OpsVec;
990 
991     const DataLayout &DL;
992     ScalarEvolution &SE;
993     const BoUpSLP &R;
994 
995     /// \returns the operand data at \p OpIdx and \p Lane.
996     OperandData &getData(unsigned OpIdx, unsigned Lane) {
997       return OpsVec[OpIdx][Lane];
998     }
999 
1000     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1001     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1002       return OpsVec[OpIdx][Lane];
1003     }
1004 
1005     /// Clears the used flag for all entries.
1006     void clearUsed() {
1007       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1008            OpIdx != NumOperands; ++OpIdx)
1009         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1010              ++Lane)
1011           OpsVec[OpIdx][Lane].IsUsed = false;
1012     }
1013 
1014     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1015     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1016       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1017     }
1018 
1019     // The hard-coded scores listed here are not very important, though it shall
1020     // be higher for better matches to improve the resulting cost. When
1021     // computing the scores of matching one sub-tree with another, we are
1022     // basically counting the number of values that are matching. So even if all
1023     // scores are set to 1, we would still get a decent matching result.
1024     // However, sometimes we have to break ties. For example we may have to
1025     // choose between matching loads vs matching opcodes. This is what these
1026     // scores are helping us with: they provide the order of preference. Also,
1027     // this is important if the scalar is externally used or used in another
1028     // tree entry node in the different lane.
1029 
1030     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1031     static const int ScoreConsecutiveLoads = 4;
1032     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1033     static const int ScoreReversedLoads = 3;
1034     /// ExtractElementInst from same vector and consecutive indexes.
1035     static const int ScoreConsecutiveExtracts = 4;
1036     /// ExtractElementInst from same vector and reversed indices.
1037     static const int ScoreReversedExtracts = 3;
1038     /// Constants.
1039     static const int ScoreConstants = 2;
1040     /// Instructions with the same opcode.
1041     static const int ScoreSameOpcode = 2;
1042     /// Instructions with alt opcodes (e.g, add + sub).
1043     static const int ScoreAltOpcodes = 1;
1044     /// Identical instructions (a.k.a. splat or broadcast).
1045     static const int ScoreSplat = 1;
1046     /// Matching with an undef is preferable to failing.
1047     static const int ScoreUndef = 1;
1048     /// Score for failing to find a decent match.
1049     static const int ScoreFail = 0;
1050     /// User exteranl to the vectorized code.
1051     static const int ExternalUseCost = 1;
1052     /// The user is internal but in a different lane.
1053     static const int UserInDiffLaneCost = ExternalUseCost;
1054 
1055     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1056     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1057                                ScalarEvolution &SE, int NumLanes) {
1058       if (V1 == V2)
1059         return VLOperands::ScoreSplat;
1060 
1061       auto *LI1 = dyn_cast<LoadInst>(V1);
1062       auto *LI2 = dyn_cast<LoadInst>(V2);
1063       if (LI1 && LI2) {
1064         if (LI1->getParent() != LI2->getParent())
1065           return VLOperands::ScoreFail;
1066 
1067         Optional<int> Dist = getPointersDiff(
1068             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1069             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1070         if (!Dist)
1071           return VLOperands::ScoreFail;
1072         // The distance is too large - still may be profitable to use masked
1073         // loads/gathers.
1074         if (std::abs(*Dist) > NumLanes / 2)
1075           return VLOperands::ScoreAltOpcodes;
1076         // This still will detect consecutive loads, but we might have "holes"
1077         // in some cases. It is ok for non-power-2 vectorization and may produce
1078         // better results. It should not affect current vectorization.
1079         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1080                            : VLOperands::ScoreReversedLoads;
1081       }
1082 
1083       auto *C1 = dyn_cast<Constant>(V1);
1084       auto *C2 = dyn_cast<Constant>(V2);
1085       if (C1 && C2)
1086         return VLOperands::ScoreConstants;
1087 
1088       // Extracts from consecutive indexes of the same vector better score as
1089       // the extracts could be optimized away.
1090       Value *EV1;
1091       ConstantInt *Ex1Idx;
1092       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1093         // Undefs are always profitable for extractelements.
1094         if (isa<UndefValue>(V2))
1095           return VLOperands::ScoreConsecutiveExtracts;
1096         Value *EV2 = nullptr;
1097         ConstantInt *Ex2Idx = nullptr;
1098         if (match(V2,
1099                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1100                                                          m_Undef())))) {
1101           // Undefs are always profitable for extractelements.
1102           if (!Ex2Idx)
1103             return VLOperands::ScoreConsecutiveExtracts;
1104           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1105             return VLOperands::ScoreConsecutiveExtracts;
1106           if (EV2 == EV1) {
1107             int Idx1 = Ex1Idx->getZExtValue();
1108             int Idx2 = Ex2Idx->getZExtValue();
1109             int Dist = Idx2 - Idx1;
1110             // The distance is too large - still may be profitable to use
1111             // shuffles.
1112             if (std::abs(Dist) > NumLanes / 2)
1113               return VLOperands::ScoreAltOpcodes;
1114             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1115                               : VLOperands::ScoreReversedExtracts;
1116           }
1117         }
1118       }
1119 
1120       auto *I1 = dyn_cast<Instruction>(V1);
1121       auto *I2 = dyn_cast<Instruction>(V2);
1122       if (I1 && I2) {
1123         if (I1->getParent() != I2->getParent())
1124           return VLOperands::ScoreFail;
1125         InstructionsState S = getSameOpcode({I1, I2});
1126         // Note: Only consider instructions with <= 2 operands to avoid
1127         // complexity explosion.
1128         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1129           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1130                                   : VLOperands::ScoreSameOpcode;
1131       }
1132 
1133       if (isa<UndefValue>(V2))
1134         return VLOperands::ScoreUndef;
1135 
1136       return VLOperands::ScoreFail;
1137     }
1138 
1139     /// Holds the values and their lanes that are taking part in the look-ahead
1140     /// score calculation. This is used in the external uses cost calculation.
1141     /// Need to hold all the lanes in case of splat/broadcast at least to
1142     /// correctly check for the use in the different lane.
1143     SmallDenseMap<Value *, SmallSet<int, 4>> InLookAheadValues;
1144 
1145     /// \returns the additional cost due to uses of \p LHS and \p RHS that are
1146     /// either external to the vectorized code, or require shuffling.
1147     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1148                             const std::pair<Value *, int> &RHS) {
1149       int Cost = 0;
1150       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1151       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1152         Value *V = Values[Idx].first;
1153         if (isa<Constant>(V)) {
1154           // Since this is a function pass, it doesn't make semantic sense to
1155           // walk the users of a subclass of Constant. The users could be in
1156           // another function, or even another module that happens to be in
1157           // the same LLVMContext.
1158           continue;
1159         }
1160 
1161         // Calculate the absolute lane, using the minimum relative lane of LHS
1162         // and RHS as base and Idx as the offset.
1163         int Ln = std::min(LHS.second, RHS.second) + Idx;
1164         assert(Ln >= 0 && "Bad lane calculation");
1165         unsigned UsersBudget = LookAheadUsersBudget;
1166         for (User *U : V->users()) {
1167           if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1168             // The user is in the VectorizableTree. Check if we need to insert.
1169             int UserLn = UserTE->findLaneForValue(U);
1170             assert(UserLn >= 0 && "Bad lane");
1171             // If the values are different, check just the line of the current
1172             // value. If the values are the same, need to add UserInDiffLaneCost
1173             // only if UserLn does not match both line numbers.
1174             if ((LHS.first != RHS.first && UserLn != Ln) ||
1175                 (LHS.first == RHS.first && UserLn != LHS.second &&
1176                  UserLn != RHS.second)) {
1177               Cost += UserInDiffLaneCost;
1178               break;
1179             }
1180           } else {
1181             // Check if the user is in the look-ahead code.
1182             auto It2 = InLookAheadValues.find(U);
1183             if (It2 != InLookAheadValues.end()) {
1184               // The user is in the look-ahead code. Check the lane.
1185               if (!It2->getSecond().contains(Ln)) {
1186                 Cost += UserInDiffLaneCost;
1187                 break;
1188               }
1189             } else {
1190               // The user is neither in SLP tree nor in the look-ahead code.
1191               Cost += ExternalUseCost;
1192               break;
1193             }
1194           }
1195           // Limit the number of visited uses to cap compilation time.
1196           if (--UsersBudget == 0)
1197             break;
1198         }
1199       }
1200       return Cost;
1201     }
1202 
1203     /// Go through the operands of \p LHS and \p RHS recursively until \p
1204     /// MaxLevel, and return the cummulative score. For example:
1205     /// \verbatim
1206     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1207     ///     \ /         \ /         \ /        \ /
1208     ///      +           +           +          +
1209     ///     G1          G2          G3         G4
1210     /// \endverbatim
1211     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1212     /// each level recursively, accumulating the score. It starts from matching
1213     /// the additions at level 0, then moves on to the loads (level 1). The
1214     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1215     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1216     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1217     /// Please note that the order of the operands does not matter, as we
1218     /// evaluate the score of all profitable combinations of operands. In
1219     /// other words the score of G1 and G4 is the same as G1 and G2. This
1220     /// heuristic is based on ideas described in:
1221     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1222     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1223     ///   Luís F. W. Góes
1224     int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1225                            const std::pair<Value *, int> &RHS, int CurrLevel,
1226                            int MaxLevel) {
1227 
1228       Value *V1 = LHS.first;
1229       Value *V2 = RHS.first;
1230       // Get the shallow score of V1 and V2.
1231       int ShallowScoreAtThisLevel = std::max(
1232           (int)ScoreFail, getShallowScore(V1, V2, DL, SE, getNumLanes()) -
1233                               getExternalUsesCost(LHS, RHS));
1234       int Lane1 = LHS.second;
1235       int Lane2 = RHS.second;
1236 
1237       // If reached MaxLevel,
1238       //  or if V1 and V2 are not instructions,
1239       //  or if they are SPLAT,
1240       //  or if they are not consecutive,
1241       //  or if profitable to vectorize loads or extractelements, early return
1242       //  the current cost.
1243       auto *I1 = dyn_cast<Instruction>(V1);
1244       auto *I2 = dyn_cast<Instruction>(V2);
1245       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1246           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1247           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1248             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1249            ShallowScoreAtThisLevel))
1250         return ShallowScoreAtThisLevel;
1251       assert(I1 && I2 && "Should have early exited.");
1252 
1253       // Keep track of in-tree values for determining the external-use cost.
1254       InLookAheadValues[V1].insert(Lane1);
1255       InLookAheadValues[V2].insert(Lane2);
1256 
1257       // Contains the I2 operand indexes that got matched with I1 operands.
1258       SmallSet<unsigned, 4> Op2Used;
1259 
1260       // Recursion towards the operands of I1 and I2. We are trying all possible
1261       // operand pairs, and keeping track of the best score.
1262       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1263            OpIdx1 != NumOperands1; ++OpIdx1) {
1264         // Try to pair op1I with the best operand of I2.
1265         int MaxTmpScore = 0;
1266         unsigned MaxOpIdx2 = 0;
1267         bool FoundBest = false;
1268         // If I2 is commutative try all combinations.
1269         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1270         unsigned ToIdx = isCommutative(I2)
1271                              ? I2->getNumOperands()
1272                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1273         assert(FromIdx <= ToIdx && "Bad index");
1274         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1275           // Skip operands already paired with OpIdx1.
1276           if (Op2Used.count(OpIdx2))
1277             continue;
1278           // Recursively calculate the cost at each level
1279           int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1280                                             {I2->getOperand(OpIdx2), Lane2},
1281                                             CurrLevel + 1, MaxLevel);
1282           // Look for the best score.
1283           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1284             MaxTmpScore = TmpScore;
1285             MaxOpIdx2 = OpIdx2;
1286             FoundBest = true;
1287           }
1288         }
1289         if (FoundBest) {
1290           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1291           Op2Used.insert(MaxOpIdx2);
1292           ShallowScoreAtThisLevel += MaxTmpScore;
1293         }
1294       }
1295       return ShallowScoreAtThisLevel;
1296     }
1297 
1298     /// \Returns the look-ahead score, which tells us how much the sub-trees
1299     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1300     /// score. This helps break ties in an informed way when we cannot decide on
1301     /// the order of the operands by just considering the immediate
1302     /// predecessors.
1303     int getLookAheadScore(const std::pair<Value *, int> &LHS,
1304                           const std::pair<Value *, int> &RHS) {
1305       InLookAheadValues.clear();
1306       return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1307     }
1308 
1309     // Search all operands in Ops[*][Lane] for the one that matches best
1310     // Ops[OpIdx][LastLane] and return its opreand index.
1311     // If no good match can be found, return None.
1312     Optional<unsigned>
1313     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1314                    ArrayRef<ReorderingMode> ReorderingModes) {
1315       unsigned NumOperands = getNumOperands();
1316 
1317       // The operand of the previous lane at OpIdx.
1318       Value *OpLastLane = getData(OpIdx, LastLane).V;
1319 
1320       // Our strategy mode for OpIdx.
1321       ReorderingMode RMode = ReorderingModes[OpIdx];
1322 
1323       // The linearized opcode of the operand at OpIdx, Lane.
1324       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1325 
1326       // The best operand index and its score.
1327       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1328       // are using the score to differentiate between the two.
1329       struct BestOpData {
1330         Optional<unsigned> Idx = None;
1331         unsigned Score = 0;
1332       } BestOp;
1333 
1334       // Iterate through all unused operands and look for the best.
1335       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1336         // Get the operand at Idx and Lane.
1337         OperandData &OpData = getData(Idx, Lane);
1338         Value *Op = OpData.V;
1339         bool OpAPO = OpData.APO;
1340 
1341         // Skip already selected operands.
1342         if (OpData.IsUsed)
1343           continue;
1344 
1345         // Skip if we are trying to move the operand to a position with a
1346         // different opcode in the linearized tree form. This would break the
1347         // semantics.
1348         if (OpAPO != OpIdxAPO)
1349           continue;
1350 
1351         // Look for an operand that matches the current mode.
1352         switch (RMode) {
1353         case ReorderingMode::Load:
1354         case ReorderingMode::Constant:
1355         case ReorderingMode::Opcode: {
1356           bool LeftToRight = Lane > LastLane;
1357           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1358           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1359           unsigned Score =
1360               getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1361           if (Score > BestOp.Score) {
1362             BestOp.Idx = Idx;
1363             BestOp.Score = Score;
1364           }
1365           break;
1366         }
1367         case ReorderingMode::Splat:
1368           if (Op == OpLastLane)
1369             BestOp.Idx = Idx;
1370           break;
1371         case ReorderingMode::Failed:
1372           return None;
1373         }
1374       }
1375 
1376       if (BestOp.Idx) {
1377         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1378         return BestOp.Idx;
1379       }
1380       // If we could not find a good match return None.
1381       return None;
1382     }
1383 
1384     /// Helper for reorderOperandVecs.
1385     /// \returns the lane that we should start reordering from. This is the one
1386     /// which has the least number of operands that can freely move about or
1387     /// less profitable because it already has the most optimal set of operands.
1388     unsigned getBestLaneToStartReordering() const {
1389       unsigned Min = UINT_MAX;
1390       unsigned SameOpNumber = 0;
1391       // std::pair<unsigned, unsigned> is used to implement a simple voting
1392       // algorithm and choose the lane with the least number of operands that
1393       // can freely move about or less profitable because it already has the
1394       // most optimal set of operands. The first unsigned is a counter for
1395       // voting, the second unsigned is the counter of lanes with instructions
1396       // with same/alternate opcodes and same parent basic block.
1397       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1398       // Try to be closer to the original results, if we have multiple lanes
1399       // with same cost. If 2 lanes have the same cost, use the one with the
1400       // lowest index.
1401       for (int I = getNumLanes(); I > 0; --I) {
1402         unsigned Lane = I - 1;
1403         OperandsOrderData NumFreeOpsHash =
1404             getMaxNumOperandsThatCanBeReordered(Lane);
1405         // Compare the number of operands that can move and choose the one with
1406         // the least number.
1407         if (NumFreeOpsHash.NumOfAPOs < Min) {
1408           Min = NumFreeOpsHash.NumOfAPOs;
1409           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1410           HashMap.clear();
1411           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1412         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1413                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1414           // Select the most optimal lane in terms of number of operands that
1415           // should be moved around.
1416           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1417           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1418         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1419                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1420           ++HashMap[NumFreeOpsHash.Hash].first;
1421         }
1422       }
1423       // Select the lane with the minimum counter.
1424       unsigned BestLane = 0;
1425       unsigned CntMin = UINT_MAX;
1426       for (const auto &Data : reverse(HashMap)) {
1427         if (Data.second.first < CntMin) {
1428           CntMin = Data.second.first;
1429           BestLane = Data.second.second;
1430         }
1431       }
1432       return BestLane;
1433     }
1434 
1435     /// Data structure that helps to reorder operands.
1436     struct OperandsOrderData {
1437       /// The best number of operands with the same APOs, which can be
1438       /// reordered.
1439       unsigned NumOfAPOs = UINT_MAX;
1440       /// Number of operands with the same/alternate instruction opcode and
1441       /// parent.
1442       unsigned NumOpsWithSameOpcodeParent = 0;
1443       /// Hash for the actual operands ordering.
1444       /// Used to count operands, actually their position id and opcode
1445       /// value. It is used in the voting mechanism to find the lane with the
1446       /// least number of operands that can freely move about or less profitable
1447       /// because it already has the most optimal set of operands. Can be
1448       /// replaced with SmallVector<unsigned> instead but hash code is faster
1449       /// and requires less memory.
1450       unsigned Hash = 0;
1451     };
1452     /// \returns the maximum number of operands that are allowed to be reordered
1453     /// for \p Lane and the number of compatible instructions(with the same
1454     /// parent/opcode). This is used as a heuristic for selecting the first lane
1455     /// to start operand reordering.
1456     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1457       unsigned CntTrue = 0;
1458       unsigned NumOperands = getNumOperands();
1459       // Operands with the same APO can be reordered. We therefore need to count
1460       // how many of them we have for each APO, like this: Cnt[APO] = x.
1461       // Since we only have two APOs, namely true and false, we can avoid using
1462       // a map. Instead we can simply count the number of operands that
1463       // correspond to one of them (in this case the 'true' APO), and calculate
1464       // the other by subtracting it from the total number of operands.
1465       // Operands with the same instruction opcode and parent are more
1466       // profitable since we don't need to move them in many cases, with a high
1467       // probability such lane already can be vectorized effectively.
1468       bool AllUndefs = true;
1469       unsigned NumOpsWithSameOpcodeParent = 0;
1470       Instruction *OpcodeI = nullptr;
1471       BasicBlock *Parent = nullptr;
1472       unsigned Hash = 0;
1473       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1474         const OperandData &OpData = getData(OpIdx, Lane);
1475         if (OpData.APO)
1476           ++CntTrue;
1477         // Use Boyer-Moore majority voting for finding the majority opcode and
1478         // the number of times it occurs.
1479         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1480           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1481               I->getParent() != Parent) {
1482             if (NumOpsWithSameOpcodeParent == 0) {
1483               NumOpsWithSameOpcodeParent = 1;
1484               OpcodeI = I;
1485               Parent = I->getParent();
1486             } else {
1487               --NumOpsWithSameOpcodeParent;
1488             }
1489           } else {
1490             ++NumOpsWithSameOpcodeParent;
1491           }
1492         }
1493         Hash = hash_combine(
1494             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1495         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1496       }
1497       if (AllUndefs)
1498         return {};
1499       OperandsOrderData Data;
1500       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1501       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1502       Data.Hash = Hash;
1503       return Data;
1504     }
1505 
1506     /// Go through the instructions in VL and append their operands.
1507     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1508       assert(!VL.empty() && "Bad VL");
1509       assert((empty() || VL.size() == getNumLanes()) &&
1510              "Expected same number of lanes");
1511       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1512       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1513       OpsVec.resize(NumOperands);
1514       unsigned NumLanes = VL.size();
1515       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1516         OpsVec[OpIdx].resize(NumLanes);
1517         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1518           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1519           // Our tree has just 3 nodes: the root and two operands.
1520           // It is therefore trivial to get the APO. We only need to check the
1521           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1522           // RHS operand. The LHS operand of both add and sub is never attached
1523           // to an inversese operation in the linearized form, therefore its APO
1524           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1525 
1526           // Since operand reordering is performed on groups of commutative
1527           // operations or alternating sequences (e.g., +, -), we can safely
1528           // tell the inverse operations by checking commutativity.
1529           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1530           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1531           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1532                                  APO, false};
1533         }
1534       }
1535     }
1536 
1537     /// \returns the number of operands.
1538     unsigned getNumOperands() const { return OpsVec.size(); }
1539 
1540     /// \returns the number of lanes.
1541     unsigned getNumLanes() const { return OpsVec[0].size(); }
1542 
1543     /// \returns the operand value at \p OpIdx and \p Lane.
1544     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1545       return getData(OpIdx, Lane).V;
1546     }
1547 
1548     /// \returns true if the data structure is empty.
1549     bool empty() const { return OpsVec.empty(); }
1550 
1551     /// Clears the data.
1552     void clear() { OpsVec.clear(); }
1553 
1554     /// \Returns true if there are enough operands identical to \p Op to fill
1555     /// the whole vector.
1556     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1557     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1558       bool OpAPO = getData(OpIdx, Lane).APO;
1559       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1560         if (Ln == Lane)
1561           continue;
1562         // This is set to true if we found a candidate for broadcast at Lane.
1563         bool FoundCandidate = false;
1564         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1565           OperandData &Data = getData(OpI, Ln);
1566           if (Data.APO != OpAPO || Data.IsUsed)
1567             continue;
1568           if (Data.V == Op) {
1569             FoundCandidate = true;
1570             Data.IsUsed = true;
1571             break;
1572           }
1573         }
1574         if (!FoundCandidate)
1575           return false;
1576       }
1577       return true;
1578     }
1579 
1580   public:
1581     /// Initialize with all the operands of the instruction vector \p RootVL.
1582     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1583                ScalarEvolution &SE, const BoUpSLP &R)
1584         : DL(DL), SE(SE), R(R) {
1585       // Append all the operands of RootVL.
1586       appendOperandsOfVL(RootVL);
1587     }
1588 
1589     /// \Returns a value vector with the operands across all lanes for the
1590     /// opearnd at \p OpIdx.
1591     ValueList getVL(unsigned OpIdx) const {
1592       ValueList OpVL(OpsVec[OpIdx].size());
1593       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1594              "Expected same num of lanes across all operands");
1595       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1596         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1597       return OpVL;
1598     }
1599 
1600     // Performs operand reordering for 2 or more operands.
1601     // The original operands are in OrigOps[OpIdx][Lane].
1602     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1603     void reorder() {
1604       unsigned NumOperands = getNumOperands();
1605       unsigned NumLanes = getNumLanes();
1606       // Each operand has its own mode. We are using this mode to help us select
1607       // the instructions for each lane, so that they match best with the ones
1608       // we have selected so far.
1609       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1610 
1611       // This is a greedy single-pass algorithm. We are going over each lane
1612       // once and deciding on the best order right away with no back-tracking.
1613       // However, in order to increase its effectiveness, we start with the lane
1614       // that has operands that can move the least. For example, given the
1615       // following lanes:
1616       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1617       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1618       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1619       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1620       // we will start at Lane 1, since the operands of the subtraction cannot
1621       // be reordered. Then we will visit the rest of the lanes in a circular
1622       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1623 
1624       // Find the first lane that we will start our search from.
1625       unsigned FirstLane = getBestLaneToStartReordering();
1626 
1627       // Initialize the modes.
1628       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1629         Value *OpLane0 = getValue(OpIdx, FirstLane);
1630         // Keep track if we have instructions with all the same opcode on one
1631         // side.
1632         if (isa<LoadInst>(OpLane0))
1633           ReorderingModes[OpIdx] = ReorderingMode::Load;
1634         else if (isa<Instruction>(OpLane0)) {
1635           // Check if OpLane0 should be broadcast.
1636           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1637             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1638           else
1639             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1640         }
1641         else if (isa<Constant>(OpLane0))
1642           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1643         else if (isa<Argument>(OpLane0))
1644           // Our best hope is a Splat. It may save some cost in some cases.
1645           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1646         else
1647           // NOTE: This should be unreachable.
1648           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1649       }
1650 
1651       // Check that we don't have same operands. No need to reorder if operands
1652       // are just perfect diamond or shuffled diamond match. Do not do it only
1653       // for possible broadcasts or non-power of 2 number of scalars (just for
1654       // now).
1655       auto &&SkipReordering = [this]() {
1656         SmallPtrSet<Value *, 4> UniqueValues;
1657         ArrayRef<OperandData> Op0 = OpsVec.front();
1658         for (const OperandData &Data : Op0)
1659           UniqueValues.insert(Data.V);
1660         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1661           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1662                 return !UniqueValues.contains(Data.V);
1663               }))
1664             return false;
1665         }
1666         // TODO: Check if we can remove a check for non-power-2 number of
1667         // scalars after full support of non-power-2 vectorization.
1668         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1669       };
1670 
1671       // If the initial strategy fails for any of the operand indexes, then we
1672       // perform reordering again in a second pass. This helps avoid assigning
1673       // high priority to the failed strategy, and should improve reordering for
1674       // the non-failed operand indexes.
1675       for (int Pass = 0; Pass != 2; ++Pass) {
1676         // Check if no need to reorder operands since they're are perfect or
1677         // shuffled diamond match.
1678         // Need to to do it to avoid extra external use cost counting for
1679         // shuffled matches, which may cause regressions.
1680         if (SkipReordering())
1681           break;
1682         // Skip the second pass if the first pass did not fail.
1683         bool StrategyFailed = false;
1684         // Mark all operand data as free to use.
1685         clearUsed();
1686         // We keep the original operand order for the FirstLane, so reorder the
1687         // rest of the lanes. We are visiting the nodes in a circular fashion,
1688         // using FirstLane as the center point and increasing the radius
1689         // distance.
1690         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1691           // Visit the lane on the right and then the lane on the left.
1692           for (int Direction : {+1, -1}) {
1693             int Lane = FirstLane + Direction * Distance;
1694             if (Lane < 0 || Lane >= (int)NumLanes)
1695               continue;
1696             int LastLane = Lane - Direction;
1697             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1698                    "Out of bounds");
1699             // Look for a good match for each operand.
1700             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1701               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1702               Optional<unsigned> BestIdx =
1703                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1704               // By not selecting a value, we allow the operands that follow to
1705               // select a better matching value. We will get a non-null value in
1706               // the next run of getBestOperand().
1707               if (BestIdx) {
1708                 // Swap the current operand with the one returned by
1709                 // getBestOperand().
1710                 swap(OpIdx, BestIdx.getValue(), Lane);
1711               } else {
1712                 // We failed to find a best operand, set mode to 'Failed'.
1713                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1714                 // Enable the second pass.
1715                 StrategyFailed = true;
1716               }
1717             }
1718           }
1719         }
1720         // Skip second pass if the strategy did not fail.
1721         if (!StrategyFailed)
1722           break;
1723       }
1724     }
1725 
1726 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1727     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1728       switch (RMode) {
1729       case ReorderingMode::Load:
1730         return "Load";
1731       case ReorderingMode::Opcode:
1732         return "Opcode";
1733       case ReorderingMode::Constant:
1734         return "Constant";
1735       case ReorderingMode::Splat:
1736         return "Splat";
1737       case ReorderingMode::Failed:
1738         return "Failed";
1739       }
1740       llvm_unreachable("Unimplemented Reordering Type");
1741     }
1742 
1743     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1744                                                    raw_ostream &OS) {
1745       return OS << getModeStr(RMode);
1746     }
1747 
1748     /// Debug print.
1749     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1750       printMode(RMode, dbgs());
1751     }
1752 
1753     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1754       return printMode(RMode, OS);
1755     }
1756 
1757     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1758       const unsigned Indent = 2;
1759       unsigned Cnt = 0;
1760       for (const OperandDataVec &OpDataVec : OpsVec) {
1761         OS << "Operand " << Cnt++ << "\n";
1762         for (const OperandData &OpData : OpDataVec) {
1763           OS.indent(Indent) << "{";
1764           if (Value *V = OpData.V)
1765             OS << *V;
1766           else
1767             OS << "null";
1768           OS << ", APO:" << OpData.APO << "}\n";
1769         }
1770         OS << "\n";
1771       }
1772       return OS;
1773     }
1774 
1775     /// Debug print.
1776     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1777 #endif
1778   };
1779 
1780   /// Checks if the instruction is marked for deletion.
1781   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1782 
1783   /// Marks values operands for later deletion by replacing them with Undefs.
1784   void eraseInstructions(ArrayRef<Value *> AV);
1785 
1786   ~BoUpSLP();
1787 
1788 private:
1789   /// Checks if all users of \p I are the part of the vectorization tree.
1790   bool areAllUsersVectorized(Instruction *I,
1791                              ArrayRef<Value *> VectorizedVals) const;
1792 
1793   /// \returns the cost of the vectorizable entry.
1794   InstructionCost getEntryCost(const TreeEntry *E,
1795                                ArrayRef<Value *> VectorizedVals);
1796 
1797   /// This is the recursive part of buildTree.
1798   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1799                      const EdgeInfo &EI);
1800 
1801   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1802   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1803   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1804   /// returns false, setting \p CurrentOrder to either an empty vector or a
1805   /// non-identity permutation that allows to reuse extract instructions.
1806   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1807                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1808 
1809   /// Vectorize a single entry in the tree.
1810   Value *vectorizeTree(TreeEntry *E);
1811 
1812   /// Vectorize a single entry in the tree, starting in \p VL.
1813   Value *vectorizeTree(ArrayRef<Value *> VL);
1814 
1815   /// \returns the scalarization cost for this type. Scalarization in this
1816   /// context means the creation of vectors from a group of scalars. If \p
1817   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1818   /// vector elements.
1819   InstructionCost getGatherCost(FixedVectorType *Ty,
1820                                 const DenseSet<unsigned> &ShuffledIndices,
1821                                 bool NeedToShuffle) const;
1822 
1823   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1824   /// tree entries.
1825   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1826   /// previous tree entries. \p Mask is filled with the shuffle mask.
1827   Optional<TargetTransformInfo::ShuffleKind>
1828   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1829                         SmallVectorImpl<const TreeEntry *> &Entries);
1830 
1831   /// \returns the scalarization cost for this list of values. Assuming that
1832   /// this subtree gets vectorized, we may need to extract the values from the
1833   /// roots. This method calculates the cost of extracting the values.
1834   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1835 
1836   /// Set the Builder insert point to one after the last instruction in
1837   /// the bundle
1838   void setInsertPointAfterBundle(const TreeEntry *E);
1839 
1840   /// \returns a vector from a collection of scalars in \p VL.
1841   Value *gather(ArrayRef<Value *> VL);
1842 
1843   /// \returns whether the VectorizableTree is fully vectorizable and will
1844   /// be beneficial even the tree height is tiny.
1845   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1846 
1847   /// Reorder commutative or alt operands to get better probability of
1848   /// generating vectorized code.
1849   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1850                                              SmallVectorImpl<Value *> &Left,
1851                                              SmallVectorImpl<Value *> &Right,
1852                                              const DataLayout &DL,
1853                                              ScalarEvolution &SE,
1854                                              const BoUpSLP &R);
1855   struct TreeEntry {
1856     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1857     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1858 
1859     /// \returns true if the scalars in VL are equal to this entry.
1860     bool isSame(ArrayRef<Value *> VL) const {
1861       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1862         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1863           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1864         return VL.size() == Mask.size() &&
1865                std::equal(VL.begin(), VL.end(), Mask.begin(),
1866                           [Scalars](Value *V, int Idx) {
1867                             return (isa<UndefValue>(V) &&
1868                                     Idx == UndefMaskElem) ||
1869                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1870                           });
1871       };
1872       if (!ReorderIndices.empty()) {
1873         // TODO: implement matching if the nodes are just reordered, still can
1874         // treat the vector as the same if the list of scalars matches VL
1875         // directly, without reordering.
1876         SmallVector<int> Mask;
1877         inversePermutation(ReorderIndices, Mask);
1878         if (VL.size() == Scalars.size())
1879           return IsSame(Scalars, Mask);
1880         if (VL.size() == ReuseShuffleIndices.size()) {
1881           ::addMask(Mask, ReuseShuffleIndices);
1882           return IsSame(Scalars, Mask);
1883         }
1884         return false;
1885       }
1886       return IsSame(Scalars, ReuseShuffleIndices);
1887     }
1888 
1889     /// \returns true if current entry has same operands as \p TE.
1890     bool hasEqualOperands(const TreeEntry &TE) const {
1891       if (TE.getNumOperands() != getNumOperands())
1892         return false;
1893       SmallBitVector Used(getNumOperands());
1894       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1895         unsigned PrevCount = Used.count();
1896         for (unsigned K = 0; K < E; ++K) {
1897           if (Used.test(K))
1898             continue;
1899           if (getOperand(K) == TE.getOperand(I)) {
1900             Used.set(K);
1901             break;
1902           }
1903         }
1904         // Check if we actually found the matching operand.
1905         if (PrevCount == Used.count())
1906           return false;
1907       }
1908       return true;
1909     }
1910 
1911     /// \return Final vectorization factor for the node. Defined by the total
1912     /// number of vectorized scalars, including those, used several times in the
1913     /// entry and counted in the \a ReuseShuffleIndices, if any.
1914     unsigned getVectorFactor() const {
1915       if (!ReuseShuffleIndices.empty())
1916         return ReuseShuffleIndices.size();
1917       return Scalars.size();
1918     };
1919 
1920     /// A vector of scalars.
1921     ValueList Scalars;
1922 
1923     /// The Scalars are vectorized into this value. It is initialized to Null.
1924     Value *VectorizedValue = nullptr;
1925 
1926     /// Do we need to gather this sequence or vectorize it
1927     /// (either with vector instruction or with scatter/gather
1928     /// intrinsics for store/load)?
1929     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
1930     EntryState State;
1931 
1932     /// Does this sequence require some shuffling?
1933     SmallVector<int, 4> ReuseShuffleIndices;
1934 
1935     /// Does this entry require reordering?
1936     SmallVector<unsigned, 4> ReorderIndices;
1937 
1938     /// Points back to the VectorizableTree.
1939     ///
1940     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
1941     /// to be a pointer and needs to be able to initialize the child iterator.
1942     /// Thus we need a reference back to the container to translate the indices
1943     /// to entries.
1944     VecTreeTy &Container;
1945 
1946     /// The TreeEntry index containing the user of this entry.  We can actually
1947     /// have multiple users so the data structure is not truly a tree.
1948     SmallVector<EdgeInfo, 1> UserTreeIndices;
1949 
1950     /// The index of this treeEntry in VectorizableTree.
1951     int Idx = -1;
1952 
1953   private:
1954     /// The operands of each instruction in each lane Operands[op_index][lane].
1955     /// Note: This helps avoid the replication of the code that performs the
1956     /// reordering of operands during buildTree_rec() and vectorizeTree().
1957     SmallVector<ValueList, 2> Operands;
1958 
1959     /// The main/alternate instruction.
1960     Instruction *MainOp = nullptr;
1961     Instruction *AltOp = nullptr;
1962 
1963   public:
1964     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1965     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
1966       if (Operands.size() < OpIdx + 1)
1967         Operands.resize(OpIdx + 1);
1968       assert(Operands[OpIdx].empty() && "Already resized?");
1969       assert(OpVL.size() <= Scalars.size() &&
1970              "Number of operands is greater than the number of scalars.");
1971       Operands[OpIdx].resize(OpVL.size());
1972       copy(OpVL, Operands[OpIdx].begin());
1973     }
1974 
1975     /// Set the operands of this bundle in their original order.
1976     void setOperandsInOrder() {
1977       assert(Operands.empty() && "Already initialized?");
1978       auto *I0 = cast<Instruction>(Scalars[0]);
1979       Operands.resize(I0->getNumOperands());
1980       unsigned NumLanes = Scalars.size();
1981       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1982            OpIdx != NumOperands; ++OpIdx) {
1983         Operands[OpIdx].resize(NumLanes);
1984         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1985           auto *I = cast<Instruction>(Scalars[Lane]);
1986           assert(I->getNumOperands() == NumOperands &&
1987                  "Expected same number of operands");
1988           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
1989         }
1990       }
1991     }
1992 
1993     /// Reorders operands of the node to the given mask \p Mask.
1994     void reorderOperands(ArrayRef<int> Mask) {
1995       for (ValueList &Operand : Operands)
1996         reorderScalars(Operand, Mask);
1997     }
1998 
1999     /// \returns the \p OpIdx operand of this TreeEntry.
2000     ValueList &getOperand(unsigned OpIdx) {
2001       assert(OpIdx < Operands.size() && "Off bounds");
2002       return Operands[OpIdx];
2003     }
2004 
2005     /// \returns the \p OpIdx operand of this TreeEntry.
2006     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2007       assert(OpIdx < Operands.size() && "Off bounds");
2008       return Operands[OpIdx];
2009     }
2010 
2011     /// \returns the number of operands.
2012     unsigned getNumOperands() const { return Operands.size(); }
2013 
2014     /// \return the single \p OpIdx operand.
2015     Value *getSingleOperand(unsigned OpIdx) const {
2016       assert(OpIdx < Operands.size() && "Off bounds");
2017       assert(!Operands[OpIdx].empty() && "No operand available");
2018       return Operands[OpIdx][0];
2019     }
2020 
2021     /// Some of the instructions in the list have alternate opcodes.
2022     bool isAltShuffle() const {
2023       return getOpcode() != getAltOpcode();
2024     }
2025 
2026     bool isOpcodeOrAlt(Instruction *I) const {
2027       unsigned CheckedOpcode = I->getOpcode();
2028       return (getOpcode() == CheckedOpcode ||
2029               getAltOpcode() == CheckedOpcode);
2030     }
2031 
2032     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2033     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2034     /// \p OpValue.
2035     Value *isOneOf(Value *Op) const {
2036       auto *I = dyn_cast<Instruction>(Op);
2037       if (I && isOpcodeOrAlt(I))
2038         return Op;
2039       return MainOp;
2040     }
2041 
2042     void setOperations(const InstructionsState &S) {
2043       MainOp = S.MainOp;
2044       AltOp = S.AltOp;
2045     }
2046 
2047     Instruction *getMainOp() const {
2048       return MainOp;
2049     }
2050 
2051     Instruction *getAltOp() const {
2052       return AltOp;
2053     }
2054 
2055     /// The main/alternate opcodes for the list of instructions.
2056     unsigned getOpcode() const {
2057       return MainOp ? MainOp->getOpcode() : 0;
2058     }
2059 
2060     unsigned getAltOpcode() const {
2061       return AltOp ? AltOp->getOpcode() : 0;
2062     }
2063 
2064     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2065     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2066     int findLaneForValue(Value *V) const {
2067       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2068       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2069       if (!ReorderIndices.empty())
2070         FoundLane = ReorderIndices[FoundLane];
2071       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2072       if (!ReuseShuffleIndices.empty()) {
2073         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2074                                   find(ReuseShuffleIndices, FoundLane));
2075       }
2076       return FoundLane;
2077     }
2078 
2079 #ifndef NDEBUG
2080     /// Debug printer.
2081     LLVM_DUMP_METHOD void dump() const {
2082       dbgs() << Idx << ".\n";
2083       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2084         dbgs() << "Operand " << OpI << ":\n";
2085         for (const Value *V : Operands[OpI])
2086           dbgs().indent(2) << *V << "\n";
2087       }
2088       dbgs() << "Scalars: \n";
2089       for (Value *V : Scalars)
2090         dbgs().indent(2) << *V << "\n";
2091       dbgs() << "State: ";
2092       switch (State) {
2093       case Vectorize:
2094         dbgs() << "Vectorize\n";
2095         break;
2096       case ScatterVectorize:
2097         dbgs() << "ScatterVectorize\n";
2098         break;
2099       case NeedToGather:
2100         dbgs() << "NeedToGather\n";
2101         break;
2102       }
2103       dbgs() << "MainOp: ";
2104       if (MainOp)
2105         dbgs() << *MainOp << "\n";
2106       else
2107         dbgs() << "NULL\n";
2108       dbgs() << "AltOp: ";
2109       if (AltOp)
2110         dbgs() << *AltOp << "\n";
2111       else
2112         dbgs() << "NULL\n";
2113       dbgs() << "VectorizedValue: ";
2114       if (VectorizedValue)
2115         dbgs() << *VectorizedValue << "\n";
2116       else
2117         dbgs() << "NULL\n";
2118       dbgs() << "ReuseShuffleIndices: ";
2119       if (ReuseShuffleIndices.empty())
2120         dbgs() << "Empty";
2121       else
2122         for (int ReuseIdx : ReuseShuffleIndices)
2123           dbgs() << ReuseIdx << ", ";
2124       dbgs() << "\n";
2125       dbgs() << "ReorderIndices: ";
2126       for (unsigned ReorderIdx : ReorderIndices)
2127         dbgs() << ReorderIdx << ", ";
2128       dbgs() << "\n";
2129       dbgs() << "UserTreeIndices: ";
2130       for (const auto &EInfo : UserTreeIndices)
2131         dbgs() << EInfo << ", ";
2132       dbgs() << "\n";
2133     }
2134 #endif
2135   };
2136 
2137 #ifndef NDEBUG
2138   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2139                      InstructionCost VecCost,
2140                      InstructionCost ScalarCost) const {
2141     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2142     dbgs() << "SLP: Costs:\n";
2143     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2144     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2145     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2146     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2147                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2148   }
2149 #endif
2150 
2151   /// Create a new VectorizableTree entry.
2152   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2153                           const InstructionsState &S,
2154                           const EdgeInfo &UserTreeIdx,
2155                           ArrayRef<int> ReuseShuffleIndices = None,
2156                           ArrayRef<unsigned> ReorderIndices = None) {
2157     TreeEntry::EntryState EntryState =
2158         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2159     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2160                         ReuseShuffleIndices, ReorderIndices);
2161   }
2162 
2163   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2164                           TreeEntry::EntryState EntryState,
2165                           Optional<ScheduleData *> Bundle,
2166                           const InstructionsState &S,
2167                           const EdgeInfo &UserTreeIdx,
2168                           ArrayRef<int> ReuseShuffleIndices = None,
2169                           ArrayRef<unsigned> ReorderIndices = None) {
2170     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2171             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2172            "Need to vectorize gather entry?");
2173     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2174     TreeEntry *Last = VectorizableTree.back().get();
2175     Last->Idx = VectorizableTree.size() - 1;
2176     Last->State = EntryState;
2177     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2178                                      ReuseShuffleIndices.end());
2179     if (ReorderIndices.empty()) {
2180       Last->Scalars.assign(VL.begin(), VL.end());
2181       Last->setOperations(S);
2182     } else {
2183       // Reorder scalars and build final mask.
2184       Last->Scalars.assign(VL.size(), nullptr);
2185       transform(ReorderIndices, Last->Scalars.begin(),
2186                 [VL](unsigned Idx) -> Value * {
2187                   if (Idx >= VL.size())
2188                     return UndefValue::get(VL.front()->getType());
2189                   return VL[Idx];
2190                 });
2191       InstructionsState S = getSameOpcode(Last->Scalars);
2192       Last->setOperations(S);
2193       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2194     }
2195     if (Last->State != TreeEntry::NeedToGather) {
2196       for (Value *V : VL) {
2197         assert(!getTreeEntry(V) && "Scalar already in tree!");
2198         ScalarToTreeEntry[V] = Last;
2199       }
2200       // Update the scheduler bundle to point to this TreeEntry.
2201       unsigned Lane = 0;
2202       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2203            BundleMember = BundleMember->NextInBundle) {
2204         BundleMember->TE = Last;
2205         BundleMember->Lane = Lane;
2206         ++Lane;
2207       }
2208       assert((!Bundle.getValue() || Lane == VL.size()) &&
2209              "Bundle and VL out of sync");
2210     } else {
2211       MustGather.insert(VL.begin(), VL.end());
2212     }
2213 
2214     if (UserTreeIdx.UserTE)
2215       Last->UserTreeIndices.push_back(UserTreeIdx);
2216 
2217     return Last;
2218   }
2219 
2220   /// -- Vectorization State --
2221   /// Holds all of the tree entries.
2222   TreeEntry::VecTreeTy VectorizableTree;
2223 
2224 #ifndef NDEBUG
2225   /// Debug printer.
2226   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2227     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2228       VectorizableTree[Id]->dump();
2229       dbgs() << "\n";
2230     }
2231   }
2232 #endif
2233 
2234   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2235 
2236   const TreeEntry *getTreeEntry(Value *V) const {
2237     return ScalarToTreeEntry.lookup(V);
2238   }
2239 
2240   /// Maps a specific scalar to its tree entry.
2241   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2242 
2243   /// Maps a value to the proposed vectorizable size.
2244   SmallDenseMap<Value *, unsigned> InstrElementSize;
2245 
2246   /// A list of scalars that we found that we need to keep as scalars.
2247   ValueSet MustGather;
2248 
2249   /// This POD struct describes one external user in the vectorized tree.
2250   struct ExternalUser {
2251     ExternalUser(Value *S, llvm::User *U, int L)
2252         : Scalar(S), User(U), Lane(L) {}
2253 
2254     // Which scalar in our function.
2255     Value *Scalar;
2256 
2257     // Which user that uses the scalar.
2258     llvm::User *User;
2259 
2260     // Which lane does the scalar belong to.
2261     int Lane;
2262   };
2263   using UserList = SmallVector<ExternalUser, 16>;
2264 
2265   /// Checks if two instructions may access the same memory.
2266   ///
2267   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2268   /// is invariant in the calling loop.
2269   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2270                  Instruction *Inst2) {
2271     // First check if the result is already in the cache.
2272     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2273     Optional<bool> &result = AliasCache[key];
2274     if (result.hasValue()) {
2275       return result.getValue();
2276     }
2277     bool aliased = true;
2278     if (Loc1.Ptr && isSimple(Inst1))
2279       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2280     // Store the result in the cache.
2281     result = aliased;
2282     return aliased;
2283   }
2284 
2285   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2286 
2287   /// Cache for alias results.
2288   /// TODO: consider moving this to the AliasAnalysis itself.
2289   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2290 
2291   /// Removes an instruction from its block and eventually deletes it.
2292   /// It's like Instruction::eraseFromParent() except that the actual deletion
2293   /// is delayed until BoUpSLP is destructed.
2294   /// This is required to ensure that there are no incorrect collisions in the
2295   /// AliasCache, which can happen if a new instruction is allocated at the
2296   /// same address as a previously deleted instruction.
2297   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2298     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2299     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2300   }
2301 
2302   /// Temporary store for deleted instructions. Instructions will be deleted
2303   /// eventually when the BoUpSLP is destructed.
2304   DenseMap<Instruction *, bool> DeletedInstructions;
2305 
2306   /// A list of values that need to extracted out of the tree.
2307   /// This list holds pairs of (Internal Scalar : External User). External User
2308   /// can be nullptr, it means that this Internal Scalar will be used later,
2309   /// after vectorization.
2310   UserList ExternalUses;
2311 
2312   /// Values used only by @llvm.assume calls.
2313   SmallPtrSet<const Value *, 32> EphValues;
2314 
2315   /// Holds all of the instructions that we gathered.
2316   SetVector<Instruction *> GatherShuffleSeq;
2317 
2318   /// A list of blocks that we are going to CSE.
2319   SetVector<BasicBlock *> CSEBlocks;
2320 
2321   /// Contains all scheduling relevant data for an instruction.
2322   /// A ScheduleData either represents a single instruction or a member of an
2323   /// instruction bundle (= a group of instructions which is combined into a
2324   /// vector instruction).
2325   struct ScheduleData {
2326     // The initial value for the dependency counters. It means that the
2327     // dependencies are not calculated yet.
2328     enum { InvalidDeps = -1 };
2329 
2330     ScheduleData() = default;
2331 
2332     void init(int BlockSchedulingRegionID, Value *OpVal) {
2333       FirstInBundle = this;
2334       NextInBundle = nullptr;
2335       NextLoadStore = nullptr;
2336       IsScheduled = false;
2337       SchedulingRegionID = BlockSchedulingRegionID;
2338       UnscheduledDepsInBundle = UnscheduledDeps;
2339       clearDependencies();
2340       OpValue = OpVal;
2341       TE = nullptr;
2342       Lane = -1;
2343     }
2344 
2345     /// Returns true if the dependency information has been calculated.
2346     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2347 
2348     /// Returns true for single instructions and for bundle representatives
2349     /// (= the head of a bundle).
2350     bool isSchedulingEntity() const { return FirstInBundle == this; }
2351 
2352     /// Returns true if it represents an instruction bundle and not only a
2353     /// single instruction.
2354     bool isPartOfBundle() const {
2355       return NextInBundle != nullptr || FirstInBundle != this;
2356     }
2357 
2358     /// Returns true if it is ready for scheduling, i.e. it has no more
2359     /// unscheduled depending instructions/bundles.
2360     bool isReady() const {
2361       assert(isSchedulingEntity() &&
2362              "can't consider non-scheduling entity for ready list");
2363       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2364     }
2365 
2366     /// Modifies the number of unscheduled dependencies, also updating it for
2367     /// the whole bundle.
2368     int incrementUnscheduledDeps(int Incr) {
2369       UnscheduledDeps += Incr;
2370       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2371     }
2372 
2373     /// Sets the number of unscheduled dependencies to the number of
2374     /// dependencies.
2375     void resetUnscheduledDeps() {
2376       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2377     }
2378 
2379     /// Clears all dependency information.
2380     void clearDependencies() {
2381       Dependencies = InvalidDeps;
2382       resetUnscheduledDeps();
2383       MemoryDependencies.clear();
2384     }
2385 
2386     void dump(raw_ostream &os) const {
2387       if (!isSchedulingEntity()) {
2388         os << "/ " << *Inst;
2389       } else if (NextInBundle) {
2390         os << '[' << *Inst;
2391         ScheduleData *SD = NextInBundle;
2392         while (SD) {
2393           os << ';' << *SD->Inst;
2394           SD = SD->NextInBundle;
2395         }
2396         os << ']';
2397       } else {
2398         os << *Inst;
2399       }
2400     }
2401 
2402     Instruction *Inst = nullptr;
2403 
2404     /// Points to the head in an instruction bundle (and always to this for
2405     /// single instructions).
2406     ScheduleData *FirstInBundle = nullptr;
2407 
2408     /// Single linked list of all instructions in a bundle. Null if it is a
2409     /// single instruction.
2410     ScheduleData *NextInBundle = nullptr;
2411 
2412     /// Single linked list of all memory instructions (e.g. load, store, call)
2413     /// in the block - until the end of the scheduling region.
2414     ScheduleData *NextLoadStore = nullptr;
2415 
2416     /// The dependent memory instructions.
2417     /// This list is derived on demand in calculateDependencies().
2418     SmallVector<ScheduleData *, 4> MemoryDependencies;
2419 
2420     /// This ScheduleData is in the current scheduling region if this matches
2421     /// the current SchedulingRegionID of BlockScheduling.
2422     int SchedulingRegionID = 0;
2423 
2424     /// Used for getting a "good" final ordering of instructions.
2425     int SchedulingPriority = 0;
2426 
2427     /// The number of dependencies. Constitutes of the number of users of the
2428     /// instruction plus the number of dependent memory instructions (if any).
2429     /// This value is calculated on demand.
2430     /// If InvalidDeps, the number of dependencies is not calculated yet.
2431     int Dependencies = InvalidDeps;
2432 
2433     /// The number of dependencies minus the number of dependencies of scheduled
2434     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2435     /// for scheduling.
2436     /// Note that this is negative as long as Dependencies is not calculated.
2437     int UnscheduledDeps = InvalidDeps;
2438 
2439     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2440     /// single instructions.
2441     int UnscheduledDepsInBundle = InvalidDeps;
2442 
2443     /// True if this instruction is scheduled (or considered as scheduled in the
2444     /// dry-run).
2445     bool IsScheduled = false;
2446 
2447     /// Opcode of the current instruction in the schedule data.
2448     Value *OpValue = nullptr;
2449 
2450     /// The TreeEntry that this instruction corresponds to.
2451     TreeEntry *TE = nullptr;
2452 
2453     /// The lane of this node in the TreeEntry.
2454     int Lane = -1;
2455   };
2456 
2457 #ifndef NDEBUG
2458   friend inline raw_ostream &operator<<(raw_ostream &os,
2459                                         const BoUpSLP::ScheduleData &SD) {
2460     SD.dump(os);
2461     return os;
2462   }
2463 #endif
2464 
2465   friend struct GraphTraits<BoUpSLP *>;
2466   friend struct DOTGraphTraits<BoUpSLP *>;
2467 
2468   /// Contains all scheduling data for a basic block.
2469   struct BlockScheduling {
2470     BlockScheduling(BasicBlock *BB)
2471         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2472 
2473     void clear() {
2474       ReadyInsts.clear();
2475       ScheduleStart = nullptr;
2476       ScheduleEnd = nullptr;
2477       FirstLoadStoreInRegion = nullptr;
2478       LastLoadStoreInRegion = nullptr;
2479 
2480       // Reduce the maximum schedule region size by the size of the
2481       // previous scheduling run.
2482       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2483       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2484         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2485       ScheduleRegionSize = 0;
2486 
2487       // Make a new scheduling region, i.e. all existing ScheduleData is not
2488       // in the new region yet.
2489       ++SchedulingRegionID;
2490     }
2491 
2492     ScheduleData *getScheduleData(Value *V) {
2493       ScheduleData *SD = ScheduleDataMap[V];
2494       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2495         return SD;
2496       return nullptr;
2497     }
2498 
2499     ScheduleData *getScheduleData(Value *V, Value *Key) {
2500       if (V == Key)
2501         return getScheduleData(V);
2502       auto I = ExtraScheduleDataMap.find(V);
2503       if (I != ExtraScheduleDataMap.end()) {
2504         ScheduleData *SD = I->second[Key];
2505         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2506           return SD;
2507       }
2508       return nullptr;
2509     }
2510 
2511     bool isInSchedulingRegion(ScheduleData *SD) const {
2512       return SD->SchedulingRegionID == SchedulingRegionID;
2513     }
2514 
2515     /// Marks an instruction as scheduled and puts all dependent ready
2516     /// instructions into the ready-list.
2517     template <typename ReadyListType>
2518     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2519       SD->IsScheduled = true;
2520       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2521 
2522       ScheduleData *BundleMember = SD;
2523       while (BundleMember) {
2524         if (BundleMember->Inst != BundleMember->OpValue) {
2525           BundleMember = BundleMember->NextInBundle;
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         BundleMember = BundleMember->NextInBundle;
2593       }
2594     }
2595 
2596     void doForAllOpcodes(Value *V,
2597                          function_ref<void(ScheduleData *SD)> Action) {
2598       if (ScheduleData *SD = getScheduleData(V))
2599         Action(SD);
2600       auto I = ExtraScheduleDataMap.find(V);
2601       if (I != ExtraScheduleDataMap.end())
2602         for (auto &P : I->second)
2603           if (P.second->SchedulingRegionID == SchedulingRegionID)
2604             Action(P.second);
2605     }
2606 
2607     /// Put all instructions into the ReadyList which are ready for scheduling.
2608     template <typename ReadyListType>
2609     void initialFillReadyList(ReadyListType &ReadyList) {
2610       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2611         doForAllOpcodes(I, [&](ScheduleData *SD) {
2612           if (SD->isSchedulingEntity() && SD->isReady()) {
2613             ReadyList.insert(SD);
2614             LLVM_DEBUG(dbgs()
2615                        << "SLP:    initially in ready list: " << *I << "\n");
2616           }
2617         });
2618       }
2619     }
2620 
2621     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2622     /// cyclic dependencies. This is only a dry-run, no instructions are
2623     /// actually moved at this stage.
2624     /// \returns the scheduling bundle. The returned Optional value is non-None
2625     /// if \p VL is allowed to be scheduled.
2626     Optional<ScheduleData *>
2627     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2628                       const InstructionsState &S);
2629 
2630     /// Un-bundles a group of instructions.
2631     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2632 
2633     /// Allocates schedule data chunk.
2634     ScheduleData *allocateScheduleDataChunks();
2635 
2636     /// Extends the scheduling region so that V is inside the region.
2637     /// \returns true if the region size is within the limit.
2638     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2639 
2640     /// Initialize the ScheduleData structures for new instructions in the
2641     /// scheduling region.
2642     void initScheduleData(Instruction *FromI, Instruction *ToI,
2643                           ScheduleData *PrevLoadStore,
2644                           ScheduleData *NextLoadStore);
2645 
2646     /// Updates the dependency information of a bundle and of all instructions/
2647     /// bundles which depend on the original bundle.
2648     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2649                                BoUpSLP *SLP);
2650 
2651     /// Sets all instruction in the scheduling region to un-scheduled.
2652     void resetSchedule();
2653 
2654     BasicBlock *BB;
2655 
2656     /// Simple memory allocation for ScheduleData.
2657     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2658 
2659     /// The size of a ScheduleData array in ScheduleDataChunks.
2660     int ChunkSize;
2661 
2662     /// The allocator position in the current chunk, which is the last entry
2663     /// of ScheduleDataChunks.
2664     int ChunkPos;
2665 
2666     /// Attaches ScheduleData to Instruction.
2667     /// Note that the mapping survives during all vectorization iterations, i.e.
2668     /// ScheduleData structures are recycled.
2669     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2670 
2671     /// Attaches ScheduleData to Instruction with the leading key.
2672     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2673         ExtraScheduleDataMap;
2674 
2675     struct ReadyList : SmallVector<ScheduleData *, 8> {
2676       void insert(ScheduleData *SD) { push_back(SD); }
2677     };
2678 
2679     /// The ready-list for scheduling (only used for the dry-run).
2680     ReadyList ReadyInsts;
2681 
2682     /// The first instruction of the scheduling region.
2683     Instruction *ScheduleStart = nullptr;
2684 
2685     /// The first instruction _after_ the scheduling region.
2686     Instruction *ScheduleEnd = nullptr;
2687 
2688     /// The first memory accessing instruction in the scheduling region
2689     /// (can be null).
2690     ScheduleData *FirstLoadStoreInRegion = nullptr;
2691 
2692     /// The last memory accessing instruction in the scheduling region
2693     /// (can be null).
2694     ScheduleData *LastLoadStoreInRegion = nullptr;
2695 
2696     /// The current size of the scheduling region.
2697     int ScheduleRegionSize = 0;
2698 
2699     /// The maximum size allowed for the scheduling region.
2700     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2701 
2702     /// The ID of the scheduling region. For a new vectorization iteration this
2703     /// is incremented which "removes" all ScheduleData from the region.
2704     // Make sure that the initial SchedulingRegionID is greater than the
2705     // initial SchedulingRegionID in ScheduleData (which is 0).
2706     int SchedulingRegionID = 1;
2707   };
2708 
2709   /// Attaches the BlockScheduling structures to basic blocks.
2710   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2711 
2712   /// Performs the "real" scheduling. Done before vectorization is actually
2713   /// performed in a basic block.
2714   void scheduleBlock(BlockScheduling *BS);
2715 
2716   /// List of users to ignore during scheduling and that don't need extracting.
2717   ArrayRef<Value *> UserIgnoreList;
2718 
2719   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2720   /// sorted SmallVectors of unsigned.
2721   struct OrdersTypeDenseMapInfo {
2722     static OrdersType getEmptyKey() {
2723       OrdersType V;
2724       V.push_back(~1U);
2725       return V;
2726     }
2727 
2728     static OrdersType getTombstoneKey() {
2729       OrdersType V;
2730       V.push_back(~2U);
2731       return V;
2732     }
2733 
2734     static unsigned getHashValue(const OrdersType &V) {
2735       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2736     }
2737 
2738     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2739       return LHS == RHS;
2740     }
2741   };
2742 
2743   // Analysis and block reference.
2744   Function *F;
2745   ScalarEvolution *SE;
2746   TargetTransformInfo *TTI;
2747   TargetLibraryInfo *TLI;
2748   AAResults *AA;
2749   LoopInfo *LI;
2750   DominatorTree *DT;
2751   AssumptionCache *AC;
2752   DemandedBits *DB;
2753   const DataLayout *DL;
2754   OptimizationRemarkEmitter *ORE;
2755 
2756   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2757   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2758 
2759   /// Instruction builder to construct the vectorized tree.
2760   IRBuilder<> Builder;
2761 
2762   /// A map of scalar integer values to the smallest bit width with which they
2763   /// can legally be represented. The values map to (width, signed) pairs,
2764   /// where "width" indicates the minimum bit width and "signed" is True if the
2765   /// value must be signed-extended, rather than zero-extended, back to its
2766   /// original width.
2767   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2768 };
2769 
2770 } // end namespace slpvectorizer
2771 
2772 template <> struct GraphTraits<BoUpSLP *> {
2773   using TreeEntry = BoUpSLP::TreeEntry;
2774 
2775   /// NodeRef has to be a pointer per the GraphWriter.
2776   using NodeRef = TreeEntry *;
2777 
2778   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2779 
2780   /// Add the VectorizableTree to the index iterator to be able to return
2781   /// TreeEntry pointers.
2782   struct ChildIteratorType
2783       : public iterator_adaptor_base<
2784             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2785     ContainerTy &VectorizableTree;
2786 
2787     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2788                       ContainerTy &VT)
2789         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2790 
2791     NodeRef operator*() { return I->UserTE; }
2792   };
2793 
2794   static NodeRef getEntryNode(BoUpSLP &R) {
2795     return R.VectorizableTree[0].get();
2796   }
2797 
2798   static ChildIteratorType child_begin(NodeRef N) {
2799     return {N->UserTreeIndices.begin(), N->Container};
2800   }
2801 
2802   static ChildIteratorType child_end(NodeRef N) {
2803     return {N->UserTreeIndices.end(), N->Container};
2804   }
2805 
2806   /// For the node iterator we just need to turn the TreeEntry iterator into a
2807   /// TreeEntry* iterator so that it dereferences to NodeRef.
2808   class nodes_iterator {
2809     using ItTy = ContainerTy::iterator;
2810     ItTy It;
2811 
2812   public:
2813     nodes_iterator(const ItTy &It2) : It(It2) {}
2814     NodeRef operator*() { return It->get(); }
2815     nodes_iterator operator++() {
2816       ++It;
2817       return *this;
2818     }
2819     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2820   };
2821 
2822   static nodes_iterator nodes_begin(BoUpSLP *R) {
2823     return nodes_iterator(R->VectorizableTree.begin());
2824   }
2825 
2826   static nodes_iterator nodes_end(BoUpSLP *R) {
2827     return nodes_iterator(R->VectorizableTree.end());
2828   }
2829 
2830   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2831 };
2832 
2833 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2834   using TreeEntry = BoUpSLP::TreeEntry;
2835 
2836   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2837 
2838   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2839     std::string Str;
2840     raw_string_ostream OS(Str);
2841     if (isSplat(Entry->Scalars))
2842       OS << "<splat> ";
2843     for (auto V : Entry->Scalars) {
2844       OS << *V;
2845       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2846             return EU.Scalar == V;
2847           }))
2848         OS << " <extract>";
2849       OS << "\n";
2850     }
2851     return Str;
2852   }
2853 
2854   static std::string getNodeAttributes(const TreeEntry *Entry,
2855                                        const BoUpSLP *) {
2856     if (Entry->State == TreeEntry::NeedToGather)
2857       return "color=red";
2858     return "";
2859   }
2860 };
2861 
2862 } // end namespace llvm
2863 
2864 BoUpSLP::~BoUpSLP() {
2865   for (const auto &Pair : DeletedInstructions) {
2866     // Replace operands of ignored instructions with Undefs in case if they were
2867     // marked for deletion.
2868     if (Pair.getSecond()) {
2869       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2870       Pair.getFirst()->replaceAllUsesWith(Undef);
2871     }
2872     Pair.getFirst()->dropAllReferences();
2873   }
2874   for (const auto &Pair : DeletedInstructions) {
2875     assert(Pair.getFirst()->use_empty() &&
2876            "trying to erase instruction with users.");
2877     Pair.getFirst()->eraseFromParent();
2878   }
2879 #ifdef EXPENSIVE_CHECKS
2880   // If we could guarantee that this call is not extremely slow, we could
2881   // remove the ifdef limitation (see PR47712).
2882   assert(!verifyFunction(*F, &dbgs()));
2883 #endif
2884 }
2885 
2886 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2887   for (auto *V : AV) {
2888     if (auto *I = dyn_cast<Instruction>(V))
2889       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2890   };
2891 }
2892 
2893 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
2894 /// contains original mask for the scalars reused in the node. Procedure
2895 /// transform this mask in accordance with the given \p Mask.
2896 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
2897   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
2898          "Expected non-empty mask.");
2899   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
2900   Prev.swap(Reuses);
2901   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
2902     if (Mask[I] != UndefMaskElem)
2903       Reuses[Mask[I]] = Prev[I];
2904 }
2905 
2906 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
2907 /// the original order of the scalars. Procedure transforms the provided order
2908 /// in accordance with the given \p Mask. If the resulting \p Order is just an
2909 /// identity order, \p Order is cleared.
2910 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
2911   assert(!Mask.empty() && "Expected non-empty mask.");
2912   SmallVector<int> MaskOrder;
2913   if (Order.empty()) {
2914     MaskOrder.resize(Mask.size());
2915     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
2916   } else {
2917     inversePermutation(Order, MaskOrder);
2918   }
2919   reorderReuses(MaskOrder, Mask);
2920   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
2921     Order.clear();
2922     return;
2923   }
2924   Order.assign(Mask.size(), Mask.size());
2925   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
2926     if (MaskOrder[I] != UndefMaskElem)
2927       Order[MaskOrder[I]] = I;
2928   fixupOrderingIndices(Order);
2929 }
2930 
2931 Optional<BoUpSLP::OrdersType>
2932 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
2933   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
2934   unsigned NumScalars = TE.Scalars.size();
2935   OrdersType CurrentOrder(NumScalars, NumScalars);
2936   SmallVector<int> Positions;
2937   SmallBitVector UsedPositions(NumScalars);
2938   const TreeEntry *STE = nullptr;
2939   // Try to find all gathered scalars that are gets vectorized in other
2940   // vectorize node. Here we can have only one single tree vector node to
2941   // correctly identify order of the gathered scalars.
2942   for (unsigned I = 0; I < NumScalars; ++I) {
2943     Value *V = TE.Scalars[I];
2944     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
2945       continue;
2946     if (const auto *LocalSTE = getTreeEntry(V)) {
2947       if (!STE)
2948         STE = LocalSTE;
2949       else if (STE != LocalSTE)
2950         // Take the order only from the single vector node.
2951         return None;
2952       unsigned Lane =
2953           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
2954       if (Lane >= NumScalars)
2955         return None;
2956       if (CurrentOrder[Lane] != NumScalars) {
2957         if (Lane != I)
2958           continue;
2959         UsedPositions.reset(CurrentOrder[Lane]);
2960       }
2961       // The partial identity (where only some elements of the gather node are
2962       // in the identity order) is good.
2963       CurrentOrder[Lane] = I;
2964       UsedPositions.set(I);
2965     }
2966   }
2967   // Need to keep the order if we have a vector entry and at least 2 scalars or
2968   // the vectorized entry has just 2 scalars.
2969   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
2970     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
2971       for (unsigned I = 0; I < NumScalars; ++I)
2972         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
2973           return false;
2974       return true;
2975     };
2976     if (IsIdentityOrder(CurrentOrder)) {
2977       CurrentOrder.clear();
2978       return CurrentOrder;
2979     }
2980     auto *It = CurrentOrder.begin();
2981     for (unsigned I = 0; I < NumScalars;) {
2982       if (UsedPositions.test(I)) {
2983         ++I;
2984         continue;
2985       }
2986       if (*It == NumScalars) {
2987         *It = I;
2988         ++I;
2989       }
2990       ++It;
2991     }
2992     return CurrentOrder;
2993   }
2994   return None;
2995 }
2996 
2997 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
2998                                                          bool TopToBottom) {
2999   // No need to reorder if need to shuffle reuses, still need to shuffle the
3000   // node.
3001   if (!TE.ReuseShuffleIndices.empty())
3002     return None;
3003   if (TE.State == TreeEntry::Vectorize &&
3004       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3005        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3006       !TE.isAltShuffle())
3007     return TE.ReorderIndices;
3008   if (TE.State == TreeEntry::NeedToGather) {
3009     // TODO: add analysis of other gather nodes with extractelement
3010     // instructions and other values/instructions, not only undefs.
3011     if (((TE.getOpcode() == Instruction::ExtractElement &&
3012           !TE.isAltShuffle()) ||
3013          (all_of(TE.Scalars,
3014                  [](Value *V) {
3015                    return isa<UndefValue, ExtractElementInst>(V);
3016                  }) &&
3017           any_of(TE.Scalars,
3018                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3019         all_of(TE.Scalars,
3020                [](Value *V) {
3021                  auto *EE = dyn_cast<ExtractElementInst>(V);
3022                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3023                }) &&
3024         allSameType(TE.Scalars)) {
3025       // Check that gather of extractelements can be represented as
3026       // just a shuffle of a single vector.
3027       OrdersType CurrentOrder;
3028       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3029       if (Reuse || !CurrentOrder.empty()) {
3030         if (!CurrentOrder.empty())
3031           fixupOrderingIndices(CurrentOrder);
3032         return CurrentOrder;
3033       }
3034     }
3035     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3036       return CurrentOrder;
3037   }
3038   return None;
3039 }
3040 
3041 void BoUpSLP::reorderTopToBottom() {
3042   // Maps VF to the graph nodes.
3043   DenseMap<unsigned, SmallPtrSet<TreeEntry *, 4>> VFToOrderedEntries;
3044   // ExtractElement gather nodes which can be vectorized and need to handle
3045   // their ordering.
3046   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3047   // Find all reorderable nodes with the given VF.
3048   // Currently the are vectorized stores,loads,extracts + some gathering of
3049   // extracts.
3050   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3051                                  const std::unique_ptr<TreeEntry> &TE) {
3052     if (Optional<OrdersType> CurrentOrder =
3053             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3054       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3055       if (TE->State != TreeEntry::Vectorize)
3056         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3057     }
3058   });
3059 
3060   // Reorder the graph nodes according to their vectorization factor.
3061   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3062        VF /= 2) {
3063     auto It = VFToOrderedEntries.find(VF);
3064     if (It == VFToOrderedEntries.end())
3065       continue;
3066     // Try to find the most profitable order. We just are looking for the most
3067     // used order and reorder scalar elements in the nodes according to this
3068     // mostly used order.
3069     const SmallPtrSetImpl<TreeEntry *> &OrderedEntries = It->getSecond();
3070     // All operands are reordered and used only in this node - propagate the
3071     // most used order to the user node.
3072     MapVector<OrdersType, unsigned,
3073               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3074         OrdersUses;
3075     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3076     for (const TreeEntry *OpTE : OrderedEntries) {
3077       // No need to reorder this nodes, still need to extend and to use shuffle,
3078       // just need to merge reordering shuffle and the reuse shuffle.
3079       if (!OpTE->ReuseShuffleIndices.empty())
3080         continue;
3081       // Count number of orders uses.
3082       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3083         if (OpTE->State == TreeEntry::NeedToGather)
3084           return GathersToOrders.find(OpTE)->second;
3085         return OpTE->ReorderIndices;
3086       }();
3087       // Stores actually store the mask, not the order, need to invert.
3088       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3089           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3090         SmallVector<int> Mask;
3091         inversePermutation(Order, Mask);
3092         unsigned E = Order.size();
3093         OrdersType CurrentOrder(E, E);
3094         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3095           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3096         });
3097         fixupOrderingIndices(CurrentOrder);
3098         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3099       } else {
3100         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3101       }
3102     }
3103     // Set order of the user node.
3104     if (OrdersUses.empty())
3105       continue;
3106     // Choose the most used order.
3107     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3108     unsigned Cnt = OrdersUses.front().second;
3109     for (const auto &Pair : drop_begin(OrdersUses)) {
3110       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3111         BestOrder = Pair.first;
3112         Cnt = Pair.second;
3113       }
3114     }
3115     // Set order of the user node.
3116     if (BestOrder.empty())
3117       continue;
3118     SmallVector<int> Mask;
3119     inversePermutation(BestOrder, Mask);
3120     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3121     unsigned E = BestOrder.size();
3122     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3123       return I < E ? static_cast<int>(I) : UndefMaskElem;
3124     });
3125     // Do an actual reordering, if profitable.
3126     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3127       // Just do the reordering for the nodes with the given VF.
3128       if (TE->Scalars.size() != VF) {
3129         if (TE->ReuseShuffleIndices.size() == VF) {
3130           // Need to reorder the reuses masks of the operands with smaller VF to
3131           // be able to find the match between the graph nodes and scalar
3132           // operands of the given node during vectorization/cost estimation.
3133           assert(all_of(TE->UserTreeIndices,
3134                         [VF, &TE](const EdgeInfo &EI) {
3135                           return EI.UserTE->Scalars.size() == VF ||
3136                                  EI.UserTE->Scalars.size() ==
3137                                      TE->Scalars.size();
3138                         }) &&
3139                  "All users must be of VF size.");
3140           // Update ordering of the operands with the smaller VF than the given
3141           // one.
3142           reorderReuses(TE->ReuseShuffleIndices, Mask);
3143         }
3144         continue;
3145       }
3146       if (TE->State == TreeEntry::Vectorize &&
3147           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3148               InsertElementInst>(TE->getMainOp()) &&
3149           !TE->isAltShuffle()) {
3150         // Build correct orders for extract{element,value}, loads and
3151         // stores.
3152         reorderOrder(TE->ReorderIndices, Mask);
3153         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3154           TE->reorderOperands(Mask);
3155       } else {
3156         // Reorder the node and its operands.
3157         TE->reorderOperands(Mask);
3158         assert(TE->ReorderIndices.empty() &&
3159                "Expected empty reorder sequence.");
3160         reorderScalars(TE->Scalars, Mask);
3161       }
3162       if (!TE->ReuseShuffleIndices.empty()) {
3163         // Apply reversed order to keep the original ordering of the reused
3164         // elements to avoid extra reorder indices shuffling.
3165         OrdersType CurrentOrder;
3166         reorderOrder(CurrentOrder, MaskOrder);
3167         SmallVector<int> NewReuses;
3168         inversePermutation(CurrentOrder, NewReuses);
3169         addMask(NewReuses, TE->ReuseShuffleIndices);
3170         TE->ReuseShuffleIndices.swap(NewReuses);
3171       }
3172     }
3173   }
3174 }
3175 
3176 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3177   SetVector<TreeEntry *> OrderedEntries;
3178   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3179   // Find all reorderable leaf nodes with the given VF.
3180   // Currently the are vectorized loads,extracts without alternate operands +
3181   // some gathering of extracts.
3182   SmallVector<TreeEntry *> NonVectorized;
3183   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3184                               &NonVectorized](
3185                                  const std::unique_ptr<TreeEntry> &TE) {
3186     if (TE->State != TreeEntry::Vectorize)
3187       NonVectorized.push_back(TE.get());
3188     if (Optional<OrdersType> CurrentOrder =
3189             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3190       OrderedEntries.insert(TE.get());
3191       if (TE->State != TreeEntry::Vectorize)
3192         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3193     }
3194   });
3195 
3196   // Checks if the operands of the users are reordarable and have only single
3197   // use.
3198   auto &&CheckOperands =
3199       [this, &NonVectorized](const auto &Data,
3200                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3201         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3202           if (any_of(Data.second,
3203                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3204                        return OpData.first == I &&
3205                               OpData.second->State == TreeEntry::Vectorize;
3206                      }))
3207             continue;
3208           ArrayRef<Value *> VL = Data.first->getOperand(I);
3209           const TreeEntry *TE = nullptr;
3210           const auto *It = find_if(VL, [this, &TE](Value *V) {
3211             TE = getTreeEntry(V);
3212             return TE;
3213           });
3214           if (It != VL.end() && TE->isSame(VL))
3215             return false;
3216           TreeEntry *Gather = nullptr;
3217           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3218                 assert(TE->State != TreeEntry::Vectorize &&
3219                        "Only non-vectorized nodes are expected.");
3220                 if (TE->isSame(VL)) {
3221                   Gather = TE;
3222                   return true;
3223                 }
3224                 return false;
3225               }) > 1)
3226             return false;
3227           if (Gather)
3228             GatherOps.push_back(Gather);
3229         }
3230         return true;
3231       };
3232   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3233   // I.e., if the node has operands, that are reordered, try to make at least
3234   // one operand order in the natural order and reorder others + reorder the
3235   // user node itself.
3236   SmallPtrSet<const TreeEntry *, 4> Visited;
3237   while (!OrderedEntries.empty()) {
3238     // 1. Filter out only reordered nodes.
3239     // 2. If the entry has multiple uses - skip it and jump to the next node.
3240     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3241     SmallVector<TreeEntry *> Filtered;
3242     for (TreeEntry *TE : OrderedEntries) {
3243       if (!(TE->State == TreeEntry::Vectorize ||
3244             (TE->State == TreeEntry::NeedToGather &&
3245              GathersToOrders.count(TE))) ||
3246           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3247           !all_of(drop_begin(TE->UserTreeIndices),
3248                   [TE](const EdgeInfo &EI) {
3249                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3250                   }) ||
3251           !Visited.insert(TE).second) {
3252         Filtered.push_back(TE);
3253         continue;
3254       }
3255       // Build a map between user nodes and their operands order to speedup
3256       // search. The graph currently does not provide this dependency directly.
3257       for (EdgeInfo &EI : TE->UserTreeIndices) {
3258         TreeEntry *UserTE = EI.UserTE;
3259         auto It = Users.find(UserTE);
3260         if (It == Users.end())
3261           It = Users.insert({UserTE, {}}).first;
3262         It->second.emplace_back(EI.EdgeIdx, TE);
3263       }
3264     }
3265     // Erase filtered entries.
3266     for_each(Filtered,
3267              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3268     for (const auto &Data : Users) {
3269       // Check that operands are used only in the User node.
3270       SmallVector<TreeEntry *> GatherOps;
3271       if (!CheckOperands(Data, GatherOps)) {
3272         for_each(Data.second,
3273                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3274                    OrderedEntries.remove(Op.second);
3275                  });
3276         continue;
3277       }
3278       // All operands are reordered and used only in this node - propagate the
3279       // most used order to the user node.
3280       MapVector<OrdersType, unsigned,
3281                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3282           OrdersUses;
3283       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3284       for (const auto &Op : Data.second) {
3285         TreeEntry *OpTE = Op.second;
3286         if (!OpTE->ReuseShuffleIndices.empty() ||
3287             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3288           continue;
3289         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3290           if (OpTE->State == TreeEntry::NeedToGather)
3291             return GathersToOrders.find(OpTE)->second;
3292           return OpTE->ReorderIndices;
3293         }();
3294         // Stores actually store the mask, not the order, need to invert.
3295         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3296             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3297           SmallVector<int> Mask;
3298           inversePermutation(Order, Mask);
3299           unsigned E = Order.size();
3300           OrdersType CurrentOrder(E, E);
3301           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3302             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3303           });
3304           fixupOrderingIndices(CurrentOrder);
3305           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3306         } else {
3307           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3308         }
3309         if (VisitedOps.insert(OpTE).second)
3310           OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3311               OpTE->UserTreeIndices.size();
3312         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3313         --OrdersUses[{}];
3314       }
3315       // If no orders - skip current nodes and jump to the next one, if any.
3316       if (OrdersUses.empty()) {
3317         for_each(Data.second,
3318                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3319                    OrderedEntries.remove(Op.second);
3320                  });
3321         continue;
3322       }
3323       // Choose the best order.
3324       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3325       unsigned Cnt = OrdersUses.front().second;
3326       for (const auto &Pair : drop_begin(OrdersUses)) {
3327         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3328           BestOrder = Pair.first;
3329           Cnt = Pair.second;
3330         }
3331       }
3332       // Set order of the user node (reordering of operands and user nodes).
3333       if (BestOrder.empty()) {
3334         for_each(Data.second,
3335                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3336                    OrderedEntries.remove(Op.second);
3337                  });
3338         continue;
3339       }
3340       // Erase operands from OrderedEntries list and adjust their orders.
3341       VisitedOps.clear();
3342       SmallVector<int> Mask;
3343       inversePermutation(BestOrder, Mask);
3344       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3345       unsigned E = BestOrder.size();
3346       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3347         return I < E ? static_cast<int>(I) : UndefMaskElem;
3348       });
3349       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3350         TreeEntry *TE = Op.second;
3351         OrderedEntries.remove(TE);
3352         if (!VisitedOps.insert(TE).second)
3353           continue;
3354         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3355           // Just reorder reuses indices.
3356           reorderReuses(TE->ReuseShuffleIndices, Mask);
3357           continue;
3358         }
3359         // Gathers are processed separately.
3360         if (TE->State != TreeEntry::Vectorize)
3361           continue;
3362         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3363                 TE->ReorderIndices.empty()) &&
3364                "Non-matching sizes of user/operand entries.");
3365         reorderOrder(TE->ReorderIndices, Mask);
3366       }
3367       // For gathers just need to reorder its scalars.
3368       for (TreeEntry *Gather : GatherOps) {
3369         assert(Gather->ReorderIndices.empty() &&
3370                "Unexpected reordering of gathers.");
3371         if (!Gather->ReuseShuffleIndices.empty()) {
3372           // Just reorder reuses indices.
3373           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3374           continue;
3375         }
3376         reorderScalars(Gather->Scalars, Mask);
3377         OrderedEntries.remove(Gather);
3378       }
3379       // Reorder operands of the user node and set the ordering for the user
3380       // node itself.
3381       if (Data.first->State != TreeEntry::Vectorize ||
3382           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3383               Data.first->getMainOp()) ||
3384           Data.first->isAltShuffle())
3385         Data.first->reorderOperands(Mask);
3386       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3387           Data.first->isAltShuffle()) {
3388         reorderScalars(Data.first->Scalars, Mask);
3389         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3390         if (Data.first->ReuseShuffleIndices.empty() &&
3391             !Data.first->ReorderIndices.empty() &&
3392             !Data.first->isAltShuffle()) {
3393           // Insert user node to the list to try to sink reordering deeper in
3394           // the graph.
3395           OrderedEntries.insert(Data.first);
3396         }
3397       } else {
3398         reorderOrder(Data.first->ReorderIndices, Mask);
3399       }
3400     }
3401   }
3402   // If the reordering is unnecessary, just remove the reorder.
3403   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3404       VectorizableTree.front()->ReuseShuffleIndices.empty())
3405     VectorizableTree.front()->ReorderIndices.clear();
3406 }
3407 
3408 void BoUpSLP::buildExternalUses(
3409     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3410   // Collect the values that we need to extract from the tree.
3411   for (auto &TEPtr : VectorizableTree) {
3412     TreeEntry *Entry = TEPtr.get();
3413 
3414     // No need to handle users of gathered values.
3415     if (Entry->State == TreeEntry::NeedToGather)
3416       continue;
3417 
3418     // For each lane:
3419     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3420       Value *Scalar = Entry->Scalars[Lane];
3421       int FoundLane = Entry->findLaneForValue(Scalar);
3422 
3423       // Check if the scalar is externally used as an extra arg.
3424       auto ExtI = ExternallyUsedValues.find(Scalar);
3425       if (ExtI != ExternallyUsedValues.end()) {
3426         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3427                           << Lane << " from " << *Scalar << ".\n");
3428         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3429       }
3430       for (User *U : Scalar->users()) {
3431         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3432 
3433         Instruction *UserInst = dyn_cast<Instruction>(U);
3434         if (!UserInst)
3435           continue;
3436 
3437         if (isDeleted(UserInst))
3438           continue;
3439 
3440         // Skip in-tree scalars that become vectors
3441         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3442           Value *UseScalar = UseEntry->Scalars[0];
3443           // Some in-tree scalars will remain as scalar in vectorized
3444           // instructions. If that is the case, the one in Lane 0 will
3445           // be used.
3446           if (UseScalar != U ||
3447               UseEntry->State == TreeEntry::ScatterVectorize ||
3448               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3449             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3450                               << ".\n");
3451             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3452             continue;
3453           }
3454         }
3455 
3456         // Ignore users in the user ignore list.
3457         if (is_contained(UserIgnoreList, UserInst))
3458           continue;
3459 
3460         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3461                           << Lane << " from " << *Scalar << ".\n");
3462         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3463       }
3464     }
3465   }
3466 }
3467 
3468 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3469                         ArrayRef<Value *> UserIgnoreLst) {
3470   deleteTree();
3471   UserIgnoreList = UserIgnoreLst;
3472   if (!allSameType(Roots))
3473     return;
3474   buildTree_rec(Roots, 0, EdgeInfo());
3475 }
3476 
3477 namespace {
3478 /// Tracks the state we can represent the loads in the given sequence.
3479 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3480 } // anonymous namespace
3481 
3482 /// Checks if the given array of loads can be represented as a vectorized,
3483 /// scatter or just simple gather.
3484 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3485                                     const TargetTransformInfo &TTI,
3486                                     const DataLayout &DL, ScalarEvolution &SE,
3487                                     SmallVectorImpl<unsigned> &Order,
3488                                     SmallVectorImpl<Value *> &PointerOps) {
3489   // Check that a vectorized load would load the same memory as a scalar
3490   // load. For example, we don't want to vectorize loads that are smaller
3491   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3492   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3493   // from such a struct, we read/write packed bits disagreeing with the
3494   // unvectorized version.
3495   Type *ScalarTy = VL0->getType();
3496 
3497   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3498     return LoadsState::Gather;
3499 
3500   // Make sure all loads in the bundle are simple - we can't vectorize
3501   // atomic or volatile loads.
3502   PointerOps.clear();
3503   PointerOps.resize(VL.size());
3504   auto *POIter = PointerOps.begin();
3505   for (Value *V : VL) {
3506     auto *L = cast<LoadInst>(V);
3507     if (!L->isSimple())
3508       return LoadsState::Gather;
3509     *POIter = L->getPointerOperand();
3510     ++POIter;
3511   }
3512 
3513   Order.clear();
3514   // Check the order of pointer operands.
3515   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3516     Value *Ptr0;
3517     Value *PtrN;
3518     if (Order.empty()) {
3519       Ptr0 = PointerOps.front();
3520       PtrN = PointerOps.back();
3521     } else {
3522       Ptr0 = PointerOps[Order.front()];
3523       PtrN = PointerOps[Order.back()];
3524     }
3525     Optional<int> Diff =
3526         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3527     // Check that the sorted loads are consecutive.
3528     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3529       return LoadsState::Vectorize;
3530     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3531     for (Value *V : VL)
3532       CommonAlignment =
3533           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3534     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3535                                 CommonAlignment))
3536       return LoadsState::ScatterVectorize;
3537   }
3538 
3539   return LoadsState::Gather;
3540 }
3541 
3542 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3543                             const EdgeInfo &UserTreeIdx) {
3544   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3545 
3546   SmallVector<int> ReuseShuffleIndicies;
3547   SmallVector<Value *> UniqueValues;
3548   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3549                                 &UserTreeIdx,
3550                                 this](const InstructionsState &S) {
3551     // Check that every instruction appears once in this bundle.
3552     DenseMap<Value *, unsigned> UniquePositions;
3553     for (Value *V : VL) {
3554       if (isConstant(V)) {
3555         ReuseShuffleIndicies.emplace_back(
3556             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3557         UniqueValues.emplace_back(V);
3558         continue;
3559       }
3560       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3561       ReuseShuffleIndicies.emplace_back(Res.first->second);
3562       if (Res.second)
3563         UniqueValues.emplace_back(V);
3564     }
3565     size_t NumUniqueScalarValues = UniqueValues.size();
3566     if (NumUniqueScalarValues == VL.size()) {
3567       ReuseShuffleIndicies.clear();
3568     } else {
3569       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3570       if (NumUniqueScalarValues <= 1 ||
3571           (NumUniqueScalarValues == 2 &&
3572            any_of(UniqueValues, UndefValue::classof)) ||
3573           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3574         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3575         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3576         return false;
3577       }
3578       VL = UniqueValues;
3579     }
3580     return true;
3581   };
3582 
3583   InstructionsState S = getSameOpcode(VL);
3584   if (Depth == RecursionMaxDepth) {
3585     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3586     if (TryToFindDuplicates(S))
3587       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3588                    ReuseShuffleIndicies);
3589     return;
3590   }
3591 
3592   // Don't handle scalable vectors
3593   if (S.getOpcode() == Instruction::ExtractElement &&
3594       isa<ScalableVectorType>(
3595           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3596     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3597     if (TryToFindDuplicates(S))
3598       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3599                    ReuseShuffleIndicies);
3600     return;
3601   }
3602 
3603   // Don't handle vectors.
3604   if (S.OpValue->getType()->isVectorTy() &&
3605       !isa<InsertElementInst>(S.OpValue)) {
3606     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3607     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3608     return;
3609   }
3610 
3611   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3612     if (SI->getValueOperand()->getType()->isVectorTy()) {
3613       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3614       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3615       return;
3616     }
3617 
3618   // If all of the operands are identical or constant we have a simple solution.
3619   // If we deal with insert/extract instructions, they all must have constant
3620   // indices, otherwise we should gather them, not try to vectorize.
3621   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3622       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3623        !all_of(VL, isVectorLikeInstWithConstOps))) {
3624     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3625     if (TryToFindDuplicates(S))
3626       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3627                    ReuseShuffleIndicies);
3628     return;
3629   }
3630 
3631   // We now know that this is a vector of instructions of the same type from
3632   // the same block.
3633 
3634   // Don't vectorize ephemeral values.
3635   for (Value *V : VL) {
3636     if (EphValues.count(V)) {
3637       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3638                         << ") is ephemeral.\n");
3639       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3640       return;
3641     }
3642   }
3643 
3644   // Check if this is a duplicate of another entry.
3645   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3646     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3647     if (!E->isSame(VL)) {
3648       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3649       if (TryToFindDuplicates(S))
3650         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3651                      ReuseShuffleIndicies);
3652       return;
3653     }
3654     // Record the reuse of the tree node.  FIXME, currently this is only used to
3655     // properly draw the graph rather than for the actual vectorization.
3656     E->UserTreeIndices.push_back(UserTreeIdx);
3657     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3658                       << ".\n");
3659     return;
3660   }
3661 
3662   // Check that none of the instructions in the bundle are already in the tree.
3663   for (Value *V : VL) {
3664     auto *I = dyn_cast<Instruction>(V);
3665     if (!I)
3666       continue;
3667     if (getTreeEntry(I)) {
3668       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3669                         << ") is already in tree.\n");
3670       if (TryToFindDuplicates(S))
3671         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3672                      ReuseShuffleIndicies);
3673       return;
3674     }
3675   }
3676 
3677   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3678   for (Value *V : VL) {
3679     if (is_contained(UserIgnoreList, V)) {
3680       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3681       if (TryToFindDuplicates(S))
3682         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3683                      ReuseShuffleIndicies);
3684       return;
3685     }
3686   }
3687 
3688   // Check that all of the users of the scalars that we want to vectorize are
3689   // schedulable.
3690   auto *VL0 = cast<Instruction>(S.OpValue);
3691   BasicBlock *BB = VL0->getParent();
3692 
3693   if (!DT->isReachableFromEntry(BB)) {
3694     // Don't go into unreachable blocks. They may contain instructions with
3695     // dependency cycles which confuse the final scheduling.
3696     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3697     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3698     return;
3699   }
3700 
3701   // Check that every instruction appears once in this bundle.
3702   if (!TryToFindDuplicates(S))
3703     return;
3704 
3705   auto &BSRef = BlocksSchedules[BB];
3706   if (!BSRef)
3707     BSRef = std::make_unique<BlockScheduling>(BB);
3708 
3709   BlockScheduling &BS = *BSRef.get();
3710 
3711   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3712   if (!Bundle) {
3713     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3714     assert((!BS.getScheduleData(VL0) ||
3715             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3716            "tryScheduleBundle should cancelScheduling on failure");
3717     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3718                  ReuseShuffleIndicies);
3719     return;
3720   }
3721   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3722 
3723   unsigned ShuffleOrOp = S.isAltShuffle() ?
3724                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3725   switch (ShuffleOrOp) {
3726     case Instruction::PHI: {
3727       auto *PH = cast<PHINode>(VL0);
3728 
3729       // Check for terminator values (e.g. invoke).
3730       for (Value *V : VL)
3731         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3732           Instruction *Term = dyn_cast<Instruction>(
3733               cast<PHINode>(V)->getIncomingValueForBlock(
3734                   PH->getIncomingBlock(I)));
3735           if (Term && Term->isTerminator()) {
3736             LLVM_DEBUG(dbgs()
3737                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3738             BS.cancelScheduling(VL, VL0);
3739             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3740                          ReuseShuffleIndicies);
3741             return;
3742           }
3743         }
3744 
3745       TreeEntry *TE =
3746           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3747       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3748 
3749       // Keeps the reordered operands to avoid code duplication.
3750       SmallVector<ValueList, 2> OperandsVec;
3751       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3752         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3753           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3754           TE->setOperand(I, Operands);
3755           OperandsVec.push_back(Operands);
3756           continue;
3757         }
3758         ValueList Operands;
3759         // Prepare the operand vector.
3760         for (Value *V : VL)
3761           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3762               PH->getIncomingBlock(I)));
3763         TE->setOperand(I, Operands);
3764         OperandsVec.push_back(Operands);
3765       }
3766       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3767         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3768       return;
3769     }
3770     case Instruction::ExtractValue:
3771     case Instruction::ExtractElement: {
3772       OrdersType CurrentOrder;
3773       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3774       if (Reuse) {
3775         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3776         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3777                      ReuseShuffleIndicies);
3778         // This is a special case, as it does not gather, but at the same time
3779         // we are not extending buildTree_rec() towards the operands.
3780         ValueList Op0;
3781         Op0.assign(VL.size(), VL0->getOperand(0));
3782         VectorizableTree.back()->setOperand(0, Op0);
3783         return;
3784       }
3785       if (!CurrentOrder.empty()) {
3786         LLVM_DEBUG({
3787           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3788                     "with order";
3789           for (unsigned Idx : CurrentOrder)
3790             dbgs() << " " << Idx;
3791           dbgs() << "\n";
3792         });
3793         fixupOrderingIndices(CurrentOrder);
3794         // Insert new order with initial value 0, if it does not exist,
3795         // otherwise return the iterator to the existing one.
3796         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3797                      ReuseShuffleIndicies, CurrentOrder);
3798         // This is a special case, as it does not gather, but at the same time
3799         // we are not extending buildTree_rec() towards the operands.
3800         ValueList Op0;
3801         Op0.assign(VL.size(), VL0->getOperand(0));
3802         VectorizableTree.back()->setOperand(0, Op0);
3803         return;
3804       }
3805       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3806       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3807                    ReuseShuffleIndicies);
3808       BS.cancelScheduling(VL, VL0);
3809       return;
3810     }
3811     case Instruction::InsertElement: {
3812       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3813 
3814       // Check that we have a buildvector and not a shuffle of 2 or more
3815       // different vectors.
3816       ValueSet SourceVectors;
3817       int MinIdx = std::numeric_limits<int>::max();
3818       for (Value *V : VL) {
3819         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3820         Optional<int> Idx = *getInsertIndex(V, 0);
3821         if (!Idx || *Idx == UndefMaskElem)
3822           continue;
3823         MinIdx = std::min(MinIdx, *Idx);
3824       }
3825 
3826       if (count_if(VL, [&SourceVectors](Value *V) {
3827             return !SourceVectors.contains(V);
3828           }) >= 2) {
3829         // Found 2nd source vector - cancel.
3830         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3831                              "different source vectors.\n");
3832         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3833         BS.cancelScheduling(VL, VL0);
3834         return;
3835       }
3836 
3837       auto OrdCompare = [](const std::pair<int, int> &P1,
3838                            const std::pair<int, int> &P2) {
3839         return P1.first > P2.first;
3840       };
3841       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3842                     decltype(OrdCompare)>
3843           Indices(OrdCompare);
3844       for (int I = 0, E = VL.size(); I < E; ++I) {
3845         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3846         if (!Idx || *Idx == UndefMaskElem)
3847           continue;
3848         Indices.emplace(*Idx, I);
3849       }
3850       OrdersType CurrentOrder(VL.size(), VL.size());
3851       bool IsIdentity = true;
3852       for (int I = 0, E = VL.size(); I < E; ++I) {
3853         CurrentOrder[Indices.top().second] = I;
3854         IsIdentity &= Indices.top().second == I;
3855         Indices.pop();
3856       }
3857       if (IsIdentity)
3858         CurrentOrder.clear();
3859       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3860                                    None, CurrentOrder);
3861       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3862 
3863       constexpr int NumOps = 2;
3864       ValueList VectorOperands[NumOps];
3865       for (int I = 0; I < NumOps; ++I) {
3866         for (Value *V : VL)
3867           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3868 
3869         TE->setOperand(I, VectorOperands[I]);
3870       }
3871       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3872       return;
3873     }
3874     case Instruction::Load: {
3875       // Check that a vectorized load would load the same memory as a scalar
3876       // load. For example, we don't want to vectorize loads that are smaller
3877       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3878       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3879       // from such a struct, we read/write packed bits disagreeing with the
3880       // unvectorized version.
3881       SmallVector<Value *> PointerOps;
3882       OrdersType CurrentOrder;
3883       TreeEntry *TE = nullptr;
3884       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3885                                 PointerOps)) {
3886       case LoadsState::Vectorize:
3887         if (CurrentOrder.empty()) {
3888           // Original loads are consecutive and does not require reordering.
3889           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3890                             ReuseShuffleIndicies);
3891           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3892         } else {
3893           fixupOrderingIndices(CurrentOrder);
3894           // Need to reorder.
3895           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3896                             ReuseShuffleIndicies, CurrentOrder);
3897           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
3898         }
3899         TE->setOperandsInOrder();
3900         break;
3901       case LoadsState::ScatterVectorize:
3902         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3903         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
3904                           UserTreeIdx, ReuseShuffleIndicies);
3905         TE->setOperandsInOrder();
3906         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
3907         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
3908         break;
3909       case LoadsState::Gather:
3910         BS.cancelScheduling(VL, VL0);
3911         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3912                      ReuseShuffleIndicies);
3913 #ifndef NDEBUG
3914         Type *ScalarTy = VL0->getType();
3915         if (DL->getTypeSizeInBits(ScalarTy) !=
3916             DL->getTypeAllocSizeInBits(ScalarTy))
3917           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
3918         else if (any_of(VL, [](Value *V) {
3919                    return !cast<LoadInst>(V)->isSimple();
3920                  }))
3921           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
3922         else
3923           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
3924 #endif // NDEBUG
3925         break;
3926       }
3927       return;
3928     }
3929     case Instruction::ZExt:
3930     case Instruction::SExt:
3931     case Instruction::FPToUI:
3932     case Instruction::FPToSI:
3933     case Instruction::FPExt:
3934     case Instruction::PtrToInt:
3935     case Instruction::IntToPtr:
3936     case Instruction::SIToFP:
3937     case Instruction::UIToFP:
3938     case Instruction::Trunc:
3939     case Instruction::FPTrunc:
3940     case Instruction::BitCast: {
3941       Type *SrcTy = VL0->getOperand(0)->getType();
3942       for (Value *V : VL) {
3943         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
3944         if (Ty != SrcTy || !isValidElementType(Ty)) {
3945           BS.cancelScheduling(VL, VL0);
3946           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3947                        ReuseShuffleIndicies);
3948           LLVM_DEBUG(dbgs()
3949                      << "SLP: Gathering casts with different src types.\n");
3950           return;
3951         }
3952       }
3953       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3954                                    ReuseShuffleIndicies);
3955       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
3956 
3957       TE->setOperandsInOrder();
3958       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3959         ValueList Operands;
3960         // Prepare the operand vector.
3961         for (Value *V : VL)
3962           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3963 
3964         buildTree_rec(Operands, Depth + 1, {TE, i});
3965       }
3966       return;
3967     }
3968     case Instruction::ICmp:
3969     case Instruction::FCmp: {
3970       // Check that all of the compares have the same predicate.
3971       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3972       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
3973       Type *ComparedTy = VL0->getOperand(0)->getType();
3974       for (Value *V : VL) {
3975         CmpInst *Cmp = cast<CmpInst>(V);
3976         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
3977             Cmp->getOperand(0)->getType() != ComparedTy) {
3978           BS.cancelScheduling(VL, VL0);
3979           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3980                        ReuseShuffleIndicies);
3981           LLVM_DEBUG(dbgs()
3982                      << "SLP: Gathering cmp with different predicate.\n");
3983           return;
3984         }
3985       }
3986 
3987       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3988                                    ReuseShuffleIndicies);
3989       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
3990 
3991       ValueList Left, Right;
3992       if (cast<CmpInst>(VL0)->isCommutative()) {
3993         // Commutative predicate - collect + sort operands of the instructions
3994         // so that each side is more likely to have the same opcode.
3995         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
3996         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3997       } else {
3998         // Collect operands - commute if it uses the swapped predicate.
3999         for (Value *V : VL) {
4000           auto *Cmp = cast<CmpInst>(V);
4001           Value *LHS = Cmp->getOperand(0);
4002           Value *RHS = Cmp->getOperand(1);
4003           if (Cmp->getPredicate() != P0)
4004             std::swap(LHS, RHS);
4005           Left.push_back(LHS);
4006           Right.push_back(RHS);
4007         }
4008       }
4009       TE->setOperand(0, Left);
4010       TE->setOperand(1, Right);
4011       buildTree_rec(Left, Depth + 1, {TE, 0});
4012       buildTree_rec(Right, Depth + 1, {TE, 1});
4013       return;
4014     }
4015     case Instruction::Select:
4016     case Instruction::FNeg:
4017     case Instruction::Add:
4018     case Instruction::FAdd:
4019     case Instruction::Sub:
4020     case Instruction::FSub:
4021     case Instruction::Mul:
4022     case Instruction::FMul:
4023     case Instruction::UDiv:
4024     case Instruction::SDiv:
4025     case Instruction::FDiv:
4026     case Instruction::URem:
4027     case Instruction::SRem:
4028     case Instruction::FRem:
4029     case Instruction::Shl:
4030     case Instruction::LShr:
4031     case Instruction::AShr:
4032     case Instruction::And:
4033     case Instruction::Or:
4034     case Instruction::Xor: {
4035       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4036                                    ReuseShuffleIndicies);
4037       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4038 
4039       // Sort operands of the instructions so that each side is more likely to
4040       // have the same opcode.
4041       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4042         ValueList Left, Right;
4043         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4044         TE->setOperand(0, Left);
4045         TE->setOperand(1, Right);
4046         buildTree_rec(Left, Depth + 1, {TE, 0});
4047         buildTree_rec(Right, Depth + 1, {TE, 1});
4048         return;
4049       }
4050 
4051       TE->setOperandsInOrder();
4052       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4053         ValueList Operands;
4054         // Prepare the operand vector.
4055         for (Value *V : VL)
4056           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4057 
4058         buildTree_rec(Operands, Depth + 1, {TE, i});
4059       }
4060       return;
4061     }
4062     case Instruction::GetElementPtr: {
4063       // We don't combine GEPs with complicated (nested) indexing.
4064       for (Value *V : VL) {
4065         if (cast<Instruction>(V)->getNumOperands() != 2) {
4066           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4067           BS.cancelScheduling(VL, VL0);
4068           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4069                        ReuseShuffleIndicies);
4070           return;
4071         }
4072       }
4073 
4074       // We can't combine several GEPs into one vector if they operate on
4075       // different types.
4076       Type *Ty0 = VL0->getOperand(0)->getType();
4077       for (Value *V : VL) {
4078         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4079         if (Ty0 != CurTy) {
4080           LLVM_DEBUG(dbgs()
4081                      << "SLP: not-vectorizable GEP (different types).\n");
4082           BS.cancelScheduling(VL, VL0);
4083           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4084                        ReuseShuffleIndicies);
4085           return;
4086         }
4087       }
4088 
4089       // We don't combine GEPs with non-constant indexes.
4090       Type *Ty1 = VL0->getOperand(1)->getType();
4091       for (Value *V : VL) {
4092         auto Op = cast<Instruction>(V)->getOperand(1);
4093         if (!isa<ConstantInt>(Op) ||
4094             (Op->getType() != Ty1 &&
4095              Op->getType()->getScalarSizeInBits() >
4096                  DL->getIndexSizeInBits(
4097                      V->getType()->getPointerAddressSpace()))) {
4098           LLVM_DEBUG(dbgs()
4099                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4100           BS.cancelScheduling(VL, VL0);
4101           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4102                        ReuseShuffleIndicies);
4103           return;
4104         }
4105       }
4106 
4107       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4108                                    ReuseShuffleIndicies);
4109       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4110       SmallVector<ValueList, 2> Operands(2);
4111       // Prepare the operand vector for pointer operands.
4112       for (Value *V : VL)
4113         Operands.front().push_back(
4114             cast<GetElementPtrInst>(V)->getPointerOperand());
4115       TE->setOperand(0, Operands.front());
4116       // Need to cast all indices to the same type before vectorization to
4117       // avoid crash.
4118       // Required to be able to find correct matches between different gather
4119       // nodes and reuse the vectorized values rather than trying to gather them
4120       // again.
4121       int IndexIdx = 1;
4122       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4123       Type *Ty = all_of(VL,
4124                         [VL0Ty, IndexIdx](Value *V) {
4125                           return VL0Ty == cast<GetElementPtrInst>(V)
4126                                               ->getOperand(IndexIdx)
4127                                               ->getType();
4128                         })
4129                      ? VL0Ty
4130                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4131                                             ->getPointerOperandType()
4132                                             ->getScalarType());
4133       // Prepare the operand vector.
4134       for (Value *V : VL) {
4135         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4136         auto *CI = cast<ConstantInt>(Op);
4137         Operands.back().push_back(ConstantExpr::getIntegerCast(
4138             CI, Ty, CI->getValue().isSignBitSet()));
4139       }
4140       TE->setOperand(IndexIdx, Operands.back());
4141 
4142       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4143         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4144       return;
4145     }
4146     case Instruction::Store: {
4147       // Check if the stores are consecutive or if we need to swizzle them.
4148       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4149       // Avoid types that are padded when being allocated as scalars, while
4150       // being packed together in a vector (such as i1).
4151       if (DL->getTypeSizeInBits(ScalarTy) !=
4152           DL->getTypeAllocSizeInBits(ScalarTy)) {
4153         BS.cancelScheduling(VL, VL0);
4154         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4155                      ReuseShuffleIndicies);
4156         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4157         return;
4158       }
4159       // Make sure all stores in the bundle are simple - we can't vectorize
4160       // atomic or volatile stores.
4161       SmallVector<Value *, 4> PointerOps(VL.size());
4162       ValueList Operands(VL.size());
4163       auto POIter = PointerOps.begin();
4164       auto OIter = Operands.begin();
4165       for (Value *V : VL) {
4166         auto *SI = cast<StoreInst>(V);
4167         if (!SI->isSimple()) {
4168           BS.cancelScheduling(VL, VL0);
4169           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4170                        ReuseShuffleIndicies);
4171           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4172           return;
4173         }
4174         *POIter = SI->getPointerOperand();
4175         *OIter = SI->getValueOperand();
4176         ++POIter;
4177         ++OIter;
4178       }
4179 
4180       OrdersType CurrentOrder;
4181       // Check the order of pointer operands.
4182       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4183         Value *Ptr0;
4184         Value *PtrN;
4185         if (CurrentOrder.empty()) {
4186           Ptr0 = PointerOps.front();
4187           PtrN = PointerOps.back();
4188         } else {
4189           Ptr0 = PointerOps[CurrentOrder.front()];
4190           PtrN = PointerOps[CurrentOrder.back()];
4191         }
4192         Optional<int> Dist =
4193             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4194         // Check that the sorted pointer operands are consecutive.
4195         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4196           if (CurrentOrder.empty()) {
4197             // Original stores are consecutive and does not require reordering.
4198             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4199                                          UserTreeIdx, ReuseShuffleIndicies);
4200             TE->setOperandsInOrder();
4201             buildTree_rec(Operands, Depth + 1, {TE, 0});
4202             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4203           } else {
4204             fixupOrderingIndices(CurrentOrder);
4205             TreeEntry *TE =
4206                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4207                              ReuseShuffleIndicies, CurrentOrder);
4208             TE->setOperandsInOrder();
4209             buildTree_rec(Operands, Depth + 1, {TE, 0});
4210             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4211           }
4212           return;
4213         }
4214       }
4215 
4216       BS.cancelScheduling(VL, VL0);
4217       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4218                    ReuseShuffleIndicies);
4219       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4220       return;
4221     }
4222     case Instruction::Call: {
4223       // Check if the calls are all to the same vectorizable intrinsic or
4224       // library function.
4225       CallInst *CI = cast<CallInst>(VL0);
4226       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4227 
4228       VFShape Shape = VFShape::get(
4229           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4230           false /*HasGlobalPred*/);
4231       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4232 
4233       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4234         BS.cancelScheduling(VL, VL0);
4235         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4236                      ReuseShuffleIndicies);
4237         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4238         return;
4239       }
4240       Function *F = CI->getCalledFunction();
4241       unsigned NumArgs = CI->arg_size();
4242       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4243       for (unsigned j = 0; j != NumArgs; ++j)
4244         if (hasVectorInstrinsicScalarOpd(ID, j))
4245           ScalarArgs[j] = CI->getArgOperand(j);
4246       for (Value *V : VL) {
4247         CallInst *CI2 = dyn_cast<CallInst>(V);
4248         if (!CI2 || CI2->getCalledFunction() != F ||
4249             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4250             (VecFunc &&
4251              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4252             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4253           BS.cancelScheduling(VL, VL0);
4254           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4255                        ReuseShuffleIndicies);
4256           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4257                             << "\n");
4258           return;
4259         }
4260         // Some intrinsics have scalar arguments and should be same in order for
4261         // them to be vectorized.
4262         for (unsigned j = 0; j != NumArgs; ++j) {
4263           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4264             Value *A1J = CI2->getArgOperand(j);
4265             if (ScalarArgs[j] != A1J) {
4266               BS.cancelScheduling(VL, VL0);
4267               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4268                            ReuseShuffleIndicies);
4269               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4270                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4271                                 << "\n");
4272               return;
4273             }
4274           }
4275         }
4276         // Verify that the bundle operands are identical between the two calls.
4277         if (CI->hasOperandBundles() &&
4278             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4279                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4280                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4281           BS.cancelScheduling(VL, VL0);
4282           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4283                        ReuseShuffleIndicies);
4284           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4285                             << *CI << "!=" << *V << '\n');
4286           return;
4287         }
4288       }
4289 
4290       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4291                                    ReuseShuffleIndicies);
4292       TE->setOperandsInOrder();
4293       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4294         // For scalar operands no need to to create an entry since no need to
4295         // vectorize it.
4296         if (hasVectorInstrinsicScalarOpd(ID, i))
4297           continue;
4298         ValueList Operands;
4299         // Prepare the operand vector.
4300         for (Value *V : VL) {
4301           auto *CI2 = cast<CallInst>(V);
4302           Operands.push_back(CI2->getArgOperand(i));
4303         }
4304         buildTree_rec(Operands, Depth + 1, {TE, i});
4305       }
4306       return;
4307     }
4308     case Instruction::ShuffleVector: {
4309       // If this is not an alternate sequence of opcode like add-sub
4310       // then do not vectorize this instruction.
4311       if (!S.isAltShuffle()) {
4312         BS.cancelScheduling(VL, VL0);
4313         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4314                      ReuseShuffleIndicies);
4315         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4316         return;
4317       }
4318       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4319                                    ReuseShuffleIndicies);
4320       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4321 
4322       // Reorder operands if reordering would enable vectorization.
4323       if (isa<BinaryOperator>(VL0)) {
4324         ValueList Left, Right;
4325         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4326         TE->setOperand(0, Left);
4327         TE->setOperand(1, Right);
4328         buildTree_rec(Left, Depth + 1, {TE, 0});
4329         buildTree_rec(Right, Depth + 1, {TE, 1});
4330         return;
4331       }
4332 
4333       TE->setOperandsInOrder();
4334       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4335         ValueList Operands;
4336         // Prepare the operand vector.
4337         for (Value *V : VL)
4338           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4339 
4340         buildTree_rec(Operands, Depth + 1, {TE, i});
4341       }
4342       return;
4343     }
4344     default:
4345       BS.cancelScheduling(VL, VL0);
4346       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4347                    ReuseShuffleIndicies);
4348       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4349       return;
4350   }
4351 }
4352 
4353 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4354   unsigned N = 1;
4355   Type *EltTy = T;
4356 
4357   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4358          isa<VectorType>(EltTy)) {
4359     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4360       // Check that struct is homogeneous.
4361       for (const auto *Ty : ST->elements())
4362         if (Ty != *ST->element_begin())
4363           return 0;
4364       N *= ST->getNumElements();
4365       EltTy = *ST->element_begin();
4366     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4367       N *= AT->getNumElements();
4368       EltTy = AT->getElementType();
4369     } else {
4370       auto *VT = cast<FixedVectorType>(EltTy);
4371       N *= VT->getNumElements();
4372       EltTy = VT->getElementType();
4373     }
4374   }
4375 
4376   if (!isValidElementType(EltTy))
4377     return 0;
4378   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4379   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4380     return 0;
4381   return N;
4382 }
4383 
4384 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4385                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4386   const auto *It = find_if(VL, [](Value *V) {
4387     return isa<ExtractElementInst, ExtractValueInst>(V);
4388   });
4389   assert(It != VL.end() && "Expected at least one extract instruction.");
4390   auto *E0 = cast<Instruction>(*It);
4391   assert(all_of(VL,
4392                 [](Value *V) {
4393                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4394                       V);
4395                 }) &&
4396          "Invalid opcode");
4397   // Check if all of the extracts come from the same vector and from the
4398   // correct offset.
4399   Value *Vec = E0->getOperand(0);
4400 
4401   CurrentOrder.clear();
4402 
4403   // We have to extract from a vector/aggregate with the same number of elements.
4404   unsigned NElts;
4405   if (E0->getOpcode() == Instruction::ExtractValue) {
4406     const DataLayout &DL = E0->getModule()->getDataLayout();
4407     NElts = canMapToVector(Vec->getType(), DL);
4408     if (!NElts)
4409       return false;
4410     // Check if load can be rewritten as load of vector.
4411     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4412     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4413       return false;
4414   } else {
4415     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4416   }
4417 
4418   if (NElts != VL.size())
4419     return false;
4420 
4421   // Check that all of the indices extract from the correct offset.
4422   bool ShouldKeepOrder = true;
4423   unsigned E = VL.size();
4424   // Assign to all items the initial value E + 1 so we can check if the extract
4425   // instruction index was used already.
4426   // Also, later we can check that all the indices are used and we have a
4427   // consecutive access in the extract instructions, by checking that no
4428   // element of CurrentOrder still has value E + 1.
4429   CurrentOrder.assign(E, E);
4430   unsigned I = 0;
4431   for (; I < E; ++I) {
4432     auto *Inst = dyn_cast<Instruction>(VL[I]);
4433     if (!Inst)
4434       continue;
4435     if (Inst->getOperand(0) != Vec)
4436       break;
4437     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4438       if (isa<UndefValue>(EE->getIndexOperand()))
4439         continue;
4440     Optional<unsigned> Idx = getExtractIndex(Inst);
4441     if (!Idx)
4442       break;
4443     const unsigned ExtIdx = *Idx;
4444     if (ExtIdx != I) {
4445       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4446         break;
4447       ShouldKeepOrder = false;
4448       CurrentOrder[ExtIdx] = I;
4449     } else {
4450       if (CurrentOrder[I] != E)
4451         break;
4452       CurrentOrder[I] = I;
4453     }
4454   }
4455   if (I < E) {
4456     CurrentOrder.clear();
4457     return false;
4458   }
4459 
4460   return ShouldKeepOrder;
4461 }
4462 
4463 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4464                                     ArrayRef<Value *> VectorizedVals) const {
4465   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4466          all_of(I->users(), [this](User *U) {
4467            return ScalarToTreeEntry.count(U) > 0 || MustGather.contains(U);
4468          });
4469 }
4470 
4471 static std::pair<InstructionCost, InstructionCost>
4472 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4473                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4474   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4475 
4476   // Calculate the cost of the scalar and vector calls.
4477   SmallVector<Type *, 4> VecTys;
4478   for (Use &Arg : CI->args())
4479     VecTys.push_back(
4480         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4481   FastMathFlags FMF;
4482   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4483     FMF = FPCI->getFastMathFlags();
4484   SmallVector<const Value *> Arguments(CI->args());
4485   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4486                                     dyn_cast<IntrinsicInst>(CI));
4487   auto IntrinsicCost =
4488     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4489 
4490   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4491                                      VecTy->getNumElements())),
4492                             false /*HasGlobalPred*/);
4493   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4494   auto LibCost = IntrinsicCost;
4495   if (!CI->isNoBuiltin() && VecFunc) {
4496     // Calculate the cost of the vector library call.
4497     // If the corresponding vector call is cheaper, return its cost.
4498     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4499                                     TTI::TCK_RecipThroughput);
4500   }
4501   return {IntrinsicCost, LibCost};
4502 }
4503 
4504 /// Compute the cost of creating a vector of type \p VecTy containing the
4505 /// extracted values from \p VL.
4506 static InstructionCost
4507 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4508                    TargetTransformInfo::ShuffleKind ShuffleKind,
4509                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4510   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4511 
4512   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4513       VecTy->getNumElements() < NumOfParts)
4514     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4515 
4516   bool AllConsecutive = true;
4517   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4518   unsigned Idx = -1;
4519   InstructionCost Cost = 0;
4520 
4521   // Process extracts in blocks of EltsPerVector to check if the source vector
4522   // operand can be re-used directly. If not, add the cost of creating a shuffle
4523   // to extract the values into a vector register.
4524   for (auto *V : VL) {
4525     ++Idx;
4526 
4527     // Need to exclude undefs from analysis.
4528     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4529       continue;
4530 
4531     // Reached the start of a new vector registers.
4532     if (Idx % EltsPerVector == 0) {
4533       AllConsecutive = true;
4534       continue;
4535     }
4536 
4537     // Check all extracts for a vector register on the target directly
4538     // extract values in order.
4539     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4540     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4541       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4542       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4543                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4544     }
4545 
4546     if (AllConsecutive)
4547       continue;
4548 
4549     // Skip all indices, except for the last index per vector block.
4550     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4551       continue;
4552 
4553     // If we have a series of extracts which are not consecutive and hence
4554     // cannot re-use the source vector register directly, compute the shuffle
4555     // cost to extract the a vector with EltsPerVector elements.
4556     Cost += TTI.getShuffleCost(
4557         TargetTransformInfo::SK_PermuteSingleSrc,
4558         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4559   }
4560   return Cost;
4561 }
4562 
4563 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4564 /// operations operands.
4565 static void
4566 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4567                      ArrayRef<int> ReusesIndices,
4568                      const function_ref<bool(Instruction *)> IsAltOp,
4569                      SmallVectorImpl<int> &Mask,
4570                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4571                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4572   unsigned Sz = VL.size();
4573   Mask.assign(Sz, UndefMaskElem);
4574   SmallVector<int> OrderMask;
4575   if (!ReorderIndices.empty())
4576     inversePermutation(ReorderIndices, OrderMask);
4577   for (unsigned I = 0; I < Sz; ++I) {
4578     unsigned Idx = I;
4579     if (!ReorderIndices.empty())
4580       Idx = OrderMask[I];
4581     auto *OpInst = cast<Instruction>(VL[Idx]);
4582     if (IsAltOp(OpInst)) {
4583       Mask[I] = Sz + Idx;
4584       if (AltScalars)
4585         AltScalars->push_back(OpInst);
4586     } else {
4587       Mask[I] = Idx;
4588       if (OpScalars)
4589         OpScalars->push_back(OpInst);
4590     }
4591   }
4592   if (!ReusesIndices.empty()) {
4593     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4594     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4595       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4596     });
4597     Mask.swap(NewMask);
4598   }
4599 }
4600 
4601 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4602                                       ArrayRef<Value *> VectorizedVals) {
4603   ArrayRef<Value*> VL = E->Scalars;
4604 
4605   Type *ScalarTy = VL[0]->getType();
4606   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4607     ScalarTy = SI->getValueOperand()->getType();
4608   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4609     ScalarTy = CI->getOperand(0)->getType();
4610   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4611     ScalarTy = IE->getOperand(1)->getType();
4612   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4613   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4614 
4615   // If we have computed a smaller type for the expression, update VecTy so
4616   // that the costs will be accurate.
4617   if (MinBWs.count(VL[0]))
4618     VecTy = FixedVectorType::get(
4619         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4620   unsigned EntryVF = E->getVectorFactor();
4621   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4622 
4623   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4624   // FIXME: it tries to fix a problem with MSVC buildbots.
4625   TargetTransformInfo &TTIRef = *TTI;
4626   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4627                                VectorizedVals, E](InstructionCost &Cost) {
4628     DenseMap<Value *, int> ExtractVectorsTys;
4629     SmallPtrSet<Value *, 4> CheckedExtracts;
4630     for (auto *V : VL) {
4631       if (isa<UndefValue>(V))
4632         continue;
4633       // If all users of instruction are going to be vectorized and this
4634       // instruction itself is not going to be vectorized, consider this
4635       // instruction as dead and remove its cost from the final cost of the
4636       // vectorized tree.
4637       // Also, avoid adjusting the cost for extractelements with multiple uses
4638       // in different graph entries.
4639       const TreeEntry *VE = getTreeEntry(V);
4640       if (!CheckedExtracts.insert(V).second ||
4641           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4642           (VE && VE != E))
4643         continue;
4644       auto *EE = cast<ExtractElementInst>(V);
4645       Optional<unsigned> EEIdx = getExtractIndex(EE);
4646       if (!EEIdx)
4647         continue;
4648       unsigned Idx = *EEIdx;
4649       if (TTIRef.getNumberOfParts(VecTy) !=
4650           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4651         auto It =
4652             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4653         It->getSecond() = std::min<int>(It->second, Idx);
4654       }
4655       // Take credit for instruction that will become dead.
4656       if (EE->hasOneUse()) {
4657         Instruction *Ext = EE->user_back();
4658         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4659             all_of(Ext->users(),
4660                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4661           // Use getExtractWithExtendCost() to calculate the cost of
4662           // extractelement/ext pair.
4663           Cost -=
4664               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4665                                               EE->getVectorOperandType(), Idx);
4666           // Add back the cost of s|zext which is subtracted separately.
4667           Cost += TTIRef.getCastInstrCost(
4668               Ext->getOpcode(), Ext->getType(), EE->getType(),
4669               TTI::getCastContextHint(Ext), CostKind, Ext);
4670           continue;
4671         }
4672       }
4673       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4674                                         EE->getVectorOperandType(), Idx);
4675     }
4676     // Add a cost for subvector extracts/inserts if required.
4677     for (const auto &Data : ExtractVectorsTys) {
4678       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4679       unsigned NumElts = VecTy->getNumElements();
4680       if (Data.second % NumElts == 0)
4681         continue;
4682       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4683         unsigned Idx = (Data.second / NumElts) * NumElts;
4684         unsigned EENumElts = EEVTy->getNumElements();
4685         if (Idx + NumElts <= EENumElts) {
4686           Cost +=
4687               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4688                                     EEVTy, None, Idx, VecTy);
4689         } else {
4690           // Need to round up the subvector type vectorization factor to avoid a
4691           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4692           // <= EENumElts.
4693           auto *SubVT =
4694               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4695           Cost +=
4696               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4697                                     EEVTy, None, Idx, SubVT);
4698         }
4699       } else {
4700         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4701                                       VecTy, None, 0, EEVTy);
4702       }
4703     }
4704   };
4705   if (E->State == TreeEntry::NeedToGather) {
4706     if (allConstant(VL))
4707       return 0;
4708     if (isa<InsertElementInst>(VL[0]))
4709       return InstructionCost::getInvalid();
4710     SmallVector<int> Mask;
4711     SmallVector<const TreeEntry *> Entries;
4712     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4713         isGatherShuffledEntry(E, Mask, Entries);
4714     if (Shuffle.hasValue()) {
4715       InstructionCost GatherCost = 0;
4716       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4717         // Perfect match in the graph, will reuse the previously vectorized
4718         // node. Cost is 0.
4719         LLVM_DEBUG(
4720             dbgs()
4721             << "SLP: perfect diamond match for gather bundle that starts with "
4722             << *VL.front() << ".\n");
4723         if (NeedToShuffleReuses)
4724           GatherCost =
4725               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4726                                   FinalVecTy, E->ReuseShuffleIndices);
4727       } else {
4728         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4729                           << " entries for bundle that starts with "
4730                           << *VL.front() << ".\n");
4731         // Detected that instead of gather we can emit a shuffle of single/two
4732         // previously vectorized nodes. Add the cost of the permutation rather
4733         // than gather.
4734         ::addMask(Mask, E->ReuseShuffleIndices);
4735         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4736       }
4737       return GatherCost;
4738     }
4739     if ((E->getOpcode() == Instruction::ExtractElement ||
4740          all_of(E->Scalars,
4741                 [](Value *V) {
4742                   return isa<ExtractElementInst, UndefValue>(V);
4743                 })) &&
4744         allSameType(VL)) {
4745       // Check that gather of extractelements can be represented as just a
4746       // shuffle of a single/two vectors the scalars are extracted from.
4747       SmallVector<int> Mask;
4748       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4749           isFixedVectorShuffle(VL, Mask);
4750       if (ShuffleKind.hasValue()) {
4751         // Found the bunch of extractelement instructions that must be gathered
4752         // into a vector and can be represented as a permutation elements in a
4753         // single input vector or of 2 input vectors.
4754         InstructionCost Cost =
4755             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4756         AdjustExtractsCost(Cost);
4757         if (NeedToShuffleReuses)
4758           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4759                                       FinalVecTy, E->ReuseShuffleIndices);
4760         return Cost;
4761       }
4762     }
4763     if (isSplat(VL)) {
4764       // Found the broadcasting of the single scalar, calculate the cost as the
4765       // broadcast.
4766       assert(VecTy == FinalVecTy &&
4767              "No reused scalars expected for broadcast.");
4768       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4769     }
4770     InstructionCost ReuseShuffleCost = 0;
4771     if (NeedToShuffleReuses)
4772       ReuseShuffleCost = TTI->getShuffleCost(
4773           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4774     // Improve gather cost for gather of loads, if we can group some of the
4775     // loads into vector loads.
4776     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4777         !E->isAltShuffle()) {
4778       BoUpSLP::ValueSet VectorizedLoads;
4779       unsigned StartIdx = 0;
4780       unsigned VF = VL.size() / 2;
4781       unsigned VectorizedCnt = 0;
4782       unsigned ScatterVectorizeCnt = 0;
4783       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4784       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4785         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4786              Cnt += VF) {
4787           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4788           if (!VectorizedLoads.count(Slice.front()) &&
4789               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4790             SmallVector<Value *> PointerOps;
4791             OrdersType CurrentOrder;
4792             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4793                                               *SE, CurrentOrder, PointerOps);
4794             switch (LS) {
4795             case LoadsState::Vectorize:
4796             case LoadsState::ScatterVectorize:
4797               // Mark the vectorized loads so that we don't vectorize them
4798               // again.
4799               if (LS == LoadsState::Vectorize)
4800                 ++VectorizedCnt;
4801               else
4802                 ++ScatterVectorizeCnt;
4803               VectorizedLoads.insert(Slice.begin(), Slice.end());
4804               // If we vectorized initial block, no need to try to vectorize it
4805               // again.
4806               if (Cnt == StartIdx)
4807                 StartIdx += VF;
4808               break;
4809             case LoadsState::Gather:
4810               break;
4811             }
4812           }
4813         }
4814         // Check if the whole array was vectorized already - exit.
4815         if (StartIdx >= VL.size())
4816           break;
4817         // Found vectorizable parts - exit.
4818         if (!VectorizedLoads.empty())
4819           break;
4820       }
4821       if (!VectorizedLoads.empty()) {
4822         InstructionCost GatherCost = 0;
4823         unsigned NumParts = TTI->getNumberOfParts(VecTy);
4824         bool NeedInsertSubvectorAnalysis =
4825             !NumParts || (VL.size() / VF) > NumParts;
4826         // Get the cost for gathered loads.
4827         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4828           if (VectorizedLoads.contains(VL[I]))
4829             continue;
4830           GatherCost += getGatherCost(VL.slice(I, VF));
4831         }
4832         // The cost for vectorized loads.
4833         InstructionCost ScalarsCost = 0;
4834         for (Value *V : VectorizedLoads) {
4835           auto *LI = cast<LoadInst>(V);
4836           ScalarsCost += TTI->getMemoryOpCost(
4837               Instruction::Load, LI->getType(), LI->getAlign(),
4838               LI->getPointerAddressSpace(), CostKind, LI);
4839         }
4840         auto *LI = cast<LoadInst>(E->getMainOp());
4841         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4842         Align Alignment = LI->getAlign();
4843         GatherCost +=
4844             VectorizedCnt *
4845             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4846                                  LI->getPointerAddressSpace(), CostKind, LI);
4847         GatherCost += ScatterVectorizeCnt *
4848                       TTI->getGatherScatterOpCost(
4849                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4850                           /*VariableMask=*/false, Alignment, CostKind, LI);
4851         if (NeedInsertSubvectorAnalysis) {
4852           // Add the cost for the subvectors insert.
4853           for (int I = VF, E = VL.size(); I < E; I += VF)
4854             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
4855                                               None, I, LoadTy);
4856         }
4857         return ReuseShuffleCost + GatherCost - ScalarsCost;
4858       }
4859     }
4860     return ReuseShuffleCost + getGatherCost(VL);
4861   }
4862   InstructionCost CommonCost = 0;
4863   SmallVector<int> Mask;
4864   if (!E->ReorderIndices.empty()) {
4865     SmallVector<int> NewMask;
4866     if (E->getOpcode() == Instruction::Store) {
4867       // For stores the order is actually a mask.
4868       NewMask.resize(E->ReorderIndices.size());
4869       copy(E->ReorderIndices, NewMask.begin());
4870     } else {
4871       inversePermutation(E->ReorderIndices, NewMask);
4872     }
4873     ::addMask(Mask, NewMask);
4874   }
4875   if (NeedToShuffleReuses)
4876     ::addMask(Mask, E->ReuseShuffleIndices);
4877   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
4878     CommonCost =
4879         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
4880   assert((E->State == TreeEntry::Vectorize ||
4881           E->State == TreeEntry::ScatterVectorize) &&
4882          "Unhandled state");
4883   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
4884   Instruction *VL0 = E->getMainOp();
4885   unsigned ShuffleOrOp =
4886       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4887   switch (ShuffleOrOp) {
4888     case Instruction::PHI:
4889       return 0;
4890 
4891     case Instruction::ExtractValue:
4892     case Instruction::ExtractElement: {
4893       // The common cost of removal ExtractElement/ExtractValue instructions +
4894       // the cost of shuffles, if required to resuffle the original vector.
4895       if (NeedToShuffleReuses) {
4896         unsigned Idx = 0;
4897         for (unsigned I : E->ReuseShuffleIndices) {
4898           if (ShuffleOrOp == Instruction::ExtractElement) {
4899             auto *EE = cast<ExtractElementInst>(VL[I]);
4900             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4901                                                   EE->getVectorOperandType(),
4902                                                   *getExtractIndex(EE));
4903           } else {
4904             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4905                                                   VecTy, Idx);
4906             ++Idx;
4907           }
4908         }
4909         Idx = EntryVF;
4910         for (Value *V : VL) {
4911           if (ShuffleOrOp == Instruction::ExtractElement) {
4912             auto *EE = cast<ExtractElementInst>(V);
4913             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4914                                                   EE->getVectorOperandType(),
4915                                                   *getExtractIndex(EE));
4916           } else {
4917             --Idx;
4918             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4919                                                   VecTy, Idx);
4920           }
4921         }
4922       }
4923       if (ShuffleOrOp == Instruction::ExtractValue) {
4924         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
4925           auto *EI = cast<Instruction>(VL[I]);
4926           // Take credit for instruction that will become dead.
4927           if (EI->hasOneUse()) {
4928             Instruction *Ext = EI->user_back();
4929             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4930                 all_of(Ext->users(),
4931                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
4932               // Use getExtractWithExtendCost() to calculate the cost of
4933               // extractelement/ext pair.
4934               CommonCost -= TTI->getExtractWithExtendCost(
4935                   Ext->getOpcode(), Ext->getType(), VecTy, I);
4936               // Add back the cost of s|zext which is subtracted separately.
4937               CommonCost += TTI->getCastInstrCost(
4938                   Ext->getOpcode(), Ext->getType(), EI->getType(),
4939                   TTI::getCastContextHint(Ext), CostKind, Ext);
4940               continue;
4941             }
4942           }
4943           CommonCost -=
4944               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
4945         }
4946       } else {
4947         AdjustExtractsCost(CommonCost);
4948       }
4949       return CommonCost;
4950     }
4951     case Instruction::InsertElement: {
4952       assert(E->ReuseShuffleIndices.empty() &&
4953              "Unique insertelements only are expected.");
4954       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
4955 
4956       unsigned const NumElts = SrcVecTy->getNumElements();
4957       unsigned const NumScalars = VL.size();
4958       APInt DemandedElts = APInt::getZero(NumElts);
4959       // TODO: Add support for Instruction::InsertValue.
4960       SmallVector<int> Mask;
4961       if (!E->ReorderIndices.empty()) {
4962         inversePermutation(E->ReorderIndices, Mask);
4963         Mask.append(NumElts - NumScalars, UndefMaskElem);
4964       } else {
4965         Mask.assign(NumElts, UndefMaskElem);
4966         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
4967       }
4968       unsigned Offset = *getInsertIndex(VL0, 0);
4969       bool IsIdentity = true;
4970       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
4971       Mask.swap(PrevMask);
4972       for (unsigned I = 0; I < NumScalars; ++I) {
4973         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
4974         if (!InsertIdx || *InsertIdx == UndefMaskElem)
4975           continue;
4976         DemandedElts.setBit(*InsertIdx);
4977         IsIdentity &= *InsertIdx - Offset == I;
4978         Mask[*InsertIdx - Offset] = I;
4979       }
4980       assert(Offset < NumElts && "Failed to find vector index offset");
4981 
4982       InstructionCost Cost = 0;
4983       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
4984                                             /*Insert*/ true, /*Extract*/ false);
4985 
4986       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
4987         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
4988         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
4989         Cost += TTI->getShuffleCost(
4990             TargetTransformInfo::SK_PermuteSingleSrc,
4991             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
4992       } else if (!IsIdentity) {
4993         auto *FirstInsert =
4994             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
4995               return !is_contained(E->Scalars,
4996                                    cast<Instruction>(V)->getOperand(0));
4997             }));
4998         if (isUndefVector(FirstInsert->getOperand(0))) {
4999           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5000         } else {
5001           SmallVector<int> InsertMask(NumElts);
5002           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5003           for (unsigned I = 0; I < NumElts; I++) {
5004             if (Mask[I] != UndefMaskElem)
5005               InsertMask[Offset + I] = NumElts + I;
5006           }
5007           Cost +=
5008               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5009         }
5010       }
5011 
5012       return Cost;
5013     }
5014     case Instruction::ZExt:
5015     case Instruction::SExt:
5016     case Instruction::FPToUI:
5017     case Instruction::FPToSI:
5018     case Instruction::FPExt:
5019     case Instruction::PtrToInt:
5020     case Instruction::IntToPtr:
5021     case Instruction::SIToFP:
5022     case Instruction::UIToFP:
5023     case Instruction::Trunc:
5024     case Instruction::FPTrunc:
5025     case Instruction::BitCast: {
5026       Type *SrcTy = VL0->getOperand(0)->getType();
5027       InstructionCost ScalarEltCost =
5028           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5029                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5030       if (NeedToShuffleReuses) {
5031         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5032       }
5033 
5034       // Calculate the cost of this instruction.
5035       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5036 
5037       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5038       InstructionCost VecCost = 0;
5039       // Check if the values are candidates to demote.
5040       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5041         VecCost = CommonCost + TTI->getCastInstrCost(
5042                                    E->getOpcode(), VecTy, SrcVecTy,
5043                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5044       }
5045       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5046       return VecCost - ScalarCost;
5047     }
5048     case Instruction::FCmp:
5049     case Instruction::ICmp:
5050     case Instruction::Select: {
5051       // Calculate the cost of this instruction.
5052       InstructionCost ScalarEltCost =
5053           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5054                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5055       if (NeedToShuffleReuses) {
5056         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5057       }
5058       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5059       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5060 
5061       // Check if all entries in VL are either compares or selects with compares
5062       // as condition that have the same predicates.
5063       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5064       bool First = true;
5065       for (auto *V : VL) {
5066         CmpInst::Predicate CurrentPred;
5067         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5068         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5069              !match(V, MatchCmp)) ||
5070             (!First && VecPred != CurrentPred)) {
5071           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5072           break;
5073         }
5074         First = false;
5075         VecPred = CurrentPred;
5076       }
5077 
5078       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5079           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5080       // Check if it is possible and profitable to use min/max for selects in
5081       // VL.
5082       //
5083       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5084       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5085         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5086                                           {VecTy, VecTy});
5087         InstructionCost IntrinsicCost =
5088             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5089         // If the selects are the only uses of the compares, they will be dead
5090         // and we can adjust the cost by removing their cost.
5091         if (IntrinsicAndUse.second)
5092           IntrinsicCost -=
5093               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5094                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5095         VecCost = std::min(VecCost, IntrinsicCost);
5096       }
5097       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5098       return CommonCost + VecCost - ScalarCost;
5099     }
5100     case Instruction::FNeg:
5101     case Instruction::Add:
5102     case Instruction::FAdd:
5103     case Instruction::Sub:
5104     case Instruction::FSub:
5105     case Instruction::Mul:
5106     case Instruction::FMul:
5107     case Instruction::UDiv:
5108     case Instruction::SDiv:
5109     case Instruction::FDiv:
5110     case Instruction::URem:
5111     case Instruction::SRem:
5112     case Instruction::FRem:
5113     case Instruction::Shl:
5114     case Instruction::LShr:
5115     case Instruction::AShr:
5116     case Instruction::And:
5117     case Instruction::Or:
5118     case Instruction::Xor: {
5119       // Certain instructions can be cheaper to vectorize if they have a
5120       // constant second vector operand.
5121       TargetTransformInfo::OperandValueKind Op1VK =
5122           TargetTransformInfo::OK_AnyValue;
5123       TargetTransformInfo::OperandValueKind Op2VK =
5124           TargetTransformInfo::OK_UniformConstantValue;
5125       TargetTransformInfo::OperandValueProperties Op1VP =
5126           TargetTransformInfo::OP_None;
5127       TargetTransformInfo::OperandValueProperties Op2VP =
5128           TargetTransformInfo::OP_PowerOf2;
5129 
5130       // If all operands are exactly the same ConstantInt then set the
5131       // operand kind to OK_UniformConstantValue.
5132       // If instead not all operands are constants, then set the operand kind
5133       // to OK_AnyValue. If all operands are constants but not the same,
5134       // then set the operand kind to OK_NonUniformConstantValue.
5135       ConstantInt *CInt0 = nullptr;
5136       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5137         const Instruction *I = cast<Instruction>(VL[i]);
5138         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5139         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5140         if (!CInt) {
5141           Op2VK = TargetTransformInfo::OK_AnyValue;
5142           Op2VP = TargetTransformInfo::OP_None;
5143           break;
5144         }
5145         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5146             !CInt->getValue().isPowerOf2())
5147           Op2VP = TargetTransformInfo::OP_None;
5148         if (i == 0) {
5149           CInt0 = CInt;
5150           continue;
5151         }
5152         if (CInt0 != CInt)
5153           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5154       }
5155 
5156       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5157       InstructionCost ScalarEltCost =
5158           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5159                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5160       if (NeedToShuffleReuses) {
5161         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5162       }
5163       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5164       InstructionCost VecCost =
5165           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5166                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5167       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5168       return CommonCost + VecCost - ScalarCost;
5169     }
5170     case Instruction::GetElementPtr: {
5171       TargetTransformInfo::OperandValueKind Op1VK =
5172           TargetTransformInfo::OK_AnyValue;
5173       TargetTransformInfo::OperandValueKind Op2VK =
5174           TargetTransformInfo::OK_UniformConstantValue;
5175 
5176       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5177           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5178       if (NeedToShuffleReuses) {
5179         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5180       }
5181       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5182       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5183           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5184       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5185       return CommonCost + VecCost - ScalarCost;
5186     }
5187     case Instruction::Load: {
5188       // Cost of wide load - cost of scalar loads.
5189       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5190       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5191           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5192       if (NeedToShuffleReuses) {
5193         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5194       }
5195       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5196       InstructionCost VecLdCost;
5197       if (E->State == TreeEntry::Vectorize) {
5198         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5199                                          CostKind, VL0);
5200       } else {
5201         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5202         Align CommonAlignment = Alignment;
5203         for (Value *V : VL)
5204           CommonAlignment =
5205               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5206         VecLdCost = TTI->getGatherScatterOpCost(
5207             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5208             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5209       }
5210       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5211       return CommonCost + VecLdCost - ScalarLdCost;
5212     }
5213     case Instruction::Store: {
5214       // We know that we can merge the stores. Calculate the cost.
5215       bool IsReorder = !E->ReorderIndices.empty();
5216       auto *SI =
5217           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5218       Align Alignment = SI->getAlign();
5219       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5220           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5221       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5222       InstructionCost VecStCost = TTI->getMemoryOpCost(
5223           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5224       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5225       return CommonCost + VecStCost - ScalarStCost;
5226     }
5227     case Instruction::Call: {
5228       CallInst *CI = cast<CallInst>(VL0);
5229       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5230 
5231       // Calculate the cost of the scalar and vector calls.
5232       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5233       InstructionCost ScalarEltCost =
5234           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5235       if (NeedToShuffleReuses) {
5236         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5237       }
5238       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5239 
5240       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5241       InstructionCost VecCallCost =
5242           std::min(VecCallCosts.first, VecCallCosts.second);
5243 
5244       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5245                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5246                         << " for " << *CI << "\n");
5247 
5248       return CommonCost + VecCallCost - ScalarCallCost;
5249     }
5250     case Instruction::ShuffleVector: {
5251       assert(E->isAltShuffle() &&
5252              ((Instruction::isBinaryOp(E->getOpcode()) &&
5253                Instruction::isBinaryOp(E->getAltOpcode())) ||
5254               (Instruction::isCast(E->getOpcode()) &&
5255                Instruction::isCast(E->getAltOpcode()))) &&
5256              "Invalid Shuffle Vector Operand");
5257       InstructionCost ScalarCost = 0;
5258       if (NeedToShuffleReuses) {
5259         for (unsigned Idx : E->ReuseShuffleIndices) {
5260           Instruction *I = cast<Instruction>(VL[Idx]);
5261           CommonCost -= TTI->getInstructionCost(I, CostKind);
5262         }
5263         for (Value *V : VL) {
5264           Instruction *I = cast<Instruction>(V);
5265           CommonCost += TTI->getInstructionCost(I, CostKind);
5266         }
5267       }
5268       for (Value *V : VL) {
5269         Instruction *I = cast<Instruction>(V);
5270         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5271         ScalarCost += TTI->getInstructionCost(I, CostKind);
5272       }
5273       // VecCost is equal to sum of the cost of creating 2 vectors
5274       // and the cost of creating shuffle.
5275       InstructionCost VecCost = 0;
5276       // Try to find the previous shuffle node with the same operands and same
5277       // main/alternate ops.
5278       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5279         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5280           if (TE.get() == E)
5281             break;
5282           if (TE->isAltShuffle() &&
5283               ((TE->getOpcode() == E->getOpcode() &&
5284                 TE->getAltOpcode() == E->getAltOpcode()) ||
5285                (TE->getOpcode() == E->getAltOpcode() &&
5286                 TE->getAltOpcode() == E->getOpcode())) &&
5287               TE->hasEqualOperands(*E))
5288             return true;
5289         }
5290         return false;
5291       };
5292       if (TryFindNodeWithEqualOperands()) {
5293         LLVM_DEBUG({
5294           dbgs() << "SLP: diamond match for alternate node found.\n";
5295           E->dump();
5296         });
5297         // No need to add new vector costs here since we're going to reuse
5298         // same main/alternate vector ops, just do different shuffling.
5299       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5300         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5301         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5302                                                CostKind);
5303       } else {
5304         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5305         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5306         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5307         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5308         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5309                                         TTI::CastContextHint::None, CostKind);
5310         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5311                                          TTI::CastContextHint::None, CostKind);
5312       }
5313 
5314       SmallVector<int> Mask;
5315       buildSuffleEntryMask(
5316           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5317           [E](Instruction *I) {
5318             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5319             return I->getOpcode() == E->getAltOpcode();
5320           },
5321           Mask);
5322       CommonCost =
5323           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5324       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5325       return CommonCost + VecCost - ScalarCost;
5326     }
5327     default:
5328       llvm_unreachable("Unknown instruction");
5329   }
5330 }
5331 
5332 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5333   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5334                     << VectorizableTree.size() << " is fully vectorizable .\n");
5335 
5336   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5337     SmallVector<int> Mask;
5338     return TE->State == TreeEntry::NeedToGather &&
5339            !any_of(TE->Scalars,
5340                    [this](Value *V) { return EphValues.contains(V); }) &&
5341            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5342             TE->Scalars.size() < Limit ||
5343             ((TE->getOpcode() == Instruction::ExtractElement ||
5344               all_of(TE->Scalars,
5345                      [](Value *V) {
5346                        return isa<ExtractElementInst, UndefValue>(V);
5347                      })) &&
5348              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5349             (TE->State == TreeEntry::NeedToGather &&
5350              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5351   };
5352 
5353   // We only handle trees of heights 1 and 2.
5354   if (VectorizableTree.size() == 1 &&
5355       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5356        (ForReduction &&
5357         AreVectorizableGathers(VectorizableTree[0].get(),
5358                                VectorizableTree[0]->Scalars.size()) &&
5359         VectorizableTree[0]->getVectorFactor() > 2)))
5360     return true;
5361 
5362   if (VectorizableTree.size() != 2)
5363     return false;
5364 
5365   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5366   // with the second gather nodes if they have less scalar operands rather than
5367   // the initial tree element (may be profitable to shuffle the second gather)
5368   // or they are extractelements, which form shuffle.
5369   SmallVector<int> Mask;
5370   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5371       AreVectorizableGathers(VectorizableTree[1].get(),
5372                              VectorizableTree[0]->Scalars.size()))
5373     return true;
5374 
5375   // Gathering cost would be too much for tiny trees.
5376   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5377       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5378        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5379     return false;
5380 
5381   return true;
5382 }
5383 
5384 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5385                                        TargetTransformInfo *TTI,
5386                                        bool MustMatchOrInst) {
5387   // Look past the root to find a source value. Arbitrarily follow the
5388   // path through operand 0 of any 'or'. Also, peek through optional
5389   // shift-left-by-multiple-of-8-bits.
5390   Value *ZextLoad = Root;
5391   const APInt *ShAmtC;
5392   bool FoundOr = false;
5393   while (!isa<ConstantExpr>(ZextLoad) &&
5394          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5395           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5396            ShAmtC->urem(8) == 0))) {
5397     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5398     ZextLoad = BinOp->getOperand(0);
5399     if (BinOp->getOpcode() == Instruction::Or)
5400       FoundOr = true;
5401   }
5402   // Check if the input is an extended load of the required or/shift expression.
5403   Value *Load;
5404   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5405       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5406     return false;
5407 
5408   // Require that the total load bit width is a legal integer type.
5409   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5410   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5411   Type *SrcTy = Load->getType();
5412   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5413   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5414     return false;
5415 
5416   // Everything matched - assume that we can fold the whole sequence using
5417   // load combining.
5418   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5419              << *(cast<Instruction>(Root)) << "\n");
5420 
5421   return true;
5422 }
5423 
5424 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5425   if (RdxKind != RecurKind::Or)
5426     return false;
5427 
5428   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5429   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5430   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5431                                     /* MatchOr */ false);
5432 }
5433 
5434 bool BoUpSLP::isLoadCombineCandidate() const {
5435   // Peek through a final sequence of stores and check if all operations are
5436   // likely to be load-combined.
5437   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5438   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5439     Value *X;
5440     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5441         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5442       return false;
5443   }
5444   return true;
5445 }
5446 
5447 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5448   // No need to vectorize inserts of gathered values.
5449   if (VectorizableTree.size() == 2 &&
5450       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5451       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5452     return true;
5453 
5454   // We can vectorize the tree if its size is greater than or equal to the
5455   // minimum size specified by the MinTreeSize command line option.
5456   if (VectorizableTree.size() >= MinTreeSize)
5457     return false;
5458 
5459   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5460   // can vectorize it if we can prove it fully vectorizable.
5461   if (isFullyVectorizableTinyTree(ForReduction))
5462     return false;
5463 
5464   assert(VectorizableTree.empty()
5465              ? ExternalUses.empty()
5466              : true && "We shouldn't have any external users");
5467 
5468   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5469   // vectorizable.
5470   return true;
5471 }
5472 
5473 InstructionCost BoUpSLP::getSpillCost() const {
5474   // Walk from the bottom of the tree to the top, tracking which values are
5475   // live. When we see a call instruction that is not part of our tree,
5476   // query TTI to see if there is a cost to keeping values live over it
5477   // (for example, if spills and fills are required).
5478   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5479   InstructionCost Cost = 0;
5480 
5481   SmallPtrSet<Instruction*, 4> LiveValues;
5482   Instruction *PrevInst = nullptr;
5483 
5484   // The entries in VectorizableTree are not necessarily ordered by their
5485   // position in basic blocks. Collect them and order them by dominance so later
5486   // instructions are guaranteed to be visited first. For instructions in
5487   // different basic blocks, we only scan to the beginning of the block, so
5488   // their order does not matter, as long as all instructions in a basic block
5489   // are grouped together. Using dominance ensures a deterministic order.
5490   SmallVector<Instruction *, 16> OrderedScalars;
5491   for (const auto &TEPtr : VectorizableTree) {
5492     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5493     if (!Inst)
5494       continue;
5495     OrderedScalars.push_back(Inst);
5496   }
5497   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5498     auto *NodeA = DT->getNode(A->getParent());
5499     auto *NodeB = DT->getNode(B->getParent());
5500     assert(NodeA && "Should only process reachable instructions");
5501     assert(NodeB && "Should only process reachable instructions");
5502     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5503            "Different nodes should have different DFS numbers");
5504     if (NodeA != NodeB)
5505       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5506     return B->comesBefore(A);
5507   });
5508 
5509   for (Instruction *Inst : OrderedScalars) {
5510     if (!PrevInst) {
5511       PrevInst = Inst;
5512       continue;
5513     }
5514 
5515     // Update LiveValues.
5516     LiveValues.erase(PrevInst);
5517     for (auto &J : PrevInst->operands()) {
5518       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5519         LiveValues.insert(cast<Instruction>(&*J));
5520     }
5521 
5522     LLVM_DEBUG({
5523       dbgs() << "SLP: #LV: " << LiveValues.size();
5524       for (auto *X : LiveValues)
5525         dbgs() << " " << X->getName();
5526       dbgs() << ", Looking at ";
5527       Inst->dump();
5528     });
5529 
5530     // Now find the sequence of instructions between PrevInst and Inst.
5531     unsigned NumCalls = 0;
5532     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5533                                  PrevInstIt =
5534                                      PrevInst->getIterator().getReverse();
5535     while (InstIt != PrevInstIt) {
5536       if (PrevInstIt == PrevInst->getParent()->rend()) {
5537         PrevInstIt = Inst->getParent()->rbegin();
5538         continue;
5539       }
5540 
5541       // Debug information does not impact spill cost.
5542       if ((isa<CallInst>(&*PrevInstIt) &&
5543            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5544           &*PrevInstIt != PrevInst)
5545         NumCalls++;
5546 
5547       ++PrevInstIt;
5548     }
5549 
5550     if (NumCalls) {
5551       SmallVector<Type*, 4> V;
5552       for (auto *II : LiveValues) {
5553         auto *ScalarTy = II->getType();
5554         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5555           ScalarTy = VectorTy->getElementType();
5556         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5557       }
5558       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5559     }
5560 
5561     PrevInst = Inst;
5562   }
5563 
5564   return Cost;
5565 }
5566 
5567 /// Check if two insertelement instructions are from the same buildvector.
5568 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5569                                             InsertElementInst *V) {
5570   // Instructions must be from the same basic blocks.
5571   if (VU->getParent() != V->getParent())
5572     return false;
5573   // Checks if 2 insertelements are from the same buildvector.
5574   if (VU->getType() != V->getType())
5575     return false;
5576   // Multiple used inserts are separate nodes.
5577   if (!VU->hasOneUse() && !V->hasOneUse())
5578     return false;
5579   auto *IE1 = VU;
5580   auto *IE2 = V;
5581   // Go through the vector operand of insertelement instructions trying to find
5582   // either VU as the original vector for IE2 or V as the original vector for
5583   // IE1.
5584   do {
5585     if (IE2 == VU || IE1 == V)
5586       return true;
5587     if (IE1) {
5588       if (IE1 != VU && !IE1->hasOneUse())
5589         IE1 = nullptr;
5590       else
5591         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5592     }
5593     if (IE2) {
5594       if (IE2 != V && !IE2->hasOneUse())
5595         IE2 = nullptr;
5596       else
5597         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5598     }
5599   } while (IE1 || IE2);
5600   return false;
5601 }
5602 
5603 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5604   InstructionCost Cost = 0;
5605   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5606                     << VectorizableTree.size() << ".\n");
5607 
5608   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5609 
5610   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5611     TreeEntry &TE = *VectorizableTree[I].get();
5612 
5613     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5614     Cost += C;
5615     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5616                       << " for bundle that starts with " << *TE.Scalars[0]
5617                       << ".\n"
5618                       << "SLP: Current total cost = " << Cost << "\n");
5619   }
5620 
5621   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5622   InstructionCost ExtractCost = 0;
5623   SmallVector<unsigned> VF;
5624   SmallVector<SmallVector<int>> ShuffleMask;
5625   SmallVector<Value *> FirstUsers;
5626   SmallVector<APInt> DemandedElts;
5627   for (ExternalUser &EU : ExternalUses) {
5628     // We only add extract cost once for the same scalar.
5629     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5630         !ExtractCostCalculated.insert(EU.Scalar).second)
5631       continue;
5632 
5633     // Uses by ephemeral values are free (because the ephemeral value will be
5634     // removed prior to code generation, and so the extraction will be
5635     // removed as well).
5636     if (EphValues.count(EU.User))
5637       continue;
5638 
5639     // No extract cost for vector "scalar"
5640     if (isa<FixedVectorType>(EU.Scalar->getType()))
5641       continue;
5642 
5643     // Already counted the cost for external uses when tried to adjust the cost
5644     // for extractelements, no need to add it again.
5645     if (isa<ExtractElementInst>(EU.Scalar))
5646       continue;
5647 
5648     // If found user is an insertelement, do not calculate extract cost but try
5649     // to detect it as a final shuffled/identity match.
5650     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5651       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5652         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5653         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5654           continue;
5655         auto *It = find_if(FirstUsers, [VU](Value *V) {
5656           return areTwoInsertFromSameBuildVector(VU,
5657                                                  cast<InsertElementInst>(V));
5658         });
5659         int VecId = -1;
5660         if (It == FirstUsers.end()) {
5661           VF.push_back(FTy->getNumElements());
5662           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5663           // Find the insertvector, vectorized in tree, if any.
5664           Value *Base = VU;
5665           while (isa<InsertElementInst>(Base)) {
5666             // Build the mask for the vectorized insertelement instructions.
5667             if (const TreeEntry *E = getTreeEntry(Base)) {
5668               VU = cast<InsertElementInst>(Base);
5669               do {
5670                 int Idx = E->findLaneForValue(Base);
5671                 ShuffleMask.back()[Idx] = Idx;
5672                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5673               } while (E == getTreeEntry(Base));
5674               break;
5675             }
5676             Base = cast<InsertElementInst>(Base)->getOperand(0);
5677           }
5678           FirstUsers.push_back(VU);
5679           DemandedElts.push_back(APInt::getZero(VF.back()));
5680           VecId = FirstUsers.size() - 1;
5681         } else {
5682           VecId = std::distance(FirstUsers.begin(), It);
5683         }
5684         int Idx = *InsertIdx;
5685         ShuffleMask[VecId][Idx] = EU.Lane;
5686         DemandedElts[VecId].setBit(Idx);
5687         continue;
5688       }
5689     }
5690 
5691     // If we plan to rewrite the tree in a smaller type, we will need to sign
5692     // extend the extracted value back to the original type. Here, we account
5693     // for the extract and the added cost of the sign extend if needed.
5694     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5695     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5696     if (MinBWs.count(ScalarRoot)) {
5697       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5698       auto Extend =
5699           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5700       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5701       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5702                                                    VecTy, EU.Lane);
5703     } else {
5704       ExtractCost +=
5705           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5706     }
5707   }
5708 
5709   InstructionCost SpillCost = getSpillCost();
5710   Cost += SpillCost + ExtractCost;
5711   if (FirstUsers.size() == 1) {
5712     int Limit = ShuffleMask.front().size() * 2;
5713     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5714         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5715       InstructionCost C = TTI->getShuffleCost(
5716           TTI::SK_PermuteSingleSrc,
5717           cast<FixedVectorType>(FirstUsers.front()->getType()),
5718           ShuffleMask.front());
5719       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5720                         << " for final shuffle of insertelement external users "
5721                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5722                         << "SLP: Current total cost = " << Cost << "\n");
5723       Cost += C;
5724     }
5725     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5726         cast<FixedVectorType>(FirstUsers.front()->getType()),
5727         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5728     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5729                       << " for insertelements gather.\n"
5730                       << "SLP: Current total cost = " << Cost << "\n");
5731     Cost -= InsertCost;
5732   } else if (FirstUsers.size() >= 2) {
5733     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5734     // Combined masks of the first 2 vectors.
5735     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5736     copy(ShuffleMask.front(), CombinedMask.begin());
5737     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5738     auto *VecTy = FixedVectorType::get(
5739         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5740         MaxVF);
5741     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5742       if (ShuffleMask[1][I] != UndefMaskElem) {
5743         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5744         CombinedDemandedElts.setBit(I);
5745       }
5746     }
5747     InstructionCost C =
5748         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5749     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5750                       << " for final shuffle of vector node and external "
5751                          "insertelement users "
5752                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5753                       << "SLP: Current total cost = " << Cost << "\n");
5754     Cost += C;
5755     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5756         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5757     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5758                       << " for insertelements gather.\n"
5759                       << "SLP: Current total cost = " << Cost << "\n");
5760     Cost -= InsertCost;
5761     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5762       // Other elements - permutation of 2 vectors (the initial one and the
5763       // next Ith incoming vector).
5764       unsigned VF = ShuffleMask[I].size();
5765       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5766         int Mask = ShuffleMask[I][Idx];
5767         if (Mask != UndefMaskElem)
5768           CombinedMask[Idx] = MaxVF + Mask;
5769         else if (CombinedMask[Idx] != UndefMaskElem)
5770           CombinedMask[Idx] = Idx;
5771       }
5772       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5773         if (CombinedMask[Idx] != UndefMaskElem)
5774           CombinedMask[Idx] = Idx;
5775       InstructionCost C =
5776           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5777       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5778                         << " for final shuffle of vector node and external "
5779                            "insertelement users "
5780                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5781                         << "SLP: Current total cost = " << Cost << "\n");
5782       Cost += C;
5783       InstructionCost InsertCost = TTI->getScalarizationOverhead(
5784           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5785           /*Insert*/ true, /*Extract*/ false);
5786       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5787                         << " for insertelements gather.\n"
5788                         << "SLP: Current total cost = " << Cost << "\n");
5789       Cost -= InsertCost;
5790     }
5791   }
5792 
5793 #ifndef NDEBUG
5794   SmallString<256> Str;
5795   {
5796     raw_svector_ostream OS(Str);
5797     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5798        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5799        << "SLP: Total Cost = " << Cost << ".\n";
5800   }
5801   LLVM_DEBUG(dbgs() << Str);
5802   if (ViewSLPTree)
5803     ViewGraph(this, "SLP" + F->getName(), false, Str);
5804 #endif
5805 
5806   return Cost;
5807 }
5808 
5809 Optional<TargetTransformInfo::ShuffleKind>
5810 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5811                                SmallVectorImpl<const TreeEntry *> &Entries) {
5812   // TODO: currently checking only for Scalars in the tree entry, need to count
5813   // reused elements too for better cost estimation.
5814   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5815   Entries.clear();
5816   // Build a lists of values to tree entries.
5817   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5818   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5819     if (EntryPtr.get() == TE)
5820       break;
5821     if (EntryPtr->State != TreeEntry::NeedToGather)
5822       continue;
5823     for (Value *V : EntryPtr->Scalars)
5824       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5825   }
5826   // Find all tree entries used by the gathered values. If no common entries
5827   // found - not a shuffle.
5828   // Here we build a set of tree nodes for each gathered value and trying to
5829   // find the intersection between these sets. If we have at least one common
5830   // tree node for each gathered value - we have just a permutation of the
5831   // single vector. If we have 2 different sets, we're in situation where we
5832   // have a permutation of 2 input vectors.
5833   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5834   DenseMap<Value *, int> UsedValuesEntry;
5835   for (Value *V : TE->Scalars) {
5836     if (isa<UndefValue>(V))
5837       continue;
5838     // Build a list of tree entries where V is used.
5839     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5840     auto It = ValueToTEs.find(V);
5841     if (It != ValueToTEs.end())
5842       VToTEs = It->second;
5843     if (const TreeEntry *VTE = getTreeEntry(V))
5844       VToTEs.insert(VTE);
5845     if (VToTEs.empty())
5846       return None;
5847     if (UsedTEs.empty()) {
5848       // The first iteration, just insert the list of nodes to vector.
5849       UsedTEs.push_back(VToTEs);
5850     } else {
5851       // Need to check if there are any previously used tree nodes which use V.
5852       // If there are no such nodes, consider that we have another one input
5853       // vector.
5854       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
5855       unsigned Idx = 0;
5856       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
5857         // Do we have a non-empty intersection of previously listed tree entries
5858         // and tree entries using current V?
5859         set_intersect(VToTEs, Set);
5860         if (!VToTEs.empty()) {
5861           // Yes, write the new subset and continue analysis for the next
5862           // scalar.
5863           Set.swap(VToTEs);
5864           break;
5865         }
5866         VToTEs = SavedVToTEs;
5867         ++Idx;
5868       }
5869       // No non-empty intersection found - need to add a second set of possible
5870       // source vectors.
5871       if (Idx == UsedTEs.size()) {
5872         // If the number of input vectors is greater than 2 - not a permutation,
5873         // fallback to the regular gather.
5874         if (UsedTEs.size() == 2)
5875           return None;
5876         UsedTEs.push_back(SavedVToTEs);
5877         Idx = UsedTEs.size() - 1;
5878       }
5879       UsedValuesEntry.try_emplace(V, Idx);
5880     }
5881   }
5882 
5883   unsigned VF = 0;
5884   if (UsedTEs.size() == 1) {
5885     // Try to find the perfect match in another gather node at first.
5886     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
5887       return EntryPtr->isSame(TE->Scalars);
5888     });
5889     if (It != UsedTEs.front().end()) {
5890       Entries.push_back(*It);
5891       std::iota(Mask.begin(), Mask.end(), 0);
5892       return TargetTransformInfo::SK_PermuteSingleSrc;
5893     }
5894     // No perfect match, just shuffle, so choose the first tree node.
5895     Entries.push_back(*UsedTEs.front().begin());
5896   } else {
5897     // Try to find nodes with the same vector factor.
5898     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
5899     DenseMap<int, const TreeEntry *> VFToTE;
5900     for (const TreeEntry *TE : UsedTEs.front())
5901       VFToTE.try_emplace(TE->getVectorFactor(), TE);
5902     for (const TreeEntry *TE : UsedTEs.back()) {
5903       auto It = VFToTE.find(TE->getVectorFactor());
5904       if (It != VFToTE.end()) {
5905         VF = It->first;
5906         Entries.push_back(It->second);
5907         Entries.push_back(TE);
5908         break;
5909       }
5910     }
5911     // No 2 source vectors with the same vector factor - give up and do regular
5912     // gather.
5913     if (Entries.empty())
5914       return None;
5915   }
5916 
5917   // Build a shuffle mask for better cost estimation and vector emission.
5918   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
5919     Value *V = TE->Scalars[I];
5920     if (isa<UndefValue>(V))
5921       continue;
5922     unsigned Idx = UsedValuesEntry.lookup(V);
5923     const TreeEntry *VTE = Entries[Idx];
5924     int FoundLane = VTE->findLaneForValue(V);
5925     Mask[I] = Idx * VF + FoundLane;
5926     // Extra check required by isSingleSourceMaskImpl function (called by
5927     // ShuffleVectorInst::isSingleSourceMask).
5928     if (Mask[I] >= 2 * E)
5929       return None;
5930   }
5931   switch (Entries.size()) {
5932   case 1:
5933     return TargetTransformInfo::SK_PermuteSingleSrc;
5934   case 2:
5935     return TargetTransformInfo::SK_PermuteTwoSrc;
5936   default:
5937     break;
5938   }
5939   return None;
5940 }
5941 
5942 InstructionCost
5943 BoUpSLP::getGatherCost(FixedVectorType *Ty,
5944                        const DenseSet<unsigned> &ShuffledIndices,
5945                        bool NeedToShuffle) const {
5946   unsigned NumElts = Ty->getNumElements();
5947   APInt DemandedElts = APInt::getZero(NumElts);
5948   for (unsigned I = 0; I < NumElts; ++I)
5949     if (!ShuffledIndices.count(I))
5950       DemandedElts.setBit(I);
5951   InstructionCost Cost =
5952       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
5953                                     /*Extract*/ false);
5954   if (NeedToShuffle)
5955     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
5956   return Cost;
5957 }
5958 
5959 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
5960   // Find the type of the operands in VL.
5961   Type *ScalarTy = VL[0]->getType();
5962   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5963     ScalarTy = SI->getValueOperand()->getType();
5964   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5965   bool DuplicateNonConst = false;
5966   // Find the cost of inserting/extracting values from the vector.
5967   // Check if the same elements are inserted several times and count them as
5968   // shuffle candidates.
5969   DenseSet<unsigned> ShuffledElements;
5970   DenseSet<Value *> UniqueElements;
5971   // Iterate in reverse order to consider insert elements with the high cost.
5972   for (unsigned I = VL.size(); I > 0; --I) {
5973     unsigned Idx = I - 1;
5974     // No need to shuffle duplicates for constants.
5975     if (isConstant(VL[Idx])) {
5976       ShuffledElements.insert(Idx);
5977       continue;
5978     }
5979     if (!UniqueElements.insert(VL[Idx]).second) {
5980       DuplicateNonConst = true;
5981       ShuffledElements.insert(Idx);
5982     }
5983   }
5984   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
5985 }
5986 
5987 // Perform operand reordering on the instructions in VL and return the reordered
5988 // operands in Left and Right.
5989 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
5990                                              SmallVectorImpl<Value *> &Left,
5991                                              SmallVectorImpl<Value *> &Right,
5992                                              const DataLayout &DL,
5993                                              ScalarEvolution &SE,
5994                                              const BoUpSLP &R) {
5995   if (VL.empty())
5996     return;
5997   VLOperands Ops(VL, DL, SE, R);
5998   // Reorder the operands in place.
5999   Ops.reorder();
6000   Left = Ops.getVL(0);
6001   Right = Ops.getVL(1);
6002 }
6003 
6004 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6005   // Get the basic block this bundle is in. All instructions in the bundle
6006   // should be in this block.
6007   auto *Front = E->getMainOp();
6008   auto *BB = Front->getParent();
6009   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6010     auto *I = cast<Instruction>(V);
6011     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6012   }));
6013 
6014   // The last instruction in the bundle in program order.
6015   Instruction *LastInst = nullptr;
6016 
6017   // Find the last instruction. The common case should be that BB has been
6018   // scheduled, and the last instruction is VL.back(). So we start with
6019   // VL.back() and iterate over schedule data until we reach the end of the
6020   // bundle. The end of the bundle is marked by null ScheduleData.
6021   if (BlocksSchedules.count(BB)) {
6022     auto *Bundle =
6023         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6024     if (Bundle && Bundle->isPartOfBundle())
6025       for (; Bundle; Bundle = Bundle->NextInBundle)
6026         if (Bundle->OpValue == Bundle->Inst)
6027           LastInst = Bundle->Inst;
6028   }
6029 
6030   // LastInst can still be null at this point if there's either not an entry
6031   // for BB in BlocksSchedules or there's no ScheduleData available for
6032   // VL.back(). This can be the case if buildTree_rec aborts for various
6033   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6034   // size is reached, etc.). ScheduleData is initialized in the scheduling
6035   // "dry-run".
6036   //
6037   // If this happens, we can still find the last instruction by brute force. We
6038   // iterate forwards from Front (inclusive) until we either see all
6039   // instructions in the bundle or reach the end of the block. If Front is the
6040   // last instruction in program order, LastInst will be set to Front, and we
6041   // will visit all the remaining instructions in the block.
6042   //
6043   // One of the reasons we exit early from buildTree_rec is to place an upper
6044   // bound on compile-time. Thus, taking an additional compile-time hit here is
6045   // not ideal. However, this should be exceedingly rare since it requires that
6046   // we both exit early from buildTree_rec and that the bundle be out-of-order
6047   // (causing us to iterate all the way to the end of the block).
6048   if (!LastInst) {
6049     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6050     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6051       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6052         LastInst = &I;
6053       if (Bundle.empty())
6054         break;
6055     }
6056   }
6057   assert(LastInst && "Failed to find last instruction in bundle");
6058 
6059   // Set the insertion point after the last instruction in the bundle. Set the
6060   // debug location to Front.
6061   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6062   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6063 }
6064 
6065 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6066   // List of instructions/lanes from current block and/or the blocks which are
6067   // part of the current loop. These instructions will be inserted at the end to
6068   // make it possible to optimize loops and hoist invariant instructions out of
6069   // the loops body with better chances for success.
6070   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6071   SmallSet<int, 4> PostponedIndices;
6072   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6073   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6074     SmallPtrSet<BasicBlock *, 4> Visited;
6075     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6076       InsertBB = InsertBB->getSinglePredecessor();
6077     return InsertBB && InsertBB == InstBB;
6078   };
6079   for (int I = 0, E = VL.size(); I < E; ++I) {
6080     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6081       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6082            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6083           PostponedIndices.insert(I).second)
6084         PostponedInsts.emplace_back(Inst, I);
6085   }
6086 
6087   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6088     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6089     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6090     if (!InsElt)
6091       return Vec;
6092     GatherShuffleSeq.insert(InsElt);
6093     CSEBlocks.insert(InsElt->getParent());
6094     // Add to our 'need-to-extract' list.
6095     if (TreeEntry *Entry = getTreeEntry(V)) {
6096       // Find which lane we need to extract.
6097       unsigned FoundLane = Entry->findLaneForValue(V);
6098       ExternalUses.emplace_back(V, InsElt, FoundLane);
6099     }
6100     return Vec;
6101   };
6102   Value *Val0 =
6103       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6104   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6105   Value *Vec = PoisonValue::get(VecTy);
6106   SmallVector<int> NonConsts;
6107   // Insert constant values at first.
6108   for (int I = 0, E = VL.size(); I < E; ++I) {
6109     if (PostponedIndices.contains(I))
6110       continue;
6111     if (!isConstant(VL[I])) {
6112       NonConsts.push_back(I);
6113       continue;
6114     }
6115     Vec = CreateInsertElement(Vec, VL[I], I);
6116   }
6117   // Insert non-constant values.
6118   for (int I : NonConsts)
6119     Vec = CreateInsertElement(Vec, VL[I], I);
6120   // Append instructions, which are/may be part of the loop, in the end to make
6121   // it possible to hoist non-loop-based instructions.
6122   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6123     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6124 
6125   return Vec;
6126 }
6127 
6128 namespace {
6129 /// Merges shuffle masks and emits final shuffle instruction, if required.
6130 class ShuffleInstructionBuilder {
6131   IRBuilderBase &Builder;
6132   const unsigned VF = 0;
6133   bool IsFinalized = false;
6134   SmallVector<int, 4> Mask;
6135   /// Holds all of the instructions that we gathered.
6136   SetVector<Instruction *> &GatherShuffleSeq;
6137   /// A list of blocks that we are going to CSE.
6138   SetVector<BasicBlock *> &CSEBlocks;
6139 
6140 public:
6141   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6142                             SetVector<Instruction *> &GatherShuffleSeq,
6143                             SetVector<BasicBlock *> &CSEBlocks)
6144       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6145         CSEBlocks(CSEBlocks) {}
6146 
6147   /// Adds a mask, inverting it before applying.
6148   void addInversedMask(ArrayRef<unsigned> SubMask) {
6149     if (SubMask.empty())
6150       return;
6151     SmallVector<int, 4> NewMask;
6152     inversePermutation(SubMask, NewMask);
6153     addMask(NewMask);
6154   }
6155 
6156   /// Functions adds masks, merging them into  single one.
6157   void addMask(ArrayRef<unsigned> SubMask) {
6158     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6159     addMask(NewMask);
6160   }
6161 
6162   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6163 
6164   Value *finalize(Value *V) {
6165     IsFinalized = true;
6166     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6167     if (VF == ValueVF && Mask.empty())
6168       return V;
6169     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6170     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6171     addMask(NormalizedMask);
6172 
6173     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6174       return V;
6175     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6176     if (auto *I = dyn_cast<Instruction>(Vec)) {
6177       GatherShuffleSeq.insert(I);
6178       CSEBlocks.insert(I->getParent());
6179     }
6180     return Vec;
6181   }
6182 
6183   ~ShuffleInstructionBuilder() {
6184     assert((IsFinalized || Mask.empty()) &&
6185            "Shuffle construction must be finalized.");
6186   }
6187 };
6188 } // namespace
6189 
6190 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6191   unsigned VF = VL.size();
6192   InstructionsState S = getSameOpcode(VL);
6193   if (S.getOpcode()) {
6194     if (TreeEntry *E = getTreeEntry(S.OpValue))
6195       if (E->isSame(VL)) {
6196         Value *V = vectorizeTree(E);
6197         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6198           if (!E->ReuseShuffleIndices.empty()) {
6199             // Reshuffle to get only unique values.
6200             // If some of the scalars are duplicated in the vectorization tree
6201             // entry, we do not vectorize them but instead generate a mask for
6202             // the reuses. But if there are several users of the same entry,
6203             // they may have different vectorization factors. This is especially
6204             // important for PHI nodes. In this case, we need to adapt the
6205             // resulting instruction for the user vectorization factor and have
6206             // to reshuffle it again to take only unique elements of the vector.
6207             // Without this code the function incorrectly returns reduced vector
6208             // instruction with the same elements, not with the unique ones.
6209 
6210             // block:
6211             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6212             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6213             // ... (use %2)
6214             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6215             // br %block
6216             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6217             SmallSet<int, 4> UsedIdxs;
6218             int Pos = 0;
6219             int Sz = VL.size();
6220             for (int Idx : E->ReuseShuffleIndices) {
6221               if (Idx != Sz && Idx != UndefMaskElem &&
6222                   UsedIdxs.insert(Idx).second)
6223                 UniqueIdxs[Idx] = Pos;
6224               ++Pos;
6225             }
6226             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6227                                             "less than original vector size.");
6228             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6229             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6230           } else {
6231             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6232                    "Expected vectorization factor less "
6233                    "than original vector size.");
6234             SmallVector<int> UniformMask(VF, 0);
6235             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6236             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6237           }
6238           if (auto *I = dyn_cast<Instruction>(V)) {
6239             GatherShuffleSeq.insert(I);
6240             CSEBlocks.insert(I->getParent());
6241           }
6242         }
6243         return V;
6244       }
6245   }
6246 
6247   // Check that every instruction appears once in this bundle.
6248   SmallVector<int> ReuseShuffleIndicies;
6249   SmallVector<Value *> UniqueValues;
6250   if (VL.size() > 2) {
6251     DenseMap<Value *, unsigned> UniquePositions;
6252     unsigned NumValues =
6253         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6254                                     return !isa<UndefValue>(V);
6255                                   }).base());
6256     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6257     int UniqueVals = 0;
6258     for (Value *V : VL.drop_back(VL.size() - VF)) {
6259       if (isa<UndefValue>(V)) {
6260         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6261         continue;
6262       }
6263       if (isConstant(V)) {
6264         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6265         UniqueValues.emplace_back(V);
6266         continue;
6267       }
6268       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6269       ReuseShuffleIndicies.emplace_back(Res.first->second);
6270       if (Res.second) {
6271         UniqueValues.emplace_back(V);
6272         ++UniqueVals;
6273       }
6274     }
6275     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6276       // Emit pure splat vector.
6277       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6278                                   UndefMaskElem);
6279     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6280       ReuseShuffleIndicies.clear();
6281       UniqueValues.clear();
6282       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6283     }
6284     UniqueValues.append(VF - UniqueValues.size(),
6285                         PoisonValue::get(VL[0]->getType()));
6286     VL = UniqueValues;
6287   }
6288 
6289   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6290                                            CSEBlocks);
6291   Value *Vec = gather(VL);
6292   if (!ReuseShuffleIndicies.empty()) {
6293     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6294     Vec = ShuffleBuilder.finalize(Vec);
6295   }
6296   return Vec;
6297 }
6298 
6299 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6300   IRBuilder<>::InsertPointGuard Guard(Builder);
6301 
6302   if (E->VectorizedValue) {
6303     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6304     return E->VectorizedValue;
6305   }
6306 
6307   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6308   unsigned VF = E->getVectorFactor();
6309   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6310                                            CSEBlocks);
6311   if (E->State == TreeEntry::NeedToGather) {
6312     if (E->getMainOp())
6313       setInsertPointAfterBundle(E);
6314     Value *Vec;
6315     SmallVector<int> Mask;
6316     SmallVector<const TreeEntry *> Entries;
6317     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6318         isGatherShuffledEntry(E, Mask, Entries);
6319     if (Shuffle.hasValue()) {
6320       assert((Entries.size() == 1 || Entries.size() == 2) &&
6321              "Expected shuffle of 1 or 2 entries.");
6322       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6323                                         Entries.back()->VectorizedValue, Mask);
6324       if (auto *I = dyn_cast<Instruction>(Vec)) {
6325         GatherShuffleSeq.insert(I);
6326         CSEBlocks.insert(I->getParent());
6327       }
6328     } else {
6329       Vec = gather(E->Scalars);
6330     }
6331     if (NeedToShuffleReuses) {
6332       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6333       Vec = ShuffleBuilder.finalize(Vec);
6334     }
6335     E->VectorizedValue = Vec;
6336     return Vec;
6337   }
6338 
6339   assert((E->State == TreeEntry::Vectorize ||
6340           E->State == TreeEntry::ScatterVectorize) &&
6341          "Unhandled state");
6342   unsigned ShuffleOrOp =
6343       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6344   Instruction *VL0 = E->getMainOp();
6345   Type *ScalarTy = VL0->getType();
6346   if (auto *Store = dyn_cast<StoreInst>(VL0))
6347     ScalarTy = Store->getValueOperand()->getType();
6348   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6349     ScalarTy = IE->getOperand(1)->getType();
6350   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6351   switch (ShuffleOrOp) {
6352     case Instruction::PHI: {
6353       assert(
6354           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6355           "PHI reordering is free.");
6356       auto *PH = cast<PHINode>(VL0);
6357       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6358       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6359       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6360       Value *V = NewPhi;
6361       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6362       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6363       V = ShuffleBuilder.finalize(V);
6364 
6365       E->VectorizedValue = V;
6366 
6367       // PHINodes may have multiple entries from the same block. We want to
6368       // visit every block once.
6369       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6370 
6371       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6372         ValueList Operands;
6373         BasicBlock *IBB = PH->getIncomingBlock(i);
6374 
6375         if (!VisitedBBs.insert(IBB).second) {
6376           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6377           continue;
6378         }
6379 
6380         Builder.SetInsertPoint(IBB->getTerminator());
6381         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6382         Value *Vec = vectorizeTree(E->getOperand(i));
6383         NewPhi->addIncoming(Vec, IBB);
6384       }
6385 
6386       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6387              "Invalid number of incoming values");
6388       return V;
6389     }
6390 
6391     case Instruction::ExtractElement: {
6392       Value *V = E->getSingleOperand(0);
6393       Builder.SetInsertPoint(VL0);
6394       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6395       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6396       V = ShuffleBuilder.finalize(V);
6397       E->VectorizedValue = V;
6398       return V;
6399     }
6400     case Instruction::ExtractValue: {
6401       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6402       Builder.SetInsertPoint(LI);
6403       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6404       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6405       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6406       Value *NewV = propagateMetadata(V, E->Scalars);
6407       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6408       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6409       NewV = ShuffleBuilder.finalize(NewV);
6410       E->VectorizedValue = NewV;
6411       return NewV;
6412     }
6413     case Instruction::InsertElement: {
6414       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6415       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6416       Value *V = vectorizeTree(E->getOperand(1));
6417 
6418       // Create InsertVector shuffle if necessary
6419       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6420         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6421       }));
6422       const unsigned NumElts =
6423           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6424       const unsigned NumScalars = E->Scalars.size();
6425 
6426       unsigned Offset = *getInsertIndex(VL0, 0);
6427       assert(Offset < NumElts && "Failed to find vector index offset");
6428 
6429       // Create shuffle to resize vector
6430       SmallVector<int> Mask;
6431       if (!E->ReorderIndices.empty()) {
6432         inversePermutation(E->ReorderIndices, Mask);
6433         Mask.append(NumElts - NumScalars, UndefMaskElem);
6434       } else {
6435         Mask.assign(NumElts, UndefMaskElem);
6436         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6437       }
6438       // Create InsertVector shuffle if necessary
6439       bool IsIdentity = true;
6440       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6441       Mask.swap(PrevMask);
6442       for (unsigned I = 0; I < NumScalars; ++I) {
6443         Value *Scalar = E->Scalars[PrevMask[I]];
6444         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6445         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6446           continue;
6447         IsIdentity &= *InsertIdx - Offset == I;
6448         Mask[*InsertIdx - Offset] = I;
6449       }
6450       if (!IsIdentity || NumElts != NumScalars) {
6451         V = Builder.CreateShuffleVector(V, Mask);
6452         if (auto *I = dyn_cast<Instruction>(V)) {
6453           GatherShuffleSeq.insert(I);
6454           CSEBlocks.insert(I->getParent());
6455         }
6456       }
6457 
6458       if ((!IsIdentity || Offset != 0 ||
6459            !isUndefVector(FirstInsert->getOperand(0))) &&
6460           NumElts != NumScalars) {
6461         SmallVector<int> InsertMask(NumElts);
6462         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6463         for (unsigned I = 0; I < NumElts; I++) {
6464           if (Mask[I] != UndefMaskElem)
6465             InsertMask[Offset + I] = NumElts + I;
6466         }
6467 
6468         V = Builder.CreateShuffleVector(
6469             FirstInsert->getOperand(0), V, InsertMask,
6470             cast<Instruction>(E->Scalars.back())->getName());
6471         if (auto *I = dyn_cast<Instruction>(V)) {
6472           GatherShuffleSeq.insert(I);
6473           CSEBlocks.insert(I->getParent());
6474         }
6475       }
6476 
6477       ++NumVectorInstructions;
6478       E->VectorizedValue = V;
6479       return V;
6480     }
6481     case Instruction::ZExt:
6482     case Instruction::SExt:
6483     case Instruction::FPToUI:
6484     case Instruction::FPToSI:
6485     case Instruction::FPExt:
6486     case Instruction::PtrToInt:
6487     case Instruction::IntToPtr:
6488     case Instruction::SIToFP:
6489     case Instruction::UIToFP:
6490     case Instruction::Trunc:
6491     case Instruction::FPTrunc:
6492     case Instruction::BitCast: {
6493       setInsertPointAfterBundle(E);
6494 
6495       Value *InVec = vectorizeTree(E->getOperand(0));
6496 
6497       if (E->VectorizedValue) {
6498         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6499         return E->VectorizedValue;
6500       }
6501 
6502       auto *CI = cast<CastInst>(VL0);
6503       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6504       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6505       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6506       V = ShuffleBuilder.finalize(V);
6507 
6508       E->VectorizedValue = V;
6509       ++NumVectorInstructions;
6510       return V;
6511     }
6512     case Instruction::FCmp:
6513     case Instruction::ICmp: {
6514       setInsertPointAfterBundle(E);
6515 
6516       Value *L = vectorizeTree(E->getOperand(0));
6517       Value *R = vectorizeTree(E->getOperand(1));
6518 
6519       if (E->VectorizedValue) {
6520         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6521         return E->VectorizedValue;
6522       }
6523 
6524       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6525       Value *V = Builder.CreateCmp(P0, L, R);
6526       propagateIRFlags(V, E->Scalars, VL0);
6527       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6528       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6529       V = ShuffleBuilder.finalize(V);
6530 
6531       E->VectorizedValue = V;
6532       ++NumVectorInstructions;
6533       return V;
6534     }
6535     case Instruction::Select: {
6536       setInsertPointAfterBundle(E);
6537 
6538       Value *Cond = vectorizeTree(E->getOperand(0));
6539       Value *True = vectorizeTree(E->getOperand(1));
6540       Value *False = vectorizeTree(E->getOperand(2));
6541 
6542       if (E->VectorizedValue) {
6543         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6544         return E->VectorizedValue;
6545       }
6546 
6547       Value *V = Builder.CreateSelect(Cond, True, False);
6548       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6549       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6550       V = ShuffleBuilder.finalize(V);
6551 
6552       E->VectorizedValue = V;
6553       ++NumVectorInstructions;
6554       return V;
6555     }
6556     case Instruction::FNeg: {
6557       setInsertPointAfterBundle(E);
6558 
6559       Value *Op = vectorizeTree(E->getOperand(0));
6560 
6561       if (E->VectorizedValue) {
6562         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6563         return E->VectorizedValue;
6564       }
6565 
6566       Value *V = Builder.CreateUnOp(
6567           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6568       propagateIRFlags(V, E->Scalars, VL0);
6569       if (auto *I = dyn_cast<Instruction>(V))
6570         V = propagateMetadata(I, E->Scalars);
6571 
6572       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6573       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6574       V = ShuffleBuilder.finalize(V);
6575 
6576       E->VectorizedValue = V;
6577       ++NumVectorInstructions;
6578 
6579       return V;
6580     }
6581     case Instruction::Add:
6582     case Instruction::FAdd:
6583     case Instruction::Sub:
6584     case Instruction::FSub:
6585     case Instruction::Mul:
6586     case Instruction::FMul:
6587     case Instruction::UDiv:
6588     case Instruction::SDiv:
6589     case Instruction::FDiv:
6590     case Instruction::URem:
6591     case Instruction::SRem:
6592     case Instruction::FRem:
6593     case Instruction::Shl:
6594     case Instruction::LShr:
6595     case Instruction::AShr:
6596     case Instruction::And:
6597     case Instruction::Or:
6598     case Instruction::Xor: {
6599       setInsertPointAfterBundle(E);
6600 
6601       Value *LHS = vectorizeTree(E->getOperand(0));
6602       Value *RHS = vectorizeTree(E->getOperand(1));
6603 
6604       if (E->VectorizedValue) {
6605         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6606         return E->VectorizedValue;
6607       }
6608 
6609       Value *V = Builder.CreateBinOp(
6610           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6611           RHS);
6612       propagateIRFlags(V, E->Scalars, VL0);
6613       if (auto *I = dyn_cast<Instruction>(V))
6614         V = propagateMetadata(I, E->Scalars);
6615 
6616       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6617       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6618       V = ShuffleBuilder.finalize(V);
6619 
6620       E->VectorizedValue = V;
6621       ++NumVectorInstructions;
6622 
6623       return V;
6624     }
6625     case Instruction::Load: {
6626       // Loads are inserted at the head of the tree because we don't want to
6627       // sink them all the way down past store instructions.
6628       setInsertPointAfterBundle(E);
6629 
6630       LoadInst *LI = cast<LoadInst>(VL0);
6631       Instruction *NewLI;
6632       unsigned AS = LI->getPointerAddressSpace();
6633       Value *PO = LI->getPointerOperand();
6634       if (E->State == TreeEntry::Vectorize) {
6635 
6636         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6637 
6638         // The pointer operand uses an in-tree scalar so we add the new BitCast
6639         // to ExternalUses list to make sure that an extract will be generated
6640         // in the future.
6641         if (TreeEntry *Entry = getTreeEntry(PO)) {
6642           // Find which lane we need to extract.
6643           unsigned FoundLane = Entry->findLaneForValue(PO);
6644           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6645         }
6646 
6647         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6648       } else {
6649         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6650         Value *VecPtr = vectorizeTree(E->getOperand(0));
6651         // Use the minimum alignment of the gathered loads.
6652         Align CommonAlignment = LI->getAlign();
6653         for (Value *V : E->Scalars)
6654           CommonAlignment =
6655               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6656         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6657       }
6658       Value *V = propagateMetadata(NewLI, E->Scalars);
6659 
6660       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6661       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6662       V = ShuffleBuilder.finalize(V);
6663       E->VectorizedValue = V;
6664       ++NumVectorInstructions;
6665       return V;
6666     }
6667     case Instruction::Store: {
6668       auto *SI = cast<StoreInst>(VL0);
6669       unsigned AS = SI->getPointerAddressSpace();
6670 
6671       setInsertPointAfterBundle(E);
6672 
6673       Value *VecValue = vectorizeTree(E->getOperand(0));
6674       ShuffleBuilder.addMask(E->ReorderIndices);
6675       VecValue = ShuffleBuilder.finalize(VecValue);
6676 
6677       Value *ScalarPtr = SI->getPointerOperand();
6678       Value *VecPtr = Builder.CreateBitCast(
6679           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6680       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6681                                                  SI->getAlign());
6682 
6683       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6684       // ExternalUses to make sure that an extract will be generated in the
6685       // future.
6686       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6687         // Find which lane we need to extract.
6688         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6689         ExternalUses.push_back(
6690             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6691       }
6692 
6693       Value *V = propagateMetadata(ST, E->Scalars);
6694 
6695       E->VectorizedValue = V;
6696       ++NumVectorInstructions;
6697       return V;
6698     }
6699     case Instruction::GetElementPtr: {
6700       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6701       setInsertPointAfterBundle(E);
6702 
6703       Value *Op0 = vectorizeTree(E->getOperand(0));
6704 
6705       SmallVector<Value *> OpVecs;
6706       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6707         Value *OpVec = vectorizeTree(E->getOperand(J));
6708         OpVecs.push_back(OpVec);
6709       }
6710 
6711       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6712       if (Instruction *I = dyn_cast<Instruction>(V))
6713         V = propagateMetadata(I, E->Scalars);
6714 
6715       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6716       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6717       V = ShuffleBuilder.finalize(V);
6718 
6719       E->VectorizedValue = V;
6720       ++NumVectorInstructions;
6721 
6722       return V;
6723     }
6724     case Instruction::Call: {
6725       CallInst *CI = cast<CallInst>(VL0);
6726       setInsertPointAfterBundle(E);
6727 
6728       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6729       if (Function *FI = CI->getCalledFunction())
6730         IID = FI->getIntrinsicID();
6731 
6732       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6733 
6734       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6735       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6736                           VecCallCosts.first <= VecCallCosts.second;
6737 
6738       Value *ScalarArg = nullptr;
6739       std::vector<Value *> OpVecs;
6740       SmallVector<Type *, 2> TysForDecl =
6741           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6742       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6743         ValueList OpVL;
6744         // Some intrinsics have scalar arguments. This argument should not be
6745         // vectorized.
6746         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6747           CallInst *CEI = cast<CallInst>(VL0);
6748           ScalarArg = CEI->getArgOperand(j);
6749           OpVecs.push_back(CEI->getArgOperand(j));
6750           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6751             TysForDecl.push_back(ScalarArg->getType());
6752           continue;
6753         }
6754 
6755         Value *OpVec = vectorizeTree(E->getOperand(j));
6756         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6757         OpVecs.push_back(OpVec);
6758       }
6759 
6760       Function *CF;
6761       if (!UseIntrinsic) {
6762         VFShape Shape =
6763             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6764                                   VecTy->getNumElements())),
6765                          false /*HasGlobalPred*/);
6766         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6767       } else {
6768         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6769       }
6770 
6771       SmallVector<OperandBundleDef, 1> OpBundles;
6772       CI->getOperandBundlesAsDefs(OpBundles);
6773       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6774 
6775       // The scalar argument uses an in-tree scalar so we add the new vectorized
6776       // call to ExternalUses list to make sure that an extract will be
6777       // generated in the future.
6778       if (ScalarArg) {
6779         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6780           // Find which lane we need to extract.
6781           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6782           ExternalUses.push_back(
6783               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6784         }
6785       }
6786 
6787       propagateIRFlags(V, E->Scalars, VL0);
6788       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6789       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6790       V = ShuffleBuilder.finalize(V);
6791 
6792       E->VectorizedValue = V;
6793       ++NumVectorInstructions;
6794       return V;
6795     }
6796     case Instruction::ShuffleVector: {
6797       assert(E->isAltShuffle() &&
6798              ((Instruction::isBinaryOp(E->getOpcode()) &&
6799                Instruction::isBinaryOp(E->getAltOpcode())) ||
6800               (Instruction::isCast(E->getOpcode()) &&
6801                Instruction::isCast(E->getAltOpcode()))) &&
6802              "Invalid Shuffle Vector Operand");
6803 
6804       Value *LHS = nullptr, *RHS = nullptr;
6805       if (Instruction::isBinaryOp(E->getOpcode())) {
6806         setInsertPointAfterBundle(E);
6807         LHS = vectorizeTree(E->getOperand(0));
6808         RHS = vectorizeTree(E->getOperand(1));
6809       } else {
6810         setInsertPointAfterBundle(E);
6811         LHS = vectorizeTree(E->getOperand(0));
6812       }
6813 
6814       if (E->VectorizedValue) {
6815         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6816         return E->VectorizedValue;
6817       }
6818 
6819       Value *V0, *V1;
6820       if (Instruction::isBinaryOp(E->getOpcode())) {
6821         V0 = Builder.CreateBinOp(
6822             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6823         V1 = Builder.CreateBinOp(
6824             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6825       } else {
6826         V0 = Builder.CreateCast(
6827             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6828         V1 = Builder.CreateCast(
6829             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6830       }
6831       // Add V0 and V1 to later analysis to try to find and remove matching
6832       // instruction, if any.
6833       for (Value *V : {V0, V1}) {
6834         if (auto *I = dyn_cast<Instruction>(V)) {
6835           GatherShuffleSeq.insert(I);
6836           CSEBlocks.insert(I->getParent());
6837         }
6838       }
6839 
6840       // Create shuffle to take alternate operations from the vector.
6841       // Also, gather up main and alt scalar ops to propagate IR flags to
6842       // each vector operation.
6843       ValueList OpScalars, AltScalars;
6844       SmallVector<int> Mask;
6845       buildSuffleEntryMask(
6846           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6847           [E](Instruction *I) {
6848             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6849             return I->getOpcode() == E->getAltOpcode();
6850           },
6851           Mask, &OpScalars, &AltScalars);
6852 
6853       propagateIRFlags(V0, OpScalars);
6854       propagateIRFlags(V1, AltScalars);
6855 
6856       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
6857       if (auto *I = dyn_cast<Instruction>(V)) {
6858         V = propagateMetadata(I, E->Scalars);
6859         GatherShuffleSeq.insert(I);
6860         CSEBlocks.insert(I->getParent());
6861       }
6862       V = ShuffleBuilder.finalize(V);
6863 
6864       E->VectorizedValue = V;
6865       ++NumVectorInstructions;
6866 
6867       return V;
6868     }
6869     default:
6870     llvm_unreachable("unknown inst");
6871   }
6872   return nullptr;
6873 }
6874 
6875 Value *BoUpSLP::vectorizeTree() {
6876   ExtraValueToDebugLocsMap ExternallyUsedValues;
6877   return vectorizeTree(ExternallyUsedValues);
6878 }
6879 
6880 Value *
6881 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
6882   // All blocks must be scheduled before any instructions are inserted.
6883   for (auto &BSIter : BlocksSchedules) {
6884     scheduleBlock(BSIter.second.get());
6885   }
6886 
6887   Builder.SetInsertPoint(&F->getEntryBlock().front());
6888   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
6889 
6890   // If the vectorized tree can be rewritten in a smaller type, we truncate the
6891   // vectorized root. InstCombine will then rewrite the entire expression. We
6892   // sign extend the extracted values below.
6893   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6894   if (MinBWs.count(ScalarRoot)) {
6895     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
6896       // If current instr is a phi and not the last phi, insert it after the
6897       // last phi node.
6898       if (isa<PHINode>(I))
6899         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
6900       else
6901         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
6902     }
6903     auto BundleWidth = VectorizableTree[0]->Scalars.size();
6904     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6905     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
6906     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
6907     VectorizableTree[0]->VectorizedValue = Trunc;
6908   }
6909 
6910   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
6911                     << " values .\n");
6912 
6913   // Extract all of the elements with the external uses.
6914   for (const auto &ExternalUse : ExternalUses) {
6915     Value *Scalar = ExternalUse.Scalar;
6916     llvm::User *User = ExternalUse.User;
6917 
6918     // Skip users that we already RAUW. This happens when one instruction
6919     // has multiple uses of the same value.
6920     if (User && !is_contained(Scalar->users(), User))
6921       continue;
6922     TreeEntry *E = getTreeEntry(Scalar);
6923     assert(E && "Invalid scalar");
6924     assert(E->State != TreeEntry::NeedToGather &&
6925            "Extracting from a gather list");
6926 
6927     Value *Vec = E->VectorizedValue;
6928     assert(Vec && "Can't find vectorizable value");
6929 
6930     Value *Lane = Builder.getInt32(ExternalUse.Lane);
6931     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
6932       if (Scalar->getType() != Vec->getType()) {
6933         Value *Ex;
6934         // "Reuse" the existing extract to improve final codegen.
6935         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
6936           Ex = Builder.CreateExtractElement(ES->getOperand(0),
6937                                             ES->getOperand(1));
6938         } else {
6939           Ex = Builder.CreateExtractElement(Vec, Lane);
6940         }
6941         // If necessary, sign-extend or zero-extend ScalarRoot
6942         // to the larger type.
6943         if (!MinBWs.count(ScalarRoot))
6944           return Ex;
6945         if (MinBWs[ScalarRoot].second)
6946           return Builder.CreateSExt(Ex, Scalar->getType());
6947         return Builder.CreateZExt(Ex, Scalar->getType());
6948       }
6949       assert(isa<FixedVectorType>(Scalar->getType()) &&
6950              isa<InsertElementInst>(Scalar) &&
6951              "In-tree scalar of vector type is not insertelement?");
6952       return Vec;
6953     };
6954     // If User == nullptr, the Scalar is used as extra arg. Generate
6955     // ExtractElement instruction and update the record for this scalar in
6956     // ExternallyUsedValues.
6957     if (!User) {
6958       assert(ExternallyUsedValues.count(Scalar) &&
6959              "Scalar with nullptr as an external user must be registered in "
6960              "ExternallyUsedValues map");
6961       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6962         Builder.SetInsertPoint(VecI->getParent(),
6963                                std::next(VecI->getIterator()));
6964       } else {
6965         Builder.SetInsertPoint(&F->getEntryBlock().front());
6966       }
6967       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6968       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
6969       auto &NewInstLocs = ExternallyUsedValues[NewInst];
6970       auto It = ExternallyUsedValues.find(Scalar);
6971       assert(It != ExternallyUsedValues.end() &&
6972              "Externally used scalar is not found in ExternallyUsedValues");
6973       NewInstLocs.append(It->second);
6974       ExternallyUsedValues.erase(Scalar);
6975       // Required to update internally referenced instructions.
6976       Scalar->replaceAllUsesWith(NewInst);
6977       continue;
6978     }
6979 
6980     // Generate extracts for out-of-tree users.
6981     // Find the insertion point for the extractelement lane.
6982     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6983       if (PHINode *PH = dyn_cast<PHINode>(User)) {
6984         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
6985           if (PH->getIncomingValue(i) == Scalar) {
6986             Instruction *IncomingTerminator =
6987                 PH->getIncomingBlock(i)->getTerminator();
6988             if (isa<CatchSwitchInst>(IncomingTerminator)) {
6989               Builder.SetInsertPoint(VecI->getParent(),
6990                                      std::next(VecI->getIterator()));
6991             } else {
6992               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
6993             }
6994             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6995             CSEBlocks.insert(PH->getIncomingBlock(i));
6996             PH->setOperand(i, NewInst);
6997           }
6998         }
6999       } else {
7000         Builder.SetInsertPoint(cast<Instruction>(User));
7001         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7002         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7003         User->replaceUsesOfWith(Scalar, NewInst);
7004       }
7005     } else {
7006       Builder.SetInsertPoint(&F->getEntryBlock().front());
7007       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7008       CSEBlocks.insert(&F->getEntryBlock());
7009       User->replaceUsesOfWith(Scalar, NewInst);
7010     }
7011 
7012     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7013   }
7014 
7015   // For each vectorized value:
7016   for (auto &TEPtr : VectorizableTree) {
7017     TreeEntry *Entry = TEPtr.get();
7018 
7019     // No need to handle users of gathered values.
7020     if (Entry->State == TreeEntry::NeedToGather)
7021       continue;
7022 
7023     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7024 
7025     // For each lane:
7026     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7027       Value *Scalar = Entry->Scalars[Lane];
7028 
7029 #ifndef NDEBUG
7030       Type *Ty = Scalar->getType();
7031       if (!Ty->isVoidTy()) {
7032         for (User *U : Scalar->users()) {
7033           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7034 
7035           // It is legal to delete users in the ignorelist.
7036           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7037                   (isa_and_nonnull<Instruction>(U) &&
7038                    isDeleted(cast<Instruction>(U)))) &&
7039                  "Deleting out-of-tree value");
7040         }
7041       }
7042 #endif
7043       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7044       eraseInstruction(cast<Instruction>(Scalar));
7045     }
7046   }
7047 
7048   Builder.ClearInsertionPoint();
7049   InstrElementSize.clear();
7050 
7051   return VectorizableTree[0]->VectorizedValue;
7052 }
7053 
7054 void BoUpSLP::optimizeGatherSequence() {
7055   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7056                     << " gather sequences instructions.\n");
7057   // LICM InsertElementInst sequences.
7058   for (Instruction *I : GatherShuffleSeq) {
7059     if (isDeleted(I))
7060       continue;
7061 
7062     // Check if this block is inside a loop.
7063     Loop *L = LI->getLoopFor(I->getParent());
7064     if (!L)
7065       continue;
7066 
7067     // Check if it has a preheader.
7068     BasicBlock *PreHeader = L->getLoopPreheader();
7069     if (!PreHeader)
7070       continue;
7071 
7072     // If the vector or the element that we insert into it are
7073     // instructions that are defined in this basic block then we can't
7074     // hoist this instruction.
7075     if (any_of(I->operands(), [L](Value *V) {
7076           auto *OpI = dyn_cast<Instruction>(V);
7077           return OpI && L->contains(OpI);
7078         }))
7079       continue;
7080 
7081     // We can hoist this instruction. Move it to the pre-header.
7082     I->moveBefore(PreHeader->getTerminator());
7083   }
7084 
7085   // Make a list of all reachable blocks in our CSE queue.
7086   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7087   CSEWorkList.reserve(CSEBlocks.size());
7088   for (BasicBlock *BB : CSEBlocks)
7089     if (DomTreeNode *N = DT->getNode(BB)) {
7090       assert(DT->isReachableFromEntry(N));
7091       CSEWorkList.push_back(N);
7092     }
7093 
7094   // Sort blocks by domination. This ensures we visit a block after all blocks
7095   // dominating it are visited.
7096   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7097     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7098            "Different nodes should have different DFS numbers");
7099     return A->getDFSNumIn() < B->getDFSNumIn();
7100   });
7101 
7102   // Less defined shuffles can be replaced by the more defined copies.
7103   // Between two shuffles one is less defined if it has the same vector operands
7104   // and its mask indeces are the same as in the first one or undefs. E.g.
7105   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7106   // poison, <0, 0, 0, 0>.
7107   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7108                                            SmallVectorImpl<int> &NewMask) {
7109     if (I1->getType() != I2->getType())
7110       return false;
7111     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7112     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7113     if (!SI1 || !SI2)
7114       return I1->isIdenticalTo(I2);
7115     if (SI1->isIdenticalTo(SI2))
7116       return true;
7117     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7118       if (SI1->getOperand(I) != SI2->getOperand(I))
7119         return false;
7120     // Check if the second instruction is more defined than the first one.
7121     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7122     ArrayRef<int> SM1 = SI1->getShuffleMask();
7123     // Count trailing undefs in the mask to check the final number of used
7124     // registers.
7125     unsigned LastUndefsCnt = 0;
7126     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7127       if (SM1[I] == UndefMaskElem)
7128         ++LastUndefsCnt;
7129       else
7130         LastUndefsCnt = 0;
7131       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7132           NewMask[I] != SM1[I])
7133         return false;
7134       if (NewMask[I] == UndefMaskElem)
7135         NewMask[I] = SM1[I];
7136     }
7137     // Check if the last undefs actually change the final number of used vector
7138     // registers.
7139     return SM1.size() - LastUndefsCnt > 1 &&
7140            TTI->getNumberOfParts(SI1->getType()) ==
7141                TTI->getNumberOfParts(
7142                    FixedVectorType::get(SI1->getType()->getElementType(),
7143                                         SM1.size() - LastUndefsCnt));
7144   };
7145   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7146   // instructions. TODO: We can further optimize this scan if we split the
7147   // instructions into different buckets based on the insert lane.
7148   SmallVector<Instruction *, 16> Visited;
7149   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7150     assert(*I &&
7151            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7152            "Worklist not sorted properly!");
7153     BasicBlock *BB = (*I)->getBlock();
7154     // For all instructions in blocks containing gather sequences:
7155     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7156       if (isDeleted(&In))
7157         continue;
7158       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7159           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7160         continue;
7161 
7162       // Check if we can replace this instruction with any of the
7163       // visited instructions.
7164       bool Replaced = false;
7165       for (Instruction *&V : Visited) {
7166         SmallVector<int> NewMask;
7167         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7168             DT->dominates(V->getParent(), In.getParent())) {
7169           In.replaceAllUsesWith(V);
7170           eraseInstruction(&In);
7171           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7172             if (!NewMask.empty())
7173               SI->setShuffleMask(NewMask);
7174           Replaced = true;
7175           break;
7176         }
7177         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7178             GatherShuffleSeq.contains(V) &&
7179             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7180             DT->dominates(In.getParent(), V->getParent())) {
7181           In.moveAfter(V);
7182           V->replaceAllUsesWith(&In);
7183           eraseInstruction(V);
7184           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7185             if (!NewMask.empty())
7186               SI->setShuffleMask(NewMask);
7187           V = &In;
7188           Replaced = true;
7189           break;
7190         }
7191       }
7192       if (!Replaced) {
7193         assert(!is_contained(Visited, &In));
7194         Visited.push_back(&In);
7195       }
7196     }
7197   }
7198   CSEBlocks.clear();
7199   GatherShuffleSeq.clear();
7200 }
7201 
7202 // Groups the instructions to a bundle (which is then a single scheduling entity)
7203 // and schedules instructions until the bundle gets ready.
7204 Optional<BoUpSLP::ScheduleData *>
7205 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7206                                             const InstructionsState &S) {
7207   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7208   // instructions.
7209   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7210     return nullptr;
7211 
7212   // Initialize the instruction bundle.
7213   Instruction *OldScheduleEnd = ScheduleEnd;
7214   ScheduleData *PrevInBundle = nullptr;
7215   ScheduleData *Bundle = nullptr;
7216   bool ReSchedule = false;
7217   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7218 
7219   auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule,
7220                                                          ScheduleData *Bundle) {
7221     // The scheduling region got new instructions at the lower end (or it is a
7222     // new region for the first bundle). This makes it necessary to
7223     // recalculate all dependencies.
7224     // It is seldom that this needs to be done a second time after adding the
7225     // initial bundle to the region.
7226     if (ScheduleEnd != OldScheduleEnd) {
7227       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7228         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7229       ReSchedule = true;
7230     }
7231     if (ReSchedule) {
7232       resetSchedule();
7233       initialFillReadyList(ReadyInsts);
7234     }
7235     if (Bundle) {
7236       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7237                         << " in block " << BB->getName() << "\n");
7238       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7239     }
7240 
7241     // Now try to schedule the new bundle or (if no bundle) just calculate
7242     // dependencies. As soon as the bundle is "ready" it means that there are no
7243     // cyclic dependencies and we can schedule it. Note that's important that we
7244     // don't "schedule" the bundle yet (see cancelScheduling).
7245     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7246            !ReadyInsts.empty()) {
7247       ScheduleData *Picked = ReadyInsts.pop_back_val();
7248       if (Picked->isSchedulingEntity() && Picked->isReady())
7249         schedule(Picked, ReadyInsts);
7250     }
7251   };
7252 
7253   // Make sure that the scheduling region contains all
7254   // instructions of the bundle.
7255   for (Value *V : VL) {
7256     if (!extendSchedulingRegion(V, S)) {
7257       // If the scheduling region got new instructions at the lower end (or it
7258       // is a new region for the first bundle). This makes it necessary to
7259       // recalculate all dependencies.
7260       // Otherwise the compiler may crash trying to incorrectly calculate
7261       // dependencies and emit instruction in the wrong order at the actual
7262       // scheduling.
7263       TryScheduleBundle(/*ReSchedule=*/false, nullptr);
7264       return None;
7265     }
7266   }
7267 
7268   for (Value *V : VL) {
7269     ScheduleData *BundleMember = getScheduleData(V);
7270     assert(BundleMember &&
7271            "no ScheduleData for bundle member (maybe not in same basic block)");
7272     if (BundleMember->IsScheduled) {
7273       // A bundle member was scheduled as single instruction before and now
7274       // needs to be scheduled as part of the bundle. We just get rid of the
7275       // existing schedule.
7276       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7277                         << " was already scheduled\n");
7278       ReSchedule = true;
7279     }
7280     assert(BundleMember->isSchedulingEntity() &&
7281            "bundle member already part of other bundle");
7282     if (PrevInBundle) {
7283       PrevInBundle->NextInBundle = BundleMember;
7284     } else {
7285       Bundle = BundleMember;
7286     }
7287     BundleMember->UnscheduledDepsInBundle = 0;
7288     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7289 
7290     // Group the instructions to a bundle.
7291     BundleMember->FirstInBundle = Bundle;
7292     PrevInBundle = BundleMember;
7293   }
7294   assert(Bundle && "Failed to find schedule bundle");
7295   TryScheduleBundle(ReSchedule, Bundle);
7296   if (!Bundle->isReady()) {
7297     cancelScheduling(VL, S.OpValue);
7298     return None;
7299   }
7300   return Bundle;
7301 }
7302 
7303 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7304                                                 Value *OpValue) {
7305   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7306     return;
7307 
7308   ScheduleData *Bundle = getScheduleData(OpValue);
7309   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7310   assert(!Bundle->IsScheduled &&
7311          "Can't cancel bundle which is already scheduled");
7312   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7313          "tried to unbundle something which is not a bundle");
7314 
7315   // Un-bundle: make single instructions out of the bundle.
7316   ScheduleData *BundleMember = Bundle;
7317   while (BundleMember) {
7318     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7319     BundleMember->FirstInBundle = BundleMember;
7320     ScheduleData *Next = BundleMember->NextInBundle;
7321     BundleMember->NextInBundle = nullptr;
7322     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7323     if (BundleMember->UnscheduledDepsInBundle == 0) {
7324       ReadyInsts.insert(BundleMember);
7325     }
7326     BundleMember = Next;
7327   }
7328 }
7329 
7330 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7331   // Allocate a new ScheduleData for the instruction.
7332   if (ChunkPos >= ChunkSize) {
7333     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7334     ChunkPos = 0;
7335   }
7336   return &(ScheduleDataChunks.back()[ChunkPos++]);
7337 }
7338 
7339 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7340                                                       const InstructionsState &S) {
7341   if (getScheduleData(V, isOneOf(S, V)))
7342     return true;
7343   Instruction *I = dyn_cast<Instruction>(V);
7344   assert(I && "bundle member must be an instruction");
7345   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7346          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7347          "be scheduled");
7348   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7349     ScheduleData *ISD = getScheduleData(I);
7350     if (!ISD)
7351       return false;
7352     assert(isInSchedulingRegion(ISD) &&
7353            "ScheduleData not in scheduling region");
7354     ScheduleData *SD = allocateScheduleDataChunks();
7355     SD->Inst = I;
7356     SD->init(SchedulingRegionID, S.OpValue);
7357     ExtraScheduleDataMap[I][S.OpValue] = SD;
7358     return true;
7359   };
7360   if (CheckSheduleForI(I))
7361     return true;
7362   if (!ScheduleStart) {
7363     // It's the first instruction in the new region.
7364     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7365     ScheduleStart = I;
7366     ScheduleEnd = I->getNextNode();
7367     if (isOneOf(S, I) != I)
7368       CheckSheduleForI(I);
7369     assert(ScheduleEnd && "tried to vectorize a terminator?");
7370     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7371     return true;
7372   }
7373   // Search up and down at the same time, because we don't know if the new
7374   // instruction is above or below the existing scheduling region.
7375   BasicBlock::reverse_iterator UpIter =
7376       ++ScheduleStart->getIterator().getReverse();
7377   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7378   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7379   BasicBlock::iterator LowerEnd = BB->end();
7380   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7381          &*DownIter != I) {
7382     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7383       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7384       return false;
7385     }
7386 
7387     ++UpIter;
7388     ++DownIter;
7389   }
7390   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7391     assert(I->getParent() == ScheduleStart->getParent() &&
7392            "Instruction is in wrong basic block.");
7393     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7394     ScheduleStart = I;
7395     if (isOneOf(S, I) != I)
7396       CheckSheduleForI(I);
7397     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7398                       << "\n");
7399     return true;
7400   }
7401   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7402          "Expected to reach top of the basic block or instruction down the "
7403          "lower end.");
7404   assert(I->getParent() == ScheduleEnd->getParent() &&
7405          "Instruction is in wrong basic block.");
7406   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7407                    nullptr);
7408   ScheduleEnd = I->getNextNode();
7409   if (isOneOf(S, I) != I)
7410     CheckSheduleForI(I);
7411   assert(ScheduleEnd && "tried to vectorize a terminator?");
7412   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7413   return true;
7414 }
7415 
7416 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7417                                                 Instruction *ToI,
7418                                                 ScheduleData *PrevLoadStore,
7419                                                 ScheduleData *NextLoadStore) {
7420   ScheduleData *CurrentLoadStore = PrevLoadStore;
7421   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7422     ScheduleData *SD = ScheduleDataMap[I];
7423     if (!SD) {
7424       SD = allocateScheduleDataChunks();
7425       ScheduleDataMap[I] = SD;
7426       SD->Inst = I;
7427     }
7428     assert(!isInSchedulingRegion(SD) &&
7429            "new ScheduleData already in scheduling region");
7430     SD->init(SchedulingRegionID, I);
7431 
7432     if (I->mayReadOrWriteMemory() &&
7433         (!isa<IntrinsicInst>(I) ||
7434          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7435           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7436               Intrinsic::pseudoprobe))) {
7437       // Update the linked list of memory accessing instructions.
7438       if (CurrentLoadStore) {
7439         CurrentLoadStore->NextLoadStore = SD;
7440       } else {
7441         FirstLoadStoreInRegion = SD;
7442       }
7443       CurrentLoadStore = SD;
7444     }
7445   }
7446   if (NextLoadStore) {
7447     if (CurrentLoadStore)
7448       CurrentLoadStore->NextLoadStore = NextLoadStore;
7449   } else {
7450     LastLoadStoreInRegion = CurrentLoadStore;
7451   }
7452 }
7453 
7454 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7455                                                      bool InsertInReadyList,
7456                                                      BoUpSLP *SLP) {
7457   assert(SD->isSchedulingEntity());
7458 
7459   SmallVector<ScheduleData *, 10> WorkList;
7460   WorkList.push_back(SD);
7461 
7462   while (!WorkList.empty()) {
7463     ScheduleData *SD = WorkList.pop_back_val();
7464 
7465     ScheduleData *BundleMember = SD;
7466     while (BundleMember) {
7467       assert(isInSchedulingRegion(BundleMember));
7468       if (!BundleMember->hasValidDependencies()) {
7469 
7470         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7471                           << "\n");
7472         BundleMember->Dependencies = 0;
7473         BundleMember->resetUnscheduledDeps();
7474 
7475         // Handle def-use chain dependencies.
7476         if (BundleMember->OpValue != BundleMember->Inst) {
7477           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7478           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7479             BundleMember->Dependencies++;
7480             ScheduleData *DestBundle = UseSD->FirstInBundle;
7481             if (!DestBundle->IsScheduled)
7482               BundleMember->incrementUnscheduledDeps(1);
7483             if (!DestBundle->hasValidDependencies())
7484               WorkList.push_back(DestBundle);
7485           }
7486         } else {
7487           for (User *U : BundleMember->Inst->users()) {
7488             if (isa<Instruction>(U)) {
7489               ScheduleData *UseSD = getScheduleData(U);
7490               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7491                 BundleMember->Dependencies++;
7492                 ScheduleData *DestBundle = UseSD->FirstInBundle;
7493                 if (!DestBundle->IsScheduled)
7494                   BundleMember->incrementUnscheduledDeps(1);
7495                 if (!DestBundle->hasValidDependencies())
7496                   WorkList.push_back(DestBundle);
7497               }
7498             } else {
7499               // I'm not sure if this can ever happen. But we need to be safe.
7500               // This lets the instruction/bundle never be scheduled and
7501               // eventually disable vectorization.
7502               BundleMember->Dependencies++;
7503               BundleMember->incrementUnscheduledDeps(1);
7504             }
7505           }
7506         }
7507 
7508         // Handle the memory dependencies.
7509         ScheduleData *DepDest = BundleMember->NextLoadStore;
7510         if (DepDest) {
7511           Instruction *SrcInst = BundleMember->Inst;
7512           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
7513           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7514           unsigned numAliased = 0;
7515           unsigned DistToSrc = 1;
7516 
7517           while (DepDest) {
7518             assert(isInSchedulingRegion(DepDest));
7519 
7520             // We have two limits to reduce the complexity:
7521             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7522             //    SLP->isAliased (which is the expensive part in this loop).
7523             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7524             //    the whole loop (even if the loop is fast, it's quadratic).
7525             //    It's important for the loop break condition (see below) to
7526             //    check this limit even between two read-only instructions.
7527             if (DistToSrc >= MaxMemDepDistance ||
7528                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7529                      (numAliased >= AliasedCheckLimit ||
7530                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7531 
7532               // We increment the counter only if the locations are aliased
7533               // (instead of counting all alias checks). This gives a better
7534               // balance between reduced runtime and accurate dependencies.
7535               numAliased++;
7536 
7537               DepDest->MemoryDependencies.push_back(BundleMember);
7538               BundleMember->Dependencies++;
7539               ScheduleData *DestBundle = DepDest->FirstInBundle;
7540               if (!DestBundle->IsScheduled) {
7541                 BundleMember->incrementUnscheduledDeps(1);
7542               }
7543               if (!DestBundle->hasValidDependencies()) {
7544                 WorkList.push_back(DestBundle);
7545               }
7546             }
7547             DepDest = DepDest->NextLoadStore;
7548 
7549             // Example, explaining the loop break condition: Let's assume our
7550             // starting instruction is i0 and MaxMemDepDistance = 3.
7551             //
7552             //                      +--------v--v--v
7553             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7554             //             +--------^--^--^
7555             //
7556             // MaxMemDepDistance let us stop alias-checking at i3 and we add
7557             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7558             // Previously we already added dependencies from i3 to i6,i7,i8
7559             // (because of MaxMemDepDistance). As we added a dependency from
7560             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7561             // and we can abort this loop at i6.
7562             if (DistToSrc >= 2 * MaxMemDepDistance)
7563               break;
7564             DistToSrc++;
7565           }
7566         }
7567       }
7568       BundleMember = BundleMember->NextInBundle;
7569     }
7570     if (InsertInReadyList && SD->isReady()) {
7571       ReadyInsts.push_back(SD);
7572       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7573                         << "\n");
7574     }
7575   }
7576 }
7577 
7578 void BoUpSLP::BlockScheduling::resetSchedule() {
7579   assert(ScheduleStart &&
7580          "tried to reset schedule on block which has not been scheduled");
7581   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7582     doForAllOpcodes(I, [&](ScheduleData *SD) {
7583       assert(isInSchedulingRegion(SD) &&
7584              "ScheduleData not in scheduling region");
7585       SD->IsScheduled = false;
7586       SD->resetUnscheduledDeps();
7587     });
7588   }
7589   ReadyInsts.clear();
7590 }
7591 
7592 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7593   if (!BS->ScheduleStart)
7594     return;
7595 
7596   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7597 
7598   BS->resetSchedule();
7599 
7600   // For the real scheduling we use a more sophisticated ready-list: it is
7601   // sorted by the original instruction location. This lets the final schedule
7602   // be as  close as possible to the original instruction order.
7603   struct ScheduleDataCompare {
7604     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7605       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7606     }
7607   };
7608   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7609 
7610   // Ensure that all dependency data is updated and fill the ready-list with
7611   // initial instructions.
7612   int Idx = 0;
7613   int NumToSchedule = 0;
7614   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7615        I = I->getNextNode()) {
7616     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7617       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7618               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7619              "scheduler and vectorizer bundle mismatch");
7620       SD->FirstInBundle->SchedulingPriority = Idx++;
7621       if (SD->isSchedulingEntity()) {
7622         BS->calculateDependencies(SD, false, this);
7623         NumToSchedule++;
7624       }
7625     });
7626   }
7627   BS->initialFillReadyList(ReadyInsts);
7628 
7629   Instruction *LastScheduledInst = BS->ScheduleEnd;
7630 
7631   // Do the "real" scheduling.
7632   while (!ReadyInsts.empty()) {
7633     ScheduleData *picked = *ReadyInsts.begin();
7634     ReadyInsts.erase(ReadyInsts.begin());
7635 
7636     // Move the scheduled instruction(s) to their dedicated places, if not
7637     // there yet.
7638     ScheduleData *BundleMember = picked;
7639     while (BundleMember) {
7640       Instruction *pickedInst = BundleMember->Inst;
7641       if (pickedInst->getNextNode() != LastScheduledInst) {
7642         BS->BB->getInstList().remove(pickedInst);
7643         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
7644                                      pickedInst);
7645       }
7646       LastScheduledInst = pickedInst;
7647       BundleMember = BundleMember->NextInBundle;
7648     }
7649 
7650     BS->schedule(picked, ReadyInsts);
7651     NumToSchedule--;
7652   }
7653   assert(NumToSchedule == 0 && "could not schedule all instructions");
7654 
7655   // Avoid duplicate scheduling of the block.
7656   BS->ScheduleStart = nullptr;
7657 }
7658 
7659 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7660   // If V is a store, just return the width of the stored value (or value
7661   // truncated just before storing) without traversing the expression tree.
7662   // This is the common case.
7663   if (auto *Store = dyn_cast<StoreInst>(V)) {
7664     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7665       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7666     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7667   }
7668 
7669   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7670     return getVectorElementSize(IEI->getOperand(1));
7671 
7672   auto E = InstrElementSize.find(V);
7673   if (E != InstrElementSize.end())
7674     return E->second;
7675 
7676   // If V is not a store, we can traverse the expression tree to find loads
7677   // that feed it. The type of the loaded value may indicate a more suitable
7678   // width than V's type. We want to base the vector element size on the width
7679   // of memory operations where possible.
7680   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7681   SmallPtrSet<Instruction *, 16> Visited;
7682   if (auto *I = dyn_cast<Instruction>(V)) {
7683     Worklist.emplace_back(I, I->getParent());
7684     Visited.insert(I);
7685   }
7686 
7687   // Traverse the expression tree in bottom-up order looking for loads. If we
7688   // encounter an instruction we don't yet handle, we give up.
7689   auto Width = 0u;
7690   while (!Worklist.empty()) {
7691     Instruction *I;
7692     BasicBlock *Parent;
7693     std::tie(I, Parent) = Worklist.pop_back_val();
7694 
7695     // We should only be looking at scalar instructions here. If the current
7696     // instruction has a vector type, skip.
7697     auto *Ty = I->getType();
7698     if (isa<VectorType>(Ty))
7699       continue;
7700 
7701     // If the current instruction is a load, update MaxWidth to reflect the
7702     // width of the loaded value.
7703     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7704         isa<ExtractValueInst>(I))
7705       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7706 
7707     // Otherwise, we need to visit the operands of the instruction. We only
7708     // handle the interesting cases from buildTree here. If an operand is an
7709     // instruction we haven't yet visited and from the same basic block as the
7710     // user or the use is a PHI node, we add it to the worklist.
7711     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7712              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7713              isa<UnaryOperator>(I)) {
7714       for (Use &U : I->operands())
7715         if (auto *J = dyn_cast<Instruction>(U.get()))
7716           if (Visited.insert(J).second &&
7717               (isa<PHINode>(I) || J->getParent() == Parent))
7718             Worklist.emplace_back(J, J->getParent());
7719     } else {
7720       break;
7721     }
7722   }
7723 
7724   // If we didn't encounter a memory access in the expression tree, or if we
7725   // gave up for some reason, just return the width of V. Otherwise, return the
7726   // maximum width we found.
7727   if (!Width) {
7728     if (auto *CI = dyn_cast<CmpInst>(V))
7729       V = CI->getOperand(0);
7730     Width = DL->getTypeSizeInBits(V->getType());
7731   }
7732 
7733   for (Instruction *I : Visited)
7734     InstrElementSize[I] = Width;
7735 
7736   return Width;
7737 }
7738 
7739 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7740 // smaller type with a truncation. We collect the values that will be demoted
7741 // in ToDemote and additional roots that require investigating in Roots.
7742 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7743                                   SmallVectorImpl<Value *> &ToDemote,
7744                                   SmallVectorImpl<Value *> &Roots) {
7745   // We can always demote constants.
7746   if (isa<Constant>(V)) {
7747     ToDemote.push_back(V);
7748     return true;
7749   }
7750 
7751   // If the value is not an instruction in the expression with only one use, it
7752   // cannot be demoted.
7753   auto *I = dyn_cast<Instruction>(V);
7754   if (!I || !I->hasOneUse() || !Expr.count(I))
7755     return false;
7756 
7757   switch (I->getOpcode()) {
7758 
7759   // We can always demote truncations and extensions. Since truncations can
7760   // seed additional demotion, we save the truncated value.
7761   case Instruction::Trunc:
7762     Roots.push_back(I->getOperand(0));
7763     break;
7764   case Instruction::ZExt:
7765   case Instruction::SExt:
7766     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7767         isa<InsertElementInst>(I->getOperand(0)))
7768       return false;
7769     break;
7770 
7771   // We can demote certain binary operations if we can demote both of their
7772   // operands.
7773   case Instruction::Add:
7774   case Instruction::Sub:
7775   case Instruction::Mul:
7776   case Instruction::And:
7777   case Instruction::Or:
7778   case Instruction::Xor:
7779     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7780         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7781       return false;
7782     break;
7783 
7784   // We can demote selects if we can demote their true and false values.
7785   case Instruction::Select: {
7786     SelectInst *SI = cast<SelectInst>(I);
7787     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7788         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7789       return false;
7790     break;
7791   }
7792 
7793   // We can demote phis if we can demote all their incoming operands. Note that
7794   // we don't need to worry about cycles since we ensure single use above.
7795   case Instruction::PHI: {
7796     PHINode *PN = cast<PHINode>(I);
7797     for (Value *IncValue : PN->incoming_values())
7798       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7799         return false;
7800     break;
7801   }
7802 
7803   // Otherwise, conservatively give up.
7804   default:
7805     return false;
7806   }
7807 
7808   // Record the value that we can demote.
7809   ToDemote.push_back(V);
7810   return true;
7811 }
7812 
7813 void BoUpSLP::computeMinimumValueSizes() {
7814   // If there are no external uses, the expression tree must be rooted by a
7815   // store. We can't demote in-memory values, so there is nothing to do here.
7816   if (ExternalUses.empty())
7817     return;
7818 
7819   // We only attempt to truncate integer expressions.
7820   auto &TreeRoot = VectorizableTree[0]->Scalars;
7821   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
7822   if (!TreeRootIT)
7823     return;
7824 
7825   // If the expression is not rooted by a store, these roots should have
7826   // external uses. We will rely on InstCombine to rewrite the expression in
7827   // the narrower type. However, InstCombine only rewrites single-use values.
7828   // This means that if a tree entry other than a root is used externally, it
7829   // must have multiple uses and InstCombine will not rewrite it. The code
7830   // below ensures that only the roots are used externally.
7831   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
7832   for (auto &EU : ExternalUses)
7833     if (!Expr.erase(EU.Scalar))
7834       return;
7835   if (!Expr.empty())
7836     return;
7837 
7838   // Collect the scalar values of the vectorizable expression. We will use this
7839   // context to determine which values can be demoted. If we see a truncation,
7840   // we mark it as seeding another demotion.
7841   for (auto &EntryPtr : VectorizableTree)
7842     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
7843 
7844   // Ensure the roots of the vectorizable tree don't form a cycle. They must
7845   // have a single external user that is not in the vectorizable tree.
7846   for (auto *Root : TreeRoot)
7847     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
7848       return;
7849 
7850   // Conservatively determine if we can actually truncate the roots of the
7851   // expression. Collect the values that can be demoted in ToDemote and
7852   // additional roots that require investigating in Roots.
7853   SmallVector<Value *, 32> ToDemote;
7854   SmallVector<Value *, 4> Roots;
7855   for (auto *Root : TreeRoot)
7856     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
7857       return;
7858 
7859   // The maximum bit width required to represent all the values that can be
7860   // demoted without loss of precision. It would be safe to truncate the roots
7861   // of the expression to this width.
7862   auto MaxBitWidth = 8u;
7863 
7864   // We first check if all the bits of the roots are demanded. If they're not,
7865   // we can truncate the roots to this narrower type.
7866   for (auto *Root : TreeRoot) {
7867     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
7868     MaxBitWidth = std::max<unsigned>(
7869         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
7870   }
7871 
7872   // True if the roots can be zero-extended back to their original type, rather
7873   // than sign-extended. We know that if the leading bits are not demanded, we
7874   // can safely zero-extend. So we initialize IsKnownPositive to True.
7875   bool IsKnownPositive = true;
7876 
7877   // If all the bits of the roots are demanded, we can try a little harder to
7878   // compute a narrower type. This can happen, for example, if the roots are
7879   // getelementptr indices. InstCombine promotes these indices to the pointer
7880   // width. Thus, all their bits are technically demanded even though the
7881   // address computation might be vectorized in a smaller type.
7882   //
7883   // We start by looking at each entry that can be demoted. We compute the
7884   // maximum bit width required to store the scalar by using ValueTracking to
7885   // compute the number of high-order bits we can truncate.
7886   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
7887       llvm::all_of(TreeRoot, [](Value *R) {
7888         assert(R->hasOneUse() && "Root should have only one use!");
7889         return isa<GetElementPtrInst>(R->user_back());
7890       })) {
7891     MaxBitWidth = 8u;
7892 
7893     // Determine if the sign bit of all the roots is known to be zero. If not,
7894     // IsKnownPositive is set to False.
7895     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
7896       KnownBits Known = computeKnownBits(R, *DL);
7897       return Known.isNonNegative();
7898     });
7899 
7900     // Determine the maximum number of bits required to store the scalar
7901     // values.
7902     for (auto *Scalar : ToDemote) {
7903       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
7904       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
7905       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
7906     }
7907 
7908     // If we can't prove that the sign bit is zero, we must add one to the
7909     // maximum bit width to account for the unknown sign bit. This preserves
7910     // the existing sign bit so we can safely sign-extend the root back to the
7911     // original type. Otherwise, if we know the sign bit is zero, we will
7912     // zero-extend the root instead.
7913     //
7914     // FIXME: This is somewhat suboptimal, as there will be cases where adding
7915     //        one to the maximum bit width will yield a larger-than-necessary
7916     //        type. In general, we need to add an extra bit only if we can't
7917     //        prove that the upper bit of the original type is equal to the
7918     //        upper bit of the proposed smaller type. If these two bits are the
7919     //        same (either zero or one) we know that sign-extending from the
7920     //        smaller type will result in the same value. Here, since we can't
7921     //        yet prove this, we are just making the proposed smaller type
7922     //        larger to ensure correctness.
7923     if (!IsKnownPositive)
7924       ++MaxBitWidth;
7925   }
7926 
7927   // Round MaxBitWidth up to the next power-of-two.
7928   if (!isPowerOf2_64(MaxBitWidth))
7929     MaxBitWidth = NextPowerOf2(MaxBitWidth);
7930 
7931   // If the maximum bit width we compute is less than the with of the roots'
7932   // type, we can proceed with the narrowing. Otherwise, do nothing.
7933   if (MaxBitWidth >= TreeRootIT->getBitWidth())
7934     return;
7935 
7936   // If we can truncate the root, we must collect additional values that might
7937   // be demoted as a result. That is, those seeded by truncations we will
7938   // modify.
7939   while (!Roots.empty())
7940     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
7941 
7942   // Finally, map the values we can demote to the maximum bit with we computed.
7943   for (auto *Scalar : ToDemote)
7944     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
7945 }
7946 
7947 namespace {
7948 
7949 /// The SLPVectorizer Pass.
7950 struct SLPVectorizer : public FunctionPass {
7951   SLPVectorizerPass Impl;
7952 
7953   /// Pass identification, replacement for typeid
7954   static char ID;
7955 
7956   explicit SLPVectorizer() : FunctionPass(ID) {
7957     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
7958   }
7959 
7960   bool doInitialization(Module &M) override { return false; }
7961 
7962   bool runOnFunction(Function &F) override {
7963     if (skipFunction(F))
7964       return false;
7965 
7966     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
7967     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
7968     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7969     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
7970     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
7971     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7972     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7973     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
7974     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
7975     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
7976 
7977     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7978   }
7979 
7980   void getAnalysisUsage(AnalysisUsage &AU) const override {
7981     FunctionPass::getAnalysisUsage(AU);
7982     AU.addRequired<AssumptionCacheTracker>();
7983     AU.addRequired<ScalarEvolutionWrapperPass>();
7984     AU.addRequired<AAResultsWrapperPass>();
7985     AU.addRequired<TargetTransformInfoWrapperPass>();
7986     AU.addRequired<LoopInfoWrapperPass>();
7987     AU.addRequired<DominatorTreeWrapperPass>();
7988     AU.addRequired<DemandedBitsWrapperPass>();
7989     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
7990     AU.addRequired<InjectTLIMappingsLegacy>();
7991     AU.addPreserved<LoopInfoWrapperPass>();
7992     AU.addPreserved<DominatorTreeWrapperPass>();
7993     AU.addPreserved<AAResultsWrapperPass>();
7994     AU.addPreserved<GlobalsAAWrapperPass>();
7995     AU.setPreservesCFG();
7996   }
7997 };
7998 
7999 } // end anonymous namespace
8000 
8001 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8002   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8003   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8004   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8005   auto *AA = &AM.getResult<AAManager>(F);
8006   auto *LI = &AM.getResult<LoopAnalysis>(F);
8007   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8008   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8009   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8010   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8011 
8012   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8013   if (!Changed)
8014     return PreservedAnalyses::all();
8015 
8016   PreservedAnalyses PA;
8017   PA.preserveSet<CFGAnalyses>();
8018   return PA;
8019 }
8020 
8021 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8022                                 TargetTransformInfo *TTI_,
8023                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8024                                 LoopInfo *LI_, DominatorTree *DT_,
8025                                 AssumptionCache *AC_, DemandedBits *DB_,
8026                                 OptimizationRemarkEmitter *ORE_) {
8027   if (!RunSLPVectorization)
8028     return false;
8029   SE = SE_;
8030   TTI = TTI_;
8031   TLI = TLI_;
8032   AA = AA_;
8033   LI = LI_;
8034   DT = DT_;
8035   AC = AC_;
8036   DB = DB_;
8037   DL = &F.getParent()->getDataLayout();
8038 
8039   Stores.clear();
8040   GEPs.clear();
8041   bool Changed = false;
8042 
8043   // If the target claims to have no vector registers don't attempt
8044   // vectorization.
8045   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
8046     return false;
8047 
8048   // Don't vectorize when the attribute NoImplicitFloat is used.
8049   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8050     return false;
8051 
8052   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8053 
8054   // Use the bottom up slp vectorizer to construct chains that start with
8055   // store instructions.
8056   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8057 
8058   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8059   // delete instructions.
8060 
8061   // Update DFS numbers now so that we can use them for ordering.
8062   DT->updateDFSNumbers();
8063 
8064   // Scan the blocks in the function in post order.
8065   for (auto BB : post_order(&F.getEntryBlock())) {
8066     collectSeedInstructions(BB);
8067 
8068     // Vectorize trees that end at stores.
8069     if (!Stores.empty()) {
8070       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8071                         << " underlying objects.\n");
8072       Changed |= vectorizeStoreChains(R);
8073     }
8074 
8075     // Vectorize trees that end at reductions.
8076     Changed |= vectorizeChainsInBlock(BB, R);
8077 
8078     // Vectorize the index computations of getelementptr instructions. This
8079     // is primarily intended to catch gather-like idioms ending at
8080     // non-consecutive loads.
8081     if (!GEPs.empty()) {
8082       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8083                         << " underlying objects.\n");
8084       Changed |= vectorizeGEPIndices(BB, R);
8085     }
8086   }
8087 
8088   if (Changed) {
8089     R.optimizeGatherSequence();
8090     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8091   }
8092   return Changed;
8093 }
8094 
8095 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8096                                             unsigned Idx) {
8097   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8098                     << "\n");
8099   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8100   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8101   unsigned VF = Chain.size();
8102 
8103   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8104     return false;
8105 
8106   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8107                     << "\n");
8108 
8109   R.buildTree(Chain);
8110   if (R.isTreeTinyAndNotFullyVectorizable())
8111     return false;
8112   if (R.isLoadCombineCandidate())
8113     return false;
8114   R.reorderTopToBottom();
8115   R.reorderBottomToTop();
8116   R.buildExternalUses();
8117 
8118   R.computeMinimumValueSizes();
8119 
8120   InstructionCost Cost = R.getTreeCost();
8121 
8122   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8123   if (Cost < -SLPCostThreshold) {
8124     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8125 
8126     using namespace ore;
8127 
8128     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8129                                         cast<StoreInst>(Chain[0]))
8130                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8131                      << " and with tree size "
8132                      << NV("TreeSize", R.getTreeSize()));
8133 
8134     R.vectorizeTree();
8135     return true;
8136   }
8137 
8138   return false;
8139 }
8140 
8141 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8142                                         BoUpSLP &R) {
8143   // We may run into multiple chains that merge into a single chain. We mark the
8144   // stores that we vectorized so that we don't visit the same store twice.
8145   BoUpSLP::ValueSet VectorizedStores;
8146   bool Changed = false;
8147 
8148   int E = Stores.size();
8149   SmallBitVector Tails(E, false);
8150   int MaxIter = MaxStoreLookup.getValue();
8151   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8152       E, std::make_pair(E, INT_MAX));
8153   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8154   int IterCnt;
8155   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8156                                   &CheckedPairs,
8157                                   &ConsecutiveChain](int K, int Idx) {
8158     if (IterCnt >= MaxIter)
8159       return true;
8160     if (CheckedPairs[Idx].test(K))
8161       return ConsecutiveChain[K].second == 1 &&
8162              ConsecutiveChain[K].first == Idx;
8163     ++IterCnt;
8164     CheckedPairs[Idx].set(K);
8165     CheckedPairs[K].set(Idx);
8166     Optional<int> Diff = getPointersDiff(
8167         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8168         Stores[Idx]->getValueOperand()->getType(),
8169         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8170     if (!Diff || *Diff == 0)
8171       return false;
8172     int Val = *Diff;
8173     if (Val < 0) {
8174       if (ConsecutiveChain[Idx].second > -Val) {
8175         Tails.set(K);
8176         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8177       }
8178       return false;
8179     }
8180     if (ConsecutiveChain[K].second <= Val)
8181       return false;
8182 
8183     Tails.set(Idx);
8184     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8185     return Val == 1;
8186   };
8187   // Do a quadratic search on all of the given stores in reverse order and find
8188   // all of the pairs of stores that follow each other.
8189   for (int Idx = E - 1; Idx >= 0; --Idx) {
8190     // If a store has multiple consecutive store candidates, search according
8191     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8192     // This is because usually pairing with immediate succeeding or preceding
8193     // candidate create the best chance to find slp vectorization opportunity.
8194     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8195     IterCnt = 0;
8196     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8197       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8198           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8199         break;
8200   }
8201 
8202   // Tracks if we tried to vectorize stores starting from the given tail
8203   // already.
8204   SmallBitVector TriedTails(E, false);
8205   // For stores that start but don't end a link in the chain:
8206   for (int Cnt = E; Cnt > 0; --Cnt) {
8207     int I = Cnt - 1;
8208     if (ConsecutiveChain[I].first == E || Tails.test(I))
8209       continue;
8210     // We found a store instr that starts a chain. Now follow the chain and try
8211     // to vectorize it.
8212     BoUpSLP::ValueList Operands;
8213     // Collect the chain into a list.
8214     while (I != E && !VectorizedStores.count(Stores[I])) {
8215       Operands.push_back(Stores[I]);
8216       Tails.set(I);
8217       if (ConsecutiveChain[I].second != 1) {
8218         // Mark the new end in the chain and go back, if required. It might be
8219         // required if the original stores come in reversed order, for example.
8220         if (ConsecutiveChain[I].first != E &&
8221             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8222             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8223           TriedTails.set(I);
8224           Tails.reset(ConsecutiveChain[I].first);
8225           if (Cnt < ConsecutiveChain[I].first + 2)
8226             Cnt = ConsecutiveChain[I].first + 2;
8227         }
8228         break;
8229       }
8230       // Move to the next value in the chain.
8231       I = ConsecutiveChain[I].first;
8232     }
8233     assert(!Operands.empty() && "Expected non-empty list of stores.");
8234 
8235     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8236     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8237     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8238 
8239     unsigned MinVF = R.getMinVF(EltSize);
8240     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8241                               MaxElts);
8242 
8243     // FIXME: Is division-by-2 the correct step? Should we assert that the
8244     // register size is a power-of-2?
8245     unsigned StartIdx = 0;
8246     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8247       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8248         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8249         if (!VectorizedStores.count(Slice.front()) &&
8250             !VectorizedStores.count(Slice.back()) &&
8251             vectorizeStoreChain(Slice, R, Cnt)) {
8252           // Mark the vectorized stores so that we don't vectorize them again.
8253           VectorizedStores.insert(Slice.begin(), Slice.end());
8254           Changed = true;
8255           // If we vectorized initial block, no need to try to vectorize it
8256           // again.
8257           if (Cnt == StartIdx)
8258             StartIdx += Size;
8259           Cnt += Size;
8260           continue;
8261         }
8262         ++Cnt;
8263       }
8264       // Check if the whole array was vectorized already - exit.
8265       if (StartIdx >= Operands.size())
8266         break;
8267     }
8268   }
8269 
8270   return Changed;
8271 }
8272 
8273 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8274   // Initialize the collections. We will make a single pass over the block.
8275   Stores.clear();
8276   GEPs.clear();
8277 
8278   // Visit the store and getelementptr instructions in BB and organize them in
8279   // Stores and GEPs according to the underlying objects of their pointer
8280   // operands.
8281   for (Instruction &I : *BB) {
8282     // Ignore store instructions that are volatile or have a pointer operand
8283     // that doesn't point to a scalar type.
8284     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8285       if (!SI->isSimple())
8286         continue;
8287       if (!isValidElementType(SI->getValueOperand()->getType()))
8288         continue;
8289       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8290     }
8291 
8292     // Ignore getelementptr instructions that have more than one index, a
8293     // constant index, or a pointer operand that doesn't point to a scalar
8294     // type.
8295     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8296       auto Idx = GEP->idx_begin()->get();
8297       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8298         continue;
8299       if (!isValidElementType(Idx->getType()))
8300         continue;
8301       if (GEP->getType()->isVectorTy())
8302         continue;
8303       GEPs[GEP->getPointerOperand()].push_back(GEP);
8304     }
8305   }
8306 }
8307 
8308 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8309   if (!A || !B)
8310     return false;
8311   Value *VL[] = {A, B};
8312   return tryToVectorizeList(VL, R);
8313 }
8314 
8315 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8316                                            bool LimitForRegisterSize) {
8317   if (VL.size() < 2)
8318     return false;
8319 
8320   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8321                     << VL.size() << ".\n");
8322 
8323   // Check that all of the parts are instructions of the same type,
8324   // we permit an alternate opcode via InstructionsState.
8325   InstructionsState S = getSameOpcode(VL);
8326   if (!S.getOpcode())
8327     return false;
8328 
8329   Instruction *I0 = cast<Instruction>(S.OpValue);
8330   // Make sure invalid types (including vector type) are rejected before
8331   // determining vectorization factor for scalar instructions.
8332   for (Value *V : VL) {
8333     Type *Ty = V->getType();
8334     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8335       // NOTE: the following will give user internal llvm type name, which may
8336       // not be useful.
8337       R.getORE()->emit([&]() {
8338         std::string type_str;
8339         llvm::raw_string_ostream rso(type_str);
8340         Ty->print(rso);
8341         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8342                << "Cannot SLP vectorize list: type "
8343                << rso.str() + " is unsupported by vectorizer";
8344       });
8345       return false;
8346     }
8347   }
8348 
8349   unsigned Sz = R.getVectorElementSize(I0);
8350   unsigned MinVF = R.getMinVF(Sz);
8351   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8352   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8353   if (MaxVF < 2) {
8354     R.getORE()->emit([&]() {
8355       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8356              << "Cannot SLP vectorize list: vectorization factor "
8357              << "less than 2 is not supported";
8358     });
8359     return false;
8360   }
8361 
8362   bool Changed = false;
8363   bool CandidateFound = false;
8364   InstructionCost MinCost = SLPCostThreshold.getValue();
8365   Type *ScalarTy = VL[0]->getType();
8366   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8367     ScalarTy = IE->getOperand(1)->getType();
8368 
8369   unsigned NextInst = 0, MaxInst = VL.size();
8370   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8371     // No actual vectorization should happen, if number of parts is the same as
8372     // provided vectorization factor (i.e. the scalar type is used for vector
8373     // code during codegen).
8374     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8375     if (TTI->getNumberOfParts(VecTy) == VF)
8376       continue;
8377     for (unsigned I = NextInst; I < MaxInst; ++I) {
8378       unsigned OpsWidth = 0;
8379 
8380       if (I + VF > MaxInst)
8381         OpsWidth = MaxInst - I;
8382       else
8383         OpsWidth = VF;
8384 
8385       if (!isPowerOf2_32(OpsWidth))
8386         continue;
8387 
8388       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8389           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8390         break;
8391 
8392       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8393       // Check that a previous iteration of this loop did not delete the Value.
8394       if (llvm::any_of(Ops, [&R](Value *V) {
8395             auto *I = dyn_cast<Instruction>(V);
8396             return I && R.isDeleted(I);
8397           }))
8398         continue;
8399 
8400       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8401                         << "\n");
8402 
8403       R.buildTree(Ops);
8404       if (R.isTreeTinyAndNotFullyVectorizable())
8405         continue;
8406       R.reorderTopToBottom();
8407       R.reorderBottomToTop();
8408       R.buildExternalUses();
8409 
8410       R.computeMinimumValueSizes();
8411       InstructionCost Cost = R.getTreeCost();
8412       CandidateFound = true;
8413       MinCost = std::min(MinCost, Cost);
8414 
8415       if (Cost < -SLPCostThreshold) {
8416         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8417         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8418                                                     cast<Instruction>(Ops[0]))
8419                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8420                                  << " and with tree size "
8421                                  << ore::NV("TreeSize", R.getTreeSize()));
8422 
8423         R.vectorizeTree();
8424         // Move to the next bundle.
8425         I += VF - 1;
8426         NextInst = I + 1;
8427         Changed = true;
8428       }
8429     }
8430   }
8431 
8432   if (!Changed && CandidateFound) {
8433     R.getORE()->emit([&]() {
8434       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8435              << "List vectorization was possible but not beneficial with cost "
8436              << ore::NV("Cost", MinCost) << " >= "
8437              << ore::NV("Treshold", -SLPCostThreshold);
8438     });
8439   } else if (!Changed) {
8440     R.getORE()->emit([&]() {
8441       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8442              << "Cannot SLP vectorize list: vectorization was impossible"
8443              << " with available vectorization factors";
8444     });
8445   }
8446   return Changed;
8447 }
8448 
8449 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8450   if (!I)
8451     return false;
8452 
8453   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8454     return false;
8455 
8456   Value *P = I->getParent();
8457 
8458   // Vectorize in current basic block only.
8459   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8460   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8461   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8462     return false;
8463 
8464   // Try to vectorize V.
8465   if (tryToVectorizePair(Op0, Op1, R))
8466     return true;
8467 
8468   auto *A = dyn_cast<BinaryOperator>(Op0);
8469   auto *B = dyn_cast<BinaryOperator>(Op1);
8470   // Try to skip B.
8471   if (B && B->hasOneUse()) {
8472     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8473     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8474     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8475       return true;
8476     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8477       return true;
8478   }
8479 
8480   // Try to skip A.
8481   if (A && A->hasOneUse()) {
8482     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8483     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8484     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8485       return true;
8486     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8487       return true;
8488   }
8489   return false;
8490 }
8491 
8492 namespace {
8493 
8494 /// Model horizontal reductions.
8495 ///
8496 /// A horizontal reduction is a tree of reduction instructions that has values
8497 /// that can be put into a vector as its leaves. For example:
8498 ///
8499 /// mul mul mul mul
8500 ///  \  /    \  /
8501 ///   +       +
8502 ///    \     /
8503 ///       +
8504 /// This tree has "mul" as its leaf values and "+" as its reduction
8505 /// instructions. A reduction can feed into a store or a binary operation
8506 /// feeding a phi.
8507 ///    ...
8508 ///    \  /
8509 ///     +
8510 ///     |
8511 ///  phi +=
8512 ///
8513 ///  Or:
8514 ///    ...
8515 ///    \  /
8516 ///     +
8517 ///     |
8518 ///   *p =
8519 ///
8520 class HorizontalReduction {
8521   using ReductionOpsType = SmallVector<Value *, 16>;
8522   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8523   ReductionOpsListType ReductionOps;
8524   SmallVector<Value *, 32> ReducedVals;
8525   // Use map vector to make stable output.
8526   MapVector<Instruction *, Value *> ExtraArgs;
8527   WeakTrackingVH ReductionRoot;
8528   /// The type of reduction operation.
8529   RecurKind RdxKind;
8530 
8531   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8532 
8533   static bool isCmpSelMinMax(Instruction *I) {
8534     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8535            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8536   }
8537 
8538   // And/or are potentially poison-safe logical patterns like:
8539   // select x, y, false
8540   // select x, true, y
8541   static bool isBoolLogicOp(Instruction *I) {
8542     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8543            match(I, m_LogicalOr(m_Value(), m_Value()));
8544   }
8545 
8546   /// Checks if instruction is associative and can be vectorized.
8547   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8548     if (Kind == RecurKind::None)
8549       return false;
8550 
8551     // Integer ops that map to select instructions or intrinsics are fine.
8552     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8553         isBoolLogicOp(I))
8554       return true;
8555 
8556     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8557       // FP min/max are associative except for NaN and -0.0. We do not
8558       // have to rule out -0.0 here because the intrinsic semantics do not
8559       // specify a fixed result for it.
8560       return I->getFastMathFlags().noNaNs();
8561     }
8562 
8563     return I->isAssociative();
8564   }
8565 
8566   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8567     // Poison-safe 'or' takes the form: select X, true, Y
8568     // To make that work with the normal operand processing, we skip the
8569     // true value operand.
8570     // TODO: Change the code and data structures to handle this without a hack.
8571     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8572       return I->getOperand(2);
8573     return I->getOperand(Index);
8574   }
8575 
8576   /// Checks if the ParentStackElem.first should be marked as a reduction
8577   /// operation with an extra argument or as extra argument itself.
8578   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8579                     Value *ExtraArg) {
8580     if (ExtraArgs.count(ParentStackElem.first)) {
8581       ExtraArgs[ParentStackElem.first] = nullptr;
8582       // We ran into something like:
8583       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8584       // The whole ParentStackElem.first should be considered as an extra value
8585       // in this case.
8586       // Do not perform analysis of remaining operands of ParentStackElem.first
8587       // instruction, this whole instruction is an extra argument.
8588       ParentStackElem.second = INVALID_OPERAND_INDEX;
8589     } else {
8590       // We ran into something like:
8591       // ParentStackElem.first += ... + ExtraArg + ...
8592       ExtraArgs[ParentStackElem.first] = ExtraArg;
8593     }
8594   }
8595 
8596   /// Creates reduction operation with the current opcode.
8597   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8598                          Value *RHS, const Twine &Name, bool UseSelect) {
8599     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8600     switch (Kind) {
8601     case RecurKind::Or:
8602       if (UseSelect &&
8603           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8604         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8605       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8606                                  Name);
8607     case RecurKind::And:
8608       if (UseSelect &&
8609           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8610         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8611       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8612                                  Name);
8613     case RecurKind::Add:
8614     case RecurKind::Mul:
8615     case RecurKind::Xor:
8616     case RecurKind::FAdd:
8617     case RecurKind::FMul:
8618       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8619                                  Name);
8620     case RecurKind::FMax:
8621       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8622     case RecurKind::FMin:
8623       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8624     case RecurKind::SMax:
8625       if (UseSelect) {
8626         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8627         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8628       }
8629       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8630     case RecurKind::SMin:
8631       if (UseSelect) {
8632         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8633         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8634       }
8635       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8636     case RecurKind::UMax:
8637       if (UseSelect) {
8638         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8639         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8640       }
8641       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8642     case RecurKind::UMin:
8643       if (UseSelect) {
8644         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8645         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8646       }
8647       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8648     default:
8649       llvm_unreachable("Unknown reduction operation.");
8650     }
8651   }
8652 
8653   /// Creates reduction operation with the current opcode with the IR flags
8654   /// from \p ReductionOps.
8655   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8656                          Value *RHS, const Twine &Name,
8657                          const ReductionOpsListType &ReductionOps) {
8658     bool UseSelect = ReductionOps.size() == 2 ||
8659                      // Logical or/and.
8660                      (ReductionOps.size() == 1 &&
8661                       isa<SelectInst>(ReductionOps.front().front()));
8662     assert((!UseSelect || ReductionOps.size() != 2 ||
8663             isa<SelectInst>(ReductionOps[1][0])) &&
8664            "Expected cmp + select pairs for reduction");
8665     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8666     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8667       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8668         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8669         propagateIRFlags(Op, ReductionOps[1]);
8670         return Op;
8671       }
8672     }
8673     propagateIRFlags(Op, ReductionOps[0]);
8674     return Op;
8675   }
8676 
8677   /// Creates reduction operation with the current opcode with the IR flags
8678   /// from \p I.
8679   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8680                          Value *RHS, const Twine &Name, Instruction *I) {
8681     auto *SelI = dyn_cast<SelectInst>(I);
8682     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8683     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8684       if (auto *Sel = dyn_cast<SelectInst>(Op))
8685         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8686     }
8687     propagateIRFlags(Op, I);
8688     return Op;
8689   }
8690 
8691   static RecurKind getRdxKind(Instruction *I) {
8692     assert(I && "Expected instruction for reduction matching");
8693     TargetTransformInfo::ReductionFlags RdxFlags;
8694     if (match(I, m_Add(m_Value(), m_Value())))
8695       return RecurKind::Add;
8696     if (match(I, m_Mul(m_Value(), m_Value())))
8697       return RecurKind::Mul;
8698     if (match(I, m_And(m_Value(), m_Value())) ||
8699         match(I, m_LogicalAnd(m_Value(), m_Value())))
8700       return RecurKind::And;
8701     if (match(I, m_Or(m_Value(), m_Value())) ||
8702         match(I, m_LogicalOr(m_Value(), m_Value())))
8703       return RecurKind::Or;
8704     if (match(I, m_Xor(m_Value(), m_Value())))
8705       return RecurKind::Xor;
8706     if (match(I, m_FAdd(m_Value(), m_Value())))
8707       return RecurKind::FAdd;
8708     if (match(I, m_FMul(m_Value(), m_Value())))
8709       return RecurKind::FMul;
8710 
8711     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8712       return RecurKind::FMax;
8713     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8714       return RecurKind::FMin;
8715 
8716     // This matches either cmp+select or intrinsics. SLP is expected to handle
8717     // either form.
8718     // TODO: If we are canonicalizing to intrinsics, we can remove several
8719     //       special-case paths that deal with selects.
8720     if (match(I, m_SMax(m_Value(), m_Value())))
8721       return RecurKind::SMax;
8722     if (match(I, m_SMin(m_Value(), m_Value())))
8723       return RecurKind::SMin;
8724     if (match(I, m_UMax(m_Value(), m_Value())))
8725       return RecurKind::UMax;
8726     if (match(I, m_UMin(m_Value(), m_Value())))
8727       return RecurKind::UMin;
8728 
8729     if (auto *Select = dyn_cast<SelectInst>(I)) {
8730       // Try harder: look for min/max pattern based on instructions producing
8731       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8732       // During the intermediate stages of SLP, it's very common to have
8733       // pattern like this (since optimizeGatherSequence is run only once
8734       // at the end):
8735       // %1 = extractelement <2 x i32> %a, i32 0
8736       // %2 = extractelement <2 x i32> %a, i32 1
8737       // %cond = icmp sgt i32 %1, %2
8738       // %3 = extractelement <2 x i32> %a, i32 0
8739       // %4 = extractelement <2 x i32> %a, i32 1
8740       // %select = select i1 %cond, i32 %3, i32 %4
8741       CmpInst::Predicate Pred;
8742       Instruction *L1;
8743       Instruction *L2;
8744 
8745       Value *LHS = Select->getTrueValue();
8746       Value *RHS = Select->getFalseValue();
8747       Value *Cond = Select->getCondition();
8748 
8749       // TODO: Support inverse predicates.
8750       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8751         if (!isa<ExtractElementInst>(RHS) ||
8752             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8753           return RecurKind::None;
8754       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8755         if (!isa<ExtractElementInst>(LHS) ||
8756             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8757           return RecurKind::None;
8758       } else {
8759         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8760           return RecurKind::None;
8761         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8762             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8763             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8764           return RecurKind::None;
8765       }
8766 
8767       TargetTransformInfo::ReductionFlags RdxFlags;
8768       switch (Pred) {
8769       default:
8770         return RecurKind::None;
8771       case CmpInst::ICMP_SGT:
8772       case CmpInst::ICMP_SGE:
8773         return RecurKind::SMax;
8774       case CmpInst::ICMP_SLT:
8775       case CmpInst::ICMP_SLE:
8776         return RecurKind::SMin;
8777       case CmpInst::ICMP_UGT:
8778       case CmpInst::ICMP_UGE:
8779         return RecurKind::UMax;
8780       case CmpInst::ICMP_ULT:
8781       case CmpInst::ICMP_ULE:
8782         return RecurKind::UMin;
8783       }
8784     }
8785     return RecurKind::None;
8786   }
8787 
8788   /// Get the index of the first operand.
8789   static unsigned getFirstOperandIndex(Instruction *I) {
8790     return isCmpSelMinMax(I) ? 1 : 0;
8791   }
8792 
8793   /// Total number of operands in the reduction operation.
8794   static unsigned getNumberOfOperands(Instruction *I) {
8795     return isCmpSelMinMax(I) ? 3 : 2;
8796   }
8797 
8798   /// Checks if the instruction is in basic block \p BB.
8799   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8800   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8801     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
8802       auto *Sel = cast<SelectInst>(I);
8803       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
8804       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
8805     }
8806     return I->getParent() == BB;
8807   }
8808 
8809   /// Expected number of uses for reduction operations/reduced values.
8810   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
8811     if (IsCmpSelMinMax) {
8812       // SelectInst must be used twice while the condition op must have single
8813       // use only.
8814       if (auto *Sel = dyn_cast<SelectInst>(I))
8815         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
8816       return I->hasNUses(2);
8817     }
8818 
8819     // Arithmetic reduction operation must be used once only.
8820     return I->hasOneUse();
8821   }
8822 
8823   /// Initializes the list of reduction operations.
8824   void initReductionOps(Instruction *I) {
8825     if (isCmpSelMinMax(I))
8826       ReductionOps.assign(2, ReductionOpsType());
8827     else
8828       ReductionOps.assign(1, ReductionOpsType());
8829   }
8830 
8831   /// Add all reduction operations for the reduction instruction \p I.
8832   void addReductionOps(Instruction *I) {
8833     if (isCmpSelMinMax(I)) {
8834       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
8835       ReductionOps[1].emplace_back(I);
8836     } else {
8837       ReductionOps[0].emplace_back(I);
8838     }
8839   }
8840 
8841   static Value *getLHS(RecurKind Kind, Instruction *I) {
8842     if (Kind == RecurKind::None)
8843       return nullptr;
8844     return I->getOperand(getFirstOperandIndex(I));
8845   }
8846   static Value *getRHS(RecurKind Kind, Instruction *I) {
8847     if (Kind == RecurKind::None)
8848       return nullptr;
8849     return I->getOperand(getFirstOperandIndex(I) + 1);
8850   }
8851 
8852 public:
8853   HorizontalReduction() = default;
8854 
8855   /// Try to find a reduction tree.
8856   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
8857     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
8858            "Phi needs to use the binary operator");
8859     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
8860             isa<IntrinsicInst>(Inst)) &&
8861            "Expected binop, select, or intrinsic for reduction matching");
8862     RdxKind = getRdxKind(Inst);
8863 
8864     // We could have a initial reductions that is not an add.
8865     //  r *= v1 + v2 + v3 + v4
8866     // In such a case start looking for a tree rooted in the first '+'.
8867     if (Phi) {
8868       if (getLHS(RdxKind, Inst) == Phi) {
8869         Phi = nullptr;
8870         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
8871         if (!Inst)
8872           return false;
8873         RdxKind = getRdxKind(Inst);
8874       } else if (getRHS(RdxKind, Inst) == Phi) {
8875         Phi = nullptr;
8876         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
8877         if (!Inst)
8878           return false;
8879         RdxKind = getRdxKind(Inst);
8880       }
8881     }
8882 
8883     if (!isVectorizable(RdxKind, Inst))
8884       return false;
8885 
8886     // Analyze "regular" integer/FP types for reductions - no target-specific
8887     // types or pointers.
8888     Type *Ty = Inst->getType();
8889     if (!isValidElementType(Ty) || Ty->isPointerTy())
8890       return false;
8891 
8892     // Though the ultimate reduction may have multiple uses, its condition must
8893     // have only single use.
8894     if (auto *Sel = dyn_cast<SelectInst>(Inst))
8895       if (!Sel->getCondition()->hasOneUse())
8896         return false;
8897 
8898     ReductionRoot = Inst;
8899 
8900     // The opcode for leaf values that we perform a reduction on.
8901     // For example: load(x) + load(y) + load(z) + fptoui(w)
8902     // The leaf opcode for 'w' does not match, so we don't include it as a
8903     // potential candidate for the reduction.
8904     unsigned LeafOpcode = 0;
8905 
8906     // Post-order traverse the reduction tree starting at Inst. We only handle
8907     // true trees containing binary operators or selects.
8908     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
8909     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
8910     initReductionOps(Inst);
8911     while (!Stack.empty()) {
8912       Instruction *TreeN = Stack.back().first;
8913       unsigned EdgeToVisit = Stack.back().second++;
8914       const RecurKind TreeRdxKind = getRdxKind(TreeN);
8915       bool IsReducedValue = TreeRdxKind != RdxKind;
8916 
8917       // Postorder visit.
8918       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
8919         if (IsReducedValue)
8920           ReducedVals.push_back(TreeN);
8921         else {
8922           auto ExtraArgsIter = ExtraArgs.find(TreeN);
8923           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
8924             // Check if TreeN is an extra argument of its parent operation.
8925             if (Stack.size() <= 1) {
8926               // TreeN can't be an extra argument as it is a root reduction
8927               // operation.
8928               return false;
8929             }
8930             // Yes, TreeN is an extra argument, do not add it to a list of
8931             // reduction operations.
8932             // Stack[Stack.size() - 2] always points to the parent operation.
8933             markExtraArg(Stack[Stack.size() - 2], TreeN);
8934             ExtraArgs.erase(TreeN);
8935           } else
8936             addReductionOps(TreeN);
8937         }
8938         // Retract.
8939         Stack.pop_back();
8940         continue;
8941       }
8942 
8943       // Visit operands.
8944       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
8945       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
8946       if (!EdgeInst) {
8947         // Edge value is not a reduction instruction or a leaf instruction.
8948         // (It may be a constant, function argument, or something else.)
8949         markExtraArg(Stack.back(), EdgeVal);
8950         continue;
8951       }
8952       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
8953       // Continue analysis if the next operand is a reduction operation or
8954       // (possibly) a leaf value. If the leaf value opcode is not set,
8955       // the first met operation != reduction operation is considered as the
8956       // leaf opcode.
8957       // Only handle trees in the current basic block.
8958       // Each tree node needs to have minimal number of users except for the
8959       // ultimate reduction.
8960       const bool IsRdxInst = EdgeRdxKind == RdxKind;
8961       if (EdgeInst != Phi && EdgeInst != Inst &&
8962           hasSameParent(EdgeInst, Inst->getParent()) &&
8963           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
8964           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
8965         if (IsRdxInst) {
8966           // We need to be able to reassociate the reduction operations.
8967           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
8968             // I is an extra argument for TreeN (its parent operation).
8969             markExtraArg(Stack.back(), EdgeInst);
8970             continue;
8971           }
8972         } else if (!LeafOpcode) {
8973           LeafOpcode = EdgeInst->getOpcode();
8974         }
8975         Stack.push_back(
8976             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
8977         continue;
8978       }
8979       // I is an extra argument for TreeN (its parent operation).
8980       markExtraArg(Stack.back(), EdgeInst);
8981     }
8982     return true;
8983   }
8984 
8985   /// Attempt to vectorize the tree found by matchAssociativeReduction.
8986   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
8987     // If there are a sufficient number of reduction values, reduce
8988     // to a nearby power-of-2. We can safely generate oversized
8989     // vectors and rely on the backend to split them to legal sizes.
8990     unsigned NumReducedVals = ReducedVals.size();
8991     if (NumReducedVals < 4)
8992       return nullptr;
8993 
8994     // Intersect the fast-math-flags from all reduction operations.
8995     FastMathFlags RdxFMF;
8996     RdxFMF.set();
8997     for (ReductionOpsType &RdxOp : ReductionOps) {
8998       for (Value *RdxVal : RdxOp) {
8999         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9000           RdxFMF &= FPMO->getFastMathFlags();
9001       }
9002     }
9003 
9004     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9005     Builder.setFastMathFlags(RdxFMF);
9006 
9007     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9008     // The same extra argument may be used several times, so log each attempt
9009     // to use it.
9010     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9011       assert(Pair.first && "DebugLoc must be set.");
9012       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9013     }
9014 
9015     // The compare instruction of a min/max is the insertion point for new
9016     // instructions and may be replaced with a new compare instruction.
9017     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9018       assert(isa<SelectInst>(RdxRootInst) &&
9019              "Expected min/max reduction to have select root instruction");
9020       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9021       assert(isa<Instruction>(ScalarCond) &&
9022              "Expected min/max reduction to have compare condition");
9023       return cast<Instruction>(ScalarCond);
9024     };
9025 
9026     // The reduction root is used as the insertion point for new instructions,
9027     // so set it as externally used to prevent it from being deleted.
9028     ExternallyUsedValues[ReductionRoot];
9029     SmallVector<Value *, 16> IgnoreList;
9030     for (ReductionOpsType &RdxOp : ReductionOps)
9031       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9032 
9033     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9034     if (NumReducedVals > ReduxWidth) {
9035       // In the loop below, we are building a tree based on a window of
9036       // 'ReduxWidth' values.
9037       // If the operands of those values have common traits (compare predicate,
9038       // constant operand, etc), then we want to group those together to
9039       // minimize the cost of the reduction.
9040 
9041       // TODO: This should be extended to count common operands for
9042       //       compares and binops.
9043 
9044       // Step 1: Count the number of times each compare predicate occurs.
9045       SmallDenseMap<unsigned, unsigned> PredCountMap;
9046       for (Value *RdxVal : ReducedVals) {
9047         CmpInst::Predicate Pred;
9048         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9049           ++PredCountMap[Pred];
9050       }
9051       // Step 2: Sort the values so the most common predicates come first.
9052       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9053         CmpInst::Predicate PredA, PredB;
9054         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9055             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9056           return PredCountMap[PredA] > PredCountMap[PredB];
9057         }
9058         return false;
9059       });
9060     }
9061 
9062     Value *VectorizedTree = nullptr;
9063     unsigned i = 0;
9064     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9065       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9066       V.buildTree(VL, IgnoreList);
9067       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9068         break;
9069       if (V.isLoadCombineReductionCandidate(RdxKind))
9070         break;
9071       V.reorderTopToBottom();
9072       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9073       V.buildExternalUses(ExternallyUsedValues);
9074 
9075       // For a poison-safe boolean logic reduction, do not replace select
9076       // instructions with logic ops. All reduced values will be frozen (see
9077       // below) to prevent leaking poison.
9078       if (isa<SelectInst>(ReductionRoot) &&
9079           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9080           NumReducedVals != ReduxWidth)
9081         break;
9082 
9083       V.computeMinimumValueSizes();
9084 
9085       // Estimate cost.
9086       InstructionCost TreeCost =
9087           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9088       InstructionCost ReductionCost =
9089           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9090       InstructionCost Cost = TreeCost + ReductionCost;
9091       if (!Cost.isValid()) {
9092         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9093         return nullptr;
9094       }
9095       if (Cost >= -SLPCostThreshold) {
9096         V.getORE()->emit([&]() {
9097           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9098                                           cast<Instruction>(VL[0]))
9099                  << "Vectorizing horizontal reduction is possible"
9100                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9101                  << " and threshold "
9102                  << ore::NV("Threshold", -SLPCostThreshold);
9103         });
9104         break;
9105       }
9106 
9107       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9108                         << Cost << ". (HorRdx)\n");
9109       V.getORE()->emit([&]() {
9110         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9111                                   cast<Instruction>(VL[0]))
9112                << "Vectorized horizontal reduction with cost "
9113                << ore::NV("Cost", Cost) << " and with tree size "
9114                << ore::NV("TreeSize", V.getTreeSize());
9115       });
9116 
9117       // Vectorize a tree.
9118       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9119       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9120 
9121       // Emit a reduction. If the root is a select (min/max idiom), the insert
9122       // point is the compare condition of that select.
9123       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9124       if (isCmpSelMinMax(RdxRootInst))
9125         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9126       else
9127         Builder.SetInsertPoint(RdxRootInst);
9128 
9129       // To prevent poison from leaking across what used to be sequential, safe,
9130       // scalar boolean logic operations, the reduction operand must be frozen.
9131       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9132         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9133 
9134       Value *ReducedSubTree =
9135           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9136 
9137       if (!VectorizedTree) {
9138         // Initialize the final value in the reduction.
9139         VectorizedTree = ReducedSubTree;
9140       } else {
9141         // Update the final value in the reduction.
9142         Builder.SetCurrentDebugLocation(Loc);
9143         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9144                                   ReducedSubTree, "op.rdx", ReductionOps);
9145       }
9146       i += ReduxWidth;
9147       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9148     }
9149 
9150     if (VectorizedTree) {
9151       // Finish the reduction.
9152       for (; i < NumReducedVals; ++i) {
9153         auto *I = cast<Instruction>(ReducedVals[i]);
9154         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9155         VectorizedTree =
9156             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9157       }
9158       for (auto &Pair : ExternallyUsedValues) {
9159         // Add each externally used value to the final reduction.
9160         for (auto *I : Pair.second) {
9161           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9162           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9163                                     Pair.first, "op.extra", I);
9164         }
9165       }
9166 
9167       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9168 
9169       // Mark all scalar reduction ops for deletion, they are replaced by the
9170       // vector reductions.
9171       V.eraseInstructions(IgnoreList);
9172     }
9173     return VectorizedTree;
9174   }
9175 
9176   unsigned numReductionValues() const { return ReducedVals.size(); }
9177 
9178 private:
9179   /// Calculate the cost of a reduction.
9180   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9181                                    Value *FirstReducedVal, unsigned ReduxWidth,
9182                                    FastMathFlags FMF) {
9183     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9184     Type *ScalarTy = FirstReducedVal->getType();
9185     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9186     InstructionCost VectorCost, ScalarCost;
9187     switch (RdxKind) {
9188     case RecurKind::Add:
9189     case RecurKind::Mul:
9190     case RecurKind::Or:
9191     case RecurKind::And:
9192     case RecurKind::Xor:
9193     case RecurKind::FAdd:
9194     case RecurKind::FMul: {
9195       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9196       VectorCost =
9197           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9198       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9199       break;
9200     }
9201     case RecurKind::FMax:
9202     case RecurKind::FMin: {
9203       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9204       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9205       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9206                                                /*unsigned=*/false, CostKind);
9207       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9208       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9209                                            SclCondTy, RdxPred, CostKind) +
9210                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9211                                            SclCondTy, RdxPred, CostKind);
9212       break;
9213     }
9214     case RecurKind::SMax:
9215     case RecurKind::SMin:
9216     case RecurKind::UMax:
9217     case RecurKind::UMin: {
9218       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9219       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9220       bool IsUnsigned =
9221           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9222       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9223                                                CostKind);
9224       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9225       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9226                                            SclCondTy, RdxPred, CostKind) +
9227                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9228                                            SclCondTy, RdxPred, CostKind);
9229       break;
9230     }
9231     default:
9232       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9233     }
9234 
9235     // Scalar cost is repeated for N-1 elements.
9236     ScalarCost *= (ReduxWidth - 1);
9237     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9238                       << " for reduction that starts with " << *FirstReducedVal
9239                       << " (It is a splitting reduction)\n");
9240     return VectorCost - ScalarCost;
9241   }
9242 
9243   /// Emit a horizontal reduction of the vectorized value.
9244   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9245                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9246     assert(VectorizedValue && "Need to have a vectorized tree node");
9247     assert(isPowerOf2_32(ReduxWidth) &&
9248            "We only handle power-of-two reductions for now");
9249     assert(RdxKind != RecurKind::FMulAdd &&
9250            "A call to the llvm.fmuladd intrinsic is not handled yet");
9251 
9252     ++NumVectorInstructions;
9253     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9254   }
9255 };
9256 
9257 } // end anonymous namespace
9258 
9259 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9260   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9261     return cast<FixedVectorType>(IE->getType())->getNumElements();
9262 
9263   unsigned AggregateSize = 1;
9264   auto *IV = cast<InsertValueInst>(InsertInst);
9265   Type *CurrentType = IV->getType();
9266   do {
9267     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9268       for (auto *Elt : ST->elements())
9269         if (Elt != ST->getElementType(0)) // check homogeneity
9270           return None;
9271       AggregateSize *= ST->getNumElements();
9272       CurrentType = ST->getElementType(0);
9273     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9274       AggregateSize *= AT->getNumElements();
9275       CurrentType = AT->getElementType();
9276     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9277       AggregateSize *= VT->getNumElements();
9278       return AggregateSize;
9279     } else if (CurrentType->isSingleValueType()) {
9280       return AggregateSize;
9281     } else {
9282       return None;
9283     }
9284   } while (true);
9285 }
9286 
9287 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9288                                    TargetTransformInfo *TTI,
9289                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9290                                    SmallVectorImpl<Value *> &InsertElts,
9291                                    unsigned OperandOffset) {
9292   do {
9293     Value *InsertedOperand = LastInsertInst->getOperand(1);
9294     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9295     if (!OperandIndex)
9296       return false;
9297     if (isa<InsertElementInst>(InsertedOperand) ||
9298         isa<InsertValueInst>(InsertedOperand)) {
9299       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9300                                   BuildVectorOpds, InsertElts, *OperandIndex))
9301         return false;
9302     } else {
9303       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9304       InsertElts[*OperandIndex] = LastInsertInst;
9305     }
9306     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9307   } while (LastInsertInst != nullptr &&
9308            (isa<InsertValueInst>(LastInsertInst) ||
9309             isa<InsertElementInst>(LastInsertInst)) &&
9310            LastInsertInst->hasOneUse());
9311   return true;
9312 }
9313 
9314 /// Recognize construction of vectors like
9315 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9316 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9317 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9318 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9319 ///  starting from the last insertelement or insertvalue instruction.
9320 ///
9321 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9322 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9323 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9324 ///
9325 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9326 ///
9327 /// \return true if it matches.
9328 static bool findBuildAggregate(Instruction *LastInsertInst,
9329                                TargetTransformInfo *TTI,
9330                                SmallVectorImpl<Value *> &BuildVectorOpds,
9331                                SmallVectorImpl<Value *> &InsertElts) {
9332 
9333   assert((isa<InsertElementInst>(LastInsertInst) ||
9334           isa<InsertValueInst>(LastInsertInst)) &&
9335          "Expected insertelement or insertvalue instruction!");
9336 
9337   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9338          "Expected empty result vectors!");
9339 
9340   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9341   if (!AggregateSize)
9342     return false;
9343   BuildVectorOpds.resize(*AggregateSize);
9344   InsertElts.resize(*AggregateSize);
9345 
9346   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9347                              0)) {
9348     llvm::erase_value(BuildVectorOpds, nullptr);
9349     llvm::erase_value(InsertElts, nullptr);
9350     if (BuildVectorOpds.size() >= 2)
9351       return true;
9352   }
9353 
9354   return false;
9355 }
9356 
9357 /// Try and get a reduction value from a phi node.
9358 ///
9359 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9360 /// if they come from either \p ParentBB or a containing loop latch.
9361 ///
9362 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9363 /// if not possible.
9364 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9365                                 BasicBlock *ParentBB, LoopInfo *LI) {
9366   // There are situations where the reduction value is not dominated by the
9367   // reduction phi. Vectorizing such cases has been reported to cause
9368   // miscompiles. See PR25787.
9369   auto DominatedReduxValue = [&](Value *R) {
9370     return isa<Instruction>(R) &&
9371            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9372   };
9373 
9374   Value *Rdx = nullptr;
9375 
9376   // Return the incoming value if it comes from the same BB as the phi node.
9377   if (P->getIncomingBlock(0) == ParentBB) {
9378     Rdx = P->getIncomingValue(0);
9379   } else if (P->getIncomingBlock(1) == ParentBB) {
9380     Rdx = P->getIncomingValue(1);
9381   }
9382 
9383   if (Rdx && DominatedReduxValue(Rdx))
9384     return Rdx;
9385 
9386   // Otherwise, check whether we have a loop latch to look at.
9387   Loop *BBL = LI->getLoopFor(ParentBB);
9388   if (!BBL)
9389     return nullptr;
9390   BasicBlock *BBLatch = BBL->getLoopLatch();
9391   if (!BBLatch)
9392     return nullptr;
9393 
9394   // There is a loop latch, return the incoming value if it comes from
9395   // that. This reduction pattern occasionally turns up.
9396   if (P->getIncomingBlock(0) == BBLatch) {
9397     Rdx = P->getIncomingValue(0);
9398   } else if (P->getIncomingBlock(1) == BBLatch) {
9399     Rdx = P->getIncomingValue(1);
9400   }
9401 
9402   if (Rdx && DominatedReduxValue(Rdx))
9403     return Rdx;
9404 
9405   return nullptr;
9406 }
9407 
9408 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9409   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9410     return true;
9411   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9412     return true;
9413   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9414     return true;
9415   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9416     return true;
9417   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9418     return true;
9419   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9420     return true;
9421   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9422     return true;
9423   return false;
9424 }
9425 
9426 /// Attempt to reduce a horizontal reduction.
9427 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9428 /// with reduction operators \a Root (or one of its operands) in a basic block
9429 /// \a BB, then check if it can be done. If horizontal reduction is not found
9430 /// and root instruction is a binary operation, vectorization of the operands is
9431 /// attempted.
9432 /// \returns true if a horizontal reduction was matched and reduced or operands
9433 /// of one of the binary instruction were vectorized.
9434 /// \returns false if a horizontal reduction was not matched (or not possible)
9435 /// or no vectorization of any binary operation feeding \a Root instruction was
9436 /// performed.
9437 static bool tryToVectorizeHorReductionOrInstOperands(
9438     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9439     TargetTransformInfo *TTI,
9440     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9441   if (!ShouldVectorizeHor)
9442     return false;
9443 
9444   if (!Root)
9445     return false;
9446 
9447   if (Root->getParent() != BB || isa<PHINode>(Root))
9448     return false;
9449   // Start analysis starting from Root instruction. If horizontal reduction is
9450   // found, try to vectorize it. If it is not a horizontal reduction or
9451   // vectorization is not possible or not effective, and currently analyzed
9452   // instruction is a binary operation, try to vectorize the operands, using
9453   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9454   // the same procedure considering each operand as a possible root of the
9455   // horizontal reduction.
9456   // Interrupt the process if the Root instruction itself was vectorized or all
9457   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9458   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9459   // CmpInsts so we can skip extra attempts in
9460   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9461   std::queue<std::pair<Instruction *, unsigned>> Stack;
9462   Stack.emplace(Root, 0);
9463   SmallPtrSet<Value *, 8> VisitedInstrs;
9464   SmallVector<WeakTrackingVH> PostponedInsts;
9465   bool Res = false;
9466   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9467                                      Value *&B1) -> Value * {
9468     bool IsBinop = matchRdxBop(Inst, B0, B1);
9469     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9470     if (IsBinop || IsSelect) {
9471       HorizontalReduction HorRdx;
9472       if (HorRdx.matchAssociativeReduction(P, Inst))
9473         return HorRdx.tryToReduce(R, TTI);
9474     }
9475     return nullptr;
9476   };
9477   while (!Stack.empty()) {
9478     Instruction *Inst;
9479     unsigned Level;
9480     std::tie(Inst, Level) = Stack.front();
9481     Stack.pop();
9482     // Do not try to analyze instruction that has already been vectorized.
9483     // This may happen when we vectorize instruction operands on a previous
9484     // iteration while stack was populated before that happened.
9485     if (R.isDeleted(Inst))
9486       continue;
9487     Value *B0 = nullptr, *B1 = nullptr;
9488     if (Value *V = TryToReduce(Inst, B0, B1)) {
9489       Res = true;
9490       // Set P to nullptr to avoid re-analysis of phi node in
9491       // matchAssociativeReduction function unless this is the root node.
9492       P = nullptr;
9493       if (auto *I = dyn_cast<Instruction>(V)) {
9494         // Try to find another reduction.
9495         Stack.emplace(I, Level);
9496         continue;
9497       }
9498     } else {
9499       bool IsBinop = B0 && B1;
9500       if (P && IsBinop) {
9501         Inst = dyn_cast<Instruction>(B0);
9502         if (Inst == P)
9503           Inst = dyn_cast<Instruction>(B1);
9504         if (!Inst) {
9505           // Set P to nullptr to avoid re-analysis of phi node in
9506           // matchAssociativeReduction function unless this is the root node.
9507           P = nullptr;
9508           continue;
9509         }
9510       }
9511       // Set P to nullptr to avoid re-analysis of phi node in
9512       // matchAssociativeReduction function unless this is the root node.
9513       P = nullptr;
9514       // Do not try to vectorize CmpInst operands, this is done separately.
9515       // Final attempt for binop args vectorization should happen after the loop
9516       // to try to find reductions.
9517       if (!isa<CmpInst>(Inst))
9518         PostponedInsts.push_back(Inst);
9519     }
9520 
9521     // Try to vectorize operands.
9522     // Continue analysis for the instruction from the same basic block only to
9523     // save compile time.
9524     if (++Level < RecursionMaxDepth)
9525       for (auto *Op : Inst->operand_values())
9526         if (VisitedInstrs.insert(Op).second)
9527           if (auto *I = dyn_cast<Instruction>(Op))
9528             // Do not try to vectorize CmpInst operands,  this is done
9529             // separately.
9530             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9531                 I->getParent() == BB)
9532               Stack.emplace(I, Level);
9533   }
9534   // Try to vectorized binops where reductions were not found.
9535   for (Value *V : PostponedInsts)
9536     if (auto *Inst = dyn_cast<Instruction>(V))
9537       if (!R.isDeleted(Inst))
9538         Res |= Vectorize(Inst, R);
9539   return Res;
9540 }
9541 
9542 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9543                                                  BasicBlock *BB, BoUpSLP &R,
9544                                                  TargetTransformInfo *TTI) {
9545   auto *I = dyn_cast_or_null<Instruction>(V);
9546   if (!I)
9547     return false;
9548 
9549   if (!isa<BinaryOperator>(I))
9550     P = nullptr;
9551   // Try to match and vectorize a horizontal reduction.
9552   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9553     return tryToVectorize(I, R);
9554   };
9555   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9556                                                   ExtraVectorization);
9557 }
9558 
9559 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9560                                                  BasicBlock *BB, BoUpSLP &R) {
9561   const DataLayout &DL = BB->getModule()->getDataLayout();
9562   if (!R.canMapToVector(IVI->getType(), DL))
9563     return false;
9564 
9565   SmallVector<Value *, 16> BuildVectorOpds;
9566   SmallVector<Value *, 16> BuildVectorInsts;
9567   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9568     return false;
9569 
9570   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9571   // Aggregate value is unlikely to be processed in vector register, we need to
9572   // extract scalars into scalar registers, so NeedExtraction is set true.
9573   return tryToVectorizeList(BuildVectorOpds, R);
9574 }
9575 
9576 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9577                                                    BasicBlock *BB, BoUpSLP &R) {
9578   SmallVector<Value *, 16> BuildVectorInsts;
9579   SmallVector<Value *, 16> BuildVectorOpds;
9580   SmallVector<int> Mask;
9581   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9582       (llvm::all_of(
9583            BuildVectorOpds,
9584            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9585        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9586     return false;
9587 
9588   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9589   return tryToVectorizeList(BuildVectorInsts, R);
9590 }
9591 
9592 template <typename T>
9593 static bool
9594 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9595                        function_ref<unsigned(T *)> Limit,
9596                        function_ref<bool(T *, T *)> Comparator,
9597                        function_ref<bool(T *, T *)> AreCompatible,
9598                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorize,
9599                        bool LimitForRegisterSize) {
9600   bool Changed = false;
9601   // Sort by type, parent, operands.
9602   stable_sort(Incoming, Comparator);
9603 
9604   // Try to vectorize elements base on their type.
9605   SmallVector<T *> Candidates;
9606   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9607     // Look for the next elements with the same type, parent and operand
9608     // kinds.
9609     auto *SameTypeIt = IncIt;
9610     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9611       ++SameTypeIt;
9612 
9613     // Try to vectorize them.
9614     unsigned NumElts = (SameTypeIt - IncIt);
9615     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9616                       << NumElts << ")\n");
9617     // The vectorization is a 3-state attempt:
9618     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9619     // size of maximal register at first.
9620     // 2. Try to vectorize remaining instructions with the same type, if
9621     // possible. This may result in the better vectorization results rather than
9622     // if we try just to vectorize instructions with the same/alternate opcodes.
9623     // 3. Final attempt to try to vectorize all instructions with the
9624     // same/alternate ops only, this may result in some extra final
9625     // vectorization.
9626     if (NumElts > 1 &&
9627         TryToVectorize(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9628       // Success start over because instructions might have been changed.
9629       Changed = true;
9630     } else if (NumElts < Limit(*IncIt) &&
9631                (Candidates.empty() ||
9632                 Candidates.front()->getType() == (*IncIt)->getType())) {
9633       Candidates.append(IncIt, std::next(IncIt, NumElts));
9634     }
9635     // Final attempt to vectorize instructions with the same types.
9636     if (Candidates.size() > 1 &&
9637         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9638       if (TryToVectorize(Candidates, /*LimitForRegisterSize=*/false)) {
9639         // Success start over because instructions might have been changed.
9640         Changed = true;
9641       } else if (LimitForRegisterSize) {
9642         // Try to vectorize using small vectors.
9643         for (auto *It = Candidates.begin(), *End = Candidates.end();
9644              It != End;) {
9645           auto *SameTypeIt = It;
9646           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9647             ++SameTypeIt;
9648           unsigned NumElts = (SameTypeIt - It);
9649           if (NumElts > 1 && TryToVectorize(makeArrayRef(It, NumElts),
9650                                             /*LimitForRegisterSize=*/false))
9651             Changed = true;
9652           It = SameTypeIt;
9653         }
9654       }
9655       Candidates.clear();
9656     }
9657 
9658     // Start over at the next instruction of a different type (or the end).
9659     IncIt = SameTypeIt;
9660   }
9661   return Changed;
9662 }
9663 
9664 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9665 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9666 /// operands. If IsCompatibility is false, function implements strict weak
9667 /// ordering relation between two cmp instructions, returning true if the first
9668 /// instruction is "less" than the second, i.e. its predicate is less than the
9669 /// predicate of the second or the operands IDs are less than the operands IDs
9670 /// of the second cmp instruction.
9671 template <bool IsCompatibility>
9672 static bool compareCmp(Value *V, Value *V2,
9673                        function_ref<bool(Instruction *)> IsDeleted) {
9674   auto *CI1 = cast<CmpInst>(V);
9675   auto *CI2 = cast<CmpInst>(V2);
9676   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9677     return false;
9678   if (CI1->getOperand(0)->getType()->getTypeID() <
9679       CI2->getOperand(0)->getType()->getTypeID())
9680     return !IsCompatibility;
9681   if (CI1->getOperand(0)->getType()->getTypeID() >
9682       CI2->getOperand(0)->getType()->getTypeID())
9683     return false;
9684   CmpInst::Predicate Pred1 = CI1->getPredicate();
9685   CmpInst::Predicate Pred2 = CI2->getPredicate();
9686   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9687   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9688   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9689   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9690   if (BasePred1 < BasePred2)
9691     return !IsCompatibility;
9692   if (BasePred1 > BasePred2)
9693     return false;
9694   // Compare operands.
9695   bool LEPreds = Pred1 <= Pred2;
9696   bool GEPreds = Pred1 >= Pred2;
9697   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
9698     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
9699     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
9700     if (Op1->getValueID() < Op2->getValueID())
9701       return !IsCompatibility;
9702     if (Op1->getValueID() > Op2->getValueID())
9703       return false;
9704     if (auto *I1 = dyn_cast<Instruction>(Op1))
9705       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
9706         if (I1->getParent() != I2->getParent())
9707           return false;
9708         InstructionsState S = getSameOpcode({I1, I2});
9709         if (S.getOpcode())
9710           continue;
9711         return false;
9712       }
9713   }
9714   return IsCompatibility;
9715 }
9716 
9717 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9718     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9719     bool AtTerminator) {
9720   bool OpsChanged = false;
9721   SmallVector<Instruction *, 4> PostponedCmps;
9722   for (auto *I : reverse(Instructions)) {
9723     if (R.isDeleted(I))
9724       continue;
9725     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9726       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9727     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9728       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9729     else if (isa<CmpInst>(I))
9730       PostponedCmps.push_back(I);
9731   }
9732   if (AtTerminator) {
9733     // Try to find reductions first.
9734     for (Instruction *I : PostponedCmps) {
9735       if (R.isDeleted(I))
9736         continue;
9737       for (Value *Op : I->operands())
9738         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9739     }
9740     // Try to vectorize operands as vector bundles.
9741     for (Instruction *I : PostponedCmps) {
9742       if (R.isDeleted(I))
9743         continue;
9744       OpsChanged |= tryToVectorize(I, R);
9745     }
9746     // Try to vectorize list of compares.
9747     // Sort by type, compare predicate, etc.
9748     auto &&CompareSorter = [&R](Value *V, Value *V2) {
9749       return compareCmp<false>(V, V2,
9750                                [&R](Instruction *I) { return R.isDeleted(I); });
9751     };
9752 
9753     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
9754       if (V1 == V2)
9755         return true;
9756       return compareCmp<true>(V1, V2,
9757                               [&R](Instruction *I) { return R.isDeleted(I); });
9758     };
9759     auto Limit = [&R](Value *V) {
9760       unsigned EltSize = R.getVectorElementSize(V);
9761       return std::max(2U, R.getMaxVecRegSize() / EltSize);
9762     };
9763 
9764     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
9765     OpsChanged |= tryToVectorizeSequence<Value>(
9766         Vals, Limit, CompareSorter, AreCompatibleCompares,
9767         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9768           // Exclude possible reductions from other blocks.
9769           bool ArePossiblyReducedInOtherBlock =
9770               any_of(Candidates, [](Value *V) {
9771                 return any_of(V->users(), [V](User *U) {
9772                   return isa<SelectInst>(U) &&
9773                          cast<SelectInst>(U)->getParent() !=
9774                              cast<Instruction>(V)->getParent();
9775                 });
9776               });
9777           if (ArePossiblyReducedInOtherBlock)
9778             return false;
9779           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9780         },
9781         /*LimitForRegisterSize=*/true);
9782     Instructions.clear();
9783   } else {
9784     // Insert in reverse order since the PostponedCmps vector was filled in
9785     // reverse order.
9786     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9787   }
9788   return OpsChanged;
9789 }
9790 
9791 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9792   bool Changed = false;
9793   SmallVector<Value *, 4> Incoming;
9794   SmallPtrSet<Value *, 16> VisitedInstrs;
9795   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9796   // node. Allows better to identify the chains that can be vectorized in the
9797   // better way.
9798   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9799   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9800     assert(isValidElementType(V1->getType()) &&
9801            isValidElementType(V2->getType()) &&
9802            "Expected vectorizable types only.");
9803     // It is fine to compare type IDs here, since we expect only vectorizable
9804     // types, like ints, floats and pointers, we don't care about other type.
9805     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9806       return true;
9807     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
9808       return false;
9809     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9810     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9811     if (Opcodes1.size() < Opcodes2.size())
9812       return true;
9813     if (Opcodes1.size() > Opcodes2.size())
9814       return false;
9815     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9816       // Undefs are compatible with any other value.
9817       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9818         continue;
9819       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9820         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9821           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
9822           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
9823           if (!NodeI1)
9824             return NodeI2 != nullptr;
9825           if (!NodeI2)
9826             return false;
9827           assert((NodeI1 == NodeI2) ==
9828                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9829                  "Different nodes should have different DFS numbers");
9830           if (NodeI1 != NodeI2)
9831             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9832           InstructionsState S = getSameOpcode({I1, I2});
9833           if (S.getOpcode())
9834             continue;
9835           return I1->getOpcode() < I2->getOpcode();
9836         }
9837       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9838         continue;
9839       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
9840         return true;
9841       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
9842         return false;
9843     }
9844     return false;
9845   };
9846   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
9847     if (V1 == V2)
9848       return true;
9849     if (V1->getType() != V2->getType())
9850       return false;
9851     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9852     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9853     if (Opcodes1.size() != Opcodes2.size())
9854       return false;
9855     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9856       // Undefs are compatible with any other value.
9857       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9858         continue;
9859       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9860         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9861           if (I1->getParent() != I2->getParent())
9862             return false;
9863           InstructionsState S = getSameOpcode({I1, I2});
9864           if (S.getOpcode())
9865             continue;
9866           return false;
9867         }
9868       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9869         continue;
9870       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
9871         return false;
9872     }
9873     return true;
9874   };
9875   auto Limit = [&R](Value *V) {
9876     unsigned EltSize = R.getVectorElementSize(V);
9877     return std::max(2U, R.getMaxVecRegSize() / EltSize);
9878   };
9879 
9880   bool HaveVectorizedPhiNodes = false;
9881   do {
9882     // Collect the incoming values from the PHIs.
9883     Incoming.clear();
9884     for (Instruction &I : *BB) {
9885       PHINode *P = dyn_cast<PHINode>(&I);
9886       if (!P)
9887         break;
9888 
9889       // No need to analyze deleted, vectorized and non-vectorizable
9890       // instructions.
9891       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
9892           isValidElementType(P->getType()))
9893         Incoming.push_back(P);
9894     }
9895 
9896     // Find the corresponding non-phi nodes for better matching when trying to
9897     // build the tree.
9898     for (Value *V : Incoming) {
9899       SmallVectorImpl<Value *> &Opcodes =
9900           PHIToOpcodes.try_emplace(V).first->getSecond();
9901       if (!Opcodes.empty())
9902         continue;
9903       SmallVector<Value *, 4> Nodes(1, V);
9904       SmallPtrSet<Value *, 4> Visited;
9905       while (!Nodes.empty()) {
9906         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
9907         if (!Visited.insert(PHI).second)
9908           continue;
9909         for (Value *V : PHI->incoming_values()) {
9910           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
9911             Nodes.push_back(PHI1);
9912             continue;
9913           }
9914           Opcodes.emplace_back(V);
9915         }
9916       }
9917     }
9918 
9919     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
9920         Incoming, Limit, PHICompare, AreCompatiblePHIs,
9921         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9922           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9923         },
9924         /*LimitForRegisterSize=*/true);
9925     Changed |= HaveVectorizedPhiNodes;
9926     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
9927   } while (HaveVectorizedPhiNodes);
9928 
9929   VisitedInstrs.clear();
9930 
9931   SmallVector<Instruction *, 8> PostProcessInstructions;
9932   SmallDenseSet<Instruction *, 4> KeyNodes;
9933   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
9934     // Skip instructions with scalable type. The num of elements is unknown at
9935     // compile-time for scalable type.
9936     if (isa<ScalableVectorType>(it->getType()))
9937       continue;
9938 
9939     // Skip instructions marked for the deletion.
9940     if (R.isDeleted(&*it))
9941       continue;
9942     // We may go through BB multiple times so skip the one we have checked.
9943     if (!VisitedInstrs.insert(&*it).second) {
9944       if (it->use_empty() && KeyNodes.contains(&*it) &&
9945           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9946                                       it->isTerminator())) {
9947         // We would like to start over since some instructions are deleted
9948         // and the iterator may become invalid value.
9949         Changed = true;
9950         it = BB->begin();
9951         e = BB->end();
9952       }
9953       continue;
9954     }
9955 
9956     if (isa<DbgInfoIntrinsic>(it))
9957       continue;
9958 
9959     // Try to vectorize reductions that use PHINodes.
9960     if (PHINode *P = dyn_cast<PHINode>(it)) {
9961       // Check that the PHI is a reduction PHI.
9962       if (P->getNumIncomingValues() == 2) {
9963         // Try to match and vectorize a horizontal reduction.
9964         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
9965                                      TTI)) {
9966           Changed = true;
9967           it = BB->begin();
9968           e = BB->end();
9969           continue;
9970         }
9971       }
9972       // Try to vectorize the incoming values of the PHI, to catch reductions
9973       // that feed into PHIs.
9974       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
9975         // Skip if the incoming block is the current BB for now. Also, bypass
9976         // unreachable IR for efficiency and to avoid crashing.
9977         // TODO: Collect the skipped incoming values and try to vectorize them
9978         // after processing BB.
9979         if (BB == P->getIncomingBlock(I) ||
9980             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
9981           continue;
9982 
9983         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
9984                                             P->getIncomingBlock(I), R, TTI);
9985       }
9986       continue;
9987     }
9988 
9989     // Ran into an instruction without users, like terminator, or function call
9990     // with ignored return value, store. Ignore unused instructions (basing on
9991     // instruction type, except for CallInst and InvokeInst).
9992     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
9993                             isa<InvokeInst>(it))) {
9994       KeyNodes.insert(&*it);
9995       bool OpsChanged = false;
9996       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
9997         for (auto *V : it->operand_values()) {
9998           // Try to match and vectorize a horizontal reduction.
9999           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10000         }
10001       }
10002       // Start vectorization of post-process list of instructions from the
10003       // top-tree instructions to try to vectorize as many instructions as
10004       // possible.
10005       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10006                                                 it->isTerminator());
10007       if (OpsChanged) {
10008         // We would like to start over since some instructions are deleted
10009         // and the iterator may become invalid value.
10010         Changed = true;
10011         it = BB->begin();
10012         e = BB->end();
10013         continue;
10014       }
10015     }
10016 
10017     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10018         isa<InsertValueInst>(it))
10019       PostProcessInstructions.push_back(&*it);
10020   }
10021 
10022   return Changed;
10023 }
10024 
10025 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10026   auto Changed = false;
10027   for (auto &Entry : GEPs) {
10028     // If the getelementptr list has fewer than two elements, there's nothing
10029     // to do.
10030     if (Entry.second.size() < 2)
10031       continue;
10032 
10033     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10034                       << Entry.second.size() << ".\n");
10035 
10036     // Process the GEP list in chunks suitable for the target's supported
10037     // vector size. If a vector register can't hold 1 element, we are done. We
10038     // are trying to vectorize the index computations, so the maximum number of
10039     // elements is based on the size of the index expression, rather than the
10040     // size of the GEP itself (the target's pointer size).
10041     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10042     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10043     if (MaxVecRegSize < EltSize)
10044       continue;
10045 
10046     unsigned MaxElts = MaxVecRegSize / EltSize;
10047     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10048       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10049       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10050 
10051       // Initialize a set a candidate getelementptrs. Note that we use a
10052       // SetVector here to preserve program order. If the index computations
10053       // are vectorizable and begin with loads, we want to minimize the chance
10054       // of having to reorder them later.
10055       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10056 
10057       // Some of the candidates may have already been vectorized after we
10058       // initially collected them. If so, they are marked as deleted, so remove
10059       // them from the set of candidates.
10060       Candidates.remove_if(
10061           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10062 
10063       // Remove from the set of candidates all pairs of getelementptrs with
10064       // constant differences. Such getelementptrs are likely not good
10065       // candidates for vectorization in a bottom-up phase since one can be
10066       // computed from the other. We also ensure all candidate getelementptr
10067       // indices are unique.
10068       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10069         auto *GEPI = GEPList[I];
10070         if (!Candidates.count(GEPI))
10071           continue;
10072         auto *SCEVI = SE->getSCEV(GEPList[I]);
10073         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10074           auto *GEPJ = GEPList[J];
10075           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10076           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10077             Candidates.remove(GEPI);
10078             Candidates.remove(GEPJ);
10079           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10080             Candidates.remove(GEPJ);
10081           }
10082         }
10083       }
10084 
10085       // We break out of the above computation as soon as we know there are
10086       // fewer than two candidates remaining.
10087       if (Candidates.size() < 2)
10088         continue;
10089 
10090       // Add the single, non-constant index of each candidate to the bundle. We
10091       // ensured the indices met these constraints when we originally collected
10092       // the getelementptrs.
10093       SmallVector<Value *, 16> Bundle(Candidates.size());
10094       auto BundleIndex = 0u;
10095       for (auto *V : Candidates) {
10096         auto *GEP = cast<GetElementPtrInst>(V);
10097         auto *GEPIdx = GEP->idx_begin()->get();
10098         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10099         Bundle[BundleIndex++] = GEPIdx;
10100       }
10101 
10102       // Try and vectorize the indices. We are currently only interested in
10103       // gather-like cases of the form:
10104       //
10105       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10106       //
10107       // where the loads of "a", the loads of "b", and the subtractions can be
10108       // performed in parallel. It's likely that detecting this pattern in a
10109       // bottom-up phase will be simpler and less costly than building a
10110       // full-blown top-down phase beginning at the consecutive loads.
10111       Changed |= tryToVectorizeList(Bundle, R);
10112     }
10113   }
10114   return Changed;
10115 }
10116 
10117 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10118   bool Changed = false;
10119   // Sort by type, base pointers and values operand. Value operands must be
10120   // compatible (have the same opcode, same parent), otherwise it is
10121   // definitely not profitable to try to vectorize them.
10122   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10123     if (V->getPointerOperandType()->getTypeID() <
10124         V2->getPointerOperandType()->getTypeID())
10125       return true;
10126     if (V->getPointerOperandType()->getTypeID() >
10127         V2->getPointerOperandType()->getTypeID())
10128       return false;
10129     // UndefValues are compatible with all other values.
10130     if (isa<UndefValue>(V->getValueOperand()) ||
10131         isa<UndefValue>(V2->getValueOperand()))
10132       return false;
10133     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10134       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10135         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10136             DT->getNode(I1->getParent());
10137         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10138             DT->getNode(I2->getParent());
10139         assert(NodeI1 && "Should only process reachable instructions");
10140         assert(NodeI1 && "Should only process reachable instructions");
10141         assert((NodeI1 == NodeI2) ==
10142                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10143                "Different nodes should have different DFS numbers");
10144         if (NodeI1 != NodeI2)
10145           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10146         InstructionsState S = getSameOpcode({I1, I2});
10147         if (S.getOpcode())
10148           return false;
10149         return I1->getOpcode() < I2->getOpcode();
10150       }
10151     if (isa<Constant>(V->getValueOperand()) &&
10152         isa<Constant>(V2->getValueOperand()))
10153       return false;
10154     return V->getValueOperand()->getValueID() <
10155            V2->getValueOperand()->getValueID();
10156   };
10157 
10158   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10159     if (V1 == V2)
10160       return true;
10161     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10162       return false;
10163     // Undefs are compatible with any other value.
10164     if (isa<UndefValue>(V1->getValueOperand()) ||
10165         isa<UndefValue>(V2->getValueOperand()))
10166       return true;
10167     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10168       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10169         if (I1->getParent() != I2->getParent())
10170           return false;
10171         InstructionsState S = getSameOpcode({I1, I2});
10172         return S.getOpcode() > 0;
10173       }
10174     if (isa<Constant>(V1->getValueOperand()) &&
10175         isa<Constant>(V2->getValueOperand()))
10176       return true;
10177     return V1->getValueOperand()->getValueID() ==
10178            V2->getValueOperand()->getValueID();
10179   };
10180   auto Limit = [&R, this](StoreInst *SI) {
10181     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10182     return R.getMinVF(EltSize);
10183   };
10184 
10185   // Attempt to sort and vectorize each of the store-groups.
10186   for (auto &Pair : Stores) {
10187     if (Pair.second.size() < 2)
10188       continue;
10189 
10190     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10191                       << Pair.second.size() << ".\n");
10192 
10193     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10194       continue;
10195 
10196     Changed |= tryToVectorizeSequence<StoreInst>(
10197         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10198         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10199           return vectorizeStores(Candidates, R);
10200         },
10201         /*LimitForRegisterSize=*/false);
10202   }
10203   return Changed;
10204 }
10205 
10206 char SLPVectorizer::ID = 0;
10207 
10208 static const char lv_name[] = "SLP Vectorizer";
10209 
10210 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10211 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10212 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10213 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10214 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10215 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10216 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10217 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10218 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10219 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10220 
10221 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10222