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