1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The Look-ahead heuristic goes through the users of the bundle to calculate
168 // the users cost in getExternalUsesCost(). To avoid compilation time increase
169 // we limit the number of users visited to this value.
170 static cl::opt<unsigned> LookAheadUsersBudget(
171     "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
172     cl::desc("The maximum number of users to visit while visiting the "
173              "predecessors. This prevents compilation time increase."));
174 
175 static cl::opt<bool>
176     ViewSLPTree("view-slp-tree", cl::Hidden,
177                 cl::desc("Display the SLP trees with Graphviz"));
178 
179 // Limit the number of alias checks. The limit is chosen so that
180 // it has no negative effect on the llvm benchmarks.
181 static const unsigned AliasedCheckLimit = 10;
182 
183 // Another limit for the alias checks: The maximum distance between load/store
184 // instructions where alias checks are done.
185 // This limit is useful for very large basic blocks.
186 static const unsigned MaxMemDepDistance = 160;
187 
188 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
189 /// regions to be handled.
190 static const int MinScheduleRegionSize = 16;
191 
192 /// Predicate for the element types that the SLP vectorizer supports.
193 ///
194 /// The most important thing to filter here are types which are invalid in LLVM
195 /// vectors. We also filter target specific types which have absolutely no
196 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
197 /// avoids spending time checking the cost model and realizing that they will
198 /// be inevitably scalarized.
199 static bool isValidElementType(Type *Ty) {
200   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
201          !Ty->isPPC_FP128Ty();
202 }
203 
204 /// \returns True if the value is a constant (but not globals/constant
205 /// expressions).
206 static bool isConstant(Value *V) {
207   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
208 }
209 
210 /// Checks if \p V is one of vector-like instructions, i.e. undef,
211 /// insertelement/extractelement with constant indices for fixed vector type or
212 /// extractvalue instruction.
213 static bool isVectorLikeInstWithConstOps(Value *V) {
214   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
215       !isa<ExtractValueInst, UndefValue>(V))
216     return false;
217   auto *I = dyn_cast<Instruction>(V);
218   if (!I || isa<ExtractValueInst>(I))
219     return true;
220   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
221     return false;
222   if (isa<ExtractElementInst>(I))
223     return isConstant(I->getOperand(1));
224   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
225   return isConstant(I->getOperand(2));
226 }
227 
228 /// \returns true if all of the instructions in \p VL are in the same block or
229 /// false otherwise.
230 static bool allSameBlock(ArrayRef<Value *> VL) {
231   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
232   if (!I0)
233     return false;
234   if (all_of(VL, isVectorLikeInstWithConstOps))
235     return true;
236 
237   BasicBlock *BB = I0->getParent();
238   for (int I = 1, E = VL.size(); I < E; I++) {
239     auto *II = dyn_cast<Instruction>(VL[I]);
240     if (!II)
241       return false;
242 
243     if (BB != II->getParent())
244       return false;
245   }
246   return true;
247 }
248 
249 /// \returns True if all of the values in \p VL are constants (but not
250 /// globals/constant expressions).
251 static bool allConstant(ArrayRef<Value *> VL) {
252   // Constant expressions and globals can't be vectorized like normal integer/FP
253   // constants.
254   return all_of(VL, isConstant);
255 }
256 
257 /// \returns True if all of the values in \p VL are identical or some of them
258 /// are UndefValue.
259 static bool isSplat(ArrayRef<Value *> VL) {
260   Value *FirstNonUndef = nullptr;
261   for (Value *V : VL) {
262     if (isa<UndefValue>(V))
263       continue;
264     if (!FirstNonUndef) {
265       FirstNonUndef = V;
266       continue;
267     }
268     if (V != FirstNonUndef)
269       return false;
270   }
271   return FirstNonUndef != nullptr;
272 }
273 
274 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
275 static bool isCommutative(Instruction *I) {
276   if (auto *Cmp = dyn_cast<CmpInst>(I))
277     return Cmp->isCommutative();
278   if (auto *BO = dyn_cast<BinaryOperator>(I))
279     return BO->isCommutative();
280   // TODO: This should check for generic Instruction::isCommutative(), but
281   //       we need to confirm that the caller code correctly handles Intrinsics
282   //       for example (does not have 2 operands).
283   return false;
284 }
285 
286 /// Checks if the given value is actually an undefined constant vector.
287 static bool isUndefVector(const Value *V) {
288   if (isa<UndefValue>(V))
289     return true;
290   auto *C = dyn_cast<Constant>(V);
291   if (!C)
292     return false;
293   if (!C->containsUndefOrPoisonElement())
294     return false;
295   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
296   if (!VecTy)
297     return false;
298   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
299     if (Constant *Elem = C->getAggregateElement(I))
300       if (!isa<UndefValue>(Elem))
301         return false;
302   }
303   return true;
304 }
305 
306 /// Checks if the vector of instructions can be represented as a shuffle, like:
307 /// %x0 = extractelement <4 x i8> %x, i32 0
308 /// %x3 = extractelement <4 x i8> %x, i32 3
309 /// %y1 = extractelement <4 x i8> %y, i32 1
310 /// %y2 = extractelement <4 x i8> %y, i32 2
311 /// %x0x0 = mul i8 %x0, %x0
312 /// %x3x3 = mul i8 %x3, %x3
313 /// %y1y1 = mul i8 %y1, %y1
314 /// %y2y2 = mul i8 %y2, %y2
315 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
316 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
317 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
318 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
319 /// ret <4 x i8> %ins4
320 /// can be transformed into:
321 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
322 ///                                                         i32 6>
323 /// %2 = mul <4 x i8> %1, %1
324 /// ret <4 x i8> %2
325 /// We convert this initially to something like:
326 /// %x0 = extractelement <4 x i8> %x, i32 0
327 /// %x3 = extractelement <4 x i8> %x, i32 3
328 /// %y1 = extractelement <4 x i8> %y, i32 1
329 /// %y2 = extractelement <4 x i8> %y, i32 2
330 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
331 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
332 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
333 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
334 /// %5 = mul <4 x i8> %4, %4
335 /// %6 = extractelement <4 x i8> %5, i32 0
336 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
337 /// %7 = extractelement <4 x i8> %5, i32 1
338 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
339 /// %8 = extractelement <4 x i8> %5, i32 2
340 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
341 /// %9 = extractelement <4 x i8> %5, i32 3
342 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
343 /// ret <4 x i8> %ins4
344 /// InstCombiner transforms this into a shuffle and vector mul
345 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
346 /// TODO: Can we split off and reuse the shuffle mask detection from
347 /// TargetTransformInfo::getInstructionThroughput?
348 static Optional<TargetTransformInfo::ShuffleKind>
349 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
350   const auto *It =
351       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
352   if (It == VL.end())
353     return None;
354   auto *EI0 = cast<ExtractElementInst>(*It);
355   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
356     return None;
357   unsigned Size =
358       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
359   Value *Vec1 = nullptr;
360   Value *Vec2 = nullptr;
361   enum ShuffleMode { Unknown, Select, Permute };
362   ShuffleMode CommonShuffleMode = Unknown;
363   Mask.assign(VL.size(), UndefMaskElem);
364   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
365     // Undef can be represented as an undef element in a vector.
366     if (isa<UndefValue>(VL[I]))
367       continue;
368     auto *EI = cast<ExtractElementInst>(VL[I]);
369     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
370       return None;
371     auto *Vec = EI->getVectorOperand();
372     // We can extractelement from undef or poison vector.
373     if (isUndefVector(Vec))
374       continue;
375     // All vector operands must have the same number of vector elements.
376     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
377       return None;
378     if (isa<UndefValue>(EI->getIndexOperand()))
379       continue;
380     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
381     if (!Idx)
382       return None;
383     // Undefined behavior if Idx is negative or >= Size.
384     if (Idx->getValue().uge(Size))
385       continue;
386     unsigned IntIdx = Idx->getValue().getZExtValue();
387     Mask[I] = IntIdx;
388     // For correct shuffling we have to have at most 2 different vector operands
389     // in all extractelement instructions.
390     if (!Vec1 || Vec1 == Vec) {
391       Vec1 = Vec;
392     } else if (!Vec2 || Vec2 == Vec) {
393       Vec2 = Vec;
394       Mask[I] += Size;
395     } else {
396       return None;
397     }
398     if (CommonShuffleMode == Permute)
399       continue;
400     // If the extract index is not the same as the operation number, it is a
401     // permutation.
402     if (IntIdx != I) {
403       CommonShuffleMode = Permute;
404       continue;
405     }
406     CommonShuffleMode = Select;
407   }
408   // If we're not crossing lanes in different vectors, consider it as blending.
409   if (CommonShuffleMode == Select && Vec2)
410     return TargetTransformInfo::SK_Select;
411   // If Vec2 was never used, we have a permutation of a single vector, otherwise
412   // we have permutation of 2 vectors.
413   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
414               : TargetTransformInfo::SK_PermuteSingleSrc;
415 }
416 
417 namespace {
418 
419 /// Main data required for vectorization of instructions.
420 struct InstructionsState {
421   /// The very first instruction in the list with the main opcode.
422   Value *OpValue = nullptr;
423 
424   /// The main/alternate instruction.
425   Instruction *MainOp = nullptr;
426   Instruction *AltOp = nullptr;
427 
428   /// The main/alternate opcodes for the list of instructions.
429   unsigned getOpcode() const {
430     return MainOp ? MainOp->getOpcode() : 0;
431   }
432 
433   unsigned getAltOpcode() const {
434     return AltOp ? AltOp->getOpcode() : 0;
435   }
436 
437   /// Some of the instructions in the list have alternate opcodes.
438   bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
439 
440   bool isOpcodeOrAlt(Instruction *I) const {
441     unsigned CheckedOpcode = I->getOpcode();
442     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
443   }
444 
445   InstructionsState() = delete;
446   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
447       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
448 };
449 
450 } // end anonymous namespace
451 
452 /// Chooses the correct key for scheduling data. If \p Op has the same (or
453 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
454 /// OpValue.
455 static Value *isOneOf(const InstructionsState &S, Value *Op) {
456   auto *I = dyn_cast<Instruction>(Op);
457   if (I && S.isOpcodeOrAlt(I))
458     return Op;
459   return S.OpValue;
460 }
461 
462 /// \returns true if \p Opcode is allowed as part of of the main/alternate
463 /// instruction for SLP vectorization.
464 ///
465 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
466 /// "shuffled out" lane would result in division by zero.
467 static bool isValidForAlternation(unsigned Opcode) {
468   if (Instruction::isIntDivRem(Opcode))
469     return false;
470 
471   return true;
472 }
473 
474 /// \returns analysis of the Instructions in \p VL described in
475 /// InstructionsState, the Opcode that we suppose the whole list
476 /// could be vectorized even if its structure is diverse.
477 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
478                                        unsigned BaseIndex = 0) {
479   // Make sure these are all Instructions.
480   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
481     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
482 
483   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
484   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
485   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
486   unsigned AltOpcode = Opcode;
487   unsigned AltIndex = BaseIndex;
488 
489   // Check for one alternate opcode from another BinaryOperator.
490   // TODO - generalize to support all operators (types, calls etc.).
491   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
492     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
493     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
494       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
495         continue;
496       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
497           isValidForAlternation(Opcode)) {
498         AltOpcode = InstOpcode;
499         AltIndex = Cnt;
500         continue;
501       }
502     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
503       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
504       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
505       if (Ty0 == Ty1) {
506         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
507           continue;
508         if (Opcode == AltOpcode) {
509           assert(isValidForAlternation(Opcode) &&
510                  isValidForAlternation(InstOpcode) &&
511                  "Cast isn't safe for alternation, logic needs to be updated!");
512           AltOpcode = InstOpcode;
513           AltIndex = Cnt;
514           continue;
515         }
516       }
517     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518       continue;
519     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
520   }
521 
522   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
523                            cast<Instruction>(VL[AltIndex]));
524 }
525 
526 /// \returns true if all of the values in \p VL have the same type or false
527 /// otherwise.
528 static bool allSameType(ArrayRef<Value *> VL) {
529   Type *Ty = VL[0]->getType();
530   for (int i = 1, e = VL.size(); i < e; i++)
531     if (VL[i]->getType() != Ty)
532       return false;
533 
534   return true;
535 }
536 
537 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
538 static Optional<unsigned> getExtractIndex(Instruction *E) {
539   unsigned Opcode = E->getOpcode();
540   assert((Opcode == Instruction::ExtractElement ||
541           Opcode == Instruction::ExtractValue) &&
542          "Expected extractelement or extractvalue instruction.");
543   if (Opcode == Instruction::ExtractElement) {
544     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
545     if (!CI)
546       return None;
547     return CI->getZExtValue();
548   }
549   ExtractValueInst *EI = cast<ExtractValueInst>(E);
550   if (EI->getNumIndices() != 1)
551     return None;
552   return *EI->idx_begin();
553 }
554 
555 /// \returns True if in-tree use also needs extract. This refers to
556 /// possible scalar operand in vectorized instruction.
557 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
558                                     TargetLibraryInfo *TLI) {
559   unsigned Opcode = UserInst->getOpcode();
560   switch (Opcode) {
561   case Instruction::Load: {
562     LoadInst *LI = cast<LoadInst>(UserInst);
563     return (LI->getPointerOperand() == Scalar);
564   }
565   case Instruction::Store: {
566     StoreInst *SI = cast<StoreInst>(UserInst);
567     return (SI->getPointerOperand() == Scalar);
568   }
569   case Instruction::Call: {
570     CallInst *CI = cast<CallInst>(UserInst);
571     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
572     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
573       if (hasVectorInstrinsicScalarOpd(ID, i))
574         return (CI->getArgOperand(i) == Scalar);
575     }
576     LLVM_FALLTHROUGH;
577   }
578   default:
579     return false;
580   }
581 }
582 
583 /// \returns the AA location that is being access by the instruction.
584 static MemoryLocation getLocation(Instruction *I, AAResults *AA) {
585   if (StoreInst *SI = dyn_cast<StoreInst>(I))
586     return MemoryLocation::get(SI);
587   if (LoadInst *LI = dyn_cast<LoadInst>(I))
588     return MemoryLocation::get(LI);
589   return MemoryLocation();
590 }
591 
592 /// \returns True if the instruction is not a volatile or atomic load/store.
593 static bool isSimple(Instruction *I) {
594   if (LoadInst *LI = dyn_cast<LoadInst>(I))
595     return LI->isSimple();
596   if (StoreInst *SI = dyn_cast<StoreInst>(I))
597     return SI->isSimple();
598   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
599     return !MI->isVolatile();
600   return true;
601 }
602 
603 /// Shuffles \p Mask in accordance with the given \p SubMask.
604 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
605   if (SubMask.empty())
606     return;
607   if (Mask.empty()) {
608     Mask.append(SubMask.begin(), SubMask.end());
609     return;
610   }
611   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
612   int TermValue = std::min(Mask.size(), SubMask.size());
613   for (int I = 0, E = SubMask.size(); I < E; ++I) {
614     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
615         Mask[SubMask[I]] >= TermValue)
616       continue;
617     NewMask[I] = Mask[SubMask[I]];
618   }
619   Mask.swap(NewMask);
620 }
621 
622 /// Order may have elements assigned special value (size) which is out of
623 /// bounds. Such indices only appear on places which correspond to undef values
624 /// (see canReuseExtract for details) and used in order to avoid undef values
625 /// have effect on operands ordering.
626 /// The first loop below simply finds all unused indices and then the next loop
627 /// nest assigns these indices for undef values positions.
628 /// As an example below Order has two undef positions and they have assigned
629 /// values 3 and 7 respectively:
630 /// before:  6 9 5 4 9 2 1 0
631 /// after:   6 3 5 4 7 2 1 0
632 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
633   const unsigned Sz = Order.size();
634   SmallBitVector UnusedIndices(Sz, /*t=*/true);
635   SmallBitVector MaskedIndices(Sz);
636   for (unsigned I = 0; I < Sz; ++I) {
637     if (Order[I] < Sz)
638       UnusedIndices.reset(Order[I]);
639     else
640       MaskedIndices.set(I);
641   }
642   if (MaskedIndices.none())
643     return;
644   assert(UnusedIndices.count() == MaskedIndices.count() &&
645          "Non-synced masked/available indices.");
646   int Idx = UnusedIndices.find_first();
647   int MIdx = MaskedIndices.find_first();
648   while (MIdx >= 0) {
649     assert(Idx >= 0 && "Indices must be synced.");
650     Order[MIdx] = Idx;
651     Idx = UnusedIndices.find_next(Idx);
652     MIdx = MaskedIndices.find_next(MIdx);
653   }
654 }
655 
656 namespace llvm {
657 
658 static void inversePermutation(ArrayRef<unsigned> Indices,
659                                SmallVectorImpl<int> &Mask) {
660   Mask.clear();
661   const unsigned E = Indices.size();
662   Mask.resize(E, UndefMaskElem);
663   for (unsigned I = 0; I < E; ++I)
664     Mask[Indices[I]] = I;
665 }
666 
667 /// \returns inserting index of InsertElement or InsertValue instruction,
668 /// using Offset as base offset for index.
669 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
670   int Index = Offset;
671   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
672     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
673       auto *VT = cast<FixedVectorType>(IE->getType());
674       if (CI->getValue().uge(VT->getNumElements()))
675         return UndefMaskElem;
676       Index *= VT->getNumElements();
677       Index += CI->getZExtValue();
678       return Index;
679     }
680     if (isa<UndefValue>(IE->getOperand(2)))
681       return UndefMaskElem;
682     return None;
683   }
684 
685   auto *IV = cast<InsertValueInst>(InsertInst);
686   Type *CurrentType = IV->getType();
687   for (unsigned I : IV->indices()) {
688     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
689       Index *= ST->getNumElements();
690       CurrentType = ST->getElementType(I);
691     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
692       Index *= AT->getNumElements();
693       CurrentType = AT->getElementType();
694     } else {
695       return None;
696     }
697     Index += I;
698   }
699   return Index;
700 }
701 
702 /// Reorders the list of scalars in accordance with the given \p Order and then
703 /// the \p Mask. \p Order - is the original order of the scalars, need to
704 /// reorder scalars into an unordered state at first according to the given
705 /// order. Then the ordered scalars are shuffled once again in accordance with
706 /// the provided mask.
707 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
708                            ArrayRef<int> Mask) {
709   assert(!Mask.empty() && "Expected non-empty mask.");
710   SmallVector<Value *> Prev(Scalars.size(),
711                             UndefValue::get(Scalars.front()->getType()));
712   Prev.swap(Scalars);
713   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
714     if (Mask[I] != UndefMaskElem)
715       Scalars[Mask[I]] = Prev[I];
716 }
717 
718 namespace slpvectorizer {
719 
720 /// Bottom Up SLP Vectorizer.
721 class BoUpSLP {
722   struct TreeEntry;
723   struct ScheduleData;
724 
725 public:
726   using ValueList = SmallVector<Value *, 8>;
727   using InstrList = SmallVector<Instruction *, 16>;
728   using ValueSet = SmallPtrSet<Value *, 16>;
729   using StoreList = SmallVector<StoreInst *, 8>;
730   using ExtraValueToDebugLocsMap =
731       MapVector<Value *, SmallVector<Instruction *, 2>>;
732   using OrdersType = SmallVector<unsigned, 4>;
733 
734   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
735           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
736           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
737           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
738       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
739         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
740     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
741     // Use the vector register size specified by the target unless overridden
742     // by a command-line option.
743     // TODO: It would be better to limit the vectorization factor based on
744     //       data type rather than just register size. For example, x86 AVX has
745     //       256-bit registers, but it does not support integer operations
746     //       at that width (that requires AVX2).
747     if (MaxVectorRegSizeOption.getNumOccurrences())
748       MaxVecRegSize = MaxVectorRegSizeOption;
749     else
750       MaxVecRegSize =
751           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
752               .getFixedSize();
753 
754     if (MinVectorRegSizeOption.getNumOccurrences())
755       MinVecRegSize = MinVectorRegSizeOption;
756     else
757       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
758   }
759 
760   /// Vectorize the tree that starts with the elements in \p VL.
761   /// Returns the vectorized root.
762   Value *vectorizeTree();
763 
764   /// Vectorize the tree but with the list of externally used values \p
765   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
766   /// generated extractvalue instructions.
767   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
768 
769   /// \returns the cost incurred by unwanted spills and fills, caused by
770   /// holding live values over call sites.
771   InstructionCost getSpillCost() const;
772 
773   /// \returns the vectorization cost of the subtree that starts at \p VL.
774   /// A negative number means that this is profitable.
775   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
776 
777   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
778   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
779   void buildTree(ArrayRef<Value *> Roots,
780                  ArrayRef<Value *> UserIgnoreLst = None);
781 
782   /// Builds external uses of the vectorized scalars, i.e. the list of
783   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
784   /// ExternallyUsedValues contains additional list of external uses to handle
785   /// vectorization of reductions.
786   void
787   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
788 
789   /// Clear the internal data structures that are created by 'buildTree'.
790   void deleteTree() {
791     VectorizableTree.clear();
792     ScalarToTreeEntry.clear();
793     MustGather.clear();
794     ExternalUses.clear();
795     for (auto &Iter : BlocksSchedules) {
796       BlockScheduling *BS = Iter.second.get();
797       BS->clear();
798     }
799     MinBWs.clear();
800     InstrElementSize.clear();
801   }
802 
803   unsigned getTreeSize() const { return VectorizableTree.size(); }
804 
805   /// Perform LICM and CSE on the newly generated gather sequences.
806   void optimizeGatherSequence();
807 
808   /// Checks if the specified gather tree entry \p TE can be represented as a
809   /// shuffled vector entry + (possibly) permutation with other gathers. It
810   /// implements the checks only for possibly ordered scalars (Loads,
811   /// ExtractElement, ExtractValue), which can be part of the graph.
812   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
813 
814   /// Gets reordering data for the given tree entry. If the entry is vectorized
815   /// - just return ReorderIndices, otherwise check if the scalars can be
816   /// reordered and return the most optimal order.
817   /// \param TopToBottom If true, include the order of vectorized stores and
818   /// insertelement nodes, otherwise skip them.
819   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
820 
821   /// Reorders the current graph to the most profitable order starting from the
822   /// root node to the leaf nodes. The best order is chosen only from the nodes
823   /// of the same size (vectorization factor). Smaller nodes are considered
824   /// parts of subgraph with smaller VF and they are reordered independently. We
825   /// can make it because we still need to extend smaller nodes to the wider VF
826   /// and we can merge reordering shuffles with the widening shuffles.
827   void reorderTopToBottom();
828 
829   /// Reorders the current graph to the most profitable order starting from
830   /// leaves to the root. It allows to rotate small subgraphs and reduce the
831   /// number of reshuffles if the leaf nodes use the same order. In this case we
832   /// can merge the orders and just shuffle user node instead of shuffling its
833   /// operands. Plus, even the leaf nodes have different orders, it allows to
834   /// sink reordering in the graph closer to the root node and merge it later
835   /// during analysis.
836   void reorderBottomToTop(bool IgnoreReorder = false);
837 
838   /// \return The vector element size in bits to use when vectorizing the
839   /// expression tree ending at \p V. If V is a store, the size is the width of
840   /// the stored value. Otherwise, the size is the width of the largest loaded
841   /// value reaching V. This method is used by the vectorizer to calculate
842   /// vectorization factors.
843   unsigned getVectorElementSize(Value *V);
844 
845   /// Compute the minimum type sizes required to represent the entries in a
846   /// vectorizable tree.
847   void computeMinimumValueSizes();
848 
849   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
850   unsigned getMaxVecRegSize() const {
851     return MaxVecRegSize;
852   }
853 
854   // \returns minimum vector register size as set by cl::opt.
855   unsigned getMinVecRegSize() const {
856     return MinVecRegSize;
857   }
858 
859   unsigned getMinVF(unsigned Sz) const {
860     return std::max(2U, getMinVecRegSize() / Sz);
861   }
862 
863   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
864     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
865       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
866     return MaxVF ? MaxVF : UINT_MAX;
867   }
868 
869   /// Check if homogeneous aggregate is isomorphic to some VectorType.
870   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
871   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
872   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
873   ///
874   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
875   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
876 
877   /// \returns True if the VectorizableTree is both tiny and not fully
878   /// vectorizable. We do not vectorize such trees.
879   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
880 
881   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
882   /// can be load combined in the backend. Load combining may not be allowed in
883   /// the IR optimizer, so we do not want to alter the pattern. For example,
884   /// partially transforming a scalar bswap() pattern into vector code is
885   /// effectively impossible for the backend to undo.
886   /// TODO: If load combining is allowed in the IR optimizer, this analysis
887   ///       may not be necessary.
888   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
889 
890   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
891   /// can be load combined in the backend. Load combining may not be allowed in
892   /// the IR optimizer, so we do not want to alter the pattern. For example,
893   /// partially transforming a scalar bswap() pattern into vector code is
894   /// effectively impossible for the backend to undo.
895   /// TODO: If load combining is allowed in the IR optimizer, this analysis
896   ///       may not be necessary.
897   bool isLoadCombineCandidate() const;
898 
899   OptimizationRemarkEmitter *getORE() { return ORE; }
900 
901   /// This structure holds any data we need about the edges being traversed
902   /// during buildTree_rec(). We keep track of:
903   /// (i) the user TreeEntry index, and
904   /// (ii) the index of the edge.
905   struct EdgeInfo {
906     EdgeInfo() = default;
907     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
908         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
909     /// The user TreeEntry.
910     TreeEntry *UserTE = nullptr;
911     /// The operand index of the use.
912     unsigned EdgeIdx = UINT_MAX;
913 #ifndef NDEBUG
914     friend inline raw_ostream &operator<<(raw_ostream &OS,
915                                           const BoUpSLP::EdgeInfo &EI) {
916       EI.dump(OS);
917       return OS;
918     }
919     /// Debug print.
920     void dump(raw_ostream &OS) const {
921       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
922          << " EdgeIdx:" << EdgeIdx << "}";
923     }
924     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
925 #endif
926   };
927 
928   /// A helper data structure to hold the operands of a vector of instructions.
929   /// This supports a fixed vector length for all operand vectors.
930   class VLOperands {
931     /// For each operand we need (i) the value, and (ii) the opcode that it
932     /// would be attached to if the expression was in a left-linearized form.
933     /// This is required to avoid illegal operand reordering.
934     /// For example:
935     /// \verbatim
936     ///                         0 Op1
937     ///                         |/
938     /// Op1 Op2   Linearized    + Op2
939     ///   \ /     ---------->   |/
940     ///    -                    -
941     ///
942     /// Op1 - Op2            (0 + Op1) - Op2
943     /// \endverbatim
944     ///
945     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
946     ///
947     /// Another way to think of this is to track all the operations across the
948     /// path from the operand all the way to the root of the tree and to
949     /// calculate the operation that corresponds to this path. For example, the
950     /// path from Op2 to the root crosses the RHS of the '-', therefore the
951     /// corresponding operation is a '-' (which matches the one in the
952     /// linearized tree, as shown above).
953     ///
954     /// For lack of a better term, we refer to this operation as Accumulated
955     /// Path Operation (APO).
956     struct OperandData {
957       OperandData() = default;
958       OperandData(Value *V, bool APO, bool IsUsed)
959           : V(V), APO(APO), IsUsed(IsUsed) {}
960       /// The operand value.
961       Value *V = nullptr;
962       /// TreeEntries only allow a single opcode, or an alternate sequence of
963       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
964       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
965       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
966       /// (e.g., Add/Mul)
967       bool APO = false;
968       /// Helper data for the reordering function.
969       bool IsUsed = false;
970     };
971 
972     /// During operand reordering, we are trying to select the operand at lane
973     /// that matches best with the operand at the neighboring lane. Our
974     /// selection is based on the type of value we are looking for. For example,
975     /// if the neighboring lane has a load, we need to look for a load that is
976     /// accessing a consecutive address. These strategies are summarized in the
977     /// 'ReorderingMode' enumerator.
978     enum class ReorderingMode {
979       Load,     ///< Matching loads to consecutive memory addresses
980       Opcode,   ///< Matching instructions based on opcode (same or alternate)
981       Constant, ///< Matching constants
982       Splat,    ///< Matching the same instruction multiple times (broadcast)
983       Failed,   ///< We failed to create a vectorizable group
984     };
985 
986     using OperandDataVec = SmallVector<OperandData, 2>;
987 
988     /// A vector of operand vectors.
989     SmallVector<OperandDataVec, 4> OpsVec;
990 
991     const DataLayout &DL;
992     ScalarEvolution &SE;
993     const BoUpSLP &R;
994 
995     /// \returns the operand data at \p OpIdx and \p Lane.
996     OperandData &getData(unsigned OpIdx, unsigned Lane) {
997       return OpsVec[OpIdx][Lane];
998     }
999 
1000     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1001     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1002       return OpsVec[OpIdx][Lane];
1003     }
1004 
1005     /// Clears the used flag for all entries.
1006     void clearUsed() {
1007       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1008            OpIdx != NumOperands; ++OpIdx)
1009         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1010              ++Lane)
1011           OpsVec[OpIdx][Lane].IsUsed = false;
1012     }
1013 
1014     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1015     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1016       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1017     }
1018 
1019     // The hard-coded scores listed here are not very important, though it shall
1020     // be higher for better matches to improve the resulting cost. When
1021     // computing the scores of matching one sub-tree with another, we are
1022     // basically counting the number of values that are matching. So even if all
1023     // scores are set to 1, we would still get a decent matching result.
1024     // However, sometimes we have to break ties. For example we may have to
1025     // choose between matching loads vs matching opcodes. This is what these
1026     // scores are helping us with: they provide the order of preference. Also,
1027     // this is important if the scalar is externally used or used in another
1028     // tree entry node in the different lane.
1029 
1030     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1031     static const int ScoreConsecutiveLoads = 4;
1032     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1033     static const int ScoreReversedLoads = 3;
1034     /// ExtractElementInst from same vector and consecutive indexes.
1035     static const int ScoreConsecutiveExtracts = 4;
1036     /// ExtractElementInst from same vector and reversed indices.
1037     static const int ScoreReversedExtracts = 3;
1038     /// Constants.
1039     static const int ScoreConstants = 2;
1040     /// Instructions with the same opcode.
1041     static const int ScoreSameOpcode = 2;
1042     /// Instructions with alt opcodes (e.g, add + sub).
1043     static const int ScoreAltOpcodes = 1;
1044     /// Identical instructions (a.k.a. splat or broadcast).
1045     static const int ScoreSplat = 1;
1046     /// Matching with an undef is preferable to failing.
1047     static const int ScoreUndef = 1;
1048     /// Score for failing to find a decent match.
1049     static const int ScoreFail = 0;
1050     /// User exteranl to the vectorized code.
1051     static const int ExternalUseCost = 1;
1052     /// The user is internal but in a different lane.
1053     static const int UserInDiffLaneCost = ExternalUseCost;
1054 
1055     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1056     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1057                                ScalarEvolution &SE, int NumLanes) {
1058       if (V1 == V2)
1059         return VLOperands::ScoreSplat;
1060 
1061       auto *LI1 = dyn_cast<LoadInst>(V1);
1062       auto *LI2 = dyn_cast<LoadInst>(V2);
1063       if (LI1 && LI2) {
1064         if (LI1->getParent() != LI2->getParent())
1065           return VLOperands::ScoreFail;
1066 
1067         Optional<int> Dist = getPointersDiff(
1068             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1069             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1070         if (!Dist)
1071           return VLOperands::ScoreFail;
1072         // The distance is too large - still may be profitable to use masked
1073         // loads/gathers.
1074         if (std::abs(*Dist) > NumLanes / 2)
1075           return VLOperands::ScoreAltOpcodes;
1076         // This still will detect consecutive loads, but we might have "holes"
1077         // in some cases. It is ok for non-power-2 vectorization and may produce
1078         // better results. It should not affect current vectorization.
1079         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1080                            : VLOperands::ScoreReversedLoads;
1081       }
1082 
1083       auto *C1 = dyn_cast<Constant>(V1);
1084       auto *C2 = dyn_cast<Constant>(V2);
1085       if (C1 && C2)
1086         return VLOperands::ScoreConstants;
1087 
1088       // Extracts from consecutive indexes of the same vector better score as
1089       // the extracts could be optimized away.
1090       Value *EV1;
1091       ConstantInt *Ex1Idx;
1092       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1093         // Undefs are always profitable for extractelements.
1094         if (isa<UndefValue>(V2))
1095           return VLOperands::ScoreConsecutiveExtracts;
1096         Value *EV2 = nullptr;
1097         ConstantInt *Ex2Idx = nullptr;
1098         if (match(V2,
1099                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1100                                                          m_Undef())))) {
1101           // Undefs are always profitable for extractelements.
1102           if (!Ex2Idx)
1103             return VLOperands::ScoreConsecutiveExtracts;
1104           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1105             return VLOperands::ScoreConsecutiveExtracts;
1106           if (EV2 == EV1) {
1107             int Idx1 = Ex1Idx->getZExtValue();
1108             int Idx2 = Ex2Idx->getZExtValue();
1109             int Dist = Idx2 - Idx1;
1110             // The distance is too large - still may be profitable to use
1111             // shuffles.
1112             if (std::abs(Dist) > NumLanes / 2)
1113               return VLOperands::ScoreAltOpcodes;
1114             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1115                               : VLOperands::ScoreReversedExtracts;
1116           }
1117         }
1118       }
1119 
1120       auto *I1 = dyn_cast<Instruction>(V1);
1121       auto *I2 = dyn_cast<Instruction>(V2);
1122       if (I1 && I2) {
1123         if (I1->getParent() != I2->getParent())
1124           return VLOperands::ScoreFail;
1125         InstructionsState S = getSameOpcode({I1, I2});
1126         // Note: Only consider instructions with <= 2 operands to avoid
1127         // complexity explosion.
1128         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1129           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1130                                   : VLOperands::ScoreSameOpcode;
1131       }
1132 
1133       if (isa<UndefValue>(V2))
1134         return VLOperands::ScoreUndef;
1135 
1136       return VLOperands::ScoreFail;
1137     }
1138 
1139     /// Holds the values and their lanes that are taking part in the look-ahead
1140     /// score calculation. This is used in the external uses cost calculation.
1141     /// Need to hold all the lanes in case of splat/broadcast at least to
1142     /// correctly check for the use in the different lane.
1143     SmallDenseMap<Value *, SmallSet<int, 4>> InLookAheadValues;
1144 
1145     /// \returns the additional cost due to uses of \p LHS and \p RHS that are
1146     /// either external to the vectorized code, or require shuffling.
1147     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1148                             const std::pair<Value *, int> &RHS) {
1149       int Cost = 0;
1150       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1151       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1152         Value *V = Values[Idx].first;
1153         if (isa<Constant>(V)) {
1154           // Since this is a function pass, it doesn't make semantic sense to
1155           // walk the users of a subclass of Constant. The users could be in
1156           // another function, or even another module that happens to be in
1157           // the same LLVMContext.
1158           continue;
1159         }
1160 
1161         // Calculate the absolute lane, using the minimum relative lane of LHS
1162         // and RHS as base and Idx as the offset.
1163         int Ln = std::min(LHS.second, RHS.second) + Idx;
1164         assert(Ln >= 0 && "Bad lane calculation");
1165         unsigned UsersBudget = LookAheadUsersBudget;
1166         for (User *U : V->users()) {
1167           if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1168             // The user is in the VectorizableTree. Check if we need to insert.
1169             int UserLn = UserTE->findLaneForValue(U);
1170             assert(UserLn >= 0 && "Bad lane");
1171             // If the values are different, check just the line of the current
1172             // value. If the values are the same, need to add UserInDiffLaneCost
1173             // only if UserLn does not match both line numbers.
1174             if ((LHS.first != RHS.first && UserLn != Ln) ||
1175                 (LHS.first == RHS.first && UserLn != LHS.second &&
1176                  UserLn != RHS.second)) {
1177               Cost += UserInDiffLaneCost;
1178               break;
1179             }
1180           } else {
1181             // Check if the user is in the look-ahead code.
1182             auto It2 = InLookAheadValues.find(U);
1183             if (It2 != InLookAheadValues.end()) {
1184               // The user is in the look-ahead code. Check the lane.
1185               if (!It2->getSecond().contains(Ln)) {
1186                 Cost += UserInDiffLaneCost;
1187                 break;
1188               }
1189             } else {
1190               // The user is neither in SLP tree nor in the look-ahead code.
1191               Cost += ExternalUseCost;
1192               break;
1193             }
1194           }
1195           // Limit the number of visited uses to cap compilation time.
1196           if (--UsersBudget == 0)
1197             break;
1198         }
1199       }
1200       return Cost;
1201     }
1202 
1203     /// Go through the operands of \p LHS and \p RHS recursively until \p
1204     /// MaxLevel, and return the cummulative score. For example:
1205     /// \verbatim
1206     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1207     ///     \ /         \ /         \ /        \ /
1208     ///      +           +           +          +
1209     ///     G1          G2          G3         G4
1210     /// \endverbatim
1211     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1212     /// each level recursively, accumulating the score. It starts from matching
1213     /// the additions at level 0, then moves on to the loads (level 1). The
1214     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1215     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1216     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1217     /// Please note that the order of the operands does not matter, as we
1218     /// evaluate the score of all profitable combinations of operands. In
1219     /// other words the score of G1 and G4 is the same as G1 and G2. This
1220     /// heuristic is based on ideas described in:
1221     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1222     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1223     ///   Luís F. W. Góes
1224     int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1225                            const std::pair<Value *, int> &RHS, int CurrLevel,
1226                            int MaxLevel) {
1227 
1228       Value *V1 = LHS.first;
1229       Value *V2 = RHS.first;
1230       // Get the shallow score of V1 and V2.
1231       int ShallowScoreAtThisLevel = std::max(
1232           (int)ScoreFail, getShallowScore(V1, V2, DL, SE, getNumLanes()) -
1233                               getExternalUsesCost(LHS, RHS));
1234       int Lane1 = LHS.second;
1235       int Lane2 = RHS.second;
1236 
1237       // If reached MaxLevel,
1238       //  or if V1 and V2 are not instructions,
1239       //  or if they are SPLAT,
1240       //  or if they are not consecutive,
1241       //  or if profitable to vectorize loads or extractelements, early return
1242       //  the current cost.
1243       auto *I1 = dyn_cast<Instruction>(V1);
1244       auto *I2 = dyn_cast<Instruction>(V2);
1245       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1246           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1247           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1248             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1249            ShallowScoreAtThisLevel))
1250         return ShallowScoreAtThisLevel;
1251       assert(I1 && I2 && "Should have early exited.");
1252 
1253       // Keep track of in-tree values for determining the external-use cost.
1254       InLookAheadValues[V1].insert(Lane1);
1255       InLookAheadValues[V2].insert(Lane2);
1256 
1257       // Contains the I2 operand indexes that got matched with I1 operands.
1258       SmallSet<unsigned, 4> Op2Used;
1259 
1260       // Recursion towards the operands of I1 and I2. We are trying all possible
1261       // operand pairs, and keeping track of the best score.
1262       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1263            OpIdx1 != NumOperands1; ++OpIdx1) {
1264         // Try to pair op1I with the best operand of I2.
1265         int MaxTmpScore = 0;
1266         unsigned MaxOpIdx2 = 0;
1267         bool FoundBest = false;
1268         // If I2 is commutative try all combinations.
1269         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1270         unsigned ToIdx = isCommutative(I2)
1271                              ? I2->getNumOperands()
1272                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1273         assert(FromIdx <= ToIdx && "Bad index");
1274         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1275           // Skip operands already paired with OpIdx1.
1276           if (Op2Used.count(OpIdx2))
1277             continue;
1278           // Recursively calculate the cost at each level
1279           int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1280                                             {I2->getOperand(OpIdx2), Lane2},
1281                                             CurrLevel + 1, MaxLevel);
1282           // Look for the best score.
1283           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1284             MaxTmpScore = TmpScore;
1285             MaxOpIdx2 = OpIdx2;
1286             FoundBest = true;
1287           }
1288         }
1289         if (FoundBest) {
1290           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1291           Op2Used.insert(MaxOpIdx2);
1292           ShallowScoreAtThisLevel += MaxTmpScore;
1293         }
1294       }
1295       return ShallowScoreAtThisLevel;
1296     }
1297 
1298     /// \Returns the look-ahead score, which tells us how much the sub-trees
1299     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1300     /// score. This helps break ties in an informed way when we cannot decide on
1301     /// the order of the operands by just considering the immediate
1302     /// predecessors.
1303     int getLookAheadScore(const std::pair<Value *, int> &LHS,
1304                           const std::pair<Value *, int> &RHS) {
1305       InLookAheadValues.clear();
1306       return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1307     }
1308 
1309     // Search all operands in Ops[*][Lane] for the one that matches best
1310     // Ops[OpIdx][LastLane] and return its opreand index.
1311     // If no good match can be found, return None.
1312     Optional<unsigned>
1313     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1314                    ArrayRef<ReorderingMode> ReorderingModes) {
1315       unsigned NumOperands = getNumOperands();
1316 
1317       // The operand of the previous lane at OpIdx.
1318       Value *OpLastLane = getData(OpIdx, LastLane).V;
1319 
1320       // Our strategy mode for OpIdx.
1321       ReorderingMode RMode = ReorderingModes[OpIdx];
1322 
1323       // The linearized opcode of the operand at OpIdx, Lane.
1324       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1325 
1326       // The best operand index and its score.
1327       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1328       // are using the score to differentiate between the two.
1329       struct BestOpData {
1330         Optional<unsigned> Idx = None;
1331         unsigned Score = 0;
1332       } BestOp;
1333 
1334       // Iterate through all unused operands and look for the best.
1335       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1336         // Get the operand at Idx and Lane.
1337         OperandData &OpData = getData(Idx, Lane);
1338         Value *Op = OpData.V;
1339         bool OpAPO = OpData.APO;
1340 
1341         // Skip already selected operands.
1342         if (OpData.IsUsed)
1343           continue;
1344 
1345         // Skip if we are trying to move the operand to a position with a
1346         // different opcode in the linearized tree form. This would break the
1347         // semantics.
1348         if (OpAPO != OpIdxAPO)
1349           continue;
1350 
1351         // Look for an operand that matches the current mode.
1352         switch (RMode) {
1353         case ReorderingMode::Load:
1354         case ReorderingMode::Constant:
1355         case ReorderingMode::Opcode: {
1356           bool LeftToRight = Lane > LastLane;
1357           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1358           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1359           unsigned Score =
1360               getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1361           if (Score > BestOp.Score) {
1362             BestOp.Idx = Idx;
1363             BestOp.Score = Score;
1364           }
1365           break;
1366         }
1367         case ReorderingMode::Splat:
1368           if (Op == OpLastLane)
1369             BestOp.Idx = Idx;
1370           break;
1371         case ReorderingMode::Failed:
1372           return None;
1373         }
1374       }
1375 
1376       if (BestOp.Idx) {
1377         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1378         return BestOp.Idx;
1379       }
1380       // If we could not find a good match return None.
1381       return None;
1382     }
1383 
1384     /// Helper for reorderOperandVecs.
1385     /// \returns the lane that we should start reordering from. This is the one
1386     /// which has the least number of operands that can freely move about or
1387     /// less profitable because it already has the most optimal set of operands.
1388     unsigned getBestLaneToStartReordering() const {
1389       unsigned Min = UINT_MAX;
1390       unsigned SameOpNumber = 0;
1391       // std::pair<unsigned, unsigned> is used to implement a simple voting
1392       // algorithm and choose the lane with the least number of operands that
1393       // can freely move about or less profitable because it already has the
1394       // most optimal set of operands. The first unsigned is a counter for
1395       // voting, the second unsigned is the counter of lanes with instructions
1396       // with same/alternate opcodes and same parent basic block.
1397       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1398       // Try to be closer to the original results, if we have multiple lanes
1399       // with same cost. If 2 lanes have the same cost, use the one with the
1400       // lowest index.
1401       for (int I = getNumLanes(); I > 0; --I) {
1402         unsigned Lane = I - 1;
1403         OperandsOrderData NumFreeOpsHash =
1404             getMaxNumOperandsThatCanBeReordered(Lane);
1405         // Compare the number of operands that can move and choose the one with
1406         // the least number.
1407         if (NumFreeOpsHash.NumOfAPOs < Min) {
1408           Min = NumFreeOpsHash.NumOfAPOs;
1409           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1410           HashMap.clear();
1411           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1412         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1413                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1414           // Select the most optimal lane in terms of number of operands that
1415           // should be moved around.
1416           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1417           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1418         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1419                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1420           ++HashMap[NumFreeOpsHash.Hash].first;
1421         }
1422       }
1423       // Select the lane with the minimum counter.
1424       unsigned BestLane = 0;
1425       unsigned CntMin = UINT_MAX;
1426       for (const auto &Data : reverse(HashMap)) {
1427         if (Data.second.first < CntMin) {
1428           CntMin = Data.second.first;
1429           BestLane = Data.second.second;
1430         }
1431       }
1432       return BestLane;
1433     }
1434 
1435     /// Data structure that helps to reorder operands.
1436     struct OperandsOrderData {
1437       /// The best number of operands with the same APOs, which can be
1438       /// reordered.
1439       unsigned NumOfAPOs = UINT_MAX;
1440       /// Number of operands with the same/alternate instruction opcode and
1441       /// parent.
1442       unsigned NumOpsWithSameOpcodeParent = 0;
1443       /// Hash for the actual operands ordering.
1444       /// Used to count operands, actually their position id and opcode
1445       /// value. It is used in the voting mechanism to find the lane with the
1446       /// least number of operands that can freely move about or less profitable
1447       /// because it already has the most optimal set of operands. Can be
1448       /// replaced with SmallVector<unsigned> instead but hash code is faster
1449       /// and requires less memory.
1450       unsigned Hash = 0;
1451     };
1452     /// \returns the maximum number of operands that are allowed to be reordered
1453     /// for \p Lane and the number of compatible instructions(with the same
1454     /// parent/opcode). This is used as a heuristic for selecting the first lane
1455     /// to start operand reordering.
1456     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1457       unsigned CntTrue = 0;
1458       unsigned NumOperands = getNumOperands();
1459       // Operands with the same APO can be reordered. We therefore need to count
1460       // how many of them we have for each APO, like this: Cnt[APO] = x.
1461       // Since we only have two APOs, namely true and false, we can avoid using
1462       // a map. Instead we can simply count the number of operands that
1463       // correspond to one of them (in this case the 'true' APO), and calculate
1464       // the other by subtracting it from the total number of operands.
1465       // Operands with the same instruction opcode and parent are more
1466       // profitable since we don't need to move them in many cases, with a high
1467       // probability such lane already can be vectorized effectively.
1468       bool AllUndefs = true;
1469       unsigned NumOpsWithSameOpcodeParent = 0;
1470       Instruction *OpcodeI = nullptr;
1471       BasicBlock *Parent = nullptr;
1472       unsigned Hash = 0;
1473       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1474         const OperandData &OpData = getData(OpIdx, Lane);
1475         if (OpData.APO)
1476           ++CntTrue;
1477         // Use Boyer-Moore majority voting for finding the majority opcode and
1478         // the number of times it occurs.
1479         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1480           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1481               I->getParent() != Parent) {
1482             if (NumOpsWithSameOpcodeParent == 0) {
1483               NumOpsWithSameOpcodeParent = 1;
1484               OpcodeI = I;
1485               Parent = I->getParent();
1486             } else {
1487               --NumOpsWithSameOpcodeParent;
1488             }
1489           } else {
1490             ++NumOpsWithSameOpcodeParent;
1491           }
1492         }
1493         Hash = hash_combine(
1494             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1495         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1496       }
1497       if (AllUndefs)
1498         return {};
1499       OperandsOrderData Data;
1500       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1501       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1502       Data.Hash = Hash;
1503       return Data;
1504     }
1505 
1506     /// Go through the instructions in VL and append their operands.
1507     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1508       assert(!VL.empty() && "Bad VL");
1509       assert((empty() || VL.size() == getNumLanes()) &&
1510              "Expected same number of lanes");
1511       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1512       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1513       OpsVec.resize(NumOperands);
1514       unsigned NumLanes = VL.size();
1515       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1516         OpsVec[OpIdx].resize(NumLanes);
1517         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1518           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1519           // Our tree has just 3 nodes: the root and two operands.
1520           // It is therefore trivial to get the APO. We only need to check the
1521           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1522           // RHS operand. The LHS operand of both add and sub is never attached
1523           // to an inversese operation in the linearized form, therefore its APO
1524           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1525 
1526           // Since operand reordering is performed on groups of commutative
1527           // operations or alternating sequences (e.g., +, -), we can safely
1528           // tell the inverse operations by checking commutativity.
1529           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1530           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1531           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1532                                  APO, false};
1533         }
1534       }
1535     }
1536 
1537     /// \returns the number of operands.
1538     unsigned getNumOperands() const { return OpsVec.size(); }
1539 
1540     /// \returns the number of lanes.
1541     unsigned getNumLanes() const { return OpsVec[0].size(); }
1542 
1543     /// \returns the operand value at \p OpIdx and \p Lane.
1544     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1545       return getData(OpIdx, Lane).V;
1546     }
1547 
1548     /// \returns true if the data structure is empty.
1549     bool empty() const { return OpsVec.empty(); }
1550 
1551     /// Clears the data.
1552     void clear() { OpsVec.clear(); }
1553 
1554     /// \Returns true if there are enough operands identical to \p Op to fill
1555     /// the whole vector.
1556     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1557     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1558       bool OpAPO = getData(OpIdx, Lane).APO;
1559       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1560         if (Ln == Lane)
1561           continue;
1562         // This is set to true if we found a candidate for broadcast at Lane.
1563         bool FoundCandidate = false;
1564         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1565           OperandData &Data = getData(OpI, Ln);
1566           if (Data.APO != OpAPO || Data.IsUsed)
1567             continue;
1568           if (Data.V == Op) {
1569             FoundCandidate = true;
1570             Data.IsUsed = true;
1571             break;
1572           }
1573         }
1574         if (!FoundCandidate)
1575           return false;
1576       }
1577       return true;
1578     }
1579 
1580   public:
1581     /// Initialize with all the operands of the instruction vector \p RootVL.
1582     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1583                ScalarEvolution &SE, const BoUpSLP &R)
1584         : DL(DL), SE(SE), R(R) {
1585       // Append all the operands of RootVL.
1586       appendOperandsOfVL(RootVL);
1587     }
1588 
1589     /// \Returns a value vector with the operands across all lanes for the
1590     /// opearnd at \p OpIdx.
1591     ValueList getVL(unsigned OpIdx) const {
1592       ValueList OpVL(OpsVec[OpIdx].size());
1593       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1594              "Expected same num of lanes across all operands");
1595       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1596         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1597       return OpVL;
1598     }
1599 
1600     // Performs operand reordering for 2 or more operands.
1601     // The original operands are in OrigOps[OpIdx][Lane].
1602     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1603     void reorder() {
1604       unsigned NumOperands = getNumOperands();
1605       unsigned NumLanes = getNumLanes();
1606       // Each operand has its own mode. We are using this mode to help us select
1607       // the instructions for each lane, so that they match best with the ones
1608       // we have selected so far.
1609       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1610 
1611       // This is a greedy single-pass algorithm. We are going over each lane
1612       // once and deciding on the best order right away with no back-tracking.
1613       // However, in order to increase its effectiveness, we start with the lane
1614       // that has operands that can move the least. For example, given the
1615       // following lanes:
1616       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1617       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1618       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1619       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1620       // we will start at Lane 1, since the operands of the subtraction cannot
1621       // be reordered. Then we will visit the rest of the lanes in a circular
1622       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1623 
1624       // Find the first lane that we will start our search from.
1625       unsigned FirstLane = getBestLaneToStartReordering();
1626 
1627       // Initialize the modes.
1628       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1629         Value *OpLane0 = getValue(OpIdx, FirstLane);
1630         // Keep track if we have instructions with all the same opcode on one
1631         // side.
1632         if (isa<LoadInst>(OpLane0))
1633           ReorderingModes[OpIdx] = ReorderingMode::Load;
1634         else if (isa<Instruction>(OpLane0)) {
1635           // Check if OpLane0 should be broadcast.
1636           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1637             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1638           else
1639             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1640         }
1641         else if (isa<Constant>(OpLane0))
1642           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1643         else if (isa<Argument>(OpLane0))
1644           // Our best hope is a Splat. It may save some cost in some cases.
1645           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1646         else
1647           // NOTE: This should be unreachable.
1648           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1649       }
1650 
1651       // Check that we don't have same operands. No need to reorder if operands
1652       // are just perfect diamond or shuffled diamond match. Do not do it only
1653       // for possible broadcasts or non-power of 2 number of scalars (just for
1654       // now).
1655       auto &&SkipReordering = [this]() {
1656         SmallPtrSet<Value *, 4> UniqueValues;
1657         ArrayRef<OperandData> Op0 = OpsVec.front();
1658         for (const OperandData &Data : Op0)
1659           UniqueValues.insert(Data.V);
1660         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1661           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1662                 return !UniqueValues.contains(Data.V);
1663               }))
1664             return false;
1665         }
1666         // TODO: Check if we can remove a check for non-power-2 number of
1667         // scalars after full support of non-power-2 vectorization.
1668         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1669       };
1670 
1671       // If the initial strategy fails for any of the operand indexes, then we
1672       // perform reordering again in a second pass. This helps avoid assigning
1673       // high priority to the failed strategy, and should improve reordering for
1674       // the non-failed operand indexes.
1675       for (int Pass = 0; Pass != 2; ++Pass) {
1676         // Check if no need to reorder operands since they're are perfect or
1677         // shuffled diamond match.
1678         // Need to to do it to avoid extra external use cost counting for
1679         // shuffled matches, which may cause regressions.
1680         if (SkipReordering())
1681           break;
1682         // Skip the second pass if the first pass did not fail.
1683         bool StrategyFailed = false;
1684         // Mark all operand data as free to use.
1685         clearUsed();
1686         // We keep the original operand order for the FirstLane, so reorder the
1687         // rest of the lanes. We are visiting the nodes in a circular fashion,
1688         // using FirstLane as the center point and increasing the radius
1689         // distance.
1690         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1691           // Visit the lane on the right and then the lane on the left.
1692           for (int Direction : {+1, -1}) {
1693             int Lane = FirstLane + Direction * Distance;
1694             if (Lane < 0 || Lane >= (int)NumLanes)
1695               continue;
1696             int LastLane = Lane - Direction;
1697             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1698                    "Out of bounds");
1699             // Look for a good match for each operand.
1700             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1701               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1702               Optional<unsigned> BestIdx =
1703                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1704               // By not selecting a value, we allow the operands that follow to
1705               // select a better matching value. We will get a non-null value in
1706               // the next run of getBestOperand().
1707               if (BestIdx) {
1708                 // Swap the current operand with the one returned by
1709                 // getBestOperand().
1710                 swap(OpIdx, BestIdx.getValue(), Lane);
1711               } else {
1712                 // We failed to find a best operand, set mode to 'Failed'.
1713                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1714                 // Enable the second pass.
1715                 StrategyFailed = true;
1716               }
1717             }
1718           }
1719         }
1720         // Skip second pass if the strategy did not fail.
1721         if (!StrategyFailed)
1722           break;
1723       }
1724     }
1725 
1726 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1727     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1728       switch (RMode) {
1729       case ReorderingMode::Load:
1730         return "Load";
1731       case ReorderingMode::Opcode:
1732         return "Opcode";
1733       case ReorderingMode::Constant:
1734         return "Constant";
1735       case ReorderingMode::Splat:
1736         return "Splat";
1737       case ReorderingMode::Failed:
1738         return "Failed";
1739       }
1740       llvm_unreachable("Unimplemented Reordering Type");
1741     }
1742 
1743     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1744                                                    raw_ostream &OS) {
1745       return OS << getModeStr(RMode);
1746     }
1747 
1748     /// Debug print.
1749     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1750       printMode(RMode, dbgs());
1751     }
1752 
1753     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1754       return printMode(RMode, OS);
1755     }
1756 
1757     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1758       const unsigned Indent = 2;
1759       unsigned Cnt = 0;
1760       for (const OperandDataVec &OpDataVec : OpsVec) {
1761         OS << "Operand " << Cnt++ << "\n";
1762         for (const OperandData &OpData : OpDataVec) {
1763           OS.indent(Indent) << "{";
1764           if (Value *V = OpData.V)
1765             OS << *V;
1766           else
1767             OS << "null";
1768           OS << ", APO:" << OpData.APO << "}\n";
1769         }
1770         OS << "\n";
1771       }
1772       return OS;
1773     }
1774 
1775     /// Debug print.
1776     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1777 #endif
1778   };
1779 
1780   /// Checks if the instruction is marked for deletion.
1781   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1782 
1783   /// Marks values operands for later deletion by replacing them with Undefs.
1784   void eraseInstructions(ArrayRef<Value *> AV);
1785 
1786   ~BoUpSLP();
1787 
1788 private:
1789   /// Checks if all users of \p I are the part of the vectorization tree.
1790   bool areAllUsersVectorized(Instruction *I,
1791                              ArrayRef<Value *> VectorizedVals) const;
1792 
1793   /// \returns the cost of the vectorizable entry.
1794   InstructionCost getEntryCost(const TreeEntry *E,
1795                                ArrayRef<Value *> VectorizedVals);
1796 
1797   /// This is the recursive part of buildTree.
1798   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1799                      const EdgeInfo &EI);
1800 
1801   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1802   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1803   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1804   /// returns false, setting \p CurrentOrder to either an empty vector or a
1805   /// non-identity permutation that allows to reuse extract instructions.
1806   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1807                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1808 
1809   /// Vectorize a single entry in the tree.
1810   Value *vectorizeTree(TreeEntry *E);
1811 
1812   /// Vectorize a single entry in the tree, starting in \p VL.
1813   Value *vectorizeTree(ArrayRef<Value *> VL);
1814 
1815   /// \returns the scalarization cost for this type. Scalarization in this
1816   /// context means the creation of vectors from a group of scalars. If \p
1817   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1818   /// vector elements.
1819   InstructionCost getGatherCost(FixedVectorType *Ty,
1820                                 const DenseSet<unsigned> &ShuffledIndices,
1821                                 bool NeedToShuffle) const;
1822 
1823   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1824   /// tree entries.
1825   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1826   /// previous tree entries. \p Mask is filled with the shuffle mask.
1827   Optional<TargetTransformInfo::ShuffleKind>
1828   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1829                         SmallVectorImpl<const TreeEntry *> &Entries);
1830 
1831   /// \returns the scalarization cost for this list of values. Assuming that
1832   /// this subtree gets vectorized, we may need to extract the values from the
1833   /// roots. This method calculates the cost of extracting the values.
1834   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1835 
1836   /// Set the Builder insert point to one after the last instruction in
1837   /// the bundle
1838   void setInsertPointAfterBundle(const TreeEntry *E);
1839 
1840   /// \returns a vector from a collection of scalars in \p VL.
1841   Value *gather(ArrayRef<Value *> VL);
1842 
1843   /// \returns whether the VectorizableTree is fully vectorizable and will
1844   /// be beneficial even the tree height is tiny.
1845   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1846 
1847   /// Reorder commutative or alt operands to get better probability of
1848   /// generating vectorized code.
1849   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1850                                              SmallVectorImpl<Value *> &Left,
1851                                              SmallVectorImpl<Value *> &Right,
1852                                              const DataLayout &DL,
1853                                              ScalarEvolution &SE,
1854                                              const BoUpSLP &R);
1855   struct TreeEntry {
1856     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1857     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1858 
1859     /// \returns true if the scalars in VL are equal to this entry.
1860     bool isSame(ArrayRef<Value *> VL) const {
1861       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1862         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1863           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1864         return VL.size() == Mask.size() &&
1865                std::equal(VL.begin(), VL.end(), Mask.begin(),
1866                           [Scalars](Value *V, int Idx) {
1867                             return (isa<UndefValue>(V) &&
1868                                     Idx == UndefMaskElem) ||
1869                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1870                           });
1871       };
1872       if (!ReorderIndices.empty()) {
1873         // TODO: implement matching if the nodes are just reordered, still can
1874         // treat the vector as the same if the list of scalars matches VL
1875         // directly, without reordering.
1876         SmallVector<int> Mask;
1877         inversePermutation(ReorderIndices, Mask);
1878         if (VL.size() == Scalars.size())
1879           return IsSame(Scalars, Mask);
1880         if (VL.size() == ReuseShuffleIndices.size()) {
1881           ::addMask(Mask, ReuseShuffleIndices);
1882           return IsSame(Scalars, Mask);
1883         }
1884         return false;
1885       }
1886       return IsSame(Scalars, ReuseShuffleIndices);
1887     }
1888 
1889     /// \returns true if current entry has same operands as \p TE.
1890     bool hasEqualOperands(const TreeEntry &TE) const {
1891       if (TE.getNumOperands() != getNumOperands())
1892         return false;
1893       SmallBitVector Used(getNumOperands());
1894       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1895         unsigned PrevCount = Used.count();
1896         for (unsigned K = 0; K < E; ++K) {
1897           if (Used.test(K))
1898             continue;
1899           if (getOperand(K) == TE.getOperand(I)) {
1900             Used.set(K);
1901             break;
1902           }
1903         }
1904         // Check if we actually found the matching operand.
1905         if (PrevCount == Used.count())
1906           return false;
1907       }
1908       return true;
1909     }
1910 
1911     /// \return Final vectorization factor for the node. Defined by the total
1912     /// number of vectorized scalars, including those, used several times in the
1913     /// entry and counted in the \a ReuseShuffleIndices, if any.
1914     unsigned getVectorFactor() const {
1915       if (!ReuseShuffleIndices.empty())
1916         return ReuseShuffleIndices.size();
1917       return Scalars.size();
1918     };
1919 
1920     /// A vector of scalars.
1921     ValueList Scalars;
1922 
1923     /// The Scalars are vectorized into this value. It is initialized to Null.
1924     Value *VectorizedValue = nullptr;
1925 
1926     /// Do we need to gather this sequence or vectorize it
1927     /// (either with vector instruction or with scatter/gather
1928     /// intrinsics for store/load)?
1929     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
1930     EntryState State;
1931 
1932     /// Does this sequence require some shuffling?
1933     SmallVector<int, 4> ReuseShuffleIndices;
1934 
1935     /// Does this entry require reordering?
1936     SmallVector<unsigned, 4> ReorderIndices;
1937 
1938     /// Points back to the VectorizableTree.
1939     ///
1940     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
1941     /// to be a pointer and needs to be able to initialize the child iterator.
1942     /// Thus we need a reference back to the container to translate the indices
1943     /// to entries.
1944     VecTreeTy &Container;
1945 
1946     /// The TreeEntry index containing the user of this entry.  We can actually
1947     /// have multiple users so the data structure is not truly a tree.
1948     SmallVector<EdgeInfo, 1> UserTreeIndices;
1949 
1950     /// The index of this treeEntry in VectorizableTree.
1951     int Idx = -1;
1952 
1953   private:
1954     /// The operands of each instruction in each lane Operands[op_index][lane].
1955     /// Note: This helps avoid the replication of the code that performs the
1956     /// reordering of operands during buildTree_rec() and vectorizeTree().
1957     SmallVector<ValueList, 2> Operands;
1958 
1959     /// The main/alternate instruction.
1960     Instruction *MainOp = nullptr;
1961     Instruction *AltOp = nullptr;
1962 
1963   public:
1964     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1965     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
1966       if (Operands.size() < OpIdx + 1)
1967         Operands.resize(OpIdx + 1);
1968       assert(Operands[OpIdx].empty() && "Already resized?");
1969       Operands[OpIdx].resize(Scalars.size());
1970       for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane)
1971         Operands[OpIdx][Lane] = OpVL[Lane];
1972     }
1973 
1974     /// Set the operands of this bundle in their original order.
1975     void setOperandsInOrder() {
1976       assert(Operands.empty() && "Already initialized?");
1977       auto *I0 = cast<Instruction>(Scalars[0]);
1978       Operands.resize(I0->getNumOperands());
1979       unsigned NumLanes = Scalars.size();
1980       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1981            OpIdx != NumOperands; ++OpIdx) {
1982         Operands[OpIdx].resize(NumLanes);
1983         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1984           auto *I = cast<Instruction>(Scalars[Lane]);
1985           assert(I->getNumOperands() == NumOperands &&
1986                  "Expected same number of operands");
1987           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
1988         }
1989       }
1990     }
1991 
1992     /// Reorders operands of the node to the given mask \p Mask.
1993     void reorderOperands(ArrayRef<int> Mask) {
1994       for (ValueList &Operand : Operands)
1995         reorderScalars(Operand, Mask);
1996     }
1997 
1998     /// \returns the \p OpIdx operand of this TreeEntry.
1999     ValueList &getOperand(unsigned OpIdx) {
2000       assert(OpIdx < Operands.size() && "Off bounds");
2001       return Operands[OpIdx];
2002     }
2003 
2004     /// \returns the \p OpIdx operand of this TreeEntry.
2005     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2006       assert(OpIdx < Operands.size() && "Off bounds");
2007       return Operands[OpIdx];
2008     }
2009 
2010     /// \returns the number of operands.
2011     unsigned getNumOperands() const { return Operands.size(); }
2012 
2013     /// \return the single \p OpIdx operand.
2014     Value *getSingleOperand(unsigned OpIdx) const {
2015       assert(OpIdx < Operands.size() && "Off bounds");
2016       assert(!Operands[OpIdx].empty() && "No operand available");
2017       return Operands[OpIdx][0];
2018     }
2019 
2020     /// Some of the instructions in the list have alternate opcodes.
2021     bool isAltShuffle() const {
2022       return getOpcode() != getAltOpcode();
2023     }
2024 
2025     bool isOpcodeOrAlt(Instruction *I) const {
2026       unsigned CheckedOpcode = I->getOpcode();
2027       return (getOpcode() == CheckedOpcode ||
2028               getAltOpcode() == CheckedOpcode);
2029     }
2030 
2031     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2032     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2033     /// \p OpValue.
2034     Value *isOneOf(Value *Op) const {
2035       auto *I = dyn_cast<Instruction>(Op);
2036       if (I && isOpcodeOrAlt(I))
2037         return Op;
2038       return MainOp;
2039     }
2040 
2041     void setOperations(const InstructionsState &S) {
2042       MainOp = S.MainOp;
2043       AltOp = S.AltOp;
2044     }
2045 
2046     Instruction *getMainOp() const {
2047       return MainOp;
2048     }
2049 
2050     Instruction *getAltOp() const {
2051       return AltOp;
2052     }
2053 
2054     /// The main/alternate opcodes for the list of instructions.
2055     unsigned getOpcode() const {
2056       return MainOp ? MainOp->getOpcode() : 0;
2057     }
2058 
2059     unsigned getAltOpcode() const {
2060       return AltOp ? AltOp->getOpcode() : 0;
2061     }
2062 
2063     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2064     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2065     int findLaneForValue(Value *V) const {
2066       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2067       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2068       if (!ReorderIndices.empty())
2069         FoundLane = ReorderIndices[FoundLane];
2070       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2071       if (!ReuseShuffleIndices.empty()) {
2072         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2073                                   find(ReuseShuffleIndices, FoundLane));
2074       }
2075       return FoundLane;
2076     }
2077 
2078 #ifndef NDEBUG
2079     /// Debug printer.
2080     LLVM_DUMP_METHOD void dump() const {
2081       dbgs() << Idx << ".\n";
2082       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2083         dbgs() << "Operand " << OpI << ":\n";
2084         for (const Value *V : Operands[OpI])
2085           dbgs().indent(2) << *V << "\n";
2086       }
2087       dbgs() << "Scalars: \n";
2088       for (Value *V : Scalars)
2089         dbgs().indent(2) << *V << "\n";
2090       dbgs() << "State: ";
2091       switch (State) {
2092       case Vectorize:
2093         dbgs() << "Vectorize\n";
2094         break;
2095       case ScatterVectorize:
2096         dbgs() << "ScatterVectorize\n";
2097         break;
2098       case NeedToGather:
2099         dbgs() << "NeedToGather\n";
2100         break;
2101       }
2102       dbgs() << "MainOp: ";
2103       if (MainOp)
2104         dbgs() << *MainOp << "\n";
2105       else
2106         dbgs() << "NULL\n";
2107       dbgs() << "AltOp: ";
2108       if (AltOp)
2109         dbgs() << *AltOp << "\n";
2110       else
2111         dbgs() << "NULL\n";
2112       dbgs() << "VectorizedValue: ";
2113       if (VectorizedValue)
2114         dbgs() << *VectorizedValue << "\n";
2115       else
2116         dbgs() << "NULL\n";
2117       dbgs() << "ReuseShuffleIndices: ";
2118       if (ReuseShuffleIndices.empty())
2119         dbgs() << "Empty";
2120       else
2121         for (unsigned ReuseIdx : ReuseShuffleIndices)
2122           dbgs() << ReuseIdx << ", ";
2123       dbgs() << "\n";
2124       dbgs() << "ReorderIndices: ";
2125       for (unsigned ReorderIdx : ReorderIndices)
2126         dbgs() << ReorderIdx << ", ";
2127       dbgs() << "\n";
2128       dbgs() << "UserTreeIndices: ";
2129       for (const auto &EInfo : UserTreeIndices)
2130         dbgs() << EInfo << ", ";
2131       dbgs() << "\n";
2132     }
2133 #endif
2134   };
2135 
2136 #ifndef NDEBUG
2137   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2138                      InstructionCost VecCost,
2139                      InstructionCost ScalarCost) const {
2140     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2141     dbgs() << "SLP: Costs:\n";
2142     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2143     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2144     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2145     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2146                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2147   }
2148 #endif
2149 
2150   /// Create a new VectorizableTree entry.
2151   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2152                           const InstructionsState &S,
2153                           const EdgeInfo &UserTreeIdx,
2154                           ArrayRef<int> ReuseShuffleIndices = None,
2155                           ArrayRef<unsigned> ReorderIndices = None) {
2156     TreeEntry::EntryState EntryState =
2157         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2158     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2159                         ReuseShuffleIndices, ReorderIndices);
2160   }
2161 
2162   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2163                           TreeEntry::EntryState EntryState,
2164                           Optional<ScheduleData *> Bundle,
2165                           const InstructionsState &S,
2166                           const EdgeInfo &UserTreeIdx,
2167                           ArrayRef<int> ReuseShuffleIndices = None,
2168                           ArrayRef<unsigned> ReorderIndices = None) {
2169     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2170             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2171            "Need to vectorize gather entry?");
2172     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2173     TreeEntry *Last = VectorizableTree.back().get();
2174     Last->Idx = VectorizableTree.size() - 1;
2175     Last->State = EntryState;
2176     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2177                                      ReuseShuffleIndices.end());
2178     if (ReorderIndices.empty()) {
2179       Last->Scalars.assign(VL.begin(), VL.end());
2180       Last->setOperations(S);
2181     } else {
2182       // Reorder scalars and build final mask.
2183       Last->Scalars.assign(VL.size(), nullptr);
2184       transform(ReorderIndices, Last->Scalars.begin(),
2185                 [VL](unsigned Idx) -> Value * {
2186                   if (Idx >= VL.size())
2187                     return UndefValue::get(VL.front()->getType());
2188                   return VL[Idx];
2189                 });
2190       InstructionsState S = getSameOpcode(Last->Scalars);
2191       Last->setOperations(S);
2192       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2193     }
2194     if (Last->State != TreeEntry::NeedToGather) {
2195       for (Value *V : VL) {
2196         assert(!getTreeEntry(V) && "Scalar already in tree!");
2197         ScalarToTreeEntry[V] = Last;
2198       }
2199       // Update the scheduler bundle to point to this TreeEntry.
2200       unsigned Lane = 0;
2201       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2202            BundleMember = BundleMember->NextInBundle) {
2203         BundleMember->TE = Last;
2204         BundleMember->Lane = Lane;
2205         ++Lane;
2206       }
2207       assert((!Bundle.getValue() || Lane == VL.size()) &&
2208              "Bundle and VL out of sync");
2209     } else {
2210       MustGather.insert(VL.begin(), VL.end());
2211     }
2212 
2213     if (UserTreeIdx.UserTE)
2214       Last->UserTreeIndices.push_back(UserTreeIdx);
2215 
2216     return Last;
2217   }
2218 
2219   /// -- Vectorization State --
2220   /// Holds all of the tree entries.
2221   TreeEntry::VecTreeTy VectorizableTree;
2222 
2223 #ifndef NDEBUG
2224   /// Debug printer.
2225   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2226     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2227       VectorizableTree[Id]->dump();
2228       dbgs() << "\n";
2229     }
2230   }
2231 #endif
2232 
2233   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2234 
2235   const TreeEntry *getTreeEntry(Value *V) const {
2236     return ScalarToTreeEntry.lookup(V);
2237   }
2238 
2239   /// Maps a specific scalar to its tree entry.
2240   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2241 
2242   /// Maps a value to the proposed vectorizable size.
2243   SmallDenseMap<Value *, unsigned> InstrElementSize;
2244 
2245   /// A list of scalars that we found that we need to keep as scalars.
2246   ValueSet MustGather;
2247 
2248   /// This POD struct describes one external user in the vectorized tree.
2249   struct ExternalUser {
2250     ExternalUser(Value *S, llvm::User *U, int L)
2251         : Scalar(S), User(U), Lane(L) {}
2252 
2253     // Which scalar in our function.
2254     Value *Scalar;
2255 
2256     // Which user that uses the scalar.
2257     llvm::User *User;
2258 
2259     // Which lane does the scalar belong to.
2260     int Lane;
2261   };
2262   using UserList = SmallVector<ExternalUser, 16>;
2263 
2264   /// Checks if two instructions may access the same memory.
2265   ///
2266   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2267   /// is invariant in the calling loop.
2268   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2269                  Instruction *Inst2) {
2270     // First check if the result is already in the cache.
2271     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2272     Optional<bool> &result = AliasCache[key];
2273     if (result.hasValue()) {
2274       return result.getValue();
2275     }
2276     bool aliased = true;
2277     if (Loc1.Ptr && isSimple(Inst1))
2278       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2279     // Store the result in the cache.
2280     result = aliased;
2281     return aliased;
2282   }
2283 
2284   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2285 
2286   /// Cache for alias results.
2287   /// TODO: consider moving this to the AliasAnalysis itself.
2288   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2289 
2290   /// Removes an instruction from its block and eventually deletes it.
2291   /// It's like Instruction::eraseFromParent() except that the actual deletion
2292   /// is delayed until BoUpSLP is destructed.
2293   /// This is required to ensure that there are no incorrect collisions in the
2294   /// AliasCache, which can happen if a new instruction is allocated at the
2295   /// same address as a previously deleted instruction.
2296   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2297     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2298     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2299   }
2300 
2301   /// Temporary store for deleted instructions. Instructions will be deleted
2302   /// eventually when the BoUpSLP is destructed.
2303   DenseMap<Instruction *, bool> DeletedInstructions;
2304 
2305   /// A list of values that need to extracted out of the tree.
2306   /// This list holds pairs of (Internal Scalar : External User). External User
2307   /// can be nullptr, it means that this Internal Scalar will be used later,
2308   /// after vectorization.
2309   UserList ExternalUses;
2310 
2311   /// Values used only by @llvm.assume calls.
2312   SmallPtrSet<const Value *, 32> EphValues;
2313 
2314   /// Holds all of the instructions that we gathered.
2315   SetVector<Instruction *> GatherShuffleSeq;
2316 
2317   /// A list of blocks that we are going to CSE.
2318   SetVector<BasicBlock *> CSEBlocks;
2319 
2320   /// Contains all scheduling relevant data for an instruction.
2321   /// A ScheduleData either represents a single instruction or a member of an
2322   /// instruction bundle (= a group of instructions which is combined into a
2323   /// vector instruction).
2324   struct ScheduleData {
2325     // The initial value for the dependency counters. It means that the
2326     // dependencies are not calculated yet.
2327     enum { InvalidDeps = -1 };
2328 
2329     ScheduleData() = default;
2330 
2331     void init(int BlockSchedulingRegionID, Value *OpVal) {
2332       FirstInBundle = this;
2333       NextInBundle = nullptr;
2334       NextLoadStore = nullptr;
2335       IsScheduled = false;
2336       SchedulingRegionID = BlockSchedulingRegionID;
2337       UnscheduledDepsInBundle = UnscheduledDeps;
2338       clearDependencies();
2339       OpValue = OpVal;
2340       TE = nullptr;
2341       Lane = -1;
2342     }
2343 
2344     /// Returns true if the dependency information has been calculated.
2345     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2346 
2347     /// Returns true for single instructions and for bundle representatives
2348     /// (= the head of a bundle).
2349     bool isSchedulingEntity() const { return FirstInBundle == this; }
2350 
2351     /// Returns true if it represents an instruction bundle and not only a
2352     /// single instruction.
2353     bool isPartOfBundle() const {
2354       return NextInBundle != nullptr || FirstInBundle != this;
2355     }
2356 
2357     /// Returns true if it is ready for scheduling, i.e. it has no more
2358     /// unscheduled depending instructions/bundles.
2359     bool isReady() const {
2360       assert(isSchedulingEntity() &&
2361              "can't consider non-scheduling entity for ready list");
2362       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2363     }
2364 
2365     /// Modifies the number of unscheduled dependencies, also updating it for
2366     /// the whole bundle.
2367     int incrementUnscheduledDeps(int Incr) {
2368       UnscheduledDeps += Incr;
2369       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2370     }
2371 
2372     /// Sets the number of unscheduled dependencies to the number of
2373     /// dependencies.
2374     void resetUnscheduledDeps() {
2375       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2376     }
2377 
2378     /// Clears all dependency information.
2379     void clearDependencies() {
2380       Dependencies = InvalidDeps;
2381       resetUnscheduledDeps();
2382       MemoryDependencies.clear();
2383     }
2384 
2385     void dump(raw_ostream &os) const {
2386       if (!isSchedulingEntity()) {
2387         os << "/ " << *Inst;
2388       } else if (NextInBundle) {
2389         os << '[' << *Inst;
2390         ScheduleData *SD = NextInBundle;
2391         while (SD) {
2392           os << ';' << *SD->Inst;
2393           SD = SD->NextInBundle;
2394         }
2395         os << ']';
2396       } else {
2397         os << *Inst;
2398       }
2399     }
2400 
2401     Instruction *Inst = nullptr;
2402 
2403     /// Points to the head in an instruction bundle (and always to this for
2404     /// single instructions).
2405     ScheduleData *FirstInBundle = nullptr;
2406 
2407     /// Single linked list of all instructions in a bundle. Null if it is a
2408     /// single instruction.
2409     ScheduleData *NextInBundle = nullptr;
2410 
2411     /// Single linked list of all memory instructions (e.g. load, store, call)
2412     /// in the block - until the end of the scheduling region.
2413     ScheduleData *NextLoadStore = nullptr;
2414 
2415     /// The dependent memory instructions.
2416     /// This list is derived on demand in calculateDependencies().
2417     SmallVector<ScheduleData *, 4> MemoryDependencies;
2418 
2419     /// This ScheduleData is in the current scheduling region if this matches
2420     /// the current SchedulingRegionID of BlockScheduling.
2421     int SchedulingRegionID = 0;
2422 
2423     /// Used for getting a "good" final ordering of instructions.
2424     int SchedulingPriority = 0;
2425 
2426     /// The number of dependencies. Constitutes of the number of users of the
2427     /// instruction plus the number of dependent memory instructions (if any).
2428     /// This value is calculated on demand.
2429     /// If InvalidDeps, the number of dependencies is not calculated yet.
2430     int Dependencies = InvalidDeps;
2431 
2432     /// The number of dependencies minus the number of dependencies of scheduled
2433     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2434     /// for scheduling.
2435     /// Note that this is negative as long as Dependencies is not calculated.
2436     int UnscheduledDeps = InvalidDeps;
2437 
2438     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2439     /// single instructions.
2440     int UnscheduledDepsInBundle = InvalidDeps;
2441 
2442     /// True if this instruction is scheduled (or considered as scheduled in the
2443     /// dry-run).
2444     bool IsScheduled = false;
2445 
2446     /// Opcode of the current instruction in the schedule data.
2447     Value *OpValue = nullptr;
2448 
2449     /// The TreeEntry that this instruction corresponds to.
2450     TreeEntry *TE = nullptr;
2451 
2452     /// The lane of this node in the TreeEntry.
2453     int Lane = -1;
2454   };
2455 
2456 #ifndef NDEBUG
2457   friend inline raw_ostream &operator<<(raw_ostream &os,
2458                                         const BoUpSLP::ScheduleData &SD) {
2459     SD.dump(os);
2460     return os;
2461   }
2462 #endif
2463 
2464   friend struct GraphTraits<BoUpSLP *>;
2465   friend struct DOTGraphTraits<BoUpSLP *>;
2466 
2467   /// Contains all scheduling data for a basic block.
2468   struct BlockScheduling {
2469     BlockScheduling(BasicBlock *BB)
2470         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2471 
2472     void clear() {
2473       ReadyInsts.clear();
2474       ScheduleStart = nullptr;
2475       ScheduleEnd = nullptr;
2476       FirstLoadStoreInRegion = nullptr;
2477       LastLoadStoreInRegion = nullptr;
2478 
2479       // Reduce the maximum schedule region size by the size of the
2480       // previous scheduling run.
2481       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2482       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2483         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2484       ScheduleRegionSize = 0;
2485 
2486       // Make a new scheduling region, i.e. all existing ScheduleData is not
2487       // in the new region yet.
2488       ++SchedulingRegionID;
2489     }
2490 
2491     ScheduleData *getScheduleData(Value *V) {
2492       ScheduleData *SD = ScheduleDataMap[V];
2493       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2494         return SD;
2495       return nullptr;
2496     }
2497 
2498     ScheduleData *getScheduleData(Value *V, Value *Key) {
2499       if (V == Key)
2500         return getScheduleData(V);
2501       auto I = ExtraScheduleDataMap.find(V);
2502       if (I != ExtraScheduleDataMap.end()) {
2503         ScheduleData *SD = I->second[Key];
2504         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2505           return SD;
2506       }
2507       return nullptr;
2508     }
2509 
2510     bool isInSchedulingRegion(ScheduleData *SD) const {
2511       return SD->SchedulingRegionID == SchedulingRegionID;
2512     }
2513 
2514     /// Marks an instruction as scheduled and puts all dependent ready
2515     /// instructions into the ready-list.
2516     template <typename ReadyListType>
2517     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2518       SD->IsScheduled = true;
2519       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2520 
2521       ScheduleData *BundleMember = SD;
2522       while (BundleMember) {
2523         if (BundleMember->Inst != BundleMember->OpValue) {
2524           BundleMember = BundleMember->NextInBundle;
2525           continue;
2526         }
2527         // Handle the def-use chain dependencies.
2528 
2529         // Decrement the unscheduled counter and insert to ready list if ready.
2530         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2531           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2532             if (OpDef && OpDef->hasValidDependencies() &&
2533                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2534               // There are no more unscheduled dependencies after
2535               // decrementing, so we can put the dependent instruction
2536               // into the ready list.
2537               ScheduleData *DepBundle = OpDef->FirstInBundle;
2538               assert(!DepBundle->IsScheduled &&
2539                      "already scheduled bundle gets ready");
2540               ReadyList.insert(DepBundle);
2541               LLVM_DEBUG(dbgs()
2542                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2543             }
2544           });
2545         };
2546 
2547         // If BundleMember is a vector bundle, its operands may have been
2548         // reordered duiring buildTree(). We therefore need to get its operands
2549         // through the TreeEntry.
2550         if (TreeEntry *TE = BundleMember->TE) {
2551           int Lane = BundleMember->Lane;
2552           assert(Lane >= 0 && "Lane not set");
2553 
2554           // Since vectorization tree is being built recursively this assertion
2555           // ensures that the tree entry has all operands set before reaching
2556           // this code. Couple of exceptions known at the moment are extracts
2557           // where their second (immediate) operand is not added. Since
2558           // immediates do not affect scheduler behavior this is considered
2559           // okay.
2560           auto *In = TE->getMainOp();
2561           assert(In &&
2562                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2563                   In->getNumOperands() == TE->getNumOperands()) &&
2564                  "Missed TreeEntry operands?");
2565           (void)In; // fake use to avoid build failure when assertions disabled
2566 
2567           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2568                OpIdx != NumOperands; ++OpIdx)
2569             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2570               DecrUnsched(I);
2571         } else {
2572           // If BundleMember is a stand-alone instruction, no operand reordering
2573           // has taken place, so we directly access its operands.
2574           for (Use &U : BundleMember->Inst->operands())
2575             if (auto *I = dyn_cast<Instruction>(U.get()))
2576               DecrUnsched(I);
2577         }
2578         // Handle the memory dependencies.
2579         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2580           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2581             // There are no more unscheduled dependencies after decrementing,
2582             // so we can put the dependent instruction into the ready list.
2583             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2584             assert(!DepBundle->IsScheduled &&
2585                    "already scheduled bundle gets ready");
2586             ReadyList.insert(DepBundle);
2587             LLVM_DEBUG(dbgs()
2588                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2589           }
2590         }
2591         BundleMember = BundleMember->NextInBundle;
2592       }
2593     }
2594 
2595     void doForAllOpcodes(Value *V,
2596                          function_ref<void(ScheduleData *SD)> Action) {
2597       if (ScheduleData *SD = getScheduleData(V))
2598         Action(SD);
2599       auto I = ExtraScheduleDataMap.find(V);
2600       if (I != ExtraScheduleDataMap.end())
2601         for (auto &P : I->second)
2602           if (P.second->SchedulingRegionID == SchedulingRegionID)
2603             Action(P.second);
2604     }
2605 
2606     /// Put all instructions into the ReadyList which are ready for scheduling.
2607     template <typename ReadyListType>
2608     void initialFillReadyList(ReadyListType &ReadyList) {
2609       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2610         doForAllOpcodes(I, [&](ScheduleData *SD) {
2611           if (SD->isSchedulingEntity() && SD->isReady()) {
2612             ReadyList.insert(SD);
2613             LLVM_DEBUG(dbgs()
2614                        << "SLP:    initially in ready list: " << *I << "\n");
2615           }
2616         });
2617       }
2618     }
2619 
2620     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2621     /// cyclic dependencies. This is only a dry-run, no instructions are
2622     /// actually moved at this stage.
2623     /// \returns the scheduling bundle. The returned Optional value is non-None
2624     /// if \p VL is allowed to be scheduled.
2625     Optional<ScheduleData *>
2626     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2627                       const InstructionsState &S);
2628 
2629     /// Un-bundles a group of instructions.
2630     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2631 
2632     /// Allocates schedule data chunk.
2633     ScheduleData *allocateScheduleDataChunks();
2634 
2635     /// Extends the scheduling region so that V is inside the region.
2636     /// \returns true if the region size is within the limit.
2637     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2638 
2639     /// Initialize the ScheduleData structures for new instructions in the
2640     /// scheduling region.
2641     void initScheduleData(Instruction *FromI, Instruction *ToI,
2642                           ScheduleData *PrevLoadStore,
2643                           ScheduleData *NextLoadStore);
2644 
2645     /// Updates the dependency information of a bundle and of all instructions/
2646     /// bundles which depend on the original bundle.
2647     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2648                                BoUpSLP *SLP);
2649 
2650     /// Sets all instruction in the scheduling region to un-scheduled.
2651     void resetSchedule();
2652 
2653     BasicBlock *BB;
2654 
2655     /// Simple memory allocation for ScheduleData.
2656     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2657 
2658     /// The size of a ScheduleData array in ScheduleDataChunks.
2659     int ChunkSize;
2660 
2661     /// The allocator position in the current chunk, which is the last entry
2662     /// of ScheduleDataChunks.
2663     int ChunkPos;
2664 
2665     /// Attaches ScheduleData to Instruction.
2666     /// Note that the mapping survives during all vectorization iterations, i.e.
2667     /// ScheduleData structures are recycled.
2668     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2669 
2670     /// Attaches ScheduleData to Instruction with the leading key.
2671     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2672         ExtraScheduleDataMap;
2673 
2674     struct ReadyList : SmallVector<ScheduleData *, 8> {
2675       void insert(ScheduleData *SD) { push_back(SD); }
2676     };
2677 
2678     /// The ready-list for scheduling (only used for the dry-run).
2679     ReadyList ReadyInsts;
2680 
2681     /// The first instruction of the scheduling region.
2682     Instruction *ScheduleStart = nullptr;
2683 
2684     /// The first instruction _after_ the scheduling region.
2685     Instruction *ScheduleEnd = nullptr;
2686 
2687     /// The first memory accessing instruction in the scheduling region
2688     /// (can be null).
2689     ScheduleData *FirstLoadStoreInRegion = nullptr;
2690 
2691     /// The last memory accessing instruction in the scheduling region
2692     /// (can be null).
2693     ScheduleData *LastLoadStoreInRegion = nullptr;
2694 
2695     /// The current size of the scheduling region.
2696     int ScheduleRegionSize = 0;
2697 
2698     /// The maximum size allowed for the scheduling region.
2699     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2700 
2701     /// The ID of the scheduling region. For a new vectorization iteration this
2702     /// is incremented which "removes" all ScheduleData from the region.
2703     // Make sure that the initial SchedulingRegionID is greater than the
2704     // initial SchedulingRegionID in ScheduleData (which is 0).
2705     int SchedulingRegionID = 1;
2706   };
2707 
2708   /// Attaches the BlockScheduling structures to basic blocks.
2709   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2710 
2711   /// Performs the "real" scheduling. Done before vectorization is actually
2712   /// performed in a basic block.
2713   void scheduleBlock(BlockScheduling *BS);
2714 
2715   /// List of users to ignore during scheduling and that don't need extracting.
2716   ArrayRef<Value *> UserIgnoreList;
2717 
2718   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2719   /// sorted SmallVectors of unsigned.
2720   struct OrdersTypeDenseMapInfo {
2721     static OrdersType getEmptyKey() {
2722       OrdersType V;
2723       V.push_back(~1U);
2724       return V;
2725     }
2726 
2727     static OrdersType getTombstoneKey() {
2728       OrdersType V;
2729       V.push_back(~2U);
2730       return V;
2731     }
2732 
2733     static unsigned getHashValue(const OrdersType &V) {
2734       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2735     }
2736 
2737     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2738       return LHS == RHS;
2739     }
2740   };
2741 
2742   // Analysis and block reference.
2743   Function *F;
2744   ScalarEvolution *SE;
2745   TargetTransformInfo *TTI;
2746   TargetLibraryInfo *TLI;
2747   AAResults *AA;
2748   LoopInfo *LI;
2749   DominatorTree *DT;
2750   AssumptionCache *AC;
2751   DemandedBits *DB;
2752   const DataLayout *DL;
2753   OptimizationRemarkEmitter *ORE;
2754 
2755   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2756   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2757 
2758   /// Instruction builder to construct the vectorized tree.
2759   IRBuilder<> Builder;
2760 
2761   /// A map of scalar integer values to the smallest bit width with which they
2762   /// can legally be represented. The values map to (width, signed) pairs,
2763   /// where "width" indicates the minimum bit width and "signed" is True if the
2764   /// value must be signed-extended, rather than zero-extended, back to its
2765   /// original width.
2766   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2767 };
2768 
2769 } // end namespace slpvectorizer
2770 
2771 template <> struct GraphTraits<BoUpSLP *> {
2772   using TreeEntry = BoUpSLP::TreeEntry;
2773 
2774   /// NodeRef has to be a pointer per the GraphWriter.
2775   using NodeRef = TreeEntry *;
2776 
2777   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2778 
2779   /// Add the VectorizableTree to the index iterator to be able to return
2780   /// TreeEntry pointers.
2781   struct ChildIteratorType
2782       : public iterator_adaptor_base<
2783             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2784     ContainerTy &VectorizableTree;
2785 
2786     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2787                       ContainerTy &VT)
2788         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2789 
2790     NodeRef operator*() { return I->UserTE; }
2791   };
2792 
2793   static NodeRef getEntryNode(BoUpSLP &R) {
2794     return R.VectorizableTree[0].get();
2795   }
2796 
2797   static ChildIteratorType child_begin(NodeRef N) {
2798     return {N->UserTreeIndices.begin(), N->Container};
2799   }
2800 
2801   static ChildIteratorType child_end(NodeRef N) {
2802     return {N->UserTreeIndices.end(), N->Container};
2803   }
2804 
2805   /// For the node iterator we just need to turn the TreeEntry iterator into a
2806   /// TreeEntry* iterator so that it dereferences to NodeRef.
2807   class nodes_iterator {
2808     using ItTy = ContainerTy::iterator;
2809     ItTy It;
2810 
2811   public:
2812     nodes_iterator(const ItTy &It2) : It(It2) {}
2813     NodeRef operator*() { return It->get(); }
2814     nodes_iterator operator++() {
2815       ++It;
2816       return *this;
2817     }
2818     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2819   };
2820 
2821   static nodes_iterator nodes_begin(BoUpSLP *R) {
2822     return nodes_iterator(R->VectorizableTree.begin());
2823   }
2824 
2825   static nodes_iterator nodes_end(BoUpSLP *R) {
2826     return nodes_iterator(R->VectorizableTree.end());
2827   }
2828 
2829   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2830 };
2831 
2832 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2833   using TreeEntry = BoUpSLP::TreeEntry;
2834 
2835   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2836 
2837   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2838     std::string Str;
2839     raw_string_ostream OS(Str);
2840     if (isSplat(Entry->Scalars))
2841       OS << "<splat> ";
2842     for (auto V : Entry->Scalars) {
2843       OS << *V;
2844       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2845             return EU.Scalar == V;
2846           }))
2847         OS << " <extract>";
2848       OS << "\n";
2849     }
2850     return Str;
2851   }
2852 
2853   static std::string getNodeAttributes(const TreeEntry *Entry,
2854                                        const BoUpSLP *) {
2855     if (Entry->State == TreeEntry::NeedToGather)
2856       return "color=red";
2857     return "";
2858   }
2859 };
2860 
2861 } // end namespace llvm
2862 
2863 BoUpSLP::~BoUpSLP() {
2864   for (const auto &Pair : DeletedInstructions) {
2865     // Replace operands of ignored instructions with Undefs in case if they were
2866     // marked for deletion.
2867     if (Pair.getSecond()) {
2868       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2869       Pair.getFirst()->replaceAllUsesWith(Undef);
2870     }
2871     Pair.getFirst()->dropAllReferences();
2872   }
2873   for (const auto &Pair : DeletedInstructions) {
2874     assert(Pair.getFirst()->use_empty() &&
2875            "trying to erase instruction with users.");
2876     Pair.getFirst()->eraseFromParent();
2877   }
2878 #ifdef EXPENSIVE_CHECKS
2879   // If we could guarantee that this call is not extremely slow, we could
2880   // remove the ifdef limitation (see PR47712).
2881   assert(!verifyFunction(*F, &dbgs()));
2882 #endif
2883 }
2884 
2885 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2886   for (auto *V : AV) {
2887     if (auto *I = dyn_cast<Instruction>(V))
2888       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2889   };
2890 }
2891 
2892 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
2893 /// contains original mask for the scalars reused in the node. Procedure
2894 /// transform this mask in accordance with the given \p Mask.
2895 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
2896   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
2897          "Expected non-empty mask.");
2898   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
2899   Prev.swap(Reuses);
2900   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
2901     if (Mask[I] != UndefMaskElem)
2902       Reuses[Mask[I]] = Prev[I];
2903 }
2904 
2905 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
2906 /// the original order of the scalars. Procedure transforms the provided order
2907 /// in accordance with the given \p Mask. If the resulting \p Order is just an
2908 /// identity order, \p Order is cleared.
2909 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
2910   assert(!Mask.empty() && "Expected non-empty mask.");
2911   SmallVector<int> MaskOrder;
2912   if (Order.empty()) {
2913     MaskOrder.resize(Mask.size());
2914     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
2915   } else {
2916     inversePermutation(Order, MaskOrder);
2917   }
2918   reorderReuses(MaskOrder, Mask);
2919   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
2920     Order.clear();
2921     return;
2922   }
2923   Order.assign(Mask.size(), Mask.size());
2924   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
2925     if (MaskOrder[I] != UndefMaskElem)
2926       Order[MaskOrder[I]] = I;
2927   fixupOrderingIndices(Order);
2928 }
2929 
2930 Optional<BoUpSLP::OrdersType>
2931 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
2932   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
2933   unsigned NumScalars = TE.Scalars.size();
2934   OrdersType CurrentOrder(NumScalars, NumScalars);
2935   SmallVector<int> Positions;
2936   SmallBitVector UsedPositions(NumScalars);
2937   const TreeEntry *STE = nullptr;
2938   // Try to find all gathered scalars that are gets vectorized in other
2939   // vectorize node. Here we can have only one single tree vector node to
2940   // correctly identify order of the gathered scalars.
2941   for (unsigned I = 0; I < NumScalars; ++I) {
2942     Value *V = TE.Scalars[I];
2943     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
2944       continue;
2945     if (const auto *LocalSTE = getTreeEntry(V)) {
2946       if (!STE)
2947         STE = LocalSTE;
2948       else if (STE != LocalSTE)
2949         // Take the order only from the single vector node.
2950         return None;
2951       unsigned Lane =
2952           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
2953       if (Lane >= NumScalars)
2954         return None;
2955       if (CurrentOrder[Lane] != NumScalars) {
2956         if (Lane != I)
2957           continue;
2958         UsedPositions.reset(CurrentOrder[Lane]);
2959       }
2960       // The partial identity (where only some elements of the gather node are
2961       // in the identity order) is good.
2962       CurrentOrder[Lane] = I;
2963       UsedPositions.set(I);
2964     }
2965   }
2966   // Need to keep the order if we have a vector entry and at least 2 scalars or
2967   // the vectorized entry has just 2 scalars.
2968   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
2969     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
2970       for (unsigned I = 0; I < NumScalars; ++I)
2971         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
2972           return false;
2973       return true;
2974     };
2975     if (IsIdentityOrder(CurrentOrder)) {
2976       CurrentOrder.clear();
2977       return CurrentOrder;
2978     }
2979     auto *It = CurrentOrder.begin();
2980     for (unsigned I = 0; I < NumScalars;) {
2981       if (UsedPositions.test(I)) {
2982         ++I;
2983         continue;
2984       }
2985       if (*It == NumScalars) {
2986         *It = I;
2987         ++I;
2988       }
2989       ++It;
2990     }
2991     return CurrentOrder;
2992   }
2993   return None;
2994 }
2995 
2996 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
2997                                                          bool TopToBottom) {
2998   // No need to reorder if need to shuffle reuses, still need to shuffle the
2999   // node.
3000   if (!TE.ReuseShuffleIndices.empty())
3001     return None;
3002   if (TE.State == TreeEntry::Vectorize &&
3003       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3004        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3005       !TE.isAltShuffle())
3006     return TE.ReorderIndices;
3007   if (TE.State == TreeEntry::NeedToGather) {
3008     // TODO: add analysis of other gather nodes with extractelement
3009     // instructions and other values/instructions, not only undefs.
3010     if (((TE.getOpcode() == Instruction::ExtractElement &&
3011           !TE.isAltShuffle()) ||
3012          (all_of(TE.Scalars,
3013                  [](Value *V) {
3014                    return isa<UndefValue, ExtractElementInst>(V);
3015                  }) &&
3016           any_of(TE.Scalars,
3017                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3018         all_of(TE.Scalars,
3019                [](Value *V) {
3020                  auto *EE = dyn_cast<ExtractElementInst>(V);
3021                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3022                }) &&
3023         allSameType(TE.Scalars)) {
3024       // Check that gather of extractelements can be represented as
3025       // just a shuffle of a single vector.
3026       OrdersType CurrentOrder;
3027       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3028       if (Reuse || !CurrentOrder.empty()) {
3029         if (!CurrentOrder.empty())
3030           fixupOrderingIndices(CurrentOrder);
3031         return CurrentOrder;
3032       }
3033     }
3034     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3035       return CurrentOrder;
3036   }
3037   return None;
3038 }
3039 
3040 void BoUpSLP::reorderTopToBottom() {
3041   // Maps VF to the graph nodes.
3042   DenseMap<unsigned, SmallPtrSet<TreeEntry *, 4>> VFToOrderedEntries;
3043   // ExtractElement gather nodes which can be vectorized and need to handle
3044   // their ordering.
3045   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3046   // Find all reorderable nodes with the given VF.
3047   // Currently the are vectorized stores,loads,extracts + some gathering of
3048   // extracts.
3049   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3050                                  const std::unique_ptr<TreeEntry> &TE) {
3051     if (Optional<OrdersType> CurrentOrder =
3052             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3053       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3054       if (TE->State != TreeEntry::Vectorize)
3055         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3056     }
3057   });
3058 
3059   // Reorder the graph nodes according to their vectorization factor.
3060   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3061        VF /= 2) {
3062     auto It = VFToOrderedEntries.find(VF);
3063     if (It == VFToOrderedEntries.end())
3064       continue;
3065     // Try to find the most profitable order. We just are looking for the most
3066     // used order and reorder scalar elements in the nodes according to this
3067     // mostly used order.
3068     const SmallPtrSetImpl<TreeEntry *> &OrderedEntries = It->getSecond();
3069     // All operands are reordered and used only in this node - propagate the
3070     // most used order to the user node.
3071     MapVector<OrdersType, unsigned,
3072               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3073         OrdersUses;
3074     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3075     for (const TreeEntry *OpTE : OrderedEntries) {
3076       // No need to reorder this nodes, still need to extend and to use shuffle,
3077       // just need to merge reordering shuffle and the reuse shuffle.
3078       if (!OpTE->ReuseShuffleIndices.empty())
3079         continue;
3080       // Count number of orders uses.
3081       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3082         if (OpTE->State == TreeEntry::NeedToGather)
3083           return GathersToOrders.find(OpTE)->second;
3084         return OpTE->ReorderIndices;
3085       }();
3086       // Stores actually store the mask, not the order, need to invert.
3087       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3088           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3089         SmallVector<int> Mask;
3090         inversePermutation(Order, Mask);
3091         unsigned E = Order.size();
3092         OrdersType CurrentOrder(E, E);
3093         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3094           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3095         });
3096         fixupOrderingIndices(CurrentOrder);
3097         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3098       } else {
3099         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3100       }
3101     }
3102     // Set order of the user node.
3103     if (OrdersUses.empty())
3104       continue;
3105     // Choose the most used order.
3106     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3107     unsigned Cnt = OrdersUses.front().second;
3108     for (const auto &Pair : drop_begin(OrdersUses)) {
3109       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3110         BestOrder = Pair.first;
3111         Cnt = Pair.second;
3112       }
3113     }
3114     // Set order of the user node.
3115     if (BestOrder.empty())
3116       continue;
3117     SmallVector<int> Mask;
3118     inversePermutation(BestOrder, Mask);
3119     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3120     unsigned E = BestOrder.size();
3121     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3122       return I < E ? static_cast<int>(I) : UndefMaskElem;
3123     });
3124     // Do an actual reordering, if profitable.
3125     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3126       // Just do the reordering for the nodes with the given VF.
3127       if (TE->Scalars.size() != VF) {
3128         if (TE->ReuseShuffleIndices.size() == VF) {
3129           // Need to reorder the reuses masks of the operands with smaller VF to
3130           // be able to find the match between the graph nodes and scalar
3131           // operands of the given node during vectorization/cost estimation.
3132           assert(all_of(TE->UserTreeIndices,
3133                         [VF, &TE](const EdgeInfo &EI) {
3134                           return EI.UserTE->Scalars.size() == VF ||
3135                                  EI.UserTE->Scalars.size() ==
3136                                      TE->Scalars.size();
3137                         }) &&
3138                  "All users must be of VF size.");
3139           // Update ordering of the operands with the smaller VF than the given
3140           // one.
3141           reorderReuses(TE->ReuseShuffleIndices, Mask);
3142         }
3143         continue;
3144       }
3145       if (TE->State == TreeEntry::Vectorize &&
3146           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3147               InsertElementInst>(TE->getMainOp()) &&
3148           !TE->isAltShuffle()) {
3149         // Build correct orders for extract{element,value}, loads and
3150         // stores.
3151         reorderOrder(TE->ReorderIndices, Mask);
3152         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3153           TE->reorderOperands(Mask);
3154       } else {
3155         // Reorder the node and its operands.
3156         TE->reorderOperands(Mask);
3157         assert(TE->ReorderIndices.empty() &&
3158                "Expected empty reorder sequence.");
3159         reorderScalars(TE->Scalars, Mask);
3160       }
3161       if (!TE->ReuseShuffleIndices.empty()) {
3162         // Apply reversed order to keep the original ordering of the reused
3163         // elements to avoid extra reorder indices shuffling.
3164         OrdersType CurrentOrder;
3165         reorderOrder(CurrentOrder, MaskOrder);
3166         SmallVector<int> NewReuses;
3167         inversePermutation(CurrentOrder, NewReuses);
3168         addMask(NewReuses, TE->ReuseShuffleIndices);
3169         TE->ReuseShuffleIndices.swap(NewReuses);
3170       }
3171     }
3172   }
3173 }
3174 
3175 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3176   SetVector<TreeEntry *> OrderedEntries;
3177   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3178   // Find all reorderable leaf nodes with the given VF.
3179   // Currently the are vectorized loads,extracts without alternate operands +
3180   // some gathering of extracts.
3181   SmallVector<TreeEntry *> NonVectorized;
3182   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3183                               &NonVectorized](
3184                                  const std::unique_ptr<TreeEntry> &TE) {
3185     if (TE->State != TreeEntry::Vectorize)
3186       NonVectorized.push_back(TE.get());
3187     if (Optional<OrdersType> CurrentOrder =
3188             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3189       OrderedEntries.insert(TE.get());
3190       if (TE->State != TreeEntry::Vectorize)
3191         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3192     }
3193   });
3194 
3195   // Checks if the operands of the users are reordarable and have only single
3196   // use.
3197   auto &&CheckOperands =
3198       [this, &NonVectorized](const auto &Data,
3199                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3200         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3201           if (any_of(Data.second,
3202                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3203                        return OpData.first == I &&
3204                               OpData.second->State == TreeEntry::Vectorize;
3205                      }))
3206             continue;
3207           ArrayRef<Value *> VL = Data.first->getOperand(I);
3208           const TreeEntry *TE = nullptr;
3209           const auto *It = find_if(VL, [this, &TE](Value *V) {
3210             TE = getTreeEntry(V);
3211             return TE;
3212           });
3213           if (It != VL.end() && TE->isSame(VL))
3214             return false;
3215           TreeEntry *Gather = nullptr;
3216           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3217                 assert(TE->State != TreeEntry::Vectorize &&
3218                        "Only non-vectorized nodes are expected.");
3219                 if (TE->isSame(VL)) {
3220                   Gather = TE;
3221                   return true;
3222                 }
3223                 return false;
3224               }) > 1)
3225             return false;
3226           if (Gather)
3227             GatherOps.push_back(Gather);
3228         }
3229         return true;
3230       };
3231   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3232   // I.e., if the node has operands, that are reordered, try to make at least
3233   // one operand order in the natural order and reorder others + reorder the
3234   // user node itself.
3235   SmallPtrSet<const TreeEntry *, 4> Visited;
3236   while (!OrderedEntries.empty()) {
3237     // 1. Filter out only reordered nodes.
3238     // 2. If the entry has multiple uses - skip it and jump to the next node.
3239     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3240     SmallVector<TreeEntry *> Filtered;
3241     for (TreeEntry *TE : OrderedEntries) {
3242       if (!(TE->State == TreeEntry::Vectorize ||
3243             (TE->State == TreeEntry::NeedToGather &&
3244              GathersToOrders.count(TE))) ||
3245           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3246           !all_of(drop_begin(TE->UserTreeIndices),
3247                   [TE](const EdgeInfo &EI) {
3248                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3249                   }) ||
3250           !Visited.insert(TE).second) {
3251         Filtered.push_back(TE);
3252         continue;
3253       }
3254       // Build a map between user nodes and their operands order to speedup
3255       // search. The graph currently does not provide this dependency directly.
3256       for (EdgeInfo &EI : TE->UserTreeIndices) {
3257         TreeEntry *UserTE = EI.UserTE;
3258         auto It = Users.find(UserTE);
3259         if (It == Users.end())
3260           It = Users.insert({UserTE, {}}).first;
3261         It->second.emplace_back(EI.EdgeIdx, TE);
3262       }
3263     }
3264     // Erase filtered entries.
3265     for_each(Filtered,
3266              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3267     for (const auto &Data : Users) {
3268       // Check that operands are used only in the User node.
3269       SmallVector<TreeEntry *> GatherOps;
3270       if (!CheckOperands(Data, GatherOps)) {
3271         for_each(Data.second,
3272                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3273                    OrderedEntries.remove(Op.second);
3274                  });
3275         continue;
3276       }
3277       // All operands are reordered and used only in this node - propagate the
3278       // most used order to the user node.
3279       MapVector<OrdersType, unsigned,
3280                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3281           OrdersUses;
3282       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3283       for (const auto &Op : Data.second) {
3284         TreeEntry *OpTE = Op.second;
3285         if (!OpTE->ReuseShuffleIndices.empty() ||
3286             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3287           continue;
3288         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3289           if (OpTE->State == TreeEntry::NeedToGather)
3290             return GathersToOrders.find(OpTE)->second;
3291           return OpTE->ReorderIndices;
3292         }();
3293         // Stores actually store the mask, not the order, need to invert.
3294         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3295             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3296           SmallVector<int> Mask;
3297           inversePermutation(Order, Mask);
3298           unsigned E = Order.size();
3299           OrdersType CurrentOrder(E, E);
3300           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3301             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3302           });
3303           fixupOrderingIndices(CurrentOrder);
3304           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3305         } else {
3306           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3307         }
3308         if (VisitedOps.insert(OpTE).second)
3309           OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3310               OpTE->UserTreeIndices.size();
3311         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3312         --OrdersUses[{}];
3313       }
3314       // If no orders - skip current nodes and jump to the next one, if any.
3315       if (OrdersUses.empty()) {
3316         for_each(Data.second,
3317                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3318                    OrderedEntries.remove(Op.second);
3319                  });
3320         continue;
3321       }
3322       // Choose the best order.
3323       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3324       unsigned Cnt = OrdersUses.front().second;
3325       for (const auto &Pair : drop_begin(OrdersUses)) {
3326         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3327           BestOrder = Pair.first;
3328           Cnt = Pair.second;
3329         }
3330       }
3331       // Set order of the user node (reordering of operands and user nodes).
3332       if (BestOrder.empty()) {
3333         for_each(Data.second,
3334                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3335                    OrderedEntries.remove(Op.second);
3336                  });
3337         continue;
3338       }
3339       // Erase operands from OrderedEntries list and adjust their orders.
3340       VisitedOps.clear();
3341       SmallVector<int> Mask;
3342       inversePermutation(BestOrder, Mask);
3343       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3344       unsigned E = BestOrder.size();
3345       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3346         return I < E ? static_cast<int>(I) : UndefMaskElem;
3347       });
3348       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3349         TreeEntry *TE = Op.second;
3350         OrderedEntries.remove(TE);
3351         if (!VisitedOps.insert(TE).second)
3352           continue;
3353         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3354           // Just reorder reuses indices.
3355           reorderReuses(TE->ReuseShuffleIndices, Mask);
3356           continue;
3357         }
3358         // Gathers are processed separately.
3359         if (TE->State != TreeEntry::Vectorize)
3360           continue;
3361         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3362                 TE->ReorderIndices.empty()) &&
3363                "Non-matching sizes of user/operand entries.");
3364         reorderOrder(TE->ReorderIndices, Mask);
3365       }
3366       // For gathers just need to reorder its scalars.
3367       for (TreeEntry *Gather : GatherOps) {
3368         assert(Gather->ReorderIndices.empty() &&
3369                "Unexpected reordering of gathers.");
3370         if (!Gather->ReuseShuffleIndices.empty()) {
3371           // Just reorder reuses indices.
3372           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3373           continue;
3374         }
3375         reorderScalars(Gather->Scalars, Mask);
3376         OrderedEntries.remove(Gather);
3377       }
3378       // Reorder operands of the user node and set the ordering for the user
3379       // node itself.
3380       if (Data.first->State != TreeEntry::Vectorize ||
3381           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3382               Data.first->getMainOp()) ||
3383           Data.first->isAltShuffle())
3384         Data.first->reorderOperands(Mask);
3385       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3386           Data.first->isAltShuffle()) {
3387         reorderScalars(Data.first->Scalars, Mask);
3388         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3389         if (Data.first->ReuseShuffleIndices.empty() &&
3390             !Data.first->ReorderIndices.empty() &&
3391             !Data.first->isAltShuffle()) {
3392           // Insert user node to the list to try to sink reordering deeper in
3393           // the graph.
3394           OrderedEntries.insert(Data.first);
3395         }
3396       } else {
3397         reorderOrder(Data.first->ReorderIndices, Mask);
3398       }
3399     }
3400   }
3401   // If the reordering is unnecessary, just remove the reorder.
3402   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3403       VectorizableTree.front()->ReuseShuffleIndices.empty())
3404     VectorizableTree.front()->ReorderIndices.clear();
3405 }
3406 
3407 void BoUpSLP::buildExternalUses(
3408     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3409   // Collect the values that we need to extract from the tree.
3410   for (auto &TEPtr : VectorizableTree) {
3411     TreeEntry *Entry = TEPtr.get();
3412 
3413     // No need to handle users of gathered values.
3414     if (Entry->State == TreeEntry::NeedToGather)
3415       continue;
3416 
3417     // For each lane:
3418     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3419       Value *Scalar = Entry->Scalars[Lane];
3420       int FoundLane = Entry->findLaneForValue(Scalar);
3421 
3422       // Check if the scalar is externally used as an extra arg.
3423       auto ExtI = ExternallyUsedValues.find(Scalar);
3424       if (ExtI != ExternallyUsedValues.end()) {
3425         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3426                           << Lane << " from " << *Scalar << ".\n");
3427         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3428       }
3429       for (User *U : Scalar->users()) {
3430         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3431 
3432         Instruction *UserInst = dyn_cast<Instruction>(U);
3433         if (!UserInst)
3434           continue;
3435 
3436         if (isDeleted(UserInst))
3437           continue;
3438 
3439         // Skip in-tree scalars that become vectors
3440         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3441           Value *UseScalar = UseEntry->Scalars[0];
3442           // Some in-tree scalars will remain as scalar in vectorized
3443           // instructions. If that is the case, the one in Lane 0 will
3444           // be used.
3445           if (UseScalar != U ||
3446               UseEntry->State == TreeEntry::ScatterVectorize ||
3447               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3448             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3449                               << ".\n");
3450             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3451             continue;
3452           }
3453         }
3454 
3455         // Ignore users in the user ignore list.
3456         if (is_contained(UserIgnoreList, UserInst))
3457           continue;
3458 
3459         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3460                           << Lane << " from " << *Scalar << ".\n");
3461         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3462       }
3463     }
3464   }
3465 }
3466 
3467 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3468                         ArrayRef<Value *> UserIgnoreLst) {
3469   deleteTree();
3470   UserIgnoreList = UserIgnoreLst;
3471   if (!allSameType(Roots))
3472     return;
3473   buildTree_rec(Roots, 0, EdgeInfo());
3474 }
3475 
3476 namespace {
3477 /// Tracks the state we can represent the loads in the given sequence.
3478 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3479 } // anonymous namespace
3480 
3481 /// Checks if the given array of loads can be represented as a vectorized,
3482 /// scatter or just simple gather.
3483 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3484                                     const TargetTransformInfo &TTI,
3485                                     const DataLayout &DL, ScalarEvolution &SE,
3486                                     SmallVectorImpl<unsigned> &Order,
3487                                     SmallVectorImpl<Value *> &PointerOps) {
3488   // Check that a vectorized load would load the same memory as a scalar
3489   // load. For example, we don't want to vectorize loads that are smaller
3490   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3491   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3492   // from such a struct, we read/write packed bits disagreeing with the
3493   // unvectorized version.
3494   Type *ScalarTy = VL0->getType();
3495 
3496   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3497     return LoadsState::Gather;
3498 
3499   // Make sure all loads in the bundle are simple - we can't vectorize
3500   // atomic or volatile loads.
3501   PointerOps.clear();
3502   PointerOps.resize(VL.size());
3503   auto *POIter = PointerOps.begin();
3504   for (Value *V : VL) {
3505     auto *L = cast<LoadInst>(V);
3506     if (!L->isSimple())
3507       return LoadsState::Gather;
3508     *POIter = L->getPointerOperand();
3509     ++POIter;
3510   }
3511 
3512   Order.clear();
3513   // Check the order of pointer operands.
3514   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3515     Value *Ptr0;
3516     Value *PtrN;
3517     if (Order.empty()) {
3518       Ptr0 = PointerOps.front();
3519       PtrN = PointerOps.back();
3520     } else {
3521       Ptr0 = PointerOps[Order.front()];
3522       PtrN = PointerOps[Order.back()];
3523     }
3524     Optional<int> Diff =
3525         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3526     // Check that the sorted loads are consecutive.
3527     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3528       return LoadsState::Vectorize;
3529     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3530     for (Value *V : VL)
3531       CommonAlignment =
3532           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3533     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3534                                 CommonAlignment))
3535       return LoadsState::ScatterVectorize;
3536   }
3537 
3538   return LoadsState::Gather;
3539 }
3540 
3541 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3542                             const EdgeInfo &UserTreeIdx) {
3543   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3544 
3545   SmallVector<int> ReuseShuffleIndicies;
3546   SmallVector<Value *> UniqueValues;
3547   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3548                                 &UserTreeIdx,
3549                                 this](const InstructionsState &S) {
3550     // Check that every instruction appears once in this bundle.
3551     DenseMap<Value *, unsigned> UniquePositions;
3552     for (Value *V : VL) {
3553       if (isConstant(V)) {
3554         ReuseShuffleIndicies.emplace_back(
3555             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3556         UniqueValues.emplace_back(V);
3557         continue;
3558       }
3559       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3560       ReuseShuffleIndicies.emplace_back(Res.first->second);
3561       if (Res.second)
3562         UniqueValues.emplace_back(V);
3563     }
3564     size_t NumUniqueScalarValues = UniqueValues.size();
3565     if (NumUniqueScalarValues == VL.size()) {
3566       ReuseShuffleIndicies.clear();
3567     } else {
3568       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3569       if (NumUniqueScalarValues <= 1 ||
3570           (NumUniqueScalarValues == 2 &&
3571            any_of(UniqueValues, UndefValue::classof)) ||
3572           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3573         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3574         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3575         return false;
3576       }
3577       VL = UniqueValues;
3578     }
3579     return true;
3580   };
3581 
3582   InstructionsState S = getSameOpcode(VL);
3583   if (Depth == RecursionMaxDepth) {
3584     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3585     if (TryToFindDuplicates(S))
3586       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3587                    ReuseShuffleIndicies);
3588     return;
3589   }
3590 
3591   // Don't handle scalable vectors
3592   if (S.getOpcode() == Instruction::ExtractElement &&
3593       isa<ScalableVectorType>(
3594           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3595     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3596     if (TryToFindDuplicates(S))
3597       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3598                    ReuseShuffleIndicies);
3599     return;
3600   }
3601 
3602   // Don't handle vectors.
3603   if (S.OpValue->getType()->isVectorTy() &&
3604       !isa<InsertElementInst>(S.OpValue)) {
3605     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3606     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3607     return;
3608   }
3609 
3610   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3611     if (SI->getValueOperand()->getType()->isVectorTy()) {
3612       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3613       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3614       return;
3615     }
3616 
3617   // If all of the operands are identical or constant we have a simple solution.
3618   // If we deal with insert/extract instructions, they all must have constant
3619   // indices, otherwise we should gather them, not try to vectorize.
3620   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3621       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3622        !all_of(VL, isVectorLikeInstWithConstOps))) {
3623     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3624     if (TryToFindDuplicates(S))
3625       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3626                    ReuseShuffleIndicies);
3627     return;
3628   }
3629 
3630   // We now know that this is a vector of instructions of the same type from
3631   // the same block.
3632 
3633   // Don't vectorize ephemeral values.
3634   for (Value *V : VL) {
3635     if (EphValues.count(V)) {
3636       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3637                         << ") is ephemeral.\n");
3638       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3639       return;
3640     }
3641   }
3642 
3643   // Check if this is a duplicate of another entry.
3644   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3645     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3646     if (!E->isSame(VL)) {
3647       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3648       if (TryToFindDuplicates(S))
3649         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3650                      ReuseShuffleIndicies);
3651       return;
3652     }
3653     // Record the reuse of the tree node.  FIXME, currently this is only used to
3654     // properly draw the graph rather than for the actual vectorization.
3655     E->UserTreeIndices.push_back(UserTreeIdx);
3656     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3657                       << ".\n");
3658     return;
3659   }
3660 
3661   // Check that none of the instructions in the bundle are already in the tree.
3662   for (Value *V : VL) {
3663     auto *I = dyn_cast<Instruction>(V);
3664     if (!I)
3665       continue;
3666     if (getTreeEntry(I)) {
3667       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3668                         << ") is already in tree.\n");
3669       if (TryToFindDuplicates(S))
3670         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3671                      ReuseShuffleIndicies);
3672       return;
3673     }
3674   }
3675 
3676   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3677   for (Value *V : VL) {
3678     if (is_contained(UserIgnoreList, V)) {
3679       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3680       if (TryToFindDuplicates(S))
3681         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3682                      ReuseShuffleIndicies);
3683       return;
3684     }
3685   }
3686 
3687   // Check that all of the users of the scalars that we want to vectorize are
3688   // schedulable.
3689   auto *VL0 = cast<Instruction>(S.OpValue);
3690   BasicBlock *BB = VL0->getParent();
3691 
3692   if (!DT->isReachableFromEntry(BB)) {
3693     // Don't go into unreachable blocks. They may contain instructions with
3694     // dependency cycles which confuse the final scheduling.
3695     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3696     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3697     return;
3698   }
3699 
3700   // Check that every instruction appears once in this bundle.
3701   if (!TryToFindDuplicates(S))
3702     return;
3703 
3704   auto &BSRef = BlocksSchedules[BB];
3705   if (!BSRef)
3706     BSRef = std::make_unique<BlockScheduling>(BB);
3707 
3708   BlockScheduling &BS = *BSRef.get();
3709 
3710   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3711   if (!Bundle) {
3712     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3713     assert((!BS.getScheduleData(VL0) ||
3714             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3715            "tryScheduleBundle should cancelScheduling on failure");
3716     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3717                  ReuseShuffleIndicies);
3718     return;
3719   }
3720   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3721 
3722   unsigned ShuffleOrOp = S.isAltShuffle() ?
3723                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3724   switch (ShuffleOrOp) {
3725     case Instruction::PHI: {
3726       auto *PH = cast<PHINode>(VL0);
3727 
3728       // Check for terminator values (e.g. invoke).
3729       for (Value *V : VL)
3730         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3731           Instruction *Term = dyn_cast<Instruction>(
3732               cast<PHINode>(V)->getIncomingValueForBlock(
3733                   PH->getIncomingBlock(I)));
3734           if (Term && Term->isTerminator()) {
3735             LLVM_DEBUG(dbgs()
3736                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3737             BS.cancelScheduling(VL, VL0);
3738             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3739                          ReuseShuffleIndicies);
3740             return;
3741           }
3742         }
3743 
3744       TreeEntry *TE =
3745           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3746       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3747 
3748       // Keeps the reordered operands to avoid code duplication.
3749       SmallVector<ValueList, 2> OperandsVec;
3750       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3751         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3752           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3753           TE->setOperand(I, Operands);
3754           OperandsVec.push_back(Operands);
3755           continue;
3756         }
3757         ValueList Operands;
3758         // Prepare the operand vector.
3759         for (Value *V : VL)
3760           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3761               PH->getIncomingBlock(I)));
3762         TE->setOperand(I, Operands);
3763         OperandsVec.push_back(Operands);
3764       }
3765       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3766         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3767       return;
3768     }
3769     case Instruction::ExtractValue:
3770     case Instruction::ExtractElement: {
3771       OrdersType CurrentOrder;
3772       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3773       if (Reuse) {
3774         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3775         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3776                      ReuseShuffleIndicies);
3777         // This is a special case, as it does not gather, but at the same time
3778         // we are not extending buildTree_rec() towards the operands.
3779         ValueList Op0;
3780         Op0.assign(VL.size(), VL0->getOperand(0));
3781         VectorizableTree.back()->setOperand(0, Op0);
3782         return;
3783       }
3784       if (!CurrentOrder.empty()) {
3785         LLVM_DEBUG({
3786           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3787                     "with order";
3788           for (unsigned Idx : CurrentOrder)
3789             dbgs() << " " << Idx;
3790           dbgs() << "\n";
3791         });
3792         fixupOrderingIndices(CurrentOrder);
3793         // Insert new order with initial value 0, if it does not exist,
3794         // otherwise return the iterator to the existing one.
3795         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3796                      ReuseShuffleIndicies, CurrentOrder);
3797         // This is a special case, as it does not gather, but at the same time
3798         // we are not extending buildTree_rec() towards the operands.
3799         ValueList Op0;
3800         Op0.assign(VL.size(), VL0->getOperand(0));
3801         VectorizableTree.back()->setOperand(0, Op0);
3802         return;
3803       }
3804       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3805       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3806                    ReuseShuffleIndicies);
3807       BS.cancelScheduling(VL, VL0);
3808       return;
3809     }
3810     case Instruction::InsertElement: {
3811       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3812 
3813       // Check that we have a buildvector and not a shuffle of 2 or more
3814       // different vectors.
3815       ValueSet SourceVectors;
3816       int MinIdx = std::numeric_limits<int>::max();
3817       for (Value *V : VL) {
3818         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3819         Optional<int> Idx = *getInsertIndex(V, 0);
3820         if (!Idx || *Idx == UndefMaskElem)
3821           continue;
3822         MinIdx = std::min(MinIdx, *Idx);
3823       }
3824 
3825       if (count_if(VL, [&SourceVectors](Value *V) {
3826             return !SourceVectors.contains(V);
3827           }) >= 2) {
3828         // Found 2nd source vector - cancel.
3829         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3830                              "different source vectors.\n");
3831         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3832         BS.cancelScheduling(VL, VL0);
3833         return;
3834       }
3835 
3836       auto OrdCompare = [](const std::pair<int, int> &P1,
3837                            const std::pair<int, int> &P2) {
3838         return P1.first > P2.first;
3839       };
3840       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3841                     decltype(OrdCompare)>
3842           Indices(OrdCompare);
3843       for (int I = 0, E = VL.size(); I < E; ++I) {
3844         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3845         if (!Idx || *Idx == UndefMaskElem)
3846           continue;
3847         Indices.emplace(*Idx, I);
3848       }
3849       OrdersType CurrentOrder(VL.size(), VL.size());
3850       bool IsIdentity = true;
3851       for (int I = 0, E = VL.size(); I < E; ++I) {
3852         CurrentOrder[Indices.top().second] = I;
3853         IsIdentity &= Indices.top().second == I;
3854         Indices.pop();
3855       }
3856       if (IsIdentity)
3857         CurrentOrder.clear();
3858       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3859                                    None, CurrentOrder);
3860       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3861 
3862       constexpr int NumOps = 2;
3863       ValueList VectorOperands[NumOps];
3864       for (int I = 0; I < NumOps; ++I) {
3865         for (Value *V : VL)
3866           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3867 
3868         TE->setOperand(I, VectorOperands[I]);
3869       }
3870       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3871       return;
3872     }
3873     case Instruction::Load: {
3874       // Check that a vectorized load would load the same memory as a scalar
3875       // load. For example, we don't want to vectorize loads that are smaller
3876       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3877       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3878       // from such a struct, we read/write packed bits disagreeing with the
3879       // unvectorized version.
3880       SmallVector<Value *> PointerOps;
3881       OrdersType CurrentOrder;
3882       TreeEntry *TE = nullptr;
3883       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3884                                 PointerOps)) {
3885       case LoadsState::Vectorize:
3886         if (CurrentOrder.empty()) {
3887           // Original loads are consecutive and does not require reordering.
3888           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3889                             ReuseShuffleIndicies);
3890           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3891         } else {
3892           fixupOrderingIndices(CurrentOrder);
3893           // Need to reorder.
3894           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3895                             ReuseShuffleIndicies, CurrentOrder);
3896           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
3897         }
3898         TE->setOperandsInOrder();
3899         break;
3900       case LoadsState::ScatterVectorize:
3901         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3902         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
3903                           UserTreeIdx, ReuseShuffleIndicies);
3904         TE->setOperandsInOrder();
3905         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
3906         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
3907         break;
3908       case LoadsState::Gather:
3909         BS.cancelScheduling(VL, VL0);
3910         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3911                      ReuseShuffleIndicies);
3912 #ifndef NDEBUG
3913         Type *ScalarTy = VL0->getType();
3914         if (DL->getTypeSizeInBits(ScalarTy) !=
3915             DL->getTypeAllocSizeInBits(ScalarTy))
3916           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
3917         else if (any_of(VL, [](Value *V) {
3918                    return !cast<LoadInst>(V)->isSimple();
3919                  }))
3920           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
3921         else
3922           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
3923 #endif // NDEBUG
3924         break;
3925       }
3926       return;
3927     }
3928     case Instruction::ZExt:
3929     case Instruction::SExt:
3930     case Instruction::FPToUI:
3931     case Instruction::FPToSI:
3932     case Instruction::FPExt:
3933     case Instruction::PtrToInt:
3934     case Instruction::IntToPtr:
3935     case Instruction::SIToFP:
3936     case Instruction::UIToFP:
3937     case Instruction::Trunc:
3938     case Instruction::FPTrunc:
3939     case Instruction::BitCast: {
3940       Type *SrcTy = VL0->getOperand(0)->getType();
3941       for (Value *V : VL) {
3942         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
3943         if (Ty != SrcTy || !isValidElementType(Ty)) {
3944           BS.cancelScheduling(VL, VL0);
3945           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3946                        ReuseShuffleIndicies);
3947           LLVM_DEBUG(dbgs()
3948                      << "SLP: Gathering casts with different src types.\n");
3949           return;
3950         }
3951       }
3952       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3953                                    ReuseShuffleIndicies);
3954       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
3955 
3956       TE->setOperandsInOrder();
3957       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3958         ValueList Operands;
3959         // Prepare the operand vector.
3960         for (Value *V : VL)
3961           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3962 
3963         buildTree_rec(Operands, Depth + 1, {TE, i});
3964       }
3965       return;
3966     }
3967     case Instruction::ICmp:
3968     case Instruction::FCmp: {
3969       // Check that all of the compares have the same predicate.
3970       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3971       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
3972       Type *ComparedTy = VL0->getOperand(0)->getType();
3973       for (Value *V : VL) {
3974         CmpInst *Cmp = cast<CmpInst>(V);
3975         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
3976             Cmp->getOperand(0)->getType() != ComparedTy) {
3977           BS.cancelScheduling(VL, VL0);
3978           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3979                        ReuseShuffleIndicies);
3980           LLVM_DEBUG(dbgs()
3981                      << "SLP: Gathering cmp with different predicate.\n");
3982           return;
3983         }
3984       }
3985 
3986       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3987                                    ReuseShuffleIndicies);
3988       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
3989 
3990       ValueList Left, Right;
3991       if (cast<CmpInst>(VL0)->isCommutative()) {
3992         // Commutative predicate - collect + sort operands of the instructions
3993         // so that each side is more likely to have the same opcode.
3994         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
3995         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3996       } else {
3997         // Collect operands - commute if it uses the swapped predicate.
3998         for (Value *V : VL) {
3999           auto *Cmp = cast<CmpInst>(V);
4000           Value *LHS = Cmp->getOperand(0);
4001           Value *RHS = Cmp->getOperand(1);
4002           if (Cmp->getPredicate() != P0)
4003             std::swap(LHS, RHS);
4004           Left.push_back(LHS);
4005           Right.push_back(RHS);
4006         }
4007       }
4008       TE->setOperand(0, Left);
4009       TE->setOperand(1, Right);
4010       buildTree_rec(Left, Depth + 1, {TE, 0});
4011       buildTree_rec(Right, Depth + 1, {TE, 1});
4012       return;
4013     }
4014     case Instruction::Select:
4015     case Instruction::FNeg:
4016     case Instruction::Add:
4017     case Instruction::FAdd:
4018     case Instruction::Sub:
4019     case Instruction::FSub:
4020     case Instruction::Mul:
4021     case Instruction::FMul:
4022     case Instruction::UDiv:
4023     case Instruction::SDiv:
4024     case Instruction::FDiv:
4025     case Instruction::URem:
4026     case Instruction::SRem:
4027     case Instruction::FRem:
4028     case Instruction::Shl:
4029     case Instruction::LShr:
4030     case Instruction::AShr:
4031     case Instruction::And:
4032     case Instruction::Or:
4033     case Instruction::Xor: {
4034       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4035                                    ReuseShuffleIndicies);
4036       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4037 
4038       // Sort operands of the instructions so that each side is more likely to
4039       // have the same opcode.
4040       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4041         ValueList Left, Right;
4042         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4043         TE->setOperand(0, Left);
4044         TE->setOperand(1, Right);
4045         buildTree_rec(Left, Depth + 1, {TE, 0});
4046         buildTree_rec(Right, Depth + 1, {TE, 1});
4047         return;
4048       }
4049 
4050       TE->setOperandsInOrder();
4051       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4052         ValueList Operands;
4053         // Prepare the operand vector.
4054         for (Value *V : VL)
4055           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4056 
4057         buildTree_rec(Operands, Depth + 1, {TE, i});
4058       }
4059       return;
4060     }
4061     case Instruction::GetElementPtr: {
4062       // We don't combine GEPs with complicated (nested) indexing.
4063       for (Value *V : VL) {
4064         if (cast<Instruction>(V)->getNumOperands() != 2) {
4065           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4066           BS.cancelScheduling(VL, VL0);
4067           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4068                        ReuseShuffleIndicies);
4069           return;
4070         }
4071       }
4072 
4073       // We can't combine several GEPs into one vector if they operate on
4074       // different types.
4075       Type *Ty0 = VL0->getOperand(0)->getType();
4076       for (Value *V : VL) {
4077         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4078         if (Ty0 != CurTy) {
4079           LLVM_DEBUG(dbgs()
4080                      << "SLP: not-vectorizable GEP (different types).\n");
4081           BS.cancelScheduling(VL, VL0);
4082           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4083                        ReuseShuffleIndicies);
4084           return;
4085         }
4086       }
4087 
4088       // We don't combine GEPs with non-constant indexes.
4089       Type *Ty1 = VL0->getOperand(1)->getType();
4090       for (Value *V : VL) {
4091         auto Op = cast<Instruction>(V)->getOperand(1);
4092         if (!isa<ConstantInt>(Op) ||
4093             (Op->getType() != Ty1 &&
4094              Op->getType()->getScalarSizeInBits() >
4095                  DL->getIndexSizeInBits(
4096                      V->getType()->getPointerAddressSpace()))) {
4097           LLVM_DEBUG(dbgs()
4098                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4099           BS.cancelScheduling(VL, VL0);
4100           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4101                        ReuseShuffleIndicies);
4102           return;
4103         }
4104       }
4105 
4106       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4107                                    ReuseShuffleIndicies);
4108       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4109       SmallVector<ValueList, 2> Operands(2);
4110       // Prepare the operand vector for pointer operands.
4111       for (Value *V : VL)
4112         Operands.front().push_back(
4113             cast<GetElementPtrInst>(V)->getPointerOperand());
4114       TE->setOperand(0, Operands.front());
4115       // Need to cast all indices to the same type before vectorization to
4116       // avoid crash.
4117       // Required to be able to find correct matches between different gather
4118       // nodes and reuse the vectorized values rather than trying to gather them
4119       // again.
4120       int IndexIdx = 1;
4121       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4122       Type *Ty = all_of(VL,
4123                         [VL0Ty, IndexIdx](Value *V) {
4124                           return VL0Ty == cast<GetElementPtrInst>(V)
4125                                               ->getOperand(IndexIdx)
4126                                               ->getType();
4127                         })
4128                      ? VL0Ty
4129                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4130                                             ->getPointerOperandType()
4131                                             ->getScalarType());
4132       // Prepare the operand vector.
4133       for (Value *V : VL) {
4134         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4135         auto *CI = cast<ConstantInt>(Op);
4136         Operands.back().push_back(ConstantExpr::getIntegerCast(
4137             CI, Ty, CI->getValue().isSignBitSet()));
4138       }
4139       TE->setOperand(IndexIdx, Operands.back());
4140 
4141       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4142         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4143       return;
4144     }
4145     case Instruction::Store: {
4146       // Check if the stores are consecutive or if we need to swizzle them.
4147       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4148       // Avoid types that are padded when being allocated as scalars, while
4149       // being packed together in a vector (such as i1).
4150       if (DL->getTypeSizeInBits(ScalarTy) !=
4151           DL->getTypeAllocSizeInBits(ScalarTy)) {
4152         BS.cancelScheduling(VL, VL0);
4153         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4154                      ReuseShuffleIndicies);
4155         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4156         return;
4157       }
4158       // Make sure all stores in the bundle are simple - we can't vectorize
4159       // atomic or volatile stores.
4160       SmallVector<Value *, 4> PointerOps(VL.size());
4161       ValueList Operands(VL.size());
4162       auto POIter = PointerOps.begin();
4163       auto OIter = Operands.begin();
4164       for (Value *V : VL) {
4165         auto *SI = cast<StoreInst>(V);
4166         if (!SI->isSimple()) {
4167           BS.cancelScheduling(VL, VL0);
4168           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4169                        ReuseShuffleIndicies);
4170           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4171           return;
4172         }
4173         *POIter = SI->getPointerOperand();
4174         *OIter = SI->getValueOperand();
4175         ++POIter;
4176         ++OIter;
4177       }
4178 
4179       OrdersType CurrentOrder;
4180       // Check the order of pointer operands.
4181       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4182         Value *Ptr0;
4183         Value *PtrN;
4184         if (CurrentOrder.empty()) {
4185           Ptr0 = PointerOps.front();
4186           PtrN = PointerOps.back();
4187         } else {
4188           Ptr0 = PointerOps[CurrentOrder.front()];
4189           PtrN = PointerOps[CurrentOrder.back()];
4190         }
4191         Optional<int> Dist =
4192             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4193         // Check that the sorted pointer operands are consecutive.
4194         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4195           if (CurrentOrder.empty()) {
4196             // Original stores are consecutive and does not require reordering.
4197             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4198                                          UserTreeIdx, ReuseShuffleIndicies);
4199             TE->setOperandsInOrder();
4200             buildTree_rec(Operands, Depth + 1, {TE, 0});
4201             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4202           } else {
4203             fixupOrderingIndices(CurrentOrder);
4204             TreeEntry *TE =
4205                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4206                              ReuseShuffleIndicies, CurrentOrder);
4207             TE->setOperandsInOrder();
4208             buildTree_rec(Operands, Depth + 1, {TE, 0});
4209             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4210           }
4211           return;
4212         }
4213       }
4214 
4215       BS.cancelScheduling(VL, VL0);
4216       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4217                    ReuseShuffleIndicies);
4218       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4219       return;
4220     }
4221     case Instruction::Call: {
4222       // Check if the calls are all to the same vectorizable intrinsic or
4223       // library function.
4224       CallInst *CI = cast<CallInst>(VL0);
4225       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4226 
4227       VFShape Shape = VFShape::get(
4228           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4229           false /*HasGlobalPred*/);
4230       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4231 
4232       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4233         BS.cancelScheduling(VL, VL0);
4234         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4235                      ReuseShuffleIndicies);
4236         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4237         return;
4238       }
4239       Function *F = CI->getCalledFunction();
4240       unsigned NumArgs = CI->arg_size();
4241       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4242       for (unsigned j = 0; j != NumArgs; ++j)
4243         if (hasVectorInstrinsicScalarOpd(ID, j))
4244           ScalarArgs[j] = CI->getArgOperand(j);
4245       for (Value *V : VL) {
4246         CallInst *CI2 = dyn_cast<CallInst>(V);
4247         if (!CI2 || CI2->getCalledFunction() != F ||
4248             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4249             (VecFunc &&
4250              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4251             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4252           BS.cancelScheduling(VL, VL0);
4253           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4254                        ReuseShuffleIndicies);
4255           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4256                             << "\n");
4257           return;
4258         }
4259         // Some intrinsics have scalar arguments and should be same in order for
4260         // them to be vectorized.
4261         for (unsigned j = 0; j != NumArgs; ++j) {
4262           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4263             Value *A1J = CI2->getArgOperand(j);
4264             if (ScalarArgs[j] != A1J) {
4265               BS.cancelScheduling(VL, VL0);
4266               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4267                            ReuseShuffleIndicies);
4268               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4269                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4270                                 << "\n");
4271               return;
4272             }
4273           }
4274         }
4275         // Verify that the bundle operands are identical between the two calls.
4276         if (CI->hasOperandBundles() &&
4277             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4278                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4279                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4280           BS.cancelScheduling(VL, VL0);
4281           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4282                        ReuseShuffleIndicies);
4283           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4284                             << *CI << "!=" << *V << '\n');
4285           return;
4286         }
4287       }
4288 
4289       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4290                                    ReuseShuffleIndicies);
4291       TE->setOperandsInOrder();
4292       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4293         // For scalar operands no need to to create an entry since no need to
4294         // vectorize it.
4295         if (hasVectorInstrinsicScalarOpd(ID, i))
4296           continue;
4297         ValueList Operands;
4298         // Prepare the operand vector.
4299         for (Value *V : VL) {
4300           auto *CI2 = cast<CallInst>(V);
4301           Operands.push_back(CI2->getArgOperand(i));
4302         }
4303         buildTree_rec(Operands, Depth + 1, {TE, i});
4304       }
4305       return;
4306     }
4307     case Instruction::ShuffleVector: {
4308       // If this is not an alternate sequence of opcode like add-sub
4309       // then do not vectorize this instruction.
4310       if (!S.isAltShuffle()) {
4311         BS.cancelScheduling(VL, VL0);
4312         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4313                      ReuseShuffleIndicies);
4314         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4315         return;
4316       }
4317       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4318                                    ReuseShuffleIndicies);
4319       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4320 
4321       // Reorder operands if reordering would enable vectorization.
4322       if (isa<BinaryOperator>(VL0)) {
4323         ValueList Left, Right;
4324         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4325         TE->setOperand(0, Left);
4326         TE->setOperand(1, Right);
4327         buildTree_rec(Left, Depth + 1, {TE, 0});
4328         buildTree_rec(Right, Depth + 1, {TE, 1});
4329         return;
4330       }
4331 
4332       TE->setOperandsInOrder();
4333       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4334         ValueList Operands;
4335         // Prepare the operand vector.
4336         for (Value *V : VL)
4337           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4338 
4339         buildTree_rec(Operands, Depth + 1, {TE, i});
4340       }
4341       return;
4342     }
4343     default:
4344       BS.cancelScheduling(VL, VL0);
4345       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4346                    ReuseShuffleIndicies);
4347       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4348       return;
4349   }
4350 }
4351 
4352 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4353   unsigned N = 1;
4354   Type *EltTy = T;
4355 
4356   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4357          isa<VectorType>(EltTy)) {
4358     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4359       // Check that struct is homogeneous.
4360       for (const auto *Ty : ST->elements())
4361         if (Ty != *ST->element_begin())
4362           return 0;
4363       N *= ST->getNumElements();
4364       EltTy = *ST->element_begin();
4365     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4366       N *= AT->getNumElements();
4367       EltTy = AT->getElementType();
4368     } else {
4369       auto *VT = cast<FixedVectorType>(EltTy);
4370       N *= VT->getNumElements();
4371       EltTy = VT->getElementType();
4372     }
4373   }
4374 
4375   if (!isValidElementType(EltTy))
4376     return 0;
4377   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4378   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4379     return 0;
4380   return N;
4381 }
4382 
4383 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4384                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4385   const auto *It = find_if(VL, [](Value *V) {
4386     return isa<ExtractElementInst, ExtractValueInst>(V);
4387   });
4388   assert(It != VL.end() && "Expected at least one extract instruction.");
4389   auto *E0 = cast<Instruction>(*It);
4390   assert(all_of(VL,
4391                 [](Value *V) {
4392                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4393                       V);
4394                 }) &&
4395          "Invalid opcode");
4396   // Check if all of the extracts come from the same vector and from the
4397   // correct offset.
4398   Value *Vec = E0->getOperand(0);
4399 
4400   CurrentOrder.clear();
4401 
4402   // We have to extract from a vector/aggregate with the same number of elements.
4403   unsigned NElts;
4404   if (E0->getOpcode() == Instruction::ExtractValue) {
4405     const DataLayout &DL = E0->getModule()->getDataLayout();
4406     NElts = canMapToVector(Vec->getType(), DL);
4407     if (!NElts)
4408       return false;
4409     // Check if load can be rewritten as load of vector.
4410     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4411     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4412       return false;
4413   } else {
4414     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4415   }
4416 
4417   if (NElts != VL.size())
4418     return false;
4419 
4420   // Check that all of the indices extract from the correct offset.
4421   bool ShouldKeepOrder = true;
4422   unsigned E = VL.size();
4423   // Assign to all items the initial value E + 1 so we can check if the extract
4424   // instruction index was used already.
4425   // Also, later we can check that all the indices are used and we have a
4426   // consecutive access in the extract instructions, by checking that no
4427   // element of CurrentOrder still has value E + 1.
4428   CurrentOrder.assign(E, E);
4429   unsigned I = 0;
4430   for (; I < E; ++I) {
4431     auto *Inst = dyn_cast<Instruction>(VL[I]);
4432     if (!Inst)
4433       continue;
4434     if (Inst->getOperand(0) != Vec)
4435       break;
4436     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4437       if (isa<UndefValue>(EE->getIndexOperand()))
4438         continue;
4439     Optional<unsigned> Idx = getExtractIndex(Inst);
4440     if (!Idx)
4441       break;
4442     const unsigned ExtIdx = *Idx;
4443     if (ExtIdx != I) {
4444       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4445         break;
4446       ShouldKeepOrder = false;
4447       CurrentOrder[ExtIdx] = I;
4448     } else {
4449       if (CurrentOrder[I] != E)
4450         break;
4451       CurrentOrder[I] = I;
4452     }
4453   }
4454   if (I < E) {
4455     CurrentOrder.clear();
4456     return false;
4457   }
4458 
4459   return ShouldKeepOrder;
4460 }
4461 
4462 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4463                                     ArrayRef<Value *> VectorizedVals) const {
4464   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4465          all_of(I->users(), [this](User *U) {
4466            return ScalarToTreeEntry.count(U) > 0 || MustGather.contains(U);
4467          });
4468 }
4469 
4470 static std::pair<InstructionCost, InstructionCost>
4471 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4472                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4473   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4474 
4475   // Calculate the cost of the scalar and vector calls.
4476   SmallVector<Type *, 4> VecTys;
4477   for (Use &Arg : CI->args())
4478     VecTys.push_back(
4479         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4480   FastMathFlags FMF;
4481   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4482     FMF = FPCI->getFastMathFlags();
4483   SmallVector<const Value *> Arguments(CI->args());
4484   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4485                                     dyn_cast<IntrinsicInst>(CI));
4486   auto IntrinsicCost =
4487     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4488 
4489   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4490                                      VecTy->getNumElements())),
4491                             false /*HasGlobalPred*/);
4492   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4493   auto LibCost = IntrinsicCost;
4494   if (!CI->isNoBuiltin() && VecFunc) {
4495     // Calculate the cost of the vector library call.
4496     // If the corresponding vector call is cheaper, return its cost.
4497     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4498                                     TTI::TCK_RecipThroughput);
4499   }
4500   return {IntrinsicCost, LibCost};
4501 }
4502 
4503 /// Compute the cost of creating a vector of type \p VecTy containing the
4504 /// extracted values from \p VL.
4505 static InstructionCost
4506 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4507                    TargetTransformInfo::ShuffleKind ShuffleKind,
4508                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4509   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4510 
4511   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4512       VecTy->getNumElements() < NumOfParts)
4513     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4514 
4515   bool AllConsecutive = true;
4516   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4517   unsigned Idx = -1;
4518   InstructionCost Cost = 0;
4519 
4520   // Process extracts in blocks of EltsPerVector to check if the source vector
4521   // operand can be re-used directly. If not, add the cost of creating a shuffle
4522   // to extract the values into a vector register.
4523   for (auto *V : VL) {
4524     ++Idx;
4525 
4526     // Need to exclude undefs from analysis.
4527     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4528       continue;
4529 
4530     // Reached the start of a new vector registers.
4531     if (Idx % EltsPerVector == 0) {
4532       AllConsecutive = true;
4533       continue;
4534     }
4535 
4536     // Check all extracts for a vector register on the target directly
4537     // extract values in order.
4538     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4539     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4540       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4541       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4542                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4543     }
4544 
4545     if (AllConsecutive)
4546       continue;
4547 
4548     // Skip all indices, except for the last index per vector block.
4549     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4550       continue;
4551 
4552     // If we have a series of extracts which are not consecutive and hence
4553     // cannot re-use the source vector register directly, compute the shuffle
4554     // cost to extract the a vector with EltsPerVector elements.
4555     Cost += TTI.getShuffleCost(
4556         TargetTransformInfo::SK_PermuteSingleSrc,
4557         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4558   }
4559   return Cost;
4560 }
4561 
4562 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4563 /// operations operands.
4564 static void
4565 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4566                      ArrayRef<int> ReusesIndices,
4567                      const function_ref<bool(Instruction *)> IsAltOp,
4568                      SmallVectorImpl<int> &Mask,
4569                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4570                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4571   unsigned Sz = VL.size();
4572   Mask.assign(Sz, UndefMaskElem);
4573   SmallVector<int> OrderMask;
4574   if (!ReorderIndices.empty())
4575     inversePermutation(ReorderIndices, OrderMask);
4576   for (unsigned I = 0; I < Sz; ++I) {
4577     unsigned Idx = I;
4578     if (!ReorderIndices.empty())
4579       Idx = OrderMask[I];
4580     auto *OpInst = cast<Instruction>(VL[Idx]);
4581     if (IsAltOp(OpInst)) {
4582       Mask[I] = Sz + Idx;
4583       if (AltScalars)
4584         AltScalars->push_back(OpInst);
4585     } else {
4586       Mask[I] = Idx;
4587       if (OpScalars)
4588         OpScalars->push_back(OpInst);
4589     }
4590   }
4591   if (!ReusesIndices.empty()) {
4592     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4593     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4594       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4595     });
4596     Mask.swap(NewMask);
4597   }
4598 }
4599 
4600 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4601                                       ArrayRef<Value *> VectorizedVals) {
4602   ArrayRef<Value*> VL = E->Scalars;
4603 
4604   Type *ScalarTy = VL[0]->getType();
4605   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4606     ScalarTy = SI->getValueOperand()->getType();
4607   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4608     ScalarTy = CI->getOperand(0)->getType();
4609   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4610     ScalarTy = IE->getOperand(1)->getType();
4611   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4612   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4613 
4614   // If we have computed a smaller type for the expression, update VecTy so
4615   // that the costs will be accurate.
4616   if (MinBWs.count(VL[0]))
4617     VecTy = FixedVectorType::get(
4618         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4619   unsigned EntryVF = E->getVectorFactor();
4620   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4621 
4622   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4623   // FIXME: it tries to fix a problem with MSVC buildbots.
4624   TargetTransformInfo &TTIRef = *TTI;
4625   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4626                                VectorizedVals, E](InstructionCost &Cost) {
4627     DenseMap<Value *, int> ExtractVectorsTys;
4628     SmallPtrSet<Value *, 4> CheckedExtracts;
4629     for (auto *V : VL) {
4630       if (isa<UndefValue>(V))
4631         continue;
4632       // If all users of instruction are going to be vectorized and this
4633       // instruction itself is not going to be vectorized, consider this
4634       // instruction as dead and remove its cost from the final cost of the
4635       // vectorized tree.
4636       // Also, avoid adjusting the cost for extractelements with multiple uses
4637       // in different graph entries.
4638       const TreeEntry *VE = getTreeEntry(V);
4639       if (!CheckedExtracts.insert(V).second ||
4640           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4641           (VE && VE != E))
4642         continue;
4643       auto *EE = cast<ExtractElementInst>(V);
4644       Optional<unsigned> EEIdx = getExtractIndex(EE);
4645       if (!EEIdx)
4646         continue;
4647       unsigned Idx = *EEIdx;
4648       if (TTIRef.getNumberOfParts(VecTy) !=
4649           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4650         auto It =
4651             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4652         It->getSecond() = std::min<int>(It->second, Idx);
4653       }
4654       // Take credit for instruction that will become dead.
4655       if (EE->hasOneUse()) {
4656         Instruction *Ext = EE->user_back();
4657         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4658             all_of(Ext->users(),
4659                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4660           // Use getExtractWithExtendCost() to calculate the cost of
4661           // extractelement/ext pair.
4662           Cost -=
4663               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4664                                               EE->getVectorOperandType(), Idx);
4665           // Add back the cost of s|zext which is subtracted separately.
4666           Cost += TTIRef.getCastInstrCost(
4667               Ext->getOpcode(), Ext->getType(), EE->getType(),
4668               TTI::getCastContextHint(Ext), CostKind, Ext);
4669           continue;
4670         }
4671       }
4672       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4673                                         EE->getVectorOperandType(), Idx);
4674     }
4675     // Add a cost for subvector extracts/inserts if required.
4676     for (const auto &Data : ExtractVectorsTys) {
4677       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4678       unsigned NumElts = VecTy->getNumElements();
4679       if (Data.second % NumElts == 0)
4680         continue;
4681       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4682         unsigned Idx = (Data.second / NumElts) * NumElts;
4683         unsigned EENumElts = EEVTy->getNumElements();
4684         if (Idx + NumElts <= EENumElts) {
4685           Cost +=
4686               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4687                                     EEVTy, None, Idx, VecTy);
4688         } else {
4689           // Need to round up the subvector type vectorization factor to avoid a
4690           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4691           // <= EENumElts.
4692           auto *SubVT =
4693               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4694           Cost +=
4695               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4696                                     EEVTy, None, Idx, SubVT);
4697         }
4698       } else {
4699         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4700                                       VecTy, None, 0, EEVTy);
4701       }
4702     }
4703   };
4704   if (E->State == TreeEntry::NeedToGather) {
4705     if (allConstant(VL))
4706       return 0;
4707     if (isa<InsertElementInst>(VL[0]))
4708       return InstructionCost::getInvalid();
4709     SmallVector<int> Mask;
4710     SmallVector<const TreeEntry *> Entries;
4711     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4712         isGatherShuffledEntry(E, Mask, Entries);
4713     if (Shuffle.hasValue()) {
4714       InstructionCost GatherCost = 0;
4715       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4716         // Perfect match in the graph, will reuse the previously vectorized
4717         // node. Cost is 0.
4718         LLVM_DEBUG(
4719             dbgs()
4720             << "SLP: perfect diamond match for gather bundle that starts with "
4721             << *VL.front() << ".\n");
4722         if (NeedToShuffleReuses)
4723           GatherCost =
4724               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4725                                   FinalVecTy, E->ReuseShuffleIndices);
4726       } else {
4727         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4728                           << " entries for bundle that starts with "
4729                           << *VL.front() << ".\n");
4730         // Detected that instead of gather we can emit a shuffle of single/two
4731         // previously vectorized nodes. Add the cost of the permutation rather
4732         // than gather.
4733         ::addMask(Mask, E->ReuseShuffleIndices);
4734         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4735       }
4736       return GatherCost;
4737     }
4738     if ((E->getOpcode() == Instruction::ExtractElement ||
4739          all_of(E->Scalars,
4740                 [](Value *V) {
4741                   return isa<ExtractElementInst, UndefValue>(V);
4742                 })) &&
4743         allSameType(VL)) {
4744       // Check that gather of extractelements can be represented as just a
4745       // shuffle of a single/two vectors the scalars are extracted from.
4746       SmallVector<int> Mask;
4747       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4748           isFixedVectorShuffle(VL, Mask);
4749       if (ShuffleKind.hasValue()) {
4750         // Found the bunch of extractelement instructions that must be gathered
4751         // into a vector and can be represented as a permutation elements in a
4752         // single input vector or of 2 input vectors.
4753         InstructionCost Cost =
4754             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4755         AdjustExtractsCost(Cost);
4756         if (NeedToShuffleReuses)
4757           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4758                                       FinalVecTy, E->ReuseShuffleIndices);
4759         return Cost;
4760       }
4761     }
4762     if (isSplat(VL)) {
4763       // Found the broadcasting of the single scalar, calculate the cost as the
4764       // broadcast.
4765       assert(VecTy == FinalVecTy &&
4766              "No reused scalars expected for broadcast.");
4767       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4768     }
4769     InstructionCost ReuseShuffleCost = 0;
4770     if (NeedToShuffleReuses)
4771       ReuseShuffleCost = TTI->getShuffleCost(
4772           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4773     // Improve gather cost for gather of loads, if we can group some of the
4774     // loads into vector loads.
4775     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4776         !E->isAltShuffle()) {
4777       BoUpSLP::ValueSet VectorizedLoads;
4778       unsigned StartIdx = 0;
4779       unsigned VF = VL.size() / 2;
4780       unsigned VectorizedCnt = 0;
4781       unsigned ScatterVectorizeCnt = 0;
4782       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4783       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4784         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4785              Cnt += VF) {
4786           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4787           if (!VectorizedLoads.count(Slice.front()) &&
4788               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4789             SmallVector<Value *> PointerOps;
4790             OrdersType CurrentOrder;
4791             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4792                                               *SE, CurrentOrder, PointerOps);
4793             switch (LS) {
4794             case LoadsState::Vectorize:
4795             case LoadsState::ScatterVectorize:
4796               // Mark the vectorized loads so that we don't vectorize them
4797               // again.
4798               if (LS == LoadsState::Vectorize)
4799                 ++VectorizedCnt;
4800               else
4801                 ++ScatterVectorizeCnt;
4802               VectorizedLoads.insert(Slice.begin(), Slice.end());
4803               // If we vectorized initial block, no need to try to vectorize it
4804               // again.
4805               if (Cnt == StartIdx)
4806                 StartIdx += VF;
4807               break;
4808             case LoadsState::Gather:
4809               break;
4810             }
4811           }
4812         }
4813         // Check if the whole array was vectorized already - exit.
4814         if (StartIdx >= VL.size())
4815           break;
4816         // Found vectorizable parts - exit.
4817         if (!VectorizedLoads.empty())
4818           break;
4819       }
4820       if (!VectorizedLoads.empty()) {
4821         InstructionCost GatherCost = 0;
4822         unsigned NumParts = TTI->getNumberOfParts(VecTy);
4823         bool NeedInsertSubvectorAnalysis =
4824             !NumParts || (VL.size() / VF) > NumParts;
4825         // Get the cost for gathered loads.
4826         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4827           if (VectorizedLoads.contains(VL[I]))
4828             continue;
4829           GatherCost += getGatherCost(VL.slice(I, VF));
4830         }
4831         // The cost for vectorized loads.
4832         InstructionCost ScalarsCost = 0;
4833         for (Value *V : VectorizedLoads) {
4834           auto *LI = cast<LoadInst>(V);
4835           ScalarsCost += TTI->getMemoryOpCost(
4836               Instruction::Load, LI->getType(), LI->getAlign(),
4837               LI->getPointerAddressSpace(), CostKind, LI);
4838         }
4839         auto *LI = cast<LoadInst>(E->getMainOp());
4840         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4841         Align Alignment = LI->getAlign();
4842         GatherCost +=
4843             VectorizedCnt *
4844             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4845                                  LI->getPointerAddressSpace(), CostKind, LI);
4846         GatherCost += ScatterVectorizeCnt *
4847                       TTI->getGatherScatterOpCost(
4848                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4849                           /*VariableMask=*/false, Alignment, CostKind, LI);
4850         if (NeedInsertSubvectorAnalysis) {
4851           // Add the cost for the subvectors insert.
4852           for (int I = VF, E = VL.size(); I < E; I += VF)
4853             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
4854                                               None, I, LoadTy);
4855         }
4856         return ReuseShuffleCost + GatherCost - ScalarsCost;
4857       }
4858     }
4859     return ReuseShuffleCost + getGatherCost(VL);
4860   }
4861   InstructionCost CommonCost = 0;
4862   SmallVector<int> Mask;
4863   if (!E->ReorderIndices.empty()) {
4864     SmallVector<int> NewMask;
4865     if (E->getOpcode() == Instruction::Store) {
4866       // For stores the order is actually a mask.
4867       NewMask.resize(E->ReorderIndices.size());
4868       copy(E->ReorderIndices, NewMask.begin());
4869     } else {
4870       inversePermutation(E->ReorderIndices, NewMask);
4871     }
4872     ::addMask(Mask, NewMask);
4873   }
4874   if (NeedToShuffleReuses)
4875     ::addMask(Mask, E->ReuseShuffleIndices);
4876   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
4877     CommonCost =
4878         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
4879   assert((E->State == TreeEntry::Vectorize ||
4880           E->State == TreeEntry::ScatterVectorize) &&
4881          "Unhandled state");
4882   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
4883   Instruction *VL0 = E->getMainOp();
4884   unsigned ShuffleOrOp =
4885       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4886   switch (ShuffleOrOp) {
4887     case Instruction::PHI:
4888       return 0;
4889 
4890     case Instruction::ExtractValue:
4891     case Instruction::ExtractElement: {
4892       // The common cost of removal ExtractElement/ExtractValue instructions +
4893       // the cost of shuffles, if required to resuffle the original vector.
4894       if (NeedToShuffleReuses) {
4895         unsigned Idx = 0;
4896         for (unsigned I : E->ReuseShuffleIndices) {
4897           if (ShuffleOrOp == Instruction::ExtractElement) {
4898             auto *EE = cast<ExtractElementInst>(VL[I]);
4899             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4900                                                   EE->getVectorOperandType(),
4901                                                   *getExtractIndex(EE));
4902           } else {
4903             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4904                                                   VecTy, Idx);
4905             ++Idx;
4906           }
4907         }
4908         Idx = EntryVF;
4909         for (Value *V : VL) {
4910           if (ShuffleOrOp == Instruction::ExtractElement) {
4911             auto *EE = cast<ExtractElementInst>(V);
4912             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4913                                                   EE->getVectorOperandType(),
4914                                                   *getExtractIndex(EE));
4915           } else {
4916             --Idx;
4917             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4918                                                   VecTy, Idx);
4919           }
4920         }
4921       }
4922       if (ShuffleOrOp == Instruction::ExtractValue) {
4923         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
4924           auto *EI = cast<Instruction>(VL[I]);
4925           // Take credit for instruction that will become dead.
4926           if (EI->hasOneUse()) {
4927             Instruction *Ext = EI->user_back();
4928             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4929                 all_of(Ext->users(),
4930                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
4931               // Use getExtractWithExtendCost() to calculate the cost of
4932               // extractelement/ext pair.
4933               CommonCost -= TTI->getExtractWithExtendCost(
4934                   Ext->getOpcode(), Ext->getType(), VecTy, I);
4935               // Add back the cost of s|zext which is subtracted separately.
4936               CommonCost += TTI->getCastInstrCost(
4937                   Ext->getOpcode(), Ext->getType(), EI->getType(),
4938                   TTI::getCastContextHint(Ext), CostKind, Ext);
4939               continue;
4940             }
4941           }
4942           CommonCost -=
4943               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
4944         }
4945       } else {
4946         AdjustExtractsCost(CommonCost);
4947       }
4948       return CommonCost;
4949     }
4950     case Instruction::InsertElement: {
4951       assert(E->ReuseShuffleIndices.empty() &&
4952              "Unique insertelements only are expected.");
4953       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
4954 
4955       unsigned const NumElts = SrcVecTy->getNumElements();
4956       unsigned const NumScalars = VL.size();
4957       APInt DemandedElts = APInt::getZero(NumElts);
4958       // TODO: Add support for Instruction::InsertValue.
4959       SmallVector<int> Mask;
4960       if (!E->ReorderIndices.empty()) {
4961         inversePermutation(E->ReorderIndices, Mask);
4962         Mask.append(NumElts - NumScalars, UndefMaskElem);
4963       } else {
4964         Mask.assign(NumElts, UndefMaskElem);
4965         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
4966       }
4967       unsigned Offset = *getInsertIndex(VL0, 0);
4968       bool IsIdentity = true;
4969       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
4970       Mask.swap(PrevMask);
4971       for (unsigned I = 0; I < NumScalars; ++I) {
4972         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
4973         if (!InsertIdx || *InsertIdx == UndefMaskElem)
4974           continue;
4975         DemandedElts.setBit(*InsertIdx);
4976         IsIdentity &= *InsertIdx - Offset == I;
4977         Mask[*InsertIdx - Offset] = I;
4978       }
4979       assert(Offset < NumElts && "Failed to find vector index offset");
4980 
4981       InstructionCost Cost = 0;
4982       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
4983                                             /*Insert*/ true, /*Extract*/ false);
4984 
4985       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
4986         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
4987         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
4988         Cost += TTI->getShuffleCost(
4989             TargetTransformInfo::SK_PermuteSingleSrc,
4990             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
4991       } else if (!IsIdentity) {
4992         auto *FirstInsert =
4993             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
4994               return !is_contained(E->Scalars,
4995                                    cast<Instruction>(V)->getOperand(0));
4996             }));
4997         if (isUndefVector(FirstInsert->getOperand(0))) {
4998           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
4999         } else {
5000           SmallVector<int> InsertMask(NumElts);
5001           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5002           for (unsigned I = 0; I < NumElts; I++) {
5003             if (Mask[I] != UndefMaskElem)
5004               InsertMask[Offset + I] = NumElts + I;
5005           }
5006           Cost +=
5007               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5008         }
5009       }
5010 
5011       return Cost;
5012     }
5013     case Instruction::ZExt:
5014     case Instruction::SExt:
5015     case Instruction::FPToUI:
5016     case Instruction::FPToSI:
5017     case Instruction::FPExt:
5018     case Instruction::PtrToInt:
5019     case Instruction::IntToPtr:
5020     case Instruction::SIToFP:
5021     case Instruction::UIToFP:
5022     case Instruction::Trunc:
5023     case Instruction::FPTrunc:
5024     case Instruction::BitCast: {
5025       Type *SrcTy = VL0->getOperand(0)->getType();
5026       InstructionCost ScalarEltCost =
5027           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5028                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5029       if (NeedToShuffleReuses) {
5030         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5031       }
5032 
5033       // Calculate the cost of this instruction.
5034       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5035 
5036       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5037       InstructionCost VecCost = 0;
5038       // Check if the values are candidates to demote.
5039       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5040         VecCost = CommonCost + TTI->getCastInstrCost(
5041                                    E->getOpcode(), VecTy, SrcVecTy,
5042                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5043       }
5044       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5045       return VecCost - ScalarCost;
5046     }
5047     case Instruction::FCmp:
5048     case Instruction::ICmp:
5049     case Instruction::Select: {
5050       // Calculate the cost of this instruction.
5051       InstructionCost ScalarEltCost =
5052           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5053                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5054       if (NeedToShuffleReuses) {
5055         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5056       }
5057       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5058       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5059 
5060       // Check if all entries in VL are either compares or selects with compares
5061       // as condition that have the same predicates.
5062       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5063       bool First = true;
5064       for (auto *V : VL) {
5065         CmpInst::Predicate CurrentPred;
5066         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5067         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5068              !match(V, MatchCmp)) ||
5069             (!First && VecPred != CurrentPred)) {
5070           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5071           break;
5072         }
5073         First = false;
5074         VecPred = CurrentPred;
5075       }
5076 
5077       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5078           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5079       // Check if it is possible and profitable to use min/max for selects in
5080       // VL.
5081       //
5082       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5083       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5084         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5085                                           {VecTy, VecTy});
5086         InstructionCost IntrinsicCost =
5087             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5088         // If the selects are the only uses of the compares, they will be dead
5089         // and we can adjust the cost by removing their cost.
5090         if (IntrinsicAndUse.second)
5091           IntrinsicCost -=
5092               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5093                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5094         VecCost = std::min(VecCost, IntrinsicCost);
5095       }
5096       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5097       return CommonCost + VecCost - ScalarCost;
5098     }
5099     case Instruction::FNeg:
5100     case Instruction::Add:
5101     case Instruction::FAdd:
5102     case Instruction::Sub:
5103     case Instruction::FSub:
5104     case Instruction::Mul:
5105     case Instruction::FMul:
5106     case Instruction::UDiv:
5107     case Instruction::SDiv:
5108     case Instruction::FDiv:
5109     case Instruction::URem:
5110     case Instruction::SRem:
5111     case Instruction::FRem:
5112     case Instruction::Shl:
5113     case Instruction::LShr:
5114     case Instruction::AShr:
5115     case Instruction::And:
5116     case Instruction::Or:
5117     case Instruction::Xor: {
5118       // Certain instructions can be cheaper to vectorize if they have a
5119       // constant second vector operand.
5120       TargetTransformInfo::OperandValueKind Op1VK =
5121           TargetTransformInfo::OK_AnyValue;
5122       TargetTransformInfo::OperandValueKind Op2VK =
5123           TargetTransformInfo::OK_UniformConstantValue;
5124       TargetTransformInfo::OperandValueProperties Op1VP =
5125           TargetTransformInfo::OP_None;
5126       TargetTransformInfo::OperandValueProperties Op2VP =
5127           TargetTransformInfo::OP_PowerOf2;
5128 
5129       // If all operands are exactly the same ConstantInt then set the
5130       // operand kind to OK_UniformConstantValue.
5131       // If instead not all operands are constants, then set the operand kind
5132       // to OK_AnyValue. If all operands are constants but not the same,
5133       // then set the operand kind to OK_NonUniformConstantValue.
5134       ConstantInt *CInt0 = nullptr;
5135       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5136         const Instruction *I = cast<Instruction>(VL[i]);
5137         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5138         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5139         if (!CInt) {
5140           Op2VK = TargetTransformInfo::OK_AnyValue;
5141           Op2VP = TargetTransformInfo::OP_None;
5142           break;
5143         }
5144         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5145             !CInt->getValue().isPowerOf2())
5146           Op2VP = TargetTransformInfo::OP_None;
5147         if (i == 0) {
5148           CInt0 = CInt;
5149           continue;
5150         }
5151         if (CInt0 != CInt)
5152           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5153       }
5154 
5155       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5156       InstructionCost ScalarEltCost =
5157           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5158                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5159       if (NeedToShuffleReuses) {
5160         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5161       }
5162       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5163       InstructionCost VecCost =
5164           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5165                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5166       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5167       return CommonCost + VecCost - ScalarCost;
5168     }
5169     case Instruction::GetElementPtr: {
5170       TargetTransformInfo::OperandValueKind Op1VK =
5171           TargetTransformInfo::OK_AnyValue;
5172       TargetTransformInfo::OperandValueKind Op2VK =
5173           TargetTransformInfo::OK_UniformConstantValue;
5174 
5175       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5176           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5177       if (NeedToShuffleReuses) {
5178         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5179       }
5180       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5181       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5182           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5183       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5184       return CommonCost + VecCost - ScalarCost;
5185     }
5186     case Instruction::Load: {
5187       // Cost of wide load - cost of scalar loads.
5188       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5189       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5190           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5191       if (NeedToShuffleReuses) {
5192         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5193       }
5194       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5195       InstructionCost VecLdCost;
5196       if (E->State == TreeEntry::Vectorize) {
5197         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5198                                          CostKind, VL0);
5199       } else {
5200         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5201         Align CommonAlignment = Alignment;
5202         for (Value *V : VL)
5203           CommonAlignment =
5204               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5205         VecLdCost = TTI->getGatherScatterOpCost(
5206             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5207             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5208       }
5209       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5210       return CommonCost + VecLdCost - ScalarLdCost;
5211     }
5212     case Instruction::Store: {
5213       // We know that we can merge the stores. Calculate the cost.
5214       bool IsReorder = !E->ReorderIndices.empty();
5215       auto *SI =
5216           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5217       Align Alignment = SI->getAlign();
5218       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5219           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5220       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5221       InstructionCost VecStCost = TTI->getMemoryOpCost(
5222           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5223       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5224       return CommonCost + VecStCost - ScalarStCost;
5225     }
5226     case Instruction::Call: {
5227       CallInst *CI = cast<CallInst>(VL0);
5228       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5229 
5230       // Calculate the cost of the scalar and vector calls.
5231       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5232       InstructionCost ScalarEltCost =
5233           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5234       if (NeedToShuffleReuses) {
5235         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5236       }
5237       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5238 
5239       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5240       InstructionCost VecCallCost =
5241           std::min(VecCallCosts.first, VecCallCosts.second);
5242 
5243       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5244                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5245                         << " for " << *CI << "\n");
5246 
5247       return CommonCost + VecCallCost - ScalarCallCost;
5248     }
5249     case Instruction::ShuffleVector: {
5250       assert(E->isAltShuffle() &&
5251              ((Instruction::isBinaryOp(E->getOpcode()) &&
5252                Instruction::isBinaryOp(E->getAltOpcode())) ||
5253               (Instruction::isCast(E->getOpcode()) &&
5254                Instruction::isCast(E->getAltOpcode()))) &&
5255              "Invalid Shuffle Vector Operand");
5256       InstructionCost ScalarCost = 0;
5257       if (NeedToShuffleReuses) {
5258         for (unsigned Idx : E->ReuseShuffleIndices) {
5259           Instruction *I = cast<Instruction>(VL[Idx]);
5260           CommonCost -= TTI->getInstructionCost(I, CostKind);
5261         }
5262         for (Value *V : VL) {
5263           Instruction *I = cast<Instruction>(V);
5264           CommonCost += TTI->getInstructionCost(I, CostKind);
5265         }
5266       }
5267       for (Value *V : VL) {
5268         Instruction *I = cast<Instruction>(V);
5269         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5270         ScalarCost += TTI->getInstructionCost(I, CostKind);
5271       }
5272       // VecCost is equal to sum of the cost of creating 2 vectors
5273       // and the cost of creating shuffle.
5274       InstructionCost VecCost = 0;
5275       // Try to find the previous shuffle node with the same operands and same
5276       // main/alternate ops.
5277       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5278         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5279           if (TE.get() == E)
5280             break;
5281           if (TE->isAltShuffle() &&
5282               ((TE->getOpcode() == E->getOpcode() &&
5283                 TE->getAltOpcode() == E->getAltOpcode()) ||
5284                (TE->getOpcode() == E->getAltOpcode() &&
5285                 TE->getAltOpcode() == E->getOpcode())) &&
5286               TE->hasEqualOperands(*E))
5287             return true;
5288         }
5289         return false;
5290       };
5291       if (TryFindNodeWithEqualOperands()) {
5292         LLVM_DEBUG({
5293           dbgs() << "SLP: diamond match for alternate node found.\n";
5294           E->dump();
5295         });
5296         // No need to add new vector costs here since we're going to reuse
5297         // same main/alternate vector ops, just do different shuffling.
5298       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5299         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5300         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5301                                                CostKind);
5302       } else {
5303         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5304         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5305         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5306         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5307         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5308                                         TTI::CastContextHint::None, CostKind);
5309         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5310                                          TTI::CastContextHint::None, CostKind);
5311       }
5312 
5313       SmallVector<int> Mask;
5314       buildSuffleEntryMask(
5315           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5316           [E](Instruction *I) {
5317             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5318             return I->getOpcode() == E->getAltOpcode();
5319           },
5320           Mask);
5321       CommonCost =
5322           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5323       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5324       return CommonCost + VecCost - ScalarCost;
5325     }
5326     default:
5327       llvm_unreachable("Unknown instruction");
5328   }
5329 }
5330 
5331 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5332   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5333                     << VectorizableTree.size() << " is fully vectorizable .\n");
5334 
5335   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5336     SmallVector<int> Mask;
5337     return TE->State == TreeEntry::NeedToGather &&
5338            !any_of(TE->Scalars,
5339                    [this](Value *V) { return EphValues.contains(V); }) &&
5340            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5341             TE->Scalars.size() < Limit ||
5342             ((TE->getOpcode() == Instruction::ExtractElement ||
5343               all_of(TE->Scalars,
5344                      [](Value *V) {
5345                        return isa<ExtractElementInst, UndefValue>(V);
5346                      })) &&
5347              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5348             (TE->State == TreeEntry::NeedToGather &&
5349              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5350   };
5351 
5352   // We only handle trees of heights 1 and 2.
5353   if (VectorizableTree.size() == 1 &&
5354       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5355        (ForReduction &&
5356         AreVectorizableGathers(VectorizableTree[0].get(),
5357                                VectorizableTree[0]->Scalars.size()) &&
5358         VectorizableTree[0]->getVectorFactor() > 2)))
5359     return true;
5360 
5361   if (VectorizableTree.size() != 2)
5362     return false;
5363 
5364   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5365   // with the second gather nodes if they have less scalar operands rather than
5366   // the initial tree element (may be profitable to shuffle the second gather)
5367   // or they are extractelements, which form shuffle.
5368   SmallVector<int> Mask;
5369   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5370       AreVectorizableGathers(VectorizableTree[1].get(),
5371                              VectorizableTree[0]->Scalars.size()))
5372     return true;
5373 
5374   // Gathering cost would be too much for tiny trees.
5375   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5376       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5377        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5378     return false;
5379 
5380   return true;
5381 }
5382 
5383 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5384                                        TargetTransformInfo *TTI,
5385                                        bool MustMatchOrInst) {
5386   // Look past the root to find a source value. Arbitrarily follow the
5387   // path through operand 0 of any 'or'. Also, peek through optional
5388   // shift-left-by-multiple-of-8-bits.
5389   Value *ZextLoad = Root;
5390   const APInt *ShAmtC;
5391   bool FoundOr = false;
5392   while (!isa<ConstantExpr>(ZextLoad) &&
5393          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5394           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5395            ShAmtC->urem(8) == 0))) {
5396     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5397     ZextLoad = BinOp->getOperand(0);
5398     if (BinOp->getOpcode() == Instruction::Or)
5399       FoundOr = true;
5400   }
5401   // Check if the input is an extended load of the required or/shift expression.
5402   Value *Load;
5403   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5404       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5405     return false;
5406 
5407   // Require that the total load bit width is a legal integer type.
5408   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5409   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5410   Type *SrcTy = Load->getType();
5411   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5412   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5413     return false;
5414 
5415   // Everything matched - assume that we can fold the whole sequence using
5416   // load combining.
5417   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5418              << *(cast<Instruction>(Root)) << "\n");
5419 
5420   return true;
5421 }
5422 
5423 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5424   if (RdxKind != RecurKind::Or)
5425     return false;
5426 
5427   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5428   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5429   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5430                                     /* MatchOr */ false);
5431 }
5432 
5433 bool BoUpSLP::isLoadCombineCandidate() const {
5434   // Peek through a final sequence of stores and check if all operations are
5435   // likely to be load-combined.
5436   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5437   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5438     Value *X;
5439     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5440         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5441       return false;
5442   }
5443   return true;
5444 }
5445 
5446 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5447   // No need to vectorize inserts of gathered values.
5448   if (VectorizableTree.size() == 2 &&
5449       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5450       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5451     return true;
5452 
5453   // We can vectorize the tree if its size is greater than or equal to the
5454   // minimum size specified by the MinTreeSize command line option.
5455   if (VectorizableTree.size() >= MinTreeSize)
5456     return false;
5457 
5458   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5459   // can vectorize it if we can prove it fully vectorizable.
5460   if (isFullyVectorizableTinyTree(ForReduction))
5461     return false;
5462 
5463   assert(VectorizableTree.empty()
5464              ? ExternalUses.empty()
5465              : true && "We shouldn't have any external users");
5466 
5467   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5468   // vectorizable.
5469   return true;
5470 }
5471 
5472 InstructionCost BoUpSLP::getSpillCost() const {
5473   // Walk from the bottom of the tree to the top, tracking which values are
5474   // live. When we see a call instruction that is not part of our tree,
5475   // query TTI to see if there is a cost to keeping values live over it
5476   // (for example, if spills and fills are required).
5477   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5478   InstructionCost Cost = 0;
5479 
5480   SmallPtrSet<Instruction*, 4> LiveValues;
5481   Instruction *PrevInst = nullptr;
5482 
5483   // The entries in VectorizableTree are not necessarily ordered by their
5484   // position in basic blocks. Collect them and order them by dominance so later
5485   // instructions are guaranteed to be visited first. For instructions in
5486   // different basic blocks, we only scan to the beginning of the block, so
5487   // their order does not matter, as long as all instructions in a basic block
5488   // are grouped together. Using dominance ensures a deterministic order.
5489   SmallVector<Instruction *, 16> OrderedScalars;
5490   for (const auto &TEPtr : VectorizableTree) {
5491     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5492     if (!Inst)
5493       continue;
5494     OrderedScalars.push_back(Inst);
5495   }
5496   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5497     auto *NodeA = DT->getNode(A->getParent());
5498     auto *NodeB = DT->getNode(B->getParent());
5499     assert(NodeA && "Should only process reachable instructions");
5500     assert(NodeB && "Should only process reachable instructions");
5501     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5502            "Different nodes should have different DFS numbers");
5503     if (NodeA != NodeB)
5504       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5505     return B->comesBefore(A);
5506   });
5507 
5508   for (Instruction *Inst : OrderedScalars) {
5509     if (!PrevInst) {
5510       PrevInst = Inst;
5511       continue;
5512     }
5513 
5514     // Update LiveValues.
5515     LiveValues.erase(PrevInst);
5516     for (auto &J : PrevInst->operands()) {
5517       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5518         LiveValues.insert(cast<Instruction>(&*J));
5519     }
5520 
5521     LLVM_DEBUG({
5522       dbgs() << "SLP: #LV: " << LiveValues.size();
5523       for (auto *X : LiveValues)
5524         dbgs() << " " << X->getName();
5525       dbgs() << ", Looking at ";
5526       Inst->dump();
5527     });
5528 
5529     // Now find the sequence of instructions between PrevInst and Inst.
5530     unsigned NumCalls = 0;
5531     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5532                                  PrevInstIt =
5533                                      PrevInst->getIterator().getReverse();
5534     while (InstIt != PrevInstIt) {
5535       if (PrevInstIt == PrevInst->getParent()->rend()) {
5536         PrevInstIt = Inst->getParent()->rbegin();
5537         continue;
5538       }
5539 
5540       // Debug information does not impact spill cost.
5541       if ((isa<CallInst>(&*PrevInstIt) &&
5542            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5543           &*PrevInstIt != PrevInst)
5544         NumCalls++;
5545 
5546       ++PrevInstIt;
5547     }
5548 
5549     if (NumCalls) {
5550       SmallVector<Type*, 4> V;
5551       for (auto *II : LiveValues) {
5552         auto *ScalarTy = II->getType();
5553         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5554           ScalarTy = VectorTy->getElementType();
5555         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5556       }
5557       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5558     }
5559 
5560     PrevInst = Inst;
5561   }
5562 
5563   return Cost;
5564 }
5565 
5566 /// Check if two insertelement instructions are from the same buildvector.
5567 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5568                                             InsertElementInst *V) {
5569   // Instructions must be from the same basic blocks.
5570   if (VU->getParent() != V->getParent())
5571     return false;
5572   // Checks if 2 insertelements are from the same buildvector.
5573   if (VU->getType() != V->getType())
5574     return false;
5575   // Multiple used inserts are separate nodes.
5576   if (!VU->hasOneUse() && !V->hasOneUse())
5577     return false;
5578   auto *IE1 = VU;
5579   auto *IE2 = V;
5580   // Go through the vector operand of insertelement instructions trying to find
5581   // either VU as the original vector for IE2 or V as the original vector for
5582   // IE1.
5583   do {
5584     if (IE2 == VU || IE1 == V)
5585       return true;
5586     if (IE1) {
5587       if (IE1 != VU && !IE1->hasOneUse())
5588         IE1 = nullptr;
5589       else
5590         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5591     }
5592     if (IE2) {
5593       if (IE2 != V && !IE2->hasOneUse())
5594         IE2 = nullptr;
5595       else
5596         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5597     }
5598   } while (IE1 || IE2);
5599   return false;
5600 }
5601 
5602 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5603   InstructionCost Cost = 0;
5604   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5605                     << VectorizableTree.size() << ".\n");
5606 
5607   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5608 
5609   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5610     TreeEntry &TE = *VectorizableTree[I].get();
5611 
5612     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5613     Cost += C;
5614     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5615                       << " for bundle that starts with " << *TE.Scalars[0]
5616                       << ".\n"
5617                       << "SLP: Current total cost = " << Cost << "\n");
5618   }
5619 
5620   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5621   InstructionCost ExtractCost = 0;
5622   SmallVector<unsigned> VF;
5623   SmallVector<SmallVector<int>> ShuffleMask;
5624   SmallVector<Value *> FirstUsers;
5625   SmallVector<APInt> DemandedElts;
5626   for (ExternalUser &EU : ExternalUses) {
5627     // We only add extract cost once for the same scalar.
5628     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5629         !ExtractCostCalculated.insert(EU.Scalar).second)
5630       continue;
5631 
5632     // Uses by ephemeral values are free (because the ephemeral value will be
5633     // removed prior to code generation, and so the extraction will be
5634     // removed as well).
5635     if (EphValues.count(EU.User))
5636       continue;
5637 
5638     // No extract cost for vector "scalar"
5639     if (isa<FixedVectorType>(EU.Scalar->getType()))
5640       continue;
5641 
5642     // Already counted the cost for external uses when tried to adjust the cost
5643     // for extractelements, no need to add it again.
5644     if (isa<ExtractElementInst>(EU.Scalar))
5645       continue;
5646 
5647     // If found user is an insertelement, do not calculate extract cost but try
5648     // to detect it as a final shuffled/identity match.
5649     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5650       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5651         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5652         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5653           continue;
5654         auto *It = find_if(FirstUsers, [VU](Value *V) {
5655           return areTwoInsertFromSameBuildVector(VU,
5656                                                  cast<InsertElementInst>(V));
5657         });
5658         int VecId = -1;
5659         if (It == FirstUsers.end()) {
5660           VF.push_back(FTy->getNumElements());
5661           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5662           // Find the insertvector, vectorized in tree, if any.
5663           Value *Base = VU;
5664           while (isa<InsertElementInst>(Base)) {
5665             // Build the mask for the vectorized insertelement instructions.
5666             if (const TreeEntry *E = getTreeEntry(Base)) {
5667               VU = cast<InsertElementInst>(Base);
5668               do {
5669                 int Idx = E->findLaneForValue(Base);
5670                 ShuffleMask.back()[Idx] = Idx;
5671                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5672               } while (E == getTreeEntry(Base));
5673               break;
5674             }
5675             Base = cast<InsertElementInst>(Base)->getOperand(0);
5676           }
5677           FirstUsers.push_back(VU);
5678           DemandedElts.push_back(APInt::getZero(VF.back()));
5679           VecId = FirstUsers.size() - 1;
5680         } else {
5681           VecId = std::distance(FirstUsers.begin(), It);
5682         }
5683         int Idx = *InsertIdx;
5684         ShuffleMask[VecId][Idx] = EU.Lane;
5685         DemandedElts[VecId].setBit(Idx);
5686         continue;
5687       }
5688     }
5689 
5690     // If we plan to rewrite the tree in a smaller type, we will need to sign
5691     // extend the extracted value back to the original type. Here, we account
5692     // for the extract and the added cost of the sign extend if needed.
5693     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5694     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5695     if (MinBWs.count(ScalarRoot)) {
5696       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5697       auto Extend =
5698           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5699       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5700       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5701                                                    VecTy, EU.Lane);
5702     } else {
5703       ExtractCost +=
5704           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5705     }
5706   }
5707 
5708   InstructionCost SpillCost = getSpillCost();
5709   Cost += SpillCost + ExtractCost;
5710   if (FirstUsers.size() == 1) {
5711     int Limit = ShuffleMask.front().size() * 2;
5712     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5713         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5714       InstructionCost C = TTI->getShuffleCost(
5715           TTI::SK_PermuteSingleSrc,
5716           cast<FixedVectorType>(FirstUsers.front()->getType()),
5717           ShuffleMask.front());
5718       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5719                         << " for final shuffle of insertelement external users "
5720                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5721                         << "SLP: Current total cost = " << Cost << "\n");
5722       Cost += C;
5723     }
5724     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5725         cast<FixedVectorType>(FirstUsers.front()->getType()),
5726         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5727     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5728                       << " for insertelements gather.\n"
5729                       << "SLP: Current total cost = " << Cost << "\n");
5730     Cost -= InsertCost;
5731   } else if (FirstUsers.size() >= 2) {
5732     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5733     // Combined masks of the first 2 vectors.
5734     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5735     copy(ShuffleMask.front(), CombinedMask.begin());
5736     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5737     auto *VecTy = FixedVectorType::get(
5738         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5739         MaxVF);
5740     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5741       if (ShuffleMask[1][I] != UndefMaskElem) {
5742         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5743         CombinedDemandedElts.setBit(I);
5744       }
5745     }
5746     InstructionCost C =
5747         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5748     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5749                       << " for final shuffle of vector node and external "
5750                          "insertelement users "
5751                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5752                       << "SLP: Current total cost = " << Cost << "\n");
5753     Cost += C;
5754     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5755         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5756     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5757                       << " for insertelements gather.\n"
5758                       << "SLP: Current total cost = " << Cost << "\n");
5759     Cost -= InsertCost;
5760     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5761       // Other elements - permutation of 2 vectors (the initial one and the
5762       // next Ith incoming vector).
5763       unsigned VF = ShuffleMask[I].size();
5764       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5765         int Mask = ShuffleMask[I][Idx];
5766         if (Mask != UndefMaskElem)
5767           CombinedMask[Idx] = MaxVF + Mask;
5768         else if (CombinedMask[Idx] != UndefMaskElem)
5769           CombinedMask[Idx] = Idx;
5770       }
5771       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5772         if (CombinedMask[Idx] != UndefMaskElem)
5773           CombinedMask[Idx] = Idx;
5774       InstructionCost C =
5775           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5776       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5777                         << " for final shuffle of vector node and external "
5778                            "insertelement users "
5779                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5780                         << "SLP: Current total cost = " << Cost << "\n");
5781       Cost += C;
5782       InstructionCost InsertCost = TTI->getScalarizationOverhead(
5783           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5784           /*Insert*/ true, /*Extract*/ false);
5785       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5786                         << " for insertelements gather.\n"
5787                         << "SLP: Current total cost = " << Cost << "\n");
5788       Cost -= InsertCost;
5789     }
5790   }
5791 
5792 #ifndef NDEBUG
5793   SmallString<256> Str;
5794   {
5795     raw_svector_ostream OS(Str);
5796     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5797        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5798        << "SLP: Total Cost = " << Cost << ".\n";
5799   }
5800   LLVM_DEBUG(dbgs() << Str);
5801   if (ViewSLPTree)
5802     ViewGraph(this, "SLP" + F->getName(), false, Str);
5803 #endif
5804 
5805   return Cost;
5806 }
5807 
5808 Optional<TargetTransformInfo::ShuffleKind>
5809 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5810                                SmallVectorImpl<const TreeEntry *> &Entries) {
5811   // TODO: currently checking only for Scalars in the tree entry, need to count
5812   // reused elements too for better cost estimation.
5813   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5814   Entries.clear();
5815   // Build a lists of values to tree entries.
5816   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5817   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5818     if (EntryPtr.get() == TE)
5819       break;
5820     if (EntryPtr->State != TreeEntry::NeedToGather)
5821       continue;
5822     for (Value *V : EntryPtr->Scalars)
5823       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5824   }
5825   // Find all tree entries used by the gathered values. If no common entries
5826   // found - not a shuffle.
5827   // Here we build a set of tree nodes for each gathered value and trying to
5828   // find the intersection between these sets. If we have at least one common
5829   // tree node for each gathered value - we have just a permutation of the
5830   // single vector. If we have 2 different sets, we're in situation where we
5831   // have a permutation of 2 input vectors.
5832   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5833   DenseMap<Value *, int> UsedValuesEntry;
5834   for (Value *V : TE->Scalars) {
5835     if (isa<UndefValue>(V))
5836       continue;
5837     // Build a list of tree entries where V is used.
5838     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5839     auto It = ValueToTEs.find(V);
5840     if (It != ValueToTEs.end())
5841       VToTEs = It->second;
5842     if (const TreeEntry *VTE = getTreeEntry(V))
5843       VToTEs.insert(VTE);
5844     if (VToTEs.empty())
5845       return None;
5846     if (UsedTEs.empty()) {
5847       // The first iteration, just insert the list of nodes to vector.
5848       UsedTEs.push_back(VToTEs);
5849     } else {
5850       // Need to check if there are any previously used tree nodes which use V.
5851       // If there are no such nodes, consider that we have another one input
5852       // vector.
5853       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
5854       unsigned Idx = 0;
5855       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
5856         // Do we have a non-empty intersection of previously listed tree entries
5857         // and tree entries using current V?
5858         set_intersect(VToTEs, Set);
5859         if (!VToTEs.empty()) {
5860           // Yes, write the new subset and continue analysis for the next
5861           // scalar.
5862           Set.swap(VToTEs);
5863           break;
5864         }
5865         VToTEs = SavedVToTEs;
5866         ++Idx;
5867       }
5868       // No non-empty intersection found - need to add a second set of possible
5869       // source vectors.
5870       if (Idx == UsedTEs.size()) {
5871         // If the number of input vectors is greater than 2 - not a permutation,
5872         // fallback to the regular gather.
5873         if (UsedTEs.size() == 2)
5874           return None;
5875         UsedTEs.push_back(SavedVToTEs);
5876         Idx = UsedTEs.size() - 1;
5877       }
5878       UsedValuesEntry.try_emplace(V, Idx);
5879     }
5880   }
5881 
5882   unsigned VF = 0;
5883   if (UsedTEs.size() == 1) {
5884     // Try to find the perfect match in another gather node at first.
5885     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
5886       return EntryPtr->isSame(TE->Scalars);
5887     });
5888     if (It != UsedTEs.front().end()) {
5889       Entries.push_back(*It);
5890       std::iota(Mask.begin(), Mask.end(), 0);
5891       return TargetTransformInfo::SK_PermuteSingleSrc;
5892     }
5893     // No perfect match, just shuffle, so choose the first tree node.
5894     Entries.push_back(*UsedTEs.front().begin());
5895   } else {
5896     // Try to find nodes with the same vector factor.
5897     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
5898     DenseMap<int, const TreeEntry *> VFToTE;
5899     for (const TreeEntry *TE : UsedTEs.front())
5900       VFToTE.try_emplace(TE->getVectorFactor(), TE);
5901     for (const TreeEntry *TE : UsedTEs.back()) {
5902       auto It = VFToTE.find(TE->getVectorFactor());
5903       if (It != VFToTE.end()) {
5904         VF = It->first;
5905         Entries.push_back(It->second);
5906         Entries.push_back(TE);
5907         break;
5908       }
5909     }
5910     // No 2 source vectors with the same vector factor - give up and do regular
5911     // gather.
5912     if (Entries.empty())
5913       return None;
5914   }
5915 
5916   // Build a shuffle mask for better cost estimation and vector emission.
5917   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
5918     Value *V = TE->Scalars[I];
5919     if (isa<UndefValue>(V))
5920       continue;
5921     unsigned Idx = UsedValuesEntry.lookup(V);
5922     const TreeEntry *VTE = Entries[Idx];
5923     int FoundLane = VTE->findLaneForValue(V);
5924     Mask[I] = Idx * VF + FoundLane;
5925     // Extra check required by isSingleSourceMaskImpl function (called by
5926     // ShuffleVectorInst::isSingleSourceMask).
5927     if (Mask[I] >= 2 * E)
5928       return None;
5929   }
5930   switch (Entries.size()) {
5931   case 1:
5932     return TargetTransformInfo::SK_PermuteSingleSrc;
5933   case 2:
5934     return TargetTransformInfo::SK_PermuteTwoSrc;
5935   default:
5936     break;
5937   }
5938   return None;
5939 }
5940 
5941 InstructionCost
5942 BoUpSLP::getGatherCost(FixedVectorType *Ty,
5943                        const DenseSet<unsigned> &ShuffledIndices,
5944                        bool NeedToShuffle) const {
5945   unsigned NumElts = Ty->getNumElements();
5946   APInt DemandedElts = APInt::getZero(NumElts);
5947   for (unsigned I = 0; I < NumElts; ++I)
5948     if (!ShuffledIndices.count(I))
5949       DemandedElts.setBit(I);
5950   InstructionCost Cost =
5951       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
5952                                     /*Extract*/ false);
5953   if (NeedToShuffle)
5954     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
5955   return Cost;
5956 }
5957 
5958 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
5959   // Find the type of the operands in VL.
5960   Type *ScalarTy = VL[0]->getType();
5961   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5962     ScalarTy = SI->getValueOperand()->getType();
5963   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5964   bool DuplicateNonConst = false;
5965   // Find the cost of inserting/extracting values from the vector.
5966   // Check if the same elements are inserted several times and count them as
5967   // shuffle candidates.
5968   DenseSet<unsigned> ShuffledElements;
5969   DenseSet<Value *> UniqueElements;
5970   // Iterate in reverse order to consider insert elements with the high cost.
5971   for (unsigned I = VL.size(); I > 0; --I) {
5972     unsigned Idx = I - 1;
5973     // No need to shuffle duplicates for constants.
5974     if (isConstant(VL[Idx])) {
5975       ShuffledElements.insert(Idx);
5976       continue;
5977     }
5978     if (!UniqueElements.insert(VL[Idx]).second) {
5979       DuplicateNonConst = true;
5980       ShuffledElements.insert(Idx);
5981     }
5982   }
5983   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
5984 }
5985 
5986 // Perform operand reordering on the instructions in VL and return the reordered
5987 // operands in Left and Right.
5988 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
5989                                              SmallVectorImpl<Value *> &Left,
5990                                              SmallVectorImpl<Value *> &Right,
5991                                              const DataLayout &DL,
5992                                              ScalarEvolution &SE,
5993                                              const BoUpSLP &R) {
5994   if (VL.empty())
5995     return;
5996   VLOperands Ops(VL, DL, SE, R);
5997   // Reorder the operands in place.
5998   Ops.reorder();
5999   Left = Ops.getVL(0);
6000   Right = Ops.getVL(1);
6001 }
6002 
6003 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6004   // Get the basic block this bundle is in. All instructions in the bundle
6005   // should be in this block.
6006   auto *Front = E->getMainOp();
6007   auto *BB = Front->getParent();
6008   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6009     auto *I = cast<Instruction>(V);
6010     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6011   }));
6012 
6013   // The last instruction in the bundle in program order.
6014   Instruction *LastInst = nullptr;
6015 
6016   // Find the last instruction. The common case should be that BB has been
6017   // scheduled, and the last instruction is VL.back(). So we start with
6018   // VL.back() and iterate over schedule data until we reach the end of the
6019   // bundle. The end of the bundle is marked by null ScheduleData.
6020   if (BlocksSchedules.count(BB)) {
6021     auto *Bundle =
6022         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6023     if (Bundle && Bundle->isPartOfBundle())
6024       for (; Bundle; Bundle = Bundle->NextInBundle)
6025         if (Bundle->OpValue == Bundle->Inst)
6026           LastInst = Bundle->Inst;
6027   }
6028 
6029   // LastInst can still be null at this point if there's either not an entry
6030   // for BB in BlocksSchedules or there's no ScheduleData available for
6031   // VL.back(). This can be the case if buildTree_rec aborts for various
6032   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6033   // size is reached, etc.). ScheduleData is initialized in the scheduling
6034   // "dry-run".
6035   //
6036   // If this happens, we can still find the last instruction by brute force. We
6037   // iterate forwards from Front (inclusive) until we either see all
6038   // instructions in the bundle or reach the end of the block. If Front is the
6039   // last instruction in program order, LastInst will be set to Front, and we
6040   // will visit all the remaining instructions in the block.
6041   //
6042   // One of the reasons we exit early from buildTree_rec is to place an upper
6043   // bound on compile-time. Thus, taking an additional compile-time hit here is
6044   // not ideal. However, this should be exceedingly rare since it requires that
6045   // we both exit early from buildTree_rec and that the bundle be out-of-order
6046   // (causing us to iterate all the way to the end of the block).
6047   if (!LastInst) {
6048     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6049     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6050       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6051         LastInst = &I;
6052       if (Bundle.empty())
6053         break;
6054     }
6055   }
6056   assert(LastInst && "Failed to find last instruction in bundle");
6057 
6058   // Set the insertion point after the last instruction in the bundle. Set the
6059   // debug location to Front.
6060   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6061   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6062 }
6063 
6064 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6065   // List of instructions/lanes from current block and/or the blocks which are
6066   // part of the current loop. These instructions will be inserted at the end to
6067   // make it possible to optimize loops and hoist invariant instructions out of
6068   // the loops body with better chances for success.
6069   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6070   SmallSet<int, 4> PostponedIndices;
6071   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6072   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6073     SmallPtrSet<BasicBlock *, 4> Visited;
6074     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6075       InsertBB = InsertBB->getSinglePredecessor();
6076     return InsertBB && InsertBB == InstBB;
6077   };
6078   for (int I = 0, E = VL.size(); I < E; ++I) {
6079     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6080       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6081            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6082           PostponedIndices.insert(I).second)
6083         PostponedInsts.emplace_back(Inst, I);
6084   }
6085 
6086   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6087     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6088     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6089     if (!InsElt)
6090       return Vec;
6091     GatherShuffleSeq.insert(InsElt);
6092     CSEBlocks.insert(InsElt->getParent());
6093     // Add to our 'need-to-extract' list.
6094     if (TreeEntry *Entry = getTreeEntry(V)) {
6095       // Find which lane we need to extract.
6096       unsigned FoundLane = Entry->findLaneForValue(V);
6097       ExternalUses.emplace_back(V, InsElt, FoundLane);
6098     }
6099     return Vec;
6100   };
6101   Value *Val0 =
6102       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6103   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6104   Value *Vec = PoisonValue::get(VecTy);
6105   SmallVector<int> NonConsts;
6106   // Insert constant values at first.
6107   for (int I = 0, E = VL.size(); I < E; ++I) {
6108     if (PostponedIndices.contains(I))
6109       continue;
6110     if (!isConstant(VL[I])) {
6111       NonConsts.push_back(I);
6112       continue;
6113     }
6114     Vec = CreateInsertElement(Vec, VL[I], I);
6115   }
6116   // Insert non-constant values.
6117   for (int I : NonConsts)
6118     Vec = CreateInsertElement(Vec, VL[I], I);
6119   // Append instructions, which are/may be part of the loop, in the end to make
6120   // it possible to hoist non-loop-based instructions.
6121   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6122     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6123 
6124   return Vec;
6125 }
6126 
6127 namespace {
6128 /// Merges shuffle masks and emits final shuffle instruction, if required.
6129 class ShuffleInstructionBuilder {
6130   IRBuilderBase &Builder;
6131   const unsigned VF = 0;
6132   bool IsFinalized = false;
6133   SmallVector<int, 4> Mask;
6134   /// Holds all of the instructions that we gathered.
6135   SetVector<Instruction *> &GatherShuffleSeq;
6136   /// A list of blocks that we are going to CSE.
6137   SetVector<BasicBlock *> &CSEBlocks;
6138 
6139 public:
6140   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6141                             SetVector<Instruction *> &GatherShuffleSeq,
6142                             SetVector<BasicBlock *> &CSEBlocks)
6143       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6144         CSEBlocks(CSEBlocks) {}
6145 
6146   /// Adds a mask, inverting it before applying.
6147   void addInversedMask(ArrayRef<unsigned> SubMask) {
6148     if (SubMask.empty())
6149       return;
6150     SmallVector<int, 4> NewMask;
6151     inversePermutation(SubMask, NewMask);
6152     addMask(NewMask);
6153   }
6154 
6155   /// Functions adds masks, merging them into  single one.
6156   void addMask(ArrayRef<unsigned> SubMask) {
6157     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6158     addMask(NewMask);
6159   }
6160 
6161   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6162 
6163   Value *finalize(Value *V) {
6164     IsFinalized = true;
6165     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6166     if (VF == ValueVF && Mask.empty())
6167       return V;
6168     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6169     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6170     addMask(NormalizedMask);
6171 
6172     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6173       return V;
6174     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6175     if (auto *I = dyn_cast<Instruction>(Vec)) {
6176       GatherShuffleSeq.insert(I);
6177       CSEBlocks.insert(I->getParent());
6178     }
6179     return Vec;
6180   }
6181 
6182   ~ShuffleInstructionBuilder() {
6183     assert((IsFinalized || Mask.empty()) &&
6184            "Shuffle construction must be finalized.");
6185   }
6186 };
6187 } // namespace
6188 
6189 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6190   unsigned VF = VL.size();
6191   InstructionsState S = getSameOpcode(VL);
6192   if (S.getOpcode()) {
6193     if (TreeEntry *E = getTreeEntry(S.OpValue))
6194       if (E->isSame(VL)) {
6195         Value *V = vectorizeTree(E);
6196         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6197           if (!E->ReuseShuffleIndices.empty()) {
6198             // Reshuffle to get only unique values.
6199             // If some of the scalars are duplicated in the vectorization tree
6200             // entry, we do not vectorize them but instead generate a mask for
6201             // the reuses. But if there are several users of the same entry,
6202             // they may have different vectorization factors. This is especially
6203             // important for PHI nodes. In this case, we need to adapt the
6204             // resulting instruction for the user vectorization factor and have
6205             // to reshuffle it again to take only unique elements of the vector.
6206             // Without this code the function incorrectly returns reduced vector
6207             // instruction with the same elements, not with the unique ones.
6208 
6209             // block:
6210             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6211             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6212             // ... (use %2)
6213             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6214             // br %block
6215             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6216             SmallSet<int, 4> UsedIdxs;
6217             int Pos = 0;
6218             int Sz = VL.size();
6219             for (int Idx : E->ReuseShuffleIndices) {
6220               if (Idx != Sz && Idx != UndefMaskElem &&
6221                   UsedIdxs.insert(Idx).second)
6222                 UniqueIdxs[Idx] = Pos;
6223               ++Pos;
6224             }
6225             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6226                                             "less than original vector size.");
6227             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6228             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6229           } else {
6230             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6231                    "Expected vectorization factor less "
6232                    "than original vector size.");
6233             SmallVector<int> UniformMask(VF, 0);
6234             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6235             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6236           }
6237           if (auto *I = dyn_cast<Instruction>(V)) {
6238             GatherShuffleSeq.insert(I);
6239             CSEBlocks.insert(I->getParent());
6240           }
6241         }
6242         return V;
6243       }
6244   }
6245 
6246   // Check that every instruction appears once in this bundle.
6247   SmallVector<int> ReuseShuffleIndicies;
6248   SmallVector<Value *> UniqueValues;
6249   if (VL.size() > 2) {
6250     DenseMap<Value *, unsigned> UniquePositions;
6251     unsigned NumValues =
6252         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6253                                     return !isa<UndefValue>(V);
6254                                   }).base());
6255     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6256     int UniqueVals = 0;
6257     for (Value *V : VL.drop_back(VL.size() - VF)) {
6258       if (isa<UndefValue>(V)) {
6259         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6260         continue;
6261       }
6262       if (isConstant(V)) {
6263         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6264         UniqueValues.emplace_back(V);
6265         continue;
6266       }
6267       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6268       ReuseShuffleIndicies.emplace_back(Res.first->second);
6269       if (Res.second) {
6270         UniqueValues.emplace_back(V);
6271         ++UniqueVals;
6272       }
6273     }
6274     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6275       // Emit pure splat vector.
6276       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6277                                   UndefMaskElem);
6278     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6279       ReuseShuffleIndicies.clear();
6280       UniqueValues.clear();
6281       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6282     }
6283     UniqueValues.append(VF - UniqueValues.size(),
6284                         PoisonValue::get(VL[0]->getType()));
6285     VL = UniqueValues;
6286   }
6287 
6288   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6289                                            CSEBlocks);
6290   Value *Vec = gather(VL);
6291   if (!ReuseShuffleIndicies.empty()) {
6292     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6293     Vec = ShuffleBuilder.finalize(Vec);
6294   }
6295   return Vec;
6296 }
6297 
6298 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6299   IRBuilder<>::InsertPointGuard Guard(Builder);
6300 
6301   if (E->VectorizedValue) {
6302     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6303     return E->VectorizedValue;
6304   }
6305 
6306   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6307   unsigned VF = E->getVectorFactor();
6308   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6309                                            CSEBlocks);
6310   if (E->State == TreeEntry::NeedToGather) {
6311     if (E->getMainOp())
6312       setInsertPointAfterBundle(E);
6313     Value *Vec;
6314     SmallVector<int> Mask;
6315     SmallVector<const TreeEntry *> Entries;
6316     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6317         isGatherShuffledEntry(E, Mask, Entries);
6318     if (Shuffle.hasValue()) {
6319       assert((Entries.size() == 1 || Entries.size() == 2) &&
6320              "Expected shuffle of 1 or 2 entries.");
6321       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6322                                         Entries.back()->VectorizedValue, Mask);
6323       if (auto *I = dyn_cast<Instruction>(Vec)) {
6324         GatherShuffleSeq.insert(I);
6325         CSEBlocks.insert(I->getParent());
6326       }
6327     } else {
6328       Vec = gather(E->Scalars);
6329     }
6330     if (NeedToShuffleReuses) {
6331       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6332       Vec = ShuffleBuilder.finalize(Vec);
6333     }
6334     E->VectorizedValue = Vec;
6335     return Vec;
6336   }
6337 
6338   assert((E->State == TreeEntry::Vectorize ||
6339           E->State == TreeEntry::ScatterVectorize) &&
6340          "Unhandled state");
6341   unsigned ShuffleOrOp =
6342       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6343   Instruction *VL0 = E->getMainOp();
6344   Type *ScalarTy = VL0->getType();
6345   if (auto *Store = dyn_cast<StoreInst>(VL0))
6346     ScalarTy = Store->getValueOperand()->getType();
6347   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6348     ScalarTy = IE->getOperand(1)->getType();
6349   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6350   switch (ShuffleOrOp) {
6351     case Instruction::PHI: {
6352       assert(
6353           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6354           "PHI reordering is free.");
6355       auto *PH = cast<PHINode>(VL0);
6356       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6357       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6358       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6359       Value *V = NewPhi;
6360       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6361       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6362       V = ShuffleBuilder.finalize(V);
6363 
6364       E->VectorizedValue = V;
6365 
6366       // PHINodes may have multiple entries from the same block. We want to
6367       // visit every block once.
6368       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6369 
6370       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6371         ValueList Operands;
6372         BasicBlock *IBB = PH->getIncomingBlock(i);
6373 
6374         if (!VisitedBBs.insert(IBB).second) {
6375           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6376           continue;
6377         }
6378 
6379         Builder.SetInsertPoint(IBB->getTerminator());
6380         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6381         Value *Vec = vectorizeTree(E->getOperand(i));
6382         NewPhi->addIncoming(Vec, IBB);
6383       }
6384 
6385       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6386              "Invalid number of incoming values");
6387       return V;
6388     }
6389 
6390     case Instruction::ExtractElement: {
6391       Value *V = E->getSingleOperand(0);
6392       Builder.SetInsertPoint(VL0);
6393       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6394       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6395       V = ShuffleBuilder.finalize(V);
6396       E->VectorizedValue = V;
6397       return V;
6398     }
6399     case Instruction::ExtractValue: {
6400       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6401       Builder.SetInsertPoint(LI);
6402       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6403       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6404       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6405       Value *NewV = propagateMetadata(V, E->Scalars);
6406       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6407       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6408       NewV = ShuffleBuilder.finalize(NewV);
6409       E->VectorizedValue = NewV;
6410       return NewV;
6411     }
6412     case Instruction::InsertElement: {
6413       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6414       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6415       Value *V = vectorizeTree(E->getOperand(1));
6416 
6417       // Create InsertVector shuffle if necessary
6418       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6419         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6420       }));
6421       const unsigned NumElts =
6422           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6423       const unsigned NumScalars = E->Scalars.size();
6424 
6425       unsigned Offset = *getInsertIndex(VL0, 0);
6426       assert(Offset < NumElts && "Failed to find vector index offset");
6427 
6428       // Create shuffle to resize vector
6429       SmallVector<int> Mask;
6430       if (!E->ReorderIndices.empty()) {
6431         inversePermutation(E->ReorderIndices, Mask);
6432         Mask.append(NumElts - NumScalars, UndefMaskElem);
6433       } else {
6434         Mask.assign(NumElts, UndefMaskElem);
6435         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6436       }
6437       // Create InsertVector shuffle if necessary
6438       bool IsIdentity = true;
6439       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6440       Mask.swap(PrevMask);
6441       for (unsigned I = 0; I < NumScalars; ++I) {
6442         Value *Scalar = E->Scalars[PrevMask[I]];
6443         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6444         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6445           continue;
6446         IsIdentity &= *InsertIdx - Offset == I;
6447         Mask[*InsertIdx - Offset] = I;
6448       }
6449       if (!IsIdentity || NumElts != NumScalars) {
6450         V = Builder.CreateShuffleVector(V, Mask);
6451         if (auto *I = dyn_cast<Instruction>(V)) {
6452           GatherShuffleSeq.insert(I);
6453           CSEBlocks.insert(I->getParent());
6454         }
6455       }
6456 
6457       if ((!IsIdentity || Offset != 0 ||
6458            !isUndefVector(FirstInsert->getOperand(0))) &&
6459           NumElts != NumScalars) {
6460         SmallVector<int> InsertMask(NumElts);
6461         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6462         for (unsigned I = 0; I < NumElts; I++) {
6463           if (Mask[I] != UndefMaskElem)
6464             InsertMask[Offset + I] = NumElts + I;
6465         }
6466 
6467         V = Builder.CreateShuffleVector(
6468             FirstInsert->getOperand(0), V, InsertMask,
6469             cast<Instruction>(E->Scalars.back())->getName());
6470         if (auto *I = dyn_cast<Instruction>(V)) {
6471           GatherShuffleSeq.insert(I);
6472           CSEBlocks.insert(I->getParent());
6473         }
6474       }
6475 
6476       ++NumVectorInstructions;
6477       E->VectorizedValue = V;
6478       return V;
6479     }
6480     case Instruction::ZExt:
6481     case Instruction::SExt:
6482     case Instruction::FPToUI:
6483     case Instruction::FPToSI:
6484     case Instruction::FPExt:
6485     case Instruction::PtrToInt:
6486     case Instruction::IntToPtr:
6487     case Instruction::SIToFP:
6488     case Instruction::UIToFP:
6489     case Instruction::Trunc:
6490     case Instruction::FPTrunc:
6491     case Instruction::BitCast: {
6492       setInsertPointAfterBundle(E);
6493 
6494       Value *InVec = vectorizeTree(E->getOperand(0));
6495 
6496       if (E->VectorizedValue) {
6497         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6498         return E->VectorizedValue;
6499       }
6500 
6501       auto *CI = cast<CastInst>(VL0);
6502       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6503       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6504       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6505       V = ShuffleBuilder.finalize(V);
6506 
6507       E->VectorizedValue = V;
6508       ++NumVectorInstructions;
6509       return V;
6510     }
6511     case Instruction::FCmp:
6512     case Instruction::ICmp: {
6513       setInsertPointAfterBundle(E);
6514 
6515       Value *L = vectorizeTree(E->getOperand(0));
6516       Value *R = vectorizeTree(E->getOperand(1));
6517 
6518       if (E->VectorizedValue) {
6519         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6520         return E->VectorizedValue;
6521       }
6522 
6523       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6524       Value *V = Builder.CreateCmp(P0, L, R);
6525       propagateIRFlags(V, E->Scalars, VL0);
6526       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6527       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6528       V = ShuffleBuilder.finalize(V);
6529 
6530       E->VectorizedValue = V;
6531       ++NumVectorInstructions;
6532       return V;
6533     }
6534     case Instruction::Select: {
6535       setInsertPointAfterBundle(E);
6536 
6537       Value *Cond = vectorizeTree(E->getOperand(0));
6538       Value *True = vectorizeTree(E->getOperand(1));
6539       Value *False = vectorizeTree(E->getOperand(2));
6540 
6541       if (E->VectorizedValue) {
6542         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6543         return E->VectorizedValue;
6544       }
6545 
6546       Value *V = Builder.CreateSelect(Cond, True, False);
6547       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6548       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6549       V = ShuffleBuilder.finalize(V);
6550 
6551       E->VectorizedValue = V;
6552       ++NumVectorInstructions;
6553       return V;
6554     }
6555     case Instruction::FNeg: {
6556       setInsertPointAfterBundle(E);
6557 
6558       Value *Op = vectorizeTree(E->getOperand(0));
6559 
6560       if (E->VectorizedValue) {
6561         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6562         return E->VectorizedValue;
6563       }
6564 
6565       Value *V = Builder.CreateUnOp(
6566           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6567       propagateIRFlags(V, E->Scalars, VL0);
6568       if (auto *I = dyn_cast<Instruction>(V))
6569         V = propagateMetadata(I, E->Scalars);
6570 
6571       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6572       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6573       V = ShuffleBuilder.finalize(V);
6574 
6575       E->VectorizedValue = V;
6576       ++NumVectorInstructions;
6577 
6578       return V;
6579     }
6580     case Instruction::Add:
6581     case Instruction::FAdd:
6582     case Instruction::Sub:
6583     case Instruction::FSub:
6584     case Instruction::Mul:
6585     case Instruction::FMul:
6586     case Instruction::UDiv:
6587     case Instruction::SDiv:
6588     case Instruction::FDiv:
6589     case Instruction::URem:
6590     case Instruction::SRem:
6591     case Instruction::FRem:
6592     case Instruction::Shl:
6593     case Instruction::LShr:
6594     case Instruction::AShr:
6595     case Instruction::And:
6596     case Instruction::Or:
6597     case Instruction::Xor: {
6598       setInsertPointAfterBundle(E);
6599 
6600       Value *LHS = vectorizeTree(E->getOperand(0));
6601       Value *RHS = vectorizeTree(E->getOperand(1));
6602 
6603       if (E->VectorizedValue) {
6604         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6605         return E->VectorizedValue;
6606       }
6607 
6608       Value *V = Builder.CreateBinOp(
6609           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6610           RHS);
6611       propagateIRFlags(V, E->Scalars, VL0);
6612       if (auto *I = dyn_cast<Instruction>(V))
6613         V = propagateMetadata(I, E->Scalars);
6614 
6615       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6616       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6617       V = ShuffleBuilder.finalize(V);
6618 
6619       E->VectorizedValue = V;
6620       ++NumVectorInstructions;
6621 
6622       return V;
6623     }
6624     case Instruction::Load: {
6625       // Loads are inserted at the head of the tree because we don't want to
6626       // sink them all the way down past store instructions.
6627       setInsertPointAfterBundle(E);
6628 
6629       LoadInst *LI = cast<LoadInst>(VL0);
6630       Instruction *NewLI;
6631       unsigned AS = LI->getPointerAddressSpace();
6632       Value *PO = LI->getPointerOperand();
6633       if (E->State == TreeEntry::Vectorize) {
6634 
6635         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6636 
6637         // The pointer operand uses an in-tree scalar so we add the new BitCast
6638         // to ExternalUses list to make sure that an extract will be generated
6639         // in the future.
6640         if (TreeEntry *Entry = getTreeEntry(PO)) {
6641           // Find which lane we need to extract.
6642           unsigned FoundLane = Entry->findLaneForValue(PO);
6643           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6644         }
6645 
6646         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6647       } else {
6648         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6649         Value *VecPtr = vectorizeTree(E->getOperand(0));
6650         // Use the minimum alignment of the gathered loads.
6651         Align CommonAlignment = LI->getAlign();
6652         for (Value *V : E->Scalars)
6653           CommonAlignment =
6654               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6655         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6656       }
6657       Value *V = propagateMetadata(NewLI, E->Scalars);
6658 
6659       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6660       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6661       V = ShuffleBuilder.finalize(V);
6662       E->VectorizedValue = V;
6663       ++NumVectorInstructions;
6664       return V;
6665     }
6666     case Instruction::Store: {
6667       auto *SI = cast<StoreInst>(VL0);
6668       unsigned AS = SI->getPointerAddressSpace();
6669 
6670       setInsertPointAfterBundle(E);
6671 
6672       Value *VecValue = vectorizeTree(E->getOperand(0));
6673       ShuffleBuilder.addMask(E->ReorderIndices);
6674       VecValue = ShuffleBuilder.finalize(VecValue);
6675 
6676       Value *ScalarPtr = SI->getPointerOperand();
6677       Value *VecPtr = Builder.CreateBitCast(
6678           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6679       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6680                                                  SI->getAlign());
6681 
6682       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6683       // ExternalUses to make sure that an extract will be generated in the
6684       // future.
6685       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6686         // Find which lane we need to extract.
6687         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6688         ExternalUses.push_back(
6689             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6690       }
6691 
6692       Value *V = propagateMetadata(ST, E->Scalars);
6693 
6694       E->VectorizedValue = V;
6695       ++NumVectorInstructions;
6696       return V;
6697     }
6698     case Instruction::GetElementPtr: {
6699       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6700       setInsertPointAfterBundle(E);
6701 
6702       Value *Op0 = vectorizeTree(E->getOperand(0));
6703 
6704       SmallVector<Value *> OpVecs;
6705       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6706         Value *OpVec = vectorizeTree(E->getOperand(J));
6707         OpVecs.push_back(OpVec);
6708       }
6709 
6710       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6711       if (Instruction *I = dyn_cast<Instruction>(V))
6712         V = propagateMetadata(I, E->Scalars);
6713 
6714       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6715       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6716       V = ShuffleBuilder.finalize(V);
6717 
6718       E->VectorizedValue = V;
6719       ++NumVectorInstructions;
6720 
6721       return V;
6722     }
6723     case Instruction::Call: {
6724       CallInst *CI = cast<CallInst>(VL0);
6725       setInsertPointAfterBundle(E);
6726 
6727       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6728       if (Function *FI = CI->getCalledFunction())
6729         IID = FI->getIntrinsicID();
6730 
6731       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6732 
6733       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6734       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6735                           VecCallCosts.first <= VecCallCosts.second;
6736 
6737       Value *ScalarArg = nullptr;
6738       std::vector<Value *> OpVecs;
6739       SmallVector<Type *, 2> TysForDecl =
6740           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6741       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6742         ValueList OpVL;
6743         // Some intrinsics have scalar arguments. This argument should not be
6744         // vectorized.
6745         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6746           CallInst *CEI = cast<CallInst>(VL0);
6747           ScalarArg = CEI->getArgOperand(j);
6748           OpVecs.push_back(CEI->getArgOperand(j));
6749           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6750             TysForDecl.push_back(ScalarArg->getType());
6751           continue;
6752         }
6753 
6754         Value *OpVec = vectorizeTree(E->getOperand(j));
6755         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6756         OpVecs.push_back(OpVec);
6757       }
6758 
6759       Function *CF;
6760       if (!UseIntrinsic) {
6761         VFShape Shape =
6762             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6763                                   VecTy->getNumElements())),
6764                          false /*HasGlobalPred*/);
6765         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6766       } else {
6767         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6768       }
6769 
6770       SmallVector<OperandBundleDef, 1> OpBundles;
6771       CI->getOperandBundlesAsDefs(OpBundles);
6772       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6773 
6774       // The scalar argument uses an in-tree scalar so we add the new vectorized
6775       // call to ExternalUses list to make sure that an extract will be
6776       // generated in the future.
6777       if (ScalarArg) {
6778         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6779           // Find which lane we need to extract.
6780           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6781           ExternalUses.push_back(
6782               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6783         }
6784       }
6785 
6786       propagateIRFlags(V, E->Scalars, VL0);
6787       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6788       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6789       V = ShuffleBuilder.finalize(V);
6790 
6791       E->VectorizedValue = V;
6792       ++NumVectorInstructions;
6793       return V;
6794     }
6795     case Instruction::ShuffleVector: {
6796       assert(E->isAltShuffle() &&
6797              ((Instruction::isBinaryOp(E->getOpcode()) &&
6798                Instruction::isBinaryOp(E->getAltOpcode())) ||
6799               (Instruction::isCast(E->getOpcode()) &&
6800                Instruction::isCast(E->getAltOpcode()))) &&
6801              "Invalid Shuffle Vector Operand");
6802 
6803       Value *LHS = nullptr, *RHS = nullptr;
6804       if (Instruction::isBinaryOp(E->getOpcode())) {
6805         setInsertPointAfterBundle(E);
6806         LHS = vectorizeTree(E->getOperand(0));
6807         RHS = vectorizeTree(E->getOperand(1));
6808       } else {
6809         setInsertPointAfterBundle(E);
6810         LHS = vectorizeTree(E->getOperand(0));
6811       }
6812 
6813       if (E->VectorizedValue) {
6814         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6815         return E->VectorizedValue;
6816       }
6817 
6818       Value *V0, *V1;
6819       if (Instruction::isBinaryOp(E->getOpcode())) {
6820         V0 = Builder.CreateBinOp(
6821             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6822         V1 = Builder.CreateBinOp(
6823             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6824       } else {
6825         V0 = Builder.CreateCast(
6826             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6827         V1 = Builder.CreateCast(
6828             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6829       }
6830       // Add V0 and V1 to later analysis to try to find and remove matching
6831       // instruction, if any.
6832       for (Value *V : {V0, V1}) {
6833         if (auto *I = dyn_cast<Instruction>(V)) {
6834           GatherShuffleSeq.insert(I);
6835           CSEBlocks.insert(I->getParent());
6836         }
6837       }
6838 
6839       // Create shuffle to take alternate operations from the vector.
6840       // Also, gather up main and alt scalar ops to propagate IR flags to
6841       // each vector operation.
6842       ValueList OpScalars, AltScalars;
6843       SmallVector<int> Mask;
6844       buildSuffleEntryMask(
6845           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6846           [E](Instruction *I) {
6847             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6848             return I->getOpcode() == E->getAltOpcode();
6849           },
6850           Mask, &OpScalars, &AltScalars);
6851 
6852       propagateIRFlags(V0, OpScalars);
6853       propagateIRFlags(V1, AltScalars);
6854 
6855       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
6856       if (auto *I = dyn_cast<Instruction>(V)) {
6857         V = propagateMetadata(I, E->Scalars);
6858         GatherShuffleSeq.insert(I);
6859         CSEBlocks.insert(I->getParent());
6860       }
6861       V = ShuffleBuilder.finalize(V);
6862 
6863       E->VectorizedValue = V;
6864       ++NumVectorInstructions;
6865 
6866       return V;
6867     }
6868     default:
6869     llvm_unreachable("unknown inst");
6870   }
6871   return nullptr;
6872 }
6873 
6874 Value *BoUpSLP::vectorizeTree() {
6875   ExtraValueToDebugLocsMap ExternallyUsedValues;
6876   return vectorizeTree(ExternallyUsedValues);
6877 }
6878 
6879 Value *
6880 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
6881   // All blocks must be scheduled before any instructions are inserted.
6882   for (auto &BSIter : BlocksSchedules) {
6883     scheduleBlock(BSIter.second.get());
6884   }
6885 
6886   Builder.SetInsertPoint(&F->getEntryBlock().front());
6887   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
6888 
6889   // If the vectorized tree can be rewritten in a smaller type, we truncate the
6890   // vectorized root. InstCombine will then rewrite the entire expression. We
6891   // sign extend the extracted values below.
6892   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6893   if (MinBWs.count(ScalarRoot)) {
6894     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
6895       // If current instr is a phi and not the last phi, insert it after the
6896       // last phi node.
6897       if (isa<PHINode>(I))
6898         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
6899       else
6900         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
6901     }
6902     auto BundleWidth = VectorizableTree[0]->Scalars.size();
6903     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6904     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
6905     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
6906     VectorizableTree[0]->VectorizedValue = Trunc;
6907   }
6908 
6909   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
6910                     << " values .\n");
6911 
6912   // Extract all of the elements with the external uses.
6913   for (const auto &ExternalUse : ExternalUses) {
6914     Value *Scalar = ExternalUse.Scalar;
6915     llvm::User *User = ExternalUse.User;
6916 
6917     // Skip users that we already RAUW. This happens when one instruction
6918     // has multiple uses of the same value.
6919     if (User && !is_contained(Scalar->users(), User))
6920       continue;
6921     TreeEntry *E = getTreeEntry(Scalar);
6922     assert(E && "Invalid scalar");
6923     assert(E->State != TreeEntry::NeedToGather &&
6924            "Extracting from a gather list");
6925 
6926     Value *Vec = E->VectorizedValue;
6927     assert(Vec && "Can't find vectorizable value");
6928 
6929     Value *Lane = Builder.getInt32(ExternalUse.Lane);
6930     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
6931       if (Scalar->getType() != Vec->getType()) {
6932         Value *Ex;
6933         // "Reuse" the existing extract to improve final codegen.
6934         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
6935           Ex = Builder.CreateExtractElement(ES->getOperand(0),
6936                                             ES->getOperand(1));
6937         } else {
6938           Ex = Builder.CreateExtractElement(Vec, Lane);
6939         }
6940         // If necessary, sign-extend or zero-extend ScalarRoot
6941         // to the larger type.
6942         if (!MinBWs.count(ScalarRoot))
6943           return Ex;
6944         if (MinBWs[ScalarRoot].second)
6945           return Builder.CreateSExt(Ex, Scalar->getType());
6946         return Builder.CreateZExt(Ex, Scalar->getType());
6947       }
6948       assert(isa<FixedVectorType>(Scalar->getType()) &&
6949              isa<InsertElementInst>(Scalar) &&
6950              "In-tree scalar of vector type is not insertelement?");
6951       return Vec;
6952     };
6953     // If User == nullptr, the Scalar is used as extra arg. Generate
6954     // ExtractElement instruction and update the record for this scalar in
6955     // ExternallyUsedValues.
6956     if (!User) {
6957       assert(ExternallyUsedValues.count(Scalar) &&
6958              "Scalar with nullptr as an external user must be registered in "
6959              "ExternallyUsedValues map");
6960       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6961         Builder.SetInsertPoint(VecI->getParent(),
6962                                std::next(VecI->getIterator()));
6963       } else {
6964         Builder.SetInsertPoint(&F->getEntryBlock().front());
6965       }
6966       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6967       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
6968       auto &NewInstLocs = ExternallyUsedValues[NewInst];
6969       auto It = ExternallyUsedValues.find(Scalar);
6970       assert(It != ExternallyUsedValues.end() &&
6971              "Externally used scalar is not found in ExternallyUsedValues");
6972       NewInstLocs.append(It->second);
6973       ExternallyUsedValues.erase(Scalar);
6974       // Required to update internally referenced instructions.
6975       Scalar->replaceAllUsesWith(NewInst);
6976       continue;
6977     }
6978 
6979     // Generate extracts for out-of-tree users.
6980     // Find the insertion point for the extractelement lane.
6981     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6982       if (PHINode *PH = dyn_cast<PHINode>(User)) {
6983         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
6984           if (PH->getIncomingValue(i) == Scalar) {
6985             Instruction *IncomingTerminator =
6986                 PH->getIncomingBlock(i)->getTerminator();
6987             if (isa<CatchSwitchInst>(IncomingTerminator)) {
6988               Builder.SetInsertPoint(VecI->getParent(),
6989                                      std::next(VecI->getIterator()));
6990             } else {
6991               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
6992             }
6993             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6994             CSEBlocks.insert(PH->getIncomingBlock(i));
6995             PH->setOperand(i, NewInst);
6996           }
6997         }
6998       } else {
6999         Builder.SetInsertPoint(cast<Instruction>(User));
7000         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7001         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7002         User->replaceUsesOfWith(Scalar, NewInst);
7003       }
7004     } else {
7005       Builder.SetInsertPoint(&F->getEntryBlock().front());
7006       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7007       CSEBlocks.insert(&F->getEntryBlock());
7008       User->replaceUsesOfWith(Scalar, NewInst);
7009     }
7010 
7011     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7012   }
7013 
7014   // For each vectorized value:
7015   for (auto &TEPtr : VectorizableTree) {
7016     TreeEntry *Entry = TEPtr.get();
7017 
7018     // No need to handle users of gathered values.
7019     if (Entry->State == TreeEntry::NeedToGather)
7020       continue;
7021 
7022     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7023 
7024     // For each lane:
7025     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7026       Value *Scalar = Entry->Scalars[Lane];
7027 
7028 #ifndef NDEBUG
7029       Type *Ty = Scalar->getType();
7030       if (!Ty->isVoidTy()) {
7031         for (User *U : Scalar->users()) {
7032           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7033 
7034           // It is legal to delete users in the ignorelist.
7035           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7036                   (isa_and_nonnull<Instruction>(U) &&
7037                    isDeleted(cast<Instruction>(U)))) &&
7038                  "Deleting out-of-tree value");
7039         }
7040       }
7041 #endif
7042       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7043       eraseInstruction(cast<Instruction>(Scalar));
7044     }
7045   }
7046 
7047   Builder.ClearInsertionPoint();
7048   InstrElementSize.clear();
7049 
7050   return VectorizableTree[0]->VectorizedValue;
7051 }
7052 
7053 void BoUpSLP::optimizeGatherSequence() {
7054   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7055                     << " gather sequences instructions.\n");
7056   // LICM InsertElementInst sequences.
7057   for (Instruction *I : GatherShuffleSeq) {
7058     if (isDeleted(I))
7059       continue;
7060 
7061     // Check if this block is inside a loop.
7062     Loop *L = LI->getLoopFor(I->getParent());
7063     if (!L)
7064       continue;
7065 
7066     // Check if it has a preheader.
7067     BasicBlock *PreHeader = L->getLoopPreheader();
7068     if (!PreHeader)
7069       continue;
7070 
7071     // If the vector or the element that we insert into it are
7072     // instructions that are defined in this basic block then we can't
7073     // hoist this instruction.
7074     if (any_of(I->operands(), [L](Value *V) {
7075           auto *OpI = dyn_cast<Instruction>(V);
7076           return OpI && L->contains(OpI);
7077         }))
7078       continue;
7079 
7080     // We can hoist this instruction. Move it to the pre-header.
7081     I->moveBefore(PreHeader->getTerminator());
7082   }
7083 
7084   // Make a list of all reachable blocks in our CSE queue.
7085   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7086   CSEWorkList.reserve(CSEBlocks.size());
7087   for (BasicBlock *BB : CSEBlocks)
7088     if (DomTreeNode *N = DT->getNode(BB)) {
7089       assert(DT->isReachableFromEntry(N));
7090       CSEWorkList.push_back(N);
7091     }
7092 
7093   // Sort blocks by domination. This ensures we visit a block after all blocks
7094   // dominating it are visited.
7095   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7096     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7097            "Different nodes should have different DFS numbers");
7098     return A->getDFSNumIn() < B->getDFSNumIn();
7099   });
7100 
7101   // Less defined shuffles can be replaced by the more defined copies.
7102   // Between two shuffles one is less defined if it has the same vector operands
7103   // and its mask indeces are the same as in the first one or undefs. E.g.
7104   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7105   // poison, <0, 0, 0, 0>.
7106   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7107                                            SmallVectorImpl<int> &NewMask) {
7108     if (I1->getType() != I2->getType())
7109       return false;
7110     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7111     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7112     if (!SI1 || !SI2)
7113       return I1->isIdenticalTo(I2);
7114     if (SI1->isIdenticalTo(SI2))
7115       return true;
7116     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7117       if (SI1->getOperand(I) != SI2->getOperand(I))
7118         return false;
7119     // Check if the second instruction is more defined than the first one.
7120     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7121     ArrayRef<int> SM1 = SI1->getShuffleMask();
7122     // Count trailing undefs in the mask to check the final number of used
7123     // registers.
7124     unsigned LastUndefsCnt = 0;
7125     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7126       if (SM1[I] == UndefMaskElem)
7127         ++LastUndefsCnt;
7128       else
7129         LastUndefsCnt = 0;
7130       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7131           NewMask[I] != SM1[I])
7132         return false;
7133       if (NewMask[I] == UndefMaskElem)
7134         NewMask[I] = SM1[I];
7135     }
7136     // Check if the last undefs actually change the final number of used vector
7137     // registers.
7138     return SM1.size() - LastUndefsCnt > 1 &&
7139            TTI->getNumberOfParts(SI1->getType()) ==
7140                TTI->getNumberOfParts(
7141                    FixedVectorType::get(SI1->getType()->getElementType(),
7142                                         SM1.size() - LastUndefsCnt));
7143   };
7144   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7145   // instructions. TODO: We can further optimize this scan if we split the
7146   // instructions into different buckets based on the insert lane.
7147   SmallVector<Instruction *, 16> Visited;
7148   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7149     assert(*I &&
7150            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7151            "Worklist not sorted properly!");
7152     BasicBlock *BB = (*I)->getBlock();
7153     // For all instructions in blocks containing gather sequences:
7154     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7155       if (isDeleted(&In))
7156         continue;
7157       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7158           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7159         continue;
7160 
7161       // Check if we can replace this instruction with any of the
7162       // visited instructions.
7163       bool Replaced = false;
7164       for (Instruction *&V : Visited) {
7165         SmallVector<int> NewMask;
7166         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7167             DT->dominates(V->getParent(), In.getParent())) {
7168           In.replaceAllUsesWith(V);
7169           eraseInstruction(&In);
7170           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7171             if (!NewMask.empty())
7172               SI->setShuffleMask(NewMask);
7173           Replaced = true;
7174           break;
7175         }
7176         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7177             GatherShuffleSeq.contains(V) &&
7178             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7179             DT->dominates(In.getParent(), V->getParent())) {
7180           In.moveAfter(V);
7181           V->replaceAllUsesWith(&In);
7182           eraseInstruction(V);
7183           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7184             if (!NewMask.empty())
7185               SI->setShuffleMask(NewMask);
7186           V = &In;
7187           Replaced = true;
7188           break;
7189         }
7190       }
7191       if (!Replaced) {
7192         assert(!is_contained(Visited, &In));
7193         Visited.push_back(&In);
7194       }
7195     }
7196   }
7197   CSEBlocks.clear();
7198   GatherShuffleSeq.clear();
7199 }
7200 
7201 // Groups the instructions to a bundle (which is then a single scheduling entity)
7202 // and schedules instructions until the bundle gets ready.
7203 Optional<BoUpSLP::ScheduleData *>
7204 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7205                                             const InstructionsState &S) {
7206   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7207   // instructions.
7208   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7209     return nullptr;
7210 
7211   // Initialize the instruction bundle.
7212   Instruction *OldScheduleEnd = ScheduleEnd;
7213   ScheduleData *PrevInBundle = nullptr;
7214   ScheduleData *Bundle = nullptr;
7215   bool ReSchedule = false;
7216   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7217 
7218   auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule,
7219                                                          ScheduleData *Bundle) {
7220     // The scheduling region got new instructions at the lower end (or it is a
7221     // new region for the first bundle). This makes it necessary to
7222     // recalculate all dependencies.
7223     // It is seldom that this needs to be done a second time after adding the
7224     // initial bundle to the region.
7225     if (ScheduleEnd != OldScheduleEnd) {
7226       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7227         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7228       ReSchedule = true;
7229     }
7230     if (ReSchedule) {
7231       resetSchedule();
7232       initialFillReadyList(ReadyInsts);
7233     }
7234     if (Bundle) {
7235       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7236                         << " in block " << BB->getName() << "\n");
7237       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7238     }
7239 
7240     // Now try to schedule the new bundle or (if no bundle) just calculate
7241     // dependencies. As soon as the bundle is "ready" it means that there are no
7242     // cyclic dependencies and we can schedule it. Note that's important that we
7243     // don't "schedule" the bundle yet (see cancelScheduling).
7244     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7245            !ReadyInsts.empty()) {
7246       ScheduleData *Picked = ReadyInsts.pop_back_val();
7247       if (Picked->isSchedulingEntity() && Picked->isReady())
7248         schedule(Picked, ReadyInsts);
7249     }
7250   };
7251 
7252   // Make sure that the scheduling region contains all
7253   // instructions of the bundle.
7254   for (Value *V : VL) {
7255     if (!extendSchedulingRegion(V, S)) {
7256       // If the scheduling region got new instructions at the lower end (or it
7257       // is a new region for the first bundle). This makes it necessary to
7258       // recalculate all dependencies.
7259       // Otherwise the compiler may crash trying to incorrectly calculate
7260       // dependencies and emit instruction in the wrong order at the actual
7261       // scheduling.
7262       TryScheduleBundle(/*ReSchedule=*/false, nullptr);
7263       return None;
7264     }
7265   }
7266 
7267   for (Value *V : VL) {
7268     ScheduleData *BundleMember = getScheduleData(V);
7269     assert(BundleMember &&
7270            "no ScheduleData for bundle member (maybe not in same basic block)");
7271     if (BundleMember->IsScheduled) {
7272       // A bundle member was scheduled as single instruction before and now
7273       // needs to be scheduled as part of the bundle. We just get rid of the
7274       // existing schedule.
7275       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7276                         << " was already scheduled\n");
7277       ReSchedule = true;
7278     }
7279     assert(BundleMember->isSchedulingEntity() &&
7280            "bundle member already part of other bundle");
7281     if (PrevInBundle) {
7282       PrevInBundle->NextInBundle = BundleMember;
7283     } else {
7284       Bundle = BundleMember;
7285     }
7286     BundleMember->UnscheduledDepsInBundle = 0;
7287     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7288 
7289     // Group the instructions to a bundle.
7290     BundleMember->FirstInBundle = Bundle;
7291     PrevInBundle = BundleMember;
7292   }
7293   assert(Bundle && "Failed to find schedule bundle");
7294   TryScheduleBundle(ReSchedule, Bundle);
7295   if (!Bundle->isReady()) {
7296     cancelScheduling(VL, S.OpValue);
7297     return None;
7298   }
7299   return Bundle;
7300 }
7301 
7302 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7303                                                 Value *OpValue) {
7304   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7305     return;
7306 
7307   ScheduleData *Bundle = getScheduleData(OpValue);
7308   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7309   assert(!Bundle->IsScheduled &&
7310          "Can't cancel bundle which is already scheduled");
7311   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7312          "tried to unbundle something which is not a bundle");
7313 
7314   // Un-bundle: make single instructions out of the bundle.
7315   ScheduleData *BundleMember = Bundle;
7316   while (BundleMember) {
7317     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7318     BundleMember->FirstInBundle = BundleMember;
7319     ScheduleData *Next = BundleMember->NextInBundle;
7320     BundleMember->NextInBundle = nullptr;
7321     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7322     if (BundleMember->UnscheduledDepsInBundle == 0) {
7323       ReadyInsts.insert(BundleMember);
7324     }
7325     BundleMember = Next;
7326   }
7327 }
7328 
7329 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7330   // Allocate a new ScheduleData for the instruction.
7331   if (ChunkPos >= ChunkSize) {
7332     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7333     ChunkPos = 0;
7334   }
7335   return &(ScheduleDataChunks.back()[ChunkPos++]);
7336 }
7337 
7338 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7339                                                       const InstructionsState &S) {
7340   if (getScheduleData(V, isOneOf(S, V)))
7341     return true;
7342   Instruction *I = dyn_cast<Instruction>(V);
7343   assert(I && "bundle member must be an instruction");
7344   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7345          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7346          "be scheduled");
7347   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7348     ScheduleData *ISD = getScheduleData(I);
7349     if (!ISD)
7350       return false;
7351     assert(isInSchedulingRegion(ISD) &&
7352            "ScheduleData not in scheduling region");
7353     ScheduleData *SD = allocateScheduleDataChunks();
7354     SD->Inst = I;
7355     SD->init(SchedulingRegionID, S.OpValue);
7356     ExtraScheduleDataMap[I][S.OpValue] = SD;
7357     return true;
7358   };
7359   if (CheckSheduleForI(I))
7360     return true;
7361   if (!ScheduleStart) {
7362     // It's the first instruction in the new region.
7363     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7364     ScheduleStart = I;
7365     ScheduleEnd = I->getNextNode();
7366     if (isOneOf(S, I) != I)
7367       CheckSheduleForI(I);
7368     assert(ScheduleEnd && "tried to vectorize a terminator?");
7369     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7370     return true;
7371   }
7372   // Search up and down at the same time, because we don't know if the new
7373   // instruction is above or below the existing scheduling region.
7374   BasicBlock::reverse_iterator UpIter =
7375       ++ScheduleStart->getIterator().getReverse();
7376   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7377   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7378   BasicBlock::iterator LowerEnd = BB->end();
7379   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7380          &*DownIter != I) {
7381     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7382       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7383       return false;
7384     }
7385 
7386     ++UpIter;
7387     ++DownIter;
7388   }
7389   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7390     assert(I->getParent() == ScheduleStart->getParent() &&
7391            "Instruction is in wrong basic block.");
7392     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7393     ScheduleStart = I;
7394     if (isOneOf(S, I) != I)
7395       CheckSheduleForI(I);
7396     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7397                       << "\n");
7398     return true;
7399   }
7400   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7401          "Expected to reach top of the basic block or instruction down the "
7402          "lower end.");
7403   assert(I->getParent() == ScheduleEnd->getParent() &&
7404          "Instruction is in wrong basic block.");
7405   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7406                    nullptr);
7407   ScheduleEnd = I->getNextNode();
7408   if (isOneOf(S, I) != I)
7409     CheckSheduleForI(I);
7410   assert(ScheduleEnd && "tried to vectorize a terminator?");
7411   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7412   return true;
7413 }
7414 
7415 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7416                                                 Instruction *ToI,
7417                                                 ScheduleData *PrevLoadStore,
7418                                                 ScheduleData *NextLoadStore) {
7419   ScheduleData *CurrentLoadStore = PrevLoadStore;
7420   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7421     ScheduleData *SD = ScheduleDataMap[I];
7422     if (!SD) {
7423       SD = allocateScheduleDataChunks();
7424       ScheduleDataMap[I] = SD;
7425       SD->Inst = I;
7426     }
7427     assert(!isInSchedulingRegion(SD) &&
7428            "new ScheduleData already in scheduling region");
7429     SD->init(SchedulingRegionID, I);
7430 
7431     if (I->mayReadOrWriteMemory() &&
7432         (!isa<IntrinsicInst>(I) ||
7433          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7434           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7435               Intrinsic::pseudoprobe))) {
7436       // Update the linked list of memory accessing instructions.
7437       if (CurrentLoadStore) {
7438         CurrentLoadStore->NextLoadStore = SD;
7439       } else {
7440         FirstLoadStoreInRegion = SD;
7441       }
7442       CurrentLoadStore = SD;
7443     }
7444   }
7445   if (NextLoadStore) {
7446     if (CurrentLoadStore)
7447       CurrentLoadStore->NextLoadStore = NextLoadStore;
7448   } else {
7449     LastLoadStoreInRegion = CurrentLoadStore;
7450   }
7451 }
7452 
7453 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7454                                                      bool InsertInReadyList,
7455                                                      BoUpSLP *SLP) {
7456   assert(SD->isSchedulingEntity());
7457 
7458   SmallVector<ScheduleData *, 10> WorkList;
7459   WorkList.push_back(SD);
7460 
7461   while (!WorkList.empty()) {
7462     ScheduleData *SD = WorkList.pop_back_val();
7463 
7464     ScheduleData *BundleMember = SD;
7465     while (BundleMember) {
7466       assert(isInSchedulingRegion(BundleMember));
7467       if (!BundleMember->hasValidDependencies()) {
7468 
7469         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7470                           << "\n");
7471         BundleMember->Dependencies = 0;
7472         BundleMember->resetUnscheduledDeps();
7473 
7474         // Handle def-use chain dependencies.
7475         if (BundleMember->OpValue != BundleMember->Inst) {
7476           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7477           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7478             BundleMember->Dependencies++;
7479             ScheduleData *DestBundle = UseSD->FirstInBundle;
7480             if (!DestBundle->IsScheduled)
7481               BundleMember->incrementUnscheduledDeps(1);
7482             if (!DestBundle->hasValidDependencies())
7483               WorkList.push_back(DestBundle);
7484           }
7485         } else {
7486           for (User *U : BundleMember->Inst->users()) {
7487             if (isa<Instruction>(U)) {
7488               ScheduleData *UseSD = getScheduleData(U);
7489               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7490                 BundleMember->Dependencies++;
7491                 ScheduleData *DestBundle = UseSD->FirstInBundle;
7492                 if (!DestBundle->IsScheduled)
7493                   BundleMember->incrementUnscheduledDeps(1);
7494                 if (!DestBundle->hasValidDependencies())
7495                   WorkList.push_back(DestBundle);
7496               }
7497             } else {
7498               // I'm not sure if this can ever happen. But we need to be safe.
7499               // This lets the instruction/bundle never be scheduled and
7500               // eventually disable vectorization.
7501               BundleMember->Dependencies++;
7502               BundleMember->incrementUnscheduledDeps(1);
7503             }
7504           }
7505         }
7506 
7507         // Handle the memory dependencies.
7508         ScheduleData *DepDest = BundleMember->NextLoadStore;
7509         if (DepDest) {
7510           Instruction *SrcInst = BundleMember->Inst;
7511           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
7512           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7513           unsigned numAliased = 0;
7514           unsigned DistToSrc = 1;
7515 
7516           while (DepDest) {
7517             assert(isInSchedulingRegion(DepDest));
7518 
7519             // We have two limits to reduce the complexity:
7520             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7521             //    SLP->isAliased (which is the expensive part in this loop).
7522             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7523             //    the whole loop (even if the loop is fast, it's quadratic).
7524             //    It's important for the loop break condition (see below) to
7525             //    check this limit even between two read-only instructions.
7526             if (DistToSrc >= MaxMemDepDistance ||
7527                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7528                      (numAliased >= AliasedCheckLimit ||
7529                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7530 
7531               // We increment the counter only if the locations are aliased
7532               // (instead of counting all alias checks). This gives a better
7533               // balance between reduced runtime and accurate dependencies.
7534               numAliased++;
7535 
7536               DepDest->MemoryDependencies.push_back(BundleMember);
7537               BundleMember->Dependencies++;
7538               ScheduleData *DestBundle = DepDest->FirstInBundle;
7539               if (!DestBundle->IsScheduled) {
7540                 BundleMember->incrementUnscheduledDeps(1);
7541               }
7542               if (!DestBundle->hasValidDependencies()) {
7543                 WorkList.push_back(DestBundle);
7544               }
7545             }
7546             DepDest = DepDest->NextLoadStore;
7547 
7548             // Example, explaining the loop break condition: Let's assume our
7549             // starting instruction is i0 and MaxMemDepDistance = 3.
7550             //
7551             //                      +--------v--v--v
7552             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7553             //             +--------^--^--^
7554             //
7555             // MaxMemDepDistance let us stop alias-checking at i3 and we add
7556             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7557             // Previously we already added dependencies from i3 to i6,i7,i8
7558             // (because of MaxMemDepDistance). As we added a dependency from
7559             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7560             // and we can abort this loop at i6.
7561             if (DistToSrc >= 2 * MaxMemDepDistance)
7562               break;
7563             DistToSrc++;
7564           }
7565         }
7566       }
7567       BundleMember = BundleMember->NextInBundle;
7568     }
7569     if (InsertInReadyList && SD->isReady()) {
7570       ReadyInsts.push_back(SD);
7571       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7572                         << "\n");
7573     }
7574   }
7575 }
7576 
7577 void BoUpSLP::BlockScheduling::resetSchedule() {
7578   assert(ScheduleStart &&
7579          "tried to reset schedule on block which has not been scheduled");
7580   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7581     doForAllOpcodes(I, [&](ScheduleData *SD) {
7582       assert(isInSchedulingRegion(SD) &&
7583              "ScheduleData not in scheduling region");
7584       SD->IsScheduled = false;
7585       SD->resetUnscheduledDeps();
7586     });
7587   }
7588   ReadyInsts.clear();
7589 }
7590 
7591 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7592   if (!BS->ScheduleStart)
7593     return;
7594 
7595   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7596 
7597   BS->resetSchedule();
7598 
7599   // For the real scheduling we use a more sophisticated ready-list: it is
7600   // sorted by the original instruction location. This lets the final schedule
7601   // be as  close as possible to the original instruction order.
7602   struct ScheduleDataCompare {
7603     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7604       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7605     }
7606   };
7607   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7608 
7609   // Ensure that all dependency data is updated and fill the ready-list with
7610   // initial instructions.
7611   int Idx = 0;
7612   int NumToSchedule = 0;
7613   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7614        I = I->getNextNode()) {
7615     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7616       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7617               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7618              "scheduler and vectorizer bundle mismatch");
7619       SD->FirstInBundle->SchedulingPriority = Idx++;
7620       if (SD->isSchedulingEntity()) {
7621         BS->calculateDependencies(SD, false, this);
7622         NumToSchedule++;
7623       }
7624     });
7625   }
7626   BS->initialFillReadyList(ReadyInsts);
7627 
7628   Instruction *LastScheduledInst = BS->ScheduleEnd;
7629 
7630   // Do the "real" scheduling.
7631   while (!ReadyInsts.empty()) {
7632     ScheduleData *picked = *ReadyInsts.begin();
7633     ReadyInsts.erase(ReadyInsts.begin());
7634 
7635     // Move the scheduled instruction(s) to their dedicated places, if not
7636     // there yet.
7637     ScheduleData *BundleMember = picked;
7638     while (BundleMember) {
7639       Instruction *pickedInst = BundleMember->Inst;
7640       if (pickedInst->getNextNode() != LastScheduledInst) {
7641         BS->BB->getInstList().remove(pickedInst);
7642         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
7643                                      pickedInst);
7644       }
7645       LastScheduledInst = pickedInst;
7646       BundleMember = BundleMember->NextInBundle;
7647     }
7648 
7649     BS->schedule(picked, ReadyInsts);
7650     NumToSchedule--;
7651   }
7652   assert(NumToSchedule == 0 && "could not schedule all instructions");
7653 
7654   // Avoid duplicate scheduling of the block.
7655   BS->ScheduleStart = nullptr;
7656 }
7657 
7658 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7659   // If V is a store, just return the width of the stored value (or value
7660   // truncated just before storing) without traversing the expression tree.
7661   // This is the common case.
7662   if (auto *Store = dyn_cast<StoreInst>(V)) {
7663     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7664       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7665     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7666   }
7667 
7668   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7669     return getVectorElementSize(IEI->getOperand(1));
7670 
7671   auto E = InstrElementSize.find(V);
7672   if (E != InstrElementSize.end())
7673     return E->second;
7674 
7675   // If V is not a store, we can traverse the expression tree to find loads
7676   // that feed it. The type of the loaded value may indicate a more suitable
7677   // width than V's type. We want to base the vector element size on the width
7678   // of memory operations where possible.
7679   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7680   SmallPtrSet<Instruction *, 16> Visited;
7681   if (auto *I = dyn_cast<Instruction>(V)) {
7682     Worklist.emplace_back(I, I->getParent());
7683     Visited.insert(I);
7684   }
7685 
7686   // Traverse the expression tree in bottom-up order looking for loads. If we
7687   // encounter an instruction we don't yet handle, we give up.
7688   auto Width = 0u;
7689   while (!Worklist.empty()) {
7690     Instruction *I;
7691     BasicBlock *Parent;
7692     std::tie(I, Parent) = Worklist.pop_back_val();
7693 
7694     // We should only be looking at scalar instructions here. If the current
7695     // instruction has a vector type, skip.
7696     auto *Ty = I->getType();
7697     if (isa<VectorType>(Ty))
7698       continue;
7699 
7700     // If the current instruction is a load, update MaxWidth to reflect the
7701     // width of the loaded value.
7702     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7703         isa<ExtractValueInst>(I))
7704       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7705 
7706     // Otherwise, we need to visit the operands of the instruction. We only
7707     // handle the interesting cases from buildTree here. If an operand is an
7708     // instruction we haven't yet visited and from the same basic block as the
7709     // user or the use is a PHI node, we add it to the worklist.
7710     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7711              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7712              isa<UnaryOperator>(I)) {
7713       for (Use &U : I->operands())
7714         if (auto *J = dyn_cast<Instruction>(U.get()))
7715           if (Visited.insert(J).second &&
7716               (isa<PHINode>(I) || J->getParent() == Parent))
7717             Worklist.emplace_back(J, J->getParent());
7718     } else {
7719       break;
7720     }
7721   }
7722 
7723   // If we didn't encounter a memory access in the expression tree, or if we
7724   // gave up for some reason, just return the width of V. Otherwise, return the
7725   // maximum width we found.
7726   if (!Width) {
7727     if (auto *CI = dyn_cast<CmpInst>(V))
7728       V = CI->getOperand(0);
7729     Width = DL->getTypeSizeInBits(V->getType());
7730   }
7731 
7732   for (Instruction *I : Visited)
7733     InstrElementSize[I] = Width;
7734 
7735   return Width;
7736 }
7737 
7738 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7739 // smaller type with a truncation. We collect the values that will be demoted
7740 // in ToDemote and additional roots that require investigating in Roots.
7741 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7742                                   SmallVectorImpl<Value *> &ToDemote,
7743                                   SmallVectorImpl<Value *> &Roots) {
7744   // We can always demote constants.
7745   if (isa<Constant>(V)) {
7746     ToDemote.push_back(V);
7747     return true;
7748   }
7749 
7750   // If the value is not an instruction in the expression with only one use, it
7751   // cannot be demoted.
7752   auto *I = dyn_cast<Instruction>(V);
7753   if (!I || !I->hasOneUse() || !Expr.count(I))
7754     return false;
7755 
7756   switch (I->getOpcode()) {
7757 
7758   // We can always demote truncations and extensions. Since truncations can
7759   // seed additional demotion, we save the truncated value.
7760   case Instruction::Trunc:
7761     Roots.push_back(I->getOperand(0));
7762     break;
7763   case Instruction::ZExt:
7764   case Instruction::SExt:
7765     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7766         isa<InsertElementInst>(I->getOperand(0)))
7767       return false;
7768     break;
7769 
7770   // We can demote certain binary operations if we can demote both of their
7771   // operands.
7772   case Instruction::Add:
7773   case Instruction::Sub:
7774   case Instruction::Mul:
7775   case Instruction::And:
7776   case Instruction::Or:
7777   case Instruction::Xor:
7778     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7779         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7780       return false;
7781     break;
7782 
7783   // We can demote selects if we can demote their true and false values.
7784   case Instruction::Select: {
7785     SelectInst *SI = cast<SelectInst>(I);
7786     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7787         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7788       return false;
7789     break;
7790   }
7791 
7792   // We can demote phis if we can demote all their incoming operands. Note that
7793   // we don't need to worry about cycles since we ensure single use above.
7794   case Instruction::PHI: {
7795     PHINode *PN = cast<PHINode>(I);
7796     for (Value *IncValue : PN->incoming_values())
7797       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7798         return false;
7799     break;
7800   }
7801 
7802   // Otherwise, conservatively give up.
7803   default:
7804     return false;
7805   }
7806 
7807   // Record the value that we can demote.
7808   ToDemote.push_back(V);
7809   return true;
7810 }
7811 
7812 void BoUpSLP::computeMinimumValueSizes() {
7813   // If there are no external uses, the expression tree must be rooted by a
7814   // store. We can't demote in-memory values, so there is nothing to do here.
7815   if (ExternalUses.empty())
7816     return;
7817 
7818   // We only attempt to truncate integer expressions.
7819   auto &TreeRoot = VectorizableTree[0]->Scalars;
7820   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
7821   if (!TreeRootIT)
7822     return;
7823 
7824   // If the expression is not rooted by a store, these roots should have
7825   // external uses. We will rely on InstCombine to rewrite the expression in
7826   // the narrower type. However, InstCombine only rewrites single-use values.
7827   // This means that if a tree entry other than a root is used externally, it
7828   // must have multiple uses and InstCombine will not rewrite it. The code
7829   // below ensures that only the roots are used externally.
7830   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
7831   for (auto &EU : ExternalUses)
7832     if (!Expr.erase(EU.Scalar))
7833       return;
7834   if (!Expr.empty())
7835     return;
7836 
7837   // Collect the scalar values of the vectorizable expression. We will use this
7838   // context to determine which values can be demoted. If we see a truncation,
7839   // we mark it as seeding another demotion.
7840   for (auto &EntryPtr : VectorizableTree)
7841     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
7842 
7843   // Ensure the roots of the vectorizable tree don't form a cycle. They must
7844   // have a single external user that is not in the vectorizable tree.
7845   for (auto *Root : TreeRoot)
7846     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
7847       return;
7848 
7849   // Conservatively determine if we can actually truncate the roots of the
7850   // expression. Collect the values that can be demoted in ToDemote and
7851   // additional roots that require investigating in Roots.
7852   SmallVector<Value *, 32> ToDemote;
7853   SmallVector<Value *, 4> Roots;
7854   for (auto *Root : TreeRoot)
7855     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
7856       return;
7857 
7858   // The maximum bit width required to represent all the values that can be
7859   // demoted without loss of precision. It would be safe to truncate the roots
7860   // of the expression to this width.
7861   auto MaxBitWidth = 8u;
7862 
7863   // We first check if all the bits of the roots are demanded. If they're not,
7864   // we can truncate the roots to this narrower type.
7865   for (auto *Root : TreeRoot) {
7866     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
7867     MaxBitWidth = std::max<unsigned>(
7868         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
7869   }
7870 
7871   // True if the roots can be zero-extended back to their original type, rather
7872   // than sign-extended. We know that if the leading bits are not demanded, we
7873   // can safely zero-extend. So we initialize IsKnownPositive to True.
7874   bool IsKnownPositive = true;
7875 
7876   // If all the bits of the roots are demanded, we can try a little harder to
7877   // compute a narrower type. This can happen, for example, if the roots are
7878   // getelementptr indices. InstCombine promotes these indices to the pointer
7879   // width. Thus, all their bits are technically demanded even though the
7880   // address computation might be vectorized in a smaller type.
7881   //
7882   // We start by looking at each entry that can be demoted. We compute the
7883   // maximum bit width required to store the scalar by using ValueTracking to
7884   // compute the number of high-order bits we can truncate.
7885   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
7886       llvm::all_of(TreeRoot, [](Value *R) {
7887         assert(R->hasOneUse() && "Root should have only one use!");
7888         return isa<GetElementPtrInst>(R->user_back());
7889       })) {
7890     MaxBitWidth = 8u;
7891 
7892     // Determine if the sign bit of all the roots is known to be zero. If not,
7893     // IsKnownPositive is set to False.
7894     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
7895       KnownBits Known = computeKnownBits(R, *DL);
7896       return Known.isNonNegative();
7897     });
7898 
7899     // Determine the maximum number of bits required to store the scalar
7900     // values.
7901     for (auto *Scalar : ToDemote) {
7902       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
7903       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
7904       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
7905     }
7906 
7907     // If we can't prove that the sign bit is zero, we must add one to the
7908     // maximum bit width to account for the unknown sign bit. This preserves
7909     // the existing sign bit so we can safely sign-extend the root back to the
7910     // original type. Otherwise, if we know the sign bit is zero, we will
7911     // zero-extend the root instead.
7912     //
7913     // FIXME: This is somewhat suboptimal, as there will be cases where adding
7914     //        one to the maximum bit width will yield a larger-than-necessary
7915     //        type. In general, we need to add an extra bit only if we can't
7916     //        prove that the upper bit of the original type is equal to the
7917     //        upper bit of the proposed smaller type. If these two bits are the
7918     //        same (either zero or one) we know that sign-extending from the
7919     //        smaller type will result in the same value. Here, since we can't
7920     //        yet prove this, we are just making the proposed smaller type
7921     //        larger to ensure correctness.
7922     if (!IsKnownPositive)
7923       ++MaxBitWidth;
7924   }
7925 
7926   // Round MaxBitWidth up to the next power-of-two.
7927   if (!isPowerOf2_64(MaxBitWidth))
7928     MaxBitWidth = NextPowerOf2(MaxBitWidth);
7929 
7930   // If the maximum bit width we compute is less than the with of the roots'
7931   // type, we can proceed with the narrowing. Otherwise, do nothing.
7932   if (MaxBitWidth >= TreeRootIT->getBitWidth())
7933     return;
7934 
7935   // If we can truncate the root, we must collect additional values that might
7936   // be demoted as a result. That is, those seeded by truncations we will
7937   // modify.
7938   while (!Roots.empty())
7939     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
7940 
7941   // Finally, map the values we can demote to the maximum bit with we computed.
7942   for (auto *Scalar : ToDemote)
7943     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
7944 }
7945 
7946 namespace {
7947 
7948 /// The SLPVectorizer Pass.
7949 struct SLPVectorizer : public FunctionPass {
7950   SLPVectorizerPass Impl;
7951 
7952   /// Pass identification, replacement for typeid
7953   static char ID;
7954 
7955   explicit SLPVectorizer() : FunctionPass(ID) {
7956     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
7957   }
7958 
7959   bool doInitialization(Module &M) override { return false; }
7960 
7961   bool runOnFunction(Function &F) override {
7962     if (skipFunction(F))
7963       return false;
7964 
7965     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
7966     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
7967     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7968     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
7969     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
7970     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7971     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7972     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
7973     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
7974     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
7975 
7976     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7977   }
7978 
7979   void getAnalysisUsage(AnalysisUsage &AU) const override {
7980     FunctionPass::getAnalysisUsage(AU);
7981     AU.addRequired<AssumptionCacheTracker>();
7982     AU.addRequired<ScalarEvolutionWrapperPass>();
7983     AU.addRequired<AAResultsWrapperPass>();
7984     AU.addRequired<TargetTransformInfoWrapperPass>();
7985     AU.addRequired<LoopInfoWrapperPass>();
7986     AU.addRequired<DominatorTreeWrapperPass>();
7987     AU.addRequired<DemandedBitsWrapperPass>();
7988     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
7989     AU.addRequired<InjectTLIMappingsLegacy>();
7990     AU.addPreserved<LoopInfoWrapperPass>();
7991     AU.addPreserved<DominatorTreeWrapperPass>();
7992     AU.addPreserved<AAResultsWrapperPass>();
7993     AU.addPreserved<GlobalsAAWrapperPass>();
7994     AU.setPreservesCFG();
7995   }
7996 };
7997 
7998 } // end anonymous namespace
7999 
8000 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8001   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8002   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8003   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8004   auto *AA = &AM.getResult<AAManager>(F);
8005   auto *LI = &AM.getResult<LoopAnalysis>(F);
8006   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8007   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8008   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8009   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8010 
8011   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8012   if (!Changed)
8013     return PreservedAnalyses::all();
8014 
8015   PreservedAnalyses PA;
8016   PA.preserveSet<CFGAnalyses>();
8017   return PA;
8018 }
8019 
8020 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8021                                 TargetTransformInfo *TTI_,
8022                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8023                                 LoopInfo *LI_, DominatorTree *DT_,
8024                                 AssumptionCache *AC_, DemandedBits *DB_,
8025                                 OptimizationRemarkEmitter *ORE_) {
8026   if (!RunSLPVectorization)
8027     return false;
8028   SE = SE_;
8029   TTI = TTI_;
8030   TLI = TLI_;
8031   AA = AA_;
8032   LI = LI_;
8033   DT = DT_;
8034   AC = AC_;
8035   DB = DB_;
8036   DL = &F.getParent()->getDataLayout();
8037 
8038   Stores.clear();
8039   GEPs.clear();
8040   bool Changed = false;
8041 
8042   // If the target claims to have no vector registers don't attempt
8043   // vectorization.
8044   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
8045     return false;
8046 
8047   // Don't vectorize when the attribute NoImplicitFloat is used.
8048   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8049     return false;
8050 
8051   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8052 
8053   // Use the bottom up slp vectorizer to construct chains that start with
8054   // store instructions.
8055   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8056 
8057   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8058   // delete instructions.
8059 
8060   // Update DFS numbers now so that we can use them for ordering.
8061   DT->updateDFSNumbers();
8062 
8063   // Scan the blocks in the function in post order.
8064   for (auto BB : post_order(&F.getEntryBlock())) {
8065     collectSeedInstructions(BB);
8066 
8067     // Vectorize trees that end at stores.
8068     if (!Stores.empty()) {
8069       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8070                         << " underlying objects.\n");
8071       Changed |= vectorizeStoreChains(R);
8072     }
8073 
8074     // Vectorize trees that end at reductions.
8075     Changed |= vectorizeChainsInBlock(BB, R);
8076 
8077     // Vectorize the index computations of getelementptr instructions. This
8078     // is primarily intended to catch gather-like idioms ending at
8079     // non-consecutive loads.
8080     if (!GEPs.empty()) {
8081       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8082                         << " underlying objects.\n");
8083       Changed |= vectorizeGEPIndices(BB, R);
8084     }
8085   }
8086 
8087   if (Changed) {
8088     R.optimizeGatherSequence();
8089     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8090   }
8091   return Changed;
8092 }
8093 
8094 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8095                                             unsigned Idx) {
8096   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8097                     << "\n");
8098   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8099   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8100   unsigned VF = Chain.size();
8101 
8102   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8103     return false;
8104 
8105   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8106                     << "\n");
8107 
8108   R.buildTree(Chain);
8109   if (R.isTreeTinyAndNotFullyVectorizable())
8110     return false;
8111   if (R.isLoadCombineCandidate())
8112     return false;
8113   R.reorderTopToBottom();
8114   R.reorderBottomToTop();
8115   R.buildExternalUses();
8116 
8117   R.computeMinimumValueSizes();
8118 
8119   InstructionCost Cost = R.getTreeCost();
8120 
8121   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8122   if (Cost < -SLPCostThreshold) {
8123     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8124 
8125     using namespace ore;
8126 
8127     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8128                                         cast<StoreInst>(Chain[0]))
8129                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8130                      << " and with tree size "
8131                      << NV("TreeSize", R.getTreeSize()));
8132 
8133     R.vectorizeTree();
8134     return true;
8135   }
8136 
8137   return false;
8138 }
8139 
8140 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8141                                         BoUpSLP &R) {
8142   // We may run into multiple chains that merge into a single chain. We mark the
8143   // stores that we vectorized so that we don't visit the same store twice.
8144   BoUpSLP::ValueSet VectorizedStores;
8145   bool Changed = false;
8146 
8147   int E = Stores.size();
8148   SmallBitVector Tails(E, false);
8149   int MaxIter = MaxStoreLookup.getValue();
8150   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8151       E, std::make_pair(E, INT_MAX));
8152   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8153   int IterCnt;
8154   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8155                                   &CheckedPairs,
8156                                   &ConsecutiveChain](int K, int Idx) {
8157     if (IterCnt >= MaxIter)
8158       return true;
8159     if (CheckedPairs[Idx].test(K))
8160       return ConsecutiveChain[K].second == 1 &&
8161              ConsecutiveChain[K].first == Idx;
8162     ++IterCnt;
8163     CheckedPairs[Idx].set(K);
8164     CheckedPairs[K].set(Idx);
8165     Optional<int> Diff = getPointersDiff(
8166         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8167         Stores[Idx]->getValueOperand()->getType(),
8168         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8169     if (!Diff || *Diff == 0)
8170       return false;
8171     int Val = *Diff;
8172     if (Val < 0) {
8173       if (ConsecutiveChain[Idx].second > -Val) {
8174         Tails.set(K);
8175         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8176       }
8177       return false;
8178     }
8179     if (ConsecutiveChain[K].second <= Val)
8180       return false;
8181 
8182     Tails.set(Idx);
8183     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8184     return Val == 1;
8185   };
8186   // Do a quadratic search on all of the given stores in reverse order and find
8187   // all of the pairs of stores that follow each other.
8188   for (int Idx = E - 1; Idx >= 0; --Idx) {
8189     // If a store has multiple consecutive store candidates, search according
8190     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8191     // This is because usually pairing with immediate succeeding or preceding
8192     // candidate create the best chance to find slp vectorization opportunity.
8193     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8194     IterCnt = 0;
8195     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8196       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8197           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8198         break;
8199   }
8200 
8201   // Tracks if we tried to vectorize stores starting from the given tail
8202   // already.
8203   SmallBitVector TriedTails(E, false);
8204   // For stores that start but don't end a link in the chain:
8205   for (int Cnt = E; Cnt > 0; --Cnt) {
8206     int I = Cnt - 1;
8207     if (ConsecutiveChain[I].first == E || Tails.test(I))
8208       continue;
8209     // We found a store instr that starts a chain. Now follow the chain and try
8210     // to vectorize it.
8211     BoUpSLP::ValueList Operands;
8212     // Collect the chain into a list.
8213     while (I != E && !VectorizedStores.count(Stores[I])) {
8214       Operands.push_back(Stores[I]);
8215       Tails.set(I);
8216       if (ConsecutiveChain[I].second != 1) {
8217         // Mark the new end in the chain and go back, if required. It might be
8218         // required if the original stores come in reversed order, for example.
8219         if (ConsecutiveChain[I].first != E &&
8220             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8221             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8222           TriedTails.set(I);
8223           Tails.reset(ConsecutiveChain[I].first);
8224           if (Cnt < ConsecutiveChain[I].first + 2)
8225             Cnt = ConsecutiveChain[I].first + 2;
8226         }
8227         break;
8228       }
8229       // Move to the next value in the chain.
8230       I = ConsecutiveChain[I].first;
8231     }
8232     assert(!Operands.empty() && "Expected non-empty list of stores.");
8233 
8234     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8235     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8236     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8237 
8238     unsigned MinVF = R.getMinVF(EltSize);
8239     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8240                               MaxElts);
8241 
8242     // FIXME: Is division-by-2 the correct step? Should we assert that the
8243     // register size is a power-of-2?
8244     unsigned StartIdx = 0;
8245     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8246       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8247         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8248         if (!VectorizedStores.count(Slice.front()) &&
8249             !VectorizedStores.count(Slice.back()) &&
8250             vectorizeStoreChain(Slice, R, Cnt)) {
8251           // Mark the vectorized stores so that we don't vectorize them again.
8252           VectorizedStores.insert(Slice.begin(), Slice.end());
8253           Changed = true;
8254           // If we vectorized initial block, no need to try to vectorize it
8255           // again.
8256           if (Cnt == StartIdx)
8257             StartIdx += Size;
8258           Cnt += Size;
8259           continue;
8260         }
8261         ++Cnt;
8262       }
8263       // Check if the whole array was vectorized already - exit.
8264       if (StartIdx >= Operands.size())
8265         break;
8266     }
8267   }
8268 
8269   return Changed;
8270 }
8271 
8272 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8273   // Initialize the collections. We will make a single pass over the block.
8274   Stores.clear();
8275   GEPs.clear();
8276 
8277   // Visit the store and getelementptr instructions in BB and organize them in
8278   // Stores and GEPs according to the underlying objects of their pointer
8279   // operands.
8280   for (Instruction &I : *BB) {
8281     // Ignore store instructions that are volatile or have a pointer operand
8282     // that doesn't point to a scalar type.
8283     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8284       if (!SI->isSimple())
8285         continue;
8286       if (!isValidElementType(SI->getValueOperand()->getType()))
8287         continue;
8288       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8289     }
8290 
8291     // Ignore getelementptr instructions that have more than one index, a
8292     // constant index, or a pointer operand that doesn't point to a scalar
8293     // type.
8294     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8295       auto Idx = GEP->idx_begin()->get();
8296       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8297         continue;
8298       if (!isValidElementType(Idx->getType()))
8299         continue;
8300       if (GEP->getType()->isVectorTy())
8301         continue;
8302       GEPs[GEP->getPointerOperand()].push_back(GEP);
8303     }
8304   }
8305 }
8306 
8307 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8308   if (!A || !B)
8309     return false;
8310   Value *VL[] = {A, B};
8311   return tryToVectorizeList(VL, R);
8312 }
8313 
8314 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8315                                            bool LimitForRegisterSize) {
8316   if (VL.size() < 2)
8317     return false;
8318 
8319   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8320                     << VL.size() << ".\n");
8321 
8322   // Check that all of the parts are instructions of the same type,
8323   // we permit an alternate opcode via InstructionsState.
8324   InstructionsState S = getSameOpcode(VL);
8325   if (!S.getOpcode())
8326     return false;
8327 
8328   Instruction *I0 = cast<Instruction>(S.OpValue);
8329   // Make sure invalid types (including vector type) are rejected before
8330   // determining vectorization factor for scalar instructions.
8331   for (Value *V : VL) {
8332     Type *Ty = V->getType();
8333     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8334       // NOTE: the following will give user internal llvm type name, which may
8335       // not be useful.
8336       R.getORE()->emit([&]() {
8337         std::string type_str;
8338         llvm::raw_string_ostream rso(type_str);
8339         Ty->print(rso);
8340         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8341                << "Cannot SLP vectorize list: type "
8342                << rso.str() + " is unsupported by vectorizer";
8343       });
8344       return false;
8345     }
8346   }
8347 
8348   unsigned Sz = R.getVectorElementSize(I0);
8349   unsigned MinVF = R.getMinVF(Sz);
8350   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8351   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8352   if (MaxVF < 2) {
8353     R.getORE()->emit([&]() {
8354       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8355              << "Cannot SLP vectorize list: vectorization factor "
8356              << "less than 2 is not supported";
8357     });
8358     return false;
8359   }
8360 
8361   bool Changed = false;
8362   bool CandidateFound = false;
8363   InstructionCost MinCost = SLPCostThreshold.getValue();
8364   Type *ScalarTy = VL[0]->getType();
8365   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8366     ScalarTy = IE->getOperand(1)->getType();
8367 
8368   unsigned NextInst = 0, MaxInst = VL.size();
8369   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8370     // No actual vectorization should happen, if number of parts is the same as
8371     // provided vectorization factor (i.e. the scalar type is used for vector
8372     // code during codegen).
8373     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8374     if (TTI->getNumberOfParts(VecTy) == VF)
8375       continue;
8376     for (unsigned I = NextInst; I < MaxInst; ++I) {
8377       unsigned OpsWidth = 0;
8378 
8379       if (I + VF > MaxInst)
8380         OpsWidth = MaxInst - I;
8381       else
8382         OpsWidth = VF;
8383 
8384       if (!isPowerOf2_32(OpsWidth))
8385         continue;
8386 
8387       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8388           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8389         break;
8390 
8391       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8392       // Check that a previous iteration of this loop did not delete the Value.
8393       if (llvm::any_of(Ops, [&R](Value *V) {
8394             auto *I = dyn_cast<Instruction>(V);
8395             return I && R.isDeleted(I);
8396           }))
8397         continue;
8398 
8399       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8400                         << "\n");
8401 
8402       R.buildTree(Ops);
8403       if (R.isTreeTinyAndNotFullyVectorizable())
8404         continue;
8405       R.reorderTopToBottom();
8406       R.reorderBottomToTop();
8407       R.buildExternalUses();
8408 
8409       R.computeMinimumValueSizes();
8410       InstructionCost Cost = R.getTreeCost();
8411       CandidateFound = true;
8412       MinCost = std::min(MinCost, Cost);
8413 
8414       if (Cost < -SLPCostThreshold) {
8415         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8416         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8417                                                     cast<Instruction>(Ops[0]))
8418                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8419                                  << " and with tree size "
8420                                  << ore::NV("TreeSize", R.getTreeSize()));
8421 
8422         R.vectorizeTree();
8423         // Move to the next bundle.
8424         I += VF - 1;
8425         NextInst = I + 1;
8426         Changed = true;
8427       }
8428     }
8429   }
8430 
8431   if (!Changed && CandidateFound) {
8432     R.getORE()->emit([&]() {
8433       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8434              << "List vectorization was possible but not beneficial with cost "
8435              << ore::NV("Cost", MinCost) << " >= "
8436              << ore::NV("Treshold", -SLPCostThreshold);
8437     });
8438   } else if (!Changed) {
8439     R.getORE()->emit([&]() {
8440       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8441              << "Cannot SLP vectorize list: vectorization was impossible"
8442              << " with available vectorization factors";
8443     });
8444   }
8445   return Changed;
8446 }
8447 
8448 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8449   if (!I)
8450     return false;
8451 
8452   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8453     return false;
8454 
8455   Value *P = I->getParent();
8456 
8457   // Vectorize in current basic block only.
8458   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8459   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8460   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8461     return false;
8462 
8463   // Try to vectorize V.
8464   if (tryToVectorizePair(Op0, Op1, R))
8465     return true;
8466 
8467   auto *A = dyn_cast<BinaryOperator>(Op0);
8468   auto *B = dyn_cast<BinaryOperator>(Op1);
8469   // Try to skip B.
8470   if (B && B->hasOneUse()) {
8471     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8472     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8473     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8474       return true;
8475     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8476       return true;
8477   }
8478 
8479   // Try to skip A.
8480   if (A && A->hasOneUse()) {
8481     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8482     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8483     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8484       return true;
8485     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8486       return true;
8487   }
8488   return false;
8489 }
8490 
8491 namespace {
8492 
8493 /// Model horizontal reductions.
8494 ///
8495 /// A horizontal reduction is a tree of reduction instructions that has values
8496 /// that can be put into a vector as its leaves. For example:
8497 ///
8498 /// mul mul mul mul
8499 ///  \  /    \  /
8500 ///   +       +
8501 ///    \     /
8502 ///       +
8503 /// This tree has "mul" as its leaf values and "+" as its reduction
8504 /// instructions. A reduction can feed into a store or a binary operation
8505 /// feeding a phi.
8506 ///    ...
8507 ///    \  /
8508 ///     +
8509 ///     |
8510 ///  phi +=
8511 ///
8512 ///  Or:
8513 ///    ...
8514 ///    \  /
8515 ///     +
8516 ///     |
8517 ///   *p =
8518 ///
8519 class HorizontalReduction {
8520   using ReductionOpsType = SmallVector<Value *, 16>;
8521   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8522   ReductionOpsListType ReductionOps;
8523   SmallVector<Value *, 32> ReducedVals;
8524   // Use map vector to make stable output.
8525   MapVector<Instruction *, Value *> ExtraArgs;
8526   WeakTrackingVH ReductionRoot;
8527   /// The type of reduction operation.
8528   RecurKind RdxKind;
8529 
8530   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8531 
8532   static bool isCmpSelMinMax(Instruction *I) {
8533     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8534            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8535   }
8536 
8537   // And/or are potentially poison-safe logical patterns like:
8538   // select x, y, false
8539   // select x, true, y
8540   static bool isBoolLogicOp(Instruction *I) {
8541     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8542            match(I, m_LogicalOr(m_Value(), m_Value()));
8543   }
8544 
8545   /// Checks if instruction is associative and can be vectorized.
8546   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8547     if (Kind == RecurKind::None)
8548       return false;
8549 
8550     // Integer ops that map to select instructions or intrinsics are fine.
8551     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8552         isBoolLogicOp(I))
8553       return true;
8554 
8555     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8556       // FP min/max are associative except for NaN and -0.0. We do not
8557       // have to rule out -0.0 here because the intrinsic semantics do not
8558       // specify a fixed result for it.
8559       return I->getFastMathFlags().noNaNs();
8560     }
8561 
8562     return I->isAssociative();
8563   }
8564 
8565   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8566     // Poison-safe 'or' takes the form: select X, true, Y
8567     // To make that work with the normal operand processing, we skip the
8568     // true value operand.
8569     // TODO: Change the code and data structures to handle this without a hack.
8570     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8571       return I->getOperand(2);
8572     return I->getOperand(Index);
8573   }
8574 
8575   /// Checks if the ParentStackElem.first should be marked as a reduction
8576   /// operation with an extra argument or as extra argument itself.
8577   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8578                     Value *ExtraArg) {
8579     if (ExtraArgs.count(ParentStackElem.first)) {
8580       ExtraArgs[ParentStackElem.first] = nullptr;
8581       // We ran into something like:
8582       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8583       // The whole ParentStackElem.first should be considered as an extra value
8584       // in this case.
8585       // Do not perform analysis of remaining operands of ParentStackElem.first
8586       // instruction, this whole instruction is an extra argument.
8587       ParentStackElem.second = INVALID_OPERAND_INDEX;
8588     } else {
8589       // We ran into something like:
8590       // ParentStackElem.first += ... + ExtraArg + ...
8591       ExtraArgs[ParentStackElem.first] = ExtraArg;
8592     }
8593   }
8594 
8595   /// Creates reduction operation with the current opcode.
8596   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8597                          Value *RHS, const Twine &Name, bool UseSelect) {
8598     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8599     switch (Kind) {
8600     case RecurKind::Or:
8601       if (UseSelect &&
8602           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8603         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8604       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8605                                  Name);
8606     case RecurKind::And:
8607       if (UseSelect &&
8608           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8609         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8610       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8611                                  Name);
8612     case RecurKind::Add:
8613     case RecurKind::Mul:
8614     case RecurKind::Xor:
8615     case RecurKind::FAdd:
8616     case RecurKind::FMul:
8617       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8618                                  Name);
8619     case RecurKind::FMax:
8620       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8621     case RecurKind::FMin:
8622       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8623     case RecurKind::SMax:
8624       if (UseSelect) {
8625         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8626         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8627       }
8628       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8629     case RecurKind::SMin:
8630       if (UseSelect) {
8631         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8632         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8633       }
8634       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8635     case RecurKind::UMax:
8636       if (UseSelect) {
8637         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8638         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8639       }
8640       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8641     case RecurKind::UMin:
8642       if (UseSelect) {
8643         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8644         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8645       }
8646       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8647     default:
8648       llvm_unreachable("Unknown reduction operation.");
8649     }
8650   }
8651 
8652   /// Creates reduction operation with the current opcode with the IR flags
8653   /// from \p ReductionOps.
8654   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8655                          Value *RHS, const Twine &Name,
8656                          const ReductionOpsListType &ReductionOps) {
8657     bool UseSelect = ReductionOps.size() == 2 ||
8658                      // Logical or/and.
8659                      (ReductionOps.size() == 1 &&
8660                       isa<SelectInst>(ReductionOps.front().front()));
8661     assert((!UseSelect || ReductionOps.size() != 2 ||
8662             isa<SelectInst>(ReductionOps[1][0])) &&
8663            "Expected cmp + select pairs for reduction");
8664     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8665     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8666       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8667         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8668         propagateIRFlags(Op, ReductionOps[1]);
8669         return Op;
8670       }
8671     }
8672     propagateIRFlags(Op, ReductionOps[0]);
8673     return Op;
8674   }
8675 
8676   /// Creates reduction operation with the current opcode with the IR flags
8677   /// from \p I.
8678   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8679                          Value *RHS, const Twine &Name, Instruction *I) {
8680     auto *SelI = dyn_cast<SelectInst>(I);
8681     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8682     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8683       if (auto *Sel = dyn_cast<SelectInst>(Op))
8684         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8685     }
8686     propagateIRFlags(Op, I);
8687     return Op;
8688   }
8689 
8690   static RecurKind getRdxKind(Instruction *I) {
8691     assert(I && "Expected instruction for reduction matching");
8692     TargetTransformInfo::ReductionFlags RdxFlags;
8693     if (match(I, m_Add(m_Value(), m_Value())))
8694       return RecurKind::Add;
8695     if (match(I, m_Mul(m_Value(), m_Value())))
8696       return RecurKind::Mul;
8697     if (match(I, m_And(m_Value(), m_Value())) ||
8698         match(I, m_LogicalAnd(m_Value(), m_Value())))
8699       return RecurKind::And;
8700     if (match(I, m_Or(m_Value(), m_Value())) ||
8701         match(I, m_LogicalOr(m_Value(), m_Value())))
8702       return RecurKind::Or;
8703     if (match(I, m_Xor(m_Value(), m_Value())))
8704       return RecurKind::Xor;
8705     if (match(I, m_FAdd(m_Value(), m_Value())))
8706       return RecurKind::FAdd;
8707     if (match(I, m_FMul(m_Value(), m_Value())))
8708       return RecurKind::FMul;
8709 
8710     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8711       return RecurKind::FMax;
8712     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8713       return RecurKind::FMin;
8714 
8715     // This matches either cmp+select or intrinsics. SLP is expected to handle
8716     // either form.
8717     // TODO: If we are canonicalizing to intrinsics, we can remove several
8718     //       special-case paths that deal with selects.
8719     if (match(I, m_SMax(m_Value(), m_Value())))
8720       return RecurKind::SMax;
8721     if (match(I, m_SMin(m_Value(), m_Value())))
8722       return RecurKind::SMin;
8723     if (match(I, m_UMax(m_Value(), m_Value())))
8724       return RecurKind::UMax;
8725     if (match(I, m_UMin(m_Value(), m_Value())))
8726       return RecurKind::UMin;
8727 
8728     if (auto *Select = dyn_cast<SelectInst>(I)) {
8729       // Try harder: look for min/max pattern based on instructions producing
8730       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8731       // During the intermediate stages of SLP, it's very common to have
8732       // pattern like this (since optimizeGatherSequence is run only once
8733       // at the end):
8734       // %1 = extractelement <2 x i32> %a, i32 0
8735       // %2 = extractelement <2 x i32> %a, i32 1
8736       // %cond = icmp sgt i32 %1, %2
8737       // %3 = extractelement <2 x i32> %a, i32 0
8738       // %4 = extractelement <2 x i32> %a, i32 1
8739       // %select = select i1 %cond, i32 %3, i32 %4
8740       CmpInst::Predicate Pred;
8741       Instruction *L1;
8742       Instruction *L2;
8743 
8744       Value *LHS = Select->getTrueValue();
8745       Value *RHS = Select->getFalseValue();
8746       Value *Cond = Select->getCondition();
8747 
8748       // TODO: Support inverse predicates.
8749       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8750         if (!isa<ExtractElementInst>(RHS) ||
8751             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8752           return RecurKind::None;
8753       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8754         if (!isa<ExtractElementInst>(LHS) ||
8755             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8756           return RecurKind::None;
8757       } else {
8758         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8759           return RecurKind::None;
8760         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8761             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8762             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8763           return RecurKind::None;
8764       }
8765 
8766       TargetTransformInfo::ReductionFlags RdxFlags;
8767       switch (Pred) {
8768       default:
8769         return RecurKind::None;
8770       case CmpInst::ICMP_SGT:
8771       case CmpInst::ICMP_SGE:
8772         return RecurKind::SMax;
8773       case CmpInst::ICMP_SLT:
8774       case CmpInst::ICMP_SLE:
8775         return RecurKind::SMin;
8776       case CmpInst::ICMP_UGT:
8777       case CmpInst::ICMP_UGE:
8778         return RecurKind::UMax;
8779       case CmpInst::ICMP_ULT:
8780       case CmpInst::ICMP_ULE:
8781         return RecurKind::UMin;
8782       }
8783     }
8784     return RecurKind::None;
8785   }
8786 
8787   /// Get the index of the first operand.
8788   static unsigned getFirstOperandIndex(Instruction *I) {
8789     return isCmpSelMinMax(I) ? 1 : 0;
8790   }
8791 
8792   /// Total number of operands in the reduction operation.
8793   static unsigned getNumberOfOperands(Instruction *I) {
8794     return isCmpSelMinMax(I) ? 3 : 2;
8795   }
8796 
8797   /// Checks if the instruction is in basic block \p BB.
8798   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8799   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8800     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
8801       auto *Sel = cast<SelectInst>(I);
8802       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
8803       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
8804     }
8805     return I->getParent() == BB;
8806   }
8807 
8808   /// Expected number of uses for reduction operations/reduced values.
8809   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
8810     if (IsCmpSelMinMax) {
8811       // SelectInst must be used twice while the condition op must have single
8812       // use only.
8813       if (auto *Sel = dyn_cast<SelectInst>(I))
8814         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
8815       return I->hasNUses(2);
8816     }
8817 
8818     // Arithmetic reduction operation must be used once only.
8819     return I->hasOneUse();
8820   }
8821 
8822   /// Initializes the list of reduction operations.
8823   void initReductionOps(Instruction *I) {
8824     if (isCmpSelMinMax(I))
8825       ReductionOps.assign(2, ReductionOpsType());
8826     else
8827       ReductionOps.assign(1, ReductionOpsType());
8828   }
8829 
8830   /// Add all reduction operations for the reduction instruction \p I.
8831   void addReductionOps(Instruction *I) {
8832     if (isCmpSelMinMax(I)) {
8833       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
8834       ReductionOps[1].emplace_back(I);
8835     } else {
8836       ReductionOps[0].emplace_back(I);
8837     }
8838   }
8839 
8840   static Value *getLHS(RecurKind Kind, Instruction *I) {
8841     if (Kind == RecurKind::None)
8842       return nullptr;
8843     return I->getOperand(getFirstOperandIndex(I));
8844   }
8845   static Value *getRHS(RecurKind Kind, Instruction *I) {
8846     if (Kind == RecurKind::None)
8847       return nullptr;
8848     return I->getOperand(getFirstOperandIndex(I) + 1);
8849   }
8850 
8851 public:
8852   HorizontalReduction() = default;
8853 
8854   /// Try to find a reduction tree.
8855   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
8856     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
8857            "Phi needs to use the binary operator");
8858     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
8859             isa<IntrinsicInst>(Inst)) &&
8860            "Expected binop, select, or intrinsic for reduction matching");
8861     RdxKind = getRdxKind(Inst);
8862 
8863     // We could have a initial reductions that is not an add.
8864     //  r *= v1 + v2 + v3 + v4
8865     // In such a case start looking for a tree rooted in the first '+'.
8866     if (Phi) {
8867       if (getLHS(RdxKind, Inst) == Phi) {
8868         Phi = nullptr;
8869         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
8870         if (!Inst)
8871           return false;
8872         RdxKind = getRdxKind(Inst);
8873       } else if (getRHS(RdxKind, Inst) == Phi) {
8874         Phi = nullptr;
8875         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
8876         if (!Inst)
8877           return false;
8878         RdxKind = getRdxKind(Inst);
8879       }
8880     }
8881 
8882     if (!isVectorizable(RdxKind, Inst))
8883       return false;
8884 
8885     // Analyze "regular" integer/FP types for reductions - no target-specific
8886     // types or pointers.
8887     Type *Ty = Inst->getType();
8888     if (!isValidElementType(Ty) || Ty->isPointerTy())
8889       return false;
8890 
8891     // Though the ultimate reduction may have multiple uses, its condition must
8892     // have only single use.
8893     if (auto *Sel = dyn_cast<SelectInst>(Inst))
8894       if (!Sel->getCondition()->hasOneUse())
8895         return false;
8896 
8897     ReductionRoot = Inst;
8898 
8899     // The opcode for leaf values that we perform a reduction on.
8900     // For example: load(x) + load(y) + load(z) + fptoui(w)
8901     // The leaf opcode for 'w' does not match, so we don't include it as a
8902     // potential candidate for the reduction.
8903     unsigned LeafOpcode = 0;
8904 
8905     // Post-order traverse the reduction tree starting at Inst. We only handle
8906     // true trees containing binary operators or selects.
8907     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
8908     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
8909     initReductionOps(Inst);
8910     while (!Stack.empty()) {
8911       Instruction *TreeN = Stack.back().first;
8912       unsigned EdgeToVisit = Stack.back().second++;
8913       const RecurKind TreeRdxKind = getRdxKind(TreeN);
8914       bool IsReducedValue = TreeRdxKind != RdxKind;
8915 
8916       // Postorder visit.
8917       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
8918         if (IsReducedValue)
8919           ReducedVals.push_back(TreeN);
8920         else {
8921           auto ExtraArgsIter = ExtraArgs.find(TreeN);
8922           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
8923             // Check if TreeN is an extra argument of its parent operation.
8924             if (Stack.size() <= 1) {
8925               // TreeN can't be an extra argument as it is a root reduction
8926               // operation.
8927               return false;
8928             }
8929             // Yes, TreeN is an extra argument, do not add it to a list of
8930             // reduction operations.
8931             // Stack[Stack.size() - 2] always points to the parent operation.
8932             markExtraArg(Stack[Stack.size() - 2], TreeN);
8933             ExtraArgs.erase(TreeN);
8934           } else
8935             addReductionOps(TreeN);
8936         }
8937         // Retract.
8938         Stack.pop_back();
8939         continue;
8940       }
8941 
8942       // Visit operands.
8943       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
8944       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
8945       if (!EdgeInst) {
8946         // Edge value is not a reduction instruction or a leaf instruction.
8947         // (It may be a constant, function argument, or something else.)
8948         markExtraArg(Stack.back(), EdgeVal);
8949         continue;
8950       }
8951       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
8952       // Continue analysis if the next operand is a reduction operation or
8953       // (possibly) a leaf value. If the leaf value opcode is not set,
8954       // the first met operation != reduction operation is considered as the
8955       // leaf opcode.
8956       // Only handle trees in the current basic block.
8957       // Each tree node needs to have minimal number of users except for the
8958       // ultimate reduction.
8959       const bool IsRdxInst = EdgeRdxKind == RdxKind;
8960       if (EdgeInst != Phi && EdgeInst != Inst &&
8961           hasSameParent(EdgeInst, Inst->getParent()) &&
8962           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
8963           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
8964         if (IsRdxInst) {
8965           // We need to be able to reassociate the reduction operations.
8966           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
8967             // I is an extra argument for TreeN (its parent operation).
8968             markExtraArg(Stack.back(), EdgeInst);
8969             continue;
8970           }
8971         } else if (!LeafOpcode) {
8972           LeafOpcode = EdgeInst->getOpcode();
8973         }
8974         Stack.push_back(
8975             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
8976         continue;
8977       }
8978       // I is an extra argument for TreeN (its parent operation).
8979       markExtraArg(Stack.back(), EdgeInst);
8980     }
8981     return true;
8982   }
8983 
8984   /// Attempt to vectorize the tree found by matchAssociativeReduction.
8985   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
8986     // If there are a sufficient number of reduction values, reduce
8987     // to a nearby power-of-2. We can safely generate oversized
8988     // vectors and rely on the backend to split them to legal sizes.
8989     unsigned NumReducedVals = ReducedVals.size();
8990     if (NumReducedVals < 4)
8991       return nullptr;
8992 
8993     // Intersect the fast-math-flags from all reduction operations.
8994     FastMathFlags RdxFMF;
8995     RdxFMF.set();
8996     for (ReductionOpsType &RdxOp : ReductionOps) {
8997       for (Value *RdxVal : RdxOp) {
8998         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
8999           RdxFMF &= FPMO->getFastMathFlags();
9000       }
9001     }
9002 
9003     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9004     Builder.setFastMathFlags(RdxFMF);
9005 
9006     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9007     // The same extra argument may be used several times, so log each attempt
9008     // to use it.
9009     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9010       assert(Pair.first && "DebugLoc must be set.");
9011       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9012     }
9013 
9014     // The compare instruction of a min/max is the insertion point for new
9015     // instructions and may be replaced with a new compare instruction.
9016     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9017       assert(isa<SelectInst>(RdxRootInst) &&
9018              "Expected min/max reduction to have select root instruction");
9019       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9020       assert(isa<Instruction>(ScalarCond) &&
9021              "Expected min/max reduction to have compare condition");
9022       return cast<Instruction>(ScalarCond);
9023     };
9024 
9025     // The reduction root is used as the insertion point for new instructions,
9026     // so set it as externally used to prevent it from being deleted.
9027     ExternallyUsedValues[ReductionRoot];
9028     SmallVector<Value *, 16> IgnoreList;
9029     for (ReductionOpsType &RdxOp : ReductionOps)
9030       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9031 
9032     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9033     if (NumReducedVals > ReduxWidth) {
9034       // In the loop below, we are building a tree based on a window of
9035       // 'ReduxWidth' values.
9036       // If the operands of those values have common traits (compare predicate,
9037       // constant operand, etc), then we want to group those together to
9038       // minimize the cost of the reduction.
9039 
9040       // TODO: This should be extended to count common operands for
9041       //       compares and binops.
9042 
9043       // Step 1: Count the number of times each compare predicate occurs.
9044       SmallDenseMap<unsigned, unsigned> PredCountMap;
9045       for (Value *RdxVal : ReducedVals) {
9046         CmpInst::Predicate Pred;
9047         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9048           ++PredCountMap[Pred];
9049       }
9050       // Step 2: Sort the values so the most common predicates come first.
9051       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9052         CmpInst::Predicate PredA, PredB;
9053         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9054             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9055           return PredCountMap[PredA] > PredCountMap[PredB];
9056         }
9057         return false;
9058       });
9059     }
9060 
9061     Value *VectorizedTree = nullptr;
9062     unsigned i = 0;
9063     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9064       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9065       V.buildTree(VL, IgnoreList);
9066       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9067         break;
9068       if (V.isLoadCombineReductionCandidate(RdxKind))
9069         break;
9070       V.reorderTopToBottom();
9071       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9072       V.buildExternalUses(ExternallyUsedValues);
9073 
9074       // For a poison-safe boolean logic reduction, do not replace select
9075       // instructions with logic ops. All reduced values will be frozen (see
9076       // below) to prevent leaking poison.
9077       if (isa<SelectInst>(ReductionRoot) &&
9078           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9079           NumReducedVals != ReduxWidth)
9080         break;
9081 
9082       V.computeMinimumValueSizes();
9083 
9084       // Estimate cost.
9085       InstructionCost TreeCost =
9086           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9087       InstructionCost ReductionCost =
9088           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9089       InstructionCost Cost = TreeCost + ReductionCost;
9090       if (!Cost.isValid()) {
9091         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9092         return nullptr;
9093       }
9094       if (Cost >= -SLPCostThreshold) {
9095         V.getORE()->emit([&]() {
9096           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9097                                           cast<Instruction>(VL[0]))
9098                  << "Vectorizing horizontal reduction is possible"
9099                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9100                  << " and threshold "
9101                  << ore::NV("Threshold", -SLPCostThreshold);
9102         });
9103         break;
9104       }
9105 
9106       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9107                         << Cost << ". (HorRdx)\n");
9108       V.getORE()->emit([&]() {
9109         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9110                                   cast<Instruction>(VL[0]))
9111                << "Vectorized horizontal reduction with cost "
9112                << ore::NV("Cost", Cost) << " and with tree size "
9113                << ore::NV("TreeSize", V.getTreeSize());
9114       });
9115 
9116       // Vectorize a tree.
9117       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9118       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9119 
9120       // Emit a reduction. If the root is a select (min/max idiom), the insert
9121       // point is the compare condition of that select.
9122       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9123       if (isCmpSelMinMax(RdxRootInst))
9124         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9125       else
9126         Builder.SetInsertPoint(RdxRootInst);
9127 
9128       // To prevent poison from leaking across what used to be sequential, safe,
9129       // scalar boolean logic operations, the reduction operand must be frozen.
9130       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9131         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9132 
9133       Value *ReducedSubTree =
9134           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9135 
9136       if (!VectorizedTree) {
9137         // Initialize the final value in the reduction.
9138         VectorizedTree = ReducedSubTree;
9139       } else {
9140         // Update the final value in the reduction.
9141         Builder.SetCurrentDebugLocation(Loc);
9142         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9143                                   ReducedSubTree, "op.rdx", ReductionOps);
9144       }
9145       i += ReduxWidth;
9146       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9147     }
9148 
9149     if (VectorizedTree) {
9150       // Finish the reduction.
9151       for (; i < NumReducedVals; ++i) {
9152         auto *I = cast<Instruction>(ReducedVals[i]);
9153         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9154         VectorizedTree =
9155             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9156       }
9157       for (auto &Pair : ExternallyUsedValues) {
9158         // Add each externally used value to the final reduction.
9159         for (auto *I : Pair.second) {
9160           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9161           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9162                                     Pair.first, "op.extra", I);
9163         }
9164       }
9165 
9166       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9167 
9168       // Mark all scalar reduction ops for deletion, they are replaced by the
9169       // vector reductions.
9170       V.eraseInstructions(IgnoreList);
9171     }
9172     return VectorizedTree;
9173   }
9174 
9175   unsigned numReductionValues() const { return ReducedVals.size(); }
9176 
9177 private:
9178   /// Calculate the cost of a reduction.
9179   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9180                                    Value *FirstReducedVal, unsigned ReduxWidth,
9181                                    FastMathFlags FMF) {
9182     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9183     Type *ScalarTy = FirstReducedVal->getType();
9184     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9185     InstructionCost VectorCost, ScalarCost;
9186     switch (RdxKind) {
9187     case RecurKind::Add:
9188     case RecurKind::Mul:
9189     case RecurKind::Or:
9190     case RecurKind::And:
9191     case RecurKind::Xor:
9192     case RecurKind::FAdd:
9193     case RecurKind::FMul: {
9194       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9195       VectorCost =
9196           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9197       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9198       break;
9199     }
9200     case RecurKind::FMax:
9201     case RecurKind::FMin: {
9202       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9203       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9204       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9205                                                /*unsigned=*/false, CostKind);
9206       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9207       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9208                                            SclCondTy, RdxPred, CostKind) +
9209                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9210                                            SclCondTy, RdxPred, CostKind);
9211       break;
9212     }
9213     case RecurKind::SMax:
9214     case RecurKind::SMin:
9215     case RecurKind::UMax:
9216     case RecurKind::UMin: {
9217       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9218       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9219       bool IsUnsigned =
9220           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9221       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9222                                                CostKind);
9223       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9224       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9225                                            SclCondTy, RdxPred, CostKind) +
9226                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9227                                            SclCondTy, RdxPred, CostKind);
9228       break;
9229     }
9230     default:
9231       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9232     }
9233 
9234     // Scalar cost is repeated for N-1 elements.
9235     ScalarCost *= (ReduxWidth - 1);
9236     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9237                       << " for reduction that starts with " << *FirstReducedVal
9238                       << " (It is a splitting reduction)\n");
9239     return VectorCost - ScalarCost;
9240   }
9241 
9242   /// Emit a horizontal reduction of the vectorized value.
9243   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9244                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9245     assert(VectorizedValue && "Need to have a vectorized tree node");
9246     assert(isPowerOf2_32(ReduxWidth) &&
9247            "We only handle power-of-two reductions for now");
9248     assert(RdxKind != RecurKind::FMulAdd &&
9249            "A call to the llvm.fmuladd intrinsic is not handled yet");
9250 
9251     ++NumVectorInstructions;
9252     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9253   }
9254 };
9255 
9256 } // end anonymous namespace
9257 
9258 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9259   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9260     return cast<FixedVectorType>(IE->getType())->getNumElements();
9261 
9262   unsigned AggregateSize = 1;
9263   auto *IV = cast<InsertValueInst>(InsertInst);
9264   Type *CurrentType = IV->getType();
9265   do {
9266     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9267       for (auto *Elt : ST->elements())
9268         if (Elt != ST->getElementType(0)) // check homogeneity
9269           return None;
9270       AggregateSize *= ST->getNumElements();
9271       CurrentType = ST->getElementType(0);
9272     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9273       AggregateSize *= AT->getNumElements();
9274       CurrentType = AT->getElementType();
9275     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9276       AggregateSize *= VT->getNumElements();
9277       return AggregateSize;
9278     } else if (CurrentType->isSingleValueType()) {
9279       return AggregateSize;
9280     } else {
9281       return None;
9282     }
9283   } while (true);
9284 }
9285 
9286 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9287                                    TargetTransformInfo *TTI,
9288                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9289                                    SmallVectorImpl<Value *> &InsertElts,
9290                                    unsigned OperandOffset) {
9291   do {
9292     Value *InsertedOperand = LastInsertInst->getOperand(1);
9293     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9294     if (!OperandIndex)
9295       return false;
9296     if (isa<InsertElementInst>(InsertedOperand) ||
9297         isa<InsertValueInst>(InsertedOperand)) {
9298       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9299                                   BuildVectorOpds, InsertElts, *OperandIndex))
9300         return false;
9301     } else {
9302       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9303       InsertElts[*OperandIndex] = LastInsertInst;
9304     }
9305     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9306   } while (LastInsertInst != nullptr &&
9307            (isa<InsertValueInst>(LastInsertInst) ||
9308             isa<InsertElementInst>(LastInsertInst)) &&
9309            LastInsertInst->hasOneUse());
9310   return true;
9311 }
9312 
9313 /// Recognize construction of vectors like
9314 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9315 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9316 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9317 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9318 ///  starting from the last insertelement or insertvalue instruction.
9319 ///
9320 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9321 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9322 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9323 ///
9324 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9325 ///
9326 /// \return true if it matches.
9327 static bool findBuildAggregate(Instruction *LastInsertInst,
9328                                TargetTransformInfo *TTI,
9329                                SmallVectorImpl<Value *> &BuildVectorOpds,
9330                                SmallVectorImpl<Value *> &InsertElts) {
9331 
9332   assert((isa<InsertElementInst>(LastInsertInst) ||
9333           isa<InsertValueInst>(LastInsertInst)) &&
9334          "Expected insertelement or insertvalue instruction!");
9335 
9336   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9337          "Expected empty result vectors!");
9338 
9339   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9340   if (!AggregateSize)
9341     return false;
9342   BuildVectorOpds.resize(*AggregateSize);
9343   InsertElts.resize(*AggregateSize);
9344 
9345   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9346                              0)) {
9347     llvm::erase_value(BuildVectorOpds, nullptr);
9348     llvm::erase_value(InsertElts, nullptr);
9349     if (BuildVectorOpds.size() >= 2)
9350       return true;
9351   }
9352 
9353   return false;
9354 }
9355 
9356 /// Try and get a reduction value from a phi node.
9357 ///
9358 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9359 /// if they come from either \p ParentBB or a containing loop latch.
9360 ///
9361 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9362 /// if not possible.
9363 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9364                                 BasicBlock *ParentBB, LoopInfo *LI) {
9365   // There are situations where the reduction value is not dominated by the
9366   // reduction phi. Vectorizing such cases has been reported to cause
9367   // miscompiles. See PR25787.
9368   auto DominatedReduxValue = [&](Value *R) {
9369     return isa<Instruction>(R) &&
9370            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9371   };
9372 
9373   Value *Rdx = nullptr;
9374 
9375   // Return the incoming value if it comes from the same BB as the phi node.
9376   if (P->getIncomingBlock(0) == ParentBB) {
9377     Rdx = P->getIncomingValue(0);
9378   } else if (P->getIncomingBlock(1) == ParentBB) {
9379     Rdx = P->getIncomingValue(1);
9380   }
9381 
9382   if (Rdx && DominatedReduxValue(Rdx))
9383     return Rdx;
9384 
9385   // Otherwise, check whether we have a loop latch to look at.
9386   Loop *BBL = LI->getLoopFor(ParentBB);
9387   if (!BBL)
9388     return nullptr;
9389   BasicBlock *BBLatch = BBL->getLoopLatch();
9390   if (!BBLatch)
9391     return nullptr;
9392 
9393   // There is a loop latch, return the incoming value if it comes from
9394   // that. This reduction pattern occasionally turns up.
9395   if (P->getIncomingBlock(0) == BBLatch) {
9396     Rdx = P->getIncomingValue(0);
9397   } else if (P->getIncomingBlock(1) == BBLatch) {
9398     Rdx = P->getIncomingValue(1);
9399   }
9400 
9401   if (Rdx && DominatedReduxValue(Rdx))
9402     return Rdx;
9403 
9404   return nullptr;
9405 }
9406 
9407 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9408   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9409     return true;
9410   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9411     return true;
9412   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9413     return true;
9414   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9415     return true;
9416   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9417     return true;
9418   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9419     return true;
9420   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9421     return true;
9422   return false;
9423 }
9424 
9425 /// Attempt to reduce a horizontal reduction.
9426 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9427 /// with reduction operators \a Root (or one of its operands) in a basic block
9428 /// \a BB, then check if it can be done. If horizontal reduction is not found
9429 /// and root instruction is a binary operation, vectorization of the operands is
9430 /// attempted.
9431 /// \returns true if a horizontal reduction was matched and reduced or operands
9432 /// of one of the binary instruction were vectorized.
9433 /// \returns false if a horizontal reduction was not matched (or not possible)
9434 /// or no vectorization of any binary operation feeding \a Root instruction was
9435 /// performed.
9436 static bool tryToVectorizeHorReductionOrInstOperands(
9437     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9438     TargetTransformInfo *TTI,
9439     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9440   if (!ShouldVectorizeHor)
9441     return false;
9442 
9443   if (!Root)
9444     return false;
9445 
9446   if (Root->getParent() != BB || isa<PHINode>(Root))
9447     return false;
9448   // Start analysis starting from Root instruction. If horizontal reduction is
9449   // found, try to vectorize it. If it is not a horizontal reduction or
9450   // vectorization is not possible or not effective, and currently analyzed
9451   // instruction is a binary operation, try to vectorize the operands, using
9452   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9453   // the same procedure considering each operand as a possible root of the
9454   // horizontal reduction.
9455   // Interrupt the process if the Root instruction itself was vectorized or all
9456   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9457   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9458   // CmpInsts so we can skip extra attempts in
9459   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9460   std::queue<std::pair<Instruction *, unsigned>> Stack;
9461   Stack.emplace(Root, 0);
9462   SmallPtrSet<Value *, 8> VisitedInstrs;
9463   SmallVector<WeakTrackingVH> PostponedInsts;
9464   bool Res = false;
9465   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9466                                      Value *&B1) -> Value * {
9467     bool IsBinop = matchRdxBop(Inst, B0, B1);
9468     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9469     if (IsBinop || IsSelect) {
9470       HorizontalReduction HorRdx;
9471       if (HorRdx.matchAssociativeReduction(P, Inst))
9472         return HorRdx.tryToReduce(R, TTI);
9473     }
9474     return nullptr;
9475   };
9476   while (!Stack.empty()) {
9477     Instruction *Inst;
9478     unsigned Level;
9479     std::tie(Inst, Level) = Stack.front();
9480     Stack.pop();
9481     // Do not try to analyze instruction that has already been vectorized.
9482     // This may happen when we vectorize instruction operands on a previous
9483     // iteration while stack was populated before that happened.
9484     if (R.isDeleted(Inst))
9485       continue;
9486     Value *B0 = nullptr, *B1 = nullptr;
9487     if (Value *V = TryToReduce(Inst, B0, B1)) {
9488       Res = true;
9489       // Set P to nullptr to avoid re-analysis of phi node in
9490       // matchAssociativeReduction function unless this is the root node.
9491       P = nullptr;
9492       if (auto *I = dyn_cast<Instruction>(V)) {
9493         // Try to find another reduction.
9494         Stack.emplace(I, Level);
9495         continue;
9496       }
9497     } else {
9498       bool IsBinop = B0 && B1;
9499       if (P && IsBinop) {
9500         Inst = dyn_cast<Instruction>(B0);
9501         if (Inst == P)
9502           Inst = dyn_cast<Instruction>(B1);
9503         if (!Inst) {
9504           // Set P to nullptr to avoid re-analysis of phi node in
9505           // matchAssociativeReduction function unless this is the root node.
9506           P = nullptr;
9507           continue;
9508         }
9509       }
9510       // Set P to nullptr to avoid re-analysis of phi node in
9511       // matchAssociativeReduction function unless this is the root node.
9512       P = nullptr;
9513       // Do not try to vectorize CmpInst operands, this is done separately.
9514       // Final attempt for binop args vectorization should happen after the loop
9515       // to try to find reductions.
9516       if (!isa<CmpInst>(Inst))
9517         PostponedInsts.push_back(Inst);
9518     }
9519 
9520     // Try to vectorize operands.
9521     // Continue analysis for the instruction from the same basic block only to
9522     // save compile time.
9523     if (++Level < RecursionMaxDepth)
9524       for (auto *Op : Inst->operand_values())
9525         if (VisitedInstrs.insert(Op).second)
9526           if (auto *I = dyn_cast<Instruction>(Op))
9527             // Do not try to vectorize CmpInst operands,  this is done
9528             // separately.
9529             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9530                 I->getParent() == BB)
9531               Stack.emplace(I, Level);
9532   }
9533   // Try to vectorized binops where reductions were not found.
9534   for (Value *V : PostponedInsts)
9535     if (auto *Inst = dyn_cast<Instruction>(V))
9536       if (!R.isDeleted(Inst))
9537         Res |= Vectorize(Inst, R);
9538   return Res;
9539 }
9540 
9541 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9542                                                  BasicBlock *BB, BoUpSLP &R,
9543                                                  TargetTransformInfo *TTI) {
9544   auto *I = dyn_cast_or_null<Instruction>(V);
9545   if (!I)
9546     return false;
9547 
9548   if (!isa<BinaryOperator>(I))
9549     P = nullptr;
9550   // Try to match and vectorize a horizontal reduction.
9551   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9552     return tryToVectorize(I, R);
9553   };
9554   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9555                                                   ExtraVectorization);
9556 }
9557 
9558 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9559                                                  BasicBlock *BB, BoUpSLP &R) {
9560   const DataLayout &DL = BB->getModule()->getDataLayout();
9561   if (!R.canMapToVector(IVI->getType(), DL))
9562     return false;
9563 
9564   SmallVector<Value *, 16> BuildVectorOpds;
9565   SmallVector<Value *, 16> BuildVectorInsts;
9566   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9567     return false;
9568 
9569   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9570   // Aggregate value is unlikely to be processed in vector register, we need to
9571   // extract scalars into scalar registers, so NeedExtraction is set true.
9572   return tryToVectorizeList(BuildVectorOpds, R);
9573 }
9574 
9575 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9576                                                    BasicBlock *BB, BoUpSLP &R) {
9577   SmallVector<Value *, 16> BuildVectorInsts;
9578   SmallVector<Value *, 16> BuildVectorOpds;
9579   SmallVector<int> Mask;
9580   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9581       (llvm::all_of(
9582            BuildVectorOpds,
9583            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9584        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9585     return false;
9586 
9587   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9588   return tryToVectorizeList(BuildVectorInsts, R);
9589 }
9590 
9591 template <typename T>
9592 static bool
9593 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9594                        function_ref<unsigned(T *)> Limit,
9595                        function_ref<bool(T *, T *)> Comparator,
9596                        function_ref<bool(T *, T *)> AreCompatible,
9597                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorize,
9598                        bool LimitForRegisterSize) {
9599   bool Changed = false;
9600   // Sort by type, parent, operands.
9601   stable_sort(Incoming, Comparator);
9602 
9603   // Try to vectorize elements base on their type.
9604   SmallVector<T *> Candidates;
9605   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9606     // Look for the next elements with the same type, parent and operand
9607     // kinds.
9608     auto *SameTypeIt = IncIt;
9609     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9610       ++SameTypeIt;
9611 
9612     // Try to vectorize them.
9613     unsigned NumElts = (SameTypeIt - IncIt);
9614     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9615                       << NumElts << ")\n");
9616     // The vectorization is a 3-state attempt:
9617     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9618     // size of maximal register at first.
9619     // 2. Try to vectorize remaining instructions with the same type, if
9620     // possible. This may result in the better vectorization results rather than
9621     // if we try just to vectorize instructions with the same/alternate opcodes.
9622     // 3. Final attempt to try to vectorize all instructions with the
9623     // same/alternate ops only, this may result in some extra final
9624     // vectorization.
9625     if (NumElts > 1 &&
9626         TryToVectorize(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9627       // Success start over because instructions might have been changed.
9628       Changed = true;
9629     } else if (NumElts < Limit(*IncIt) &&
9630                (Candidates.empty() ||
9631                 Candidates.front()->getType() == (*IncIt)->getType())) {
9632       Candidates.append(IncIt, std::next(IncIt, NumElts));
9633     }
9634     // Final attempt to vectorize instructions with the same types.
9635     if (Candidates.size() > 1 &&
9636         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9637       if (TryToVectorize(Candidates, /*LimitForRegisterSize=*/false)) {
9638         // Success start over because instructions might have been changed.
9639         Changed = true;
9640       } else if (LimitForRegisterSize) {
9641         // Try to vectorize using small vectors.
9642         for (auto *It = Candidates.begin(), *End = Candidates.end();
9643              It != End;) {
9644           auto *SameTypeIt = It;
9645           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9646             ++SameTypeIt;
9647           unsigned NumElts = (SameTypeIt - It);
9648           if (NumElts > 1 && TryToVectorize(makeArrayRef(It, NumElts),
9649                                             /*LimitForRegisterSize=*/false))
9650             Changed = true;
9651           It = SameTypeIt;
9652         }
9653       }
9654       Candidates.clear();
9655     }
9656 
9657     // Start over at the next instruction of a different type (or the end).
9658     IncIt = SameTypeIt;
9659   }
9660   return Changed;
9661 }
9662 
9663 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9664 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9665 /// operands. If IsCompatibility is false, function implements strict weak
9666 /// ordering relation between two cmp instructions, returning true if the first
9667 /// instruction is "less" than the second, i.e. its predicate is less than the
9668 /// predicate of the second or the operands IDs are less than the operands IDs
9669 /// of the second cmp instruction.
9670 template <bool IsCompatibility>
9671 static bool compareCmp(Value *V, Value *V2,
9672                        function_ref<bool(Instruction *)> IsDeleted) {
9673   auto *CI1 = cast<CmpInst>(V);
9674   auto *CI2 = cast<CmpInst>(V2);
9675   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9676     return false;
9677   if (CI1->getOperand(0)->getType()->getTypeID() <
9678       CI2->getOperand(0)->getType()->getTypeID())
9679     return !IsCompatibility;
9680   if (CI1->getOperand(0)->getType()->getTypeID() >
9681       CI2->getOperand(0)->getType()->getTypeID())
9682     return false;
9683   CmpInst::Predicate Pred1 = CI1->getPredicate();
9684   CmpInst::Predicate Pred2 = CI2->getPredicate();
9685   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9686   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9687   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9688   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9689   if (BasePred1 < BasePred2)
9690     return !IsCompatibility;
9691   if (BasePred1 > BasePred2)
9692     return false;
9693   // Compare operands.
9694   bool LEPreds = Pred1 <= Pred2;
9695   bool GEPreds = Pred1 >= Pred2;
9696   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
9697     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
9698     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
9699     if (Op1->getValueID() < Op2->getValueID())
9700       return !IsCompatibility;
9701     if (Op1->getValueID() > Op2->getValueID())
9702       return false;
9703     if (auto *I1 = dyn_cast<Instruction>(Op1))
9704       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
9705         if (I1->getParent() != I2->getParent())
9706           return false;
9707         InstructionsState S = getSameOpcode({I1, I2});
9708         if (S.getOpcode())
9709           continue;
9710         return false;
9711       }
9712   }
9713   return IsCompatibility;
9714 }
9715 
9716 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9717     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9718     bool AtTerminator) {
9719   bool OpsChanged = false;
9720   SmallVector<Instruction *, 4> PostponedCmps;
9721   for (auto *I : reverse(Instructions)) {
9722     if (R.isDeleted(I))
9723       continue;
9724     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9725       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9726     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9727       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9728     else if (isa<CmpInst>(I))
9729       PostponedCmps.push_back(I);
9730   }
9731   if (AtTerminator) {
9732     // Try to find reductions first.
9733     for (Instruction *I : PostponedCmps) {
9734       if (R.isDeleted(I))
9735         continue;
9736       for (Value *Op : I->operands())
9737         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9738     }
9739     // Try to vectorize operands as vector bundles.
9740     for (Instruction *I : PostponedCmps) {
9741       if (R.isDeleted(I))
9742         continue;
9743       OpsChanged |= tryToVectorize(I, R);
9744     }
9745     // Try to vectorize list of compares.
9746     // Sort by type, compare predicate, etc.
9747     auto &&CompareSorter = [&R](Value *V, Value *V2) {
9748       return compareCmp<false>(V, V2,
9749                                [&R](Instruction *I) { return R.isDeleted(I); });
9750     };
9751 
9752     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
9753       if (V1 == V2)
9754         return true;
9755       return compareCmp<true>(V1, V2,
9756                               [&R](Instruction *I) { return R.isDeleted(I); });
9757     };
9758     auto Limit = [&R](Value *V) {
9759       unsigned EltSize = R.getVectorElementSize(V);
9760       return std::max(2U, R.getMaxVecRegSize() / EltSize);
9761     };
9762 
9763     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
9764     OpsChanged |= tryToVectorizeSequence<Value>(
9765         Vals, Limit, CompareSorter, AreCompatibleCompares,
9766         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9767           // Exclude possible reductions from other blocks.
9768           bool ArePossiblyReducedInOtherBlock =
9769               any_of(Candidates, [](Value *V) {
9770                 return any_of(V->users(), [V](User *U) {
9771                   return isa<SelectInst>(U) &&
9772                          cast<SelectInst>(U)->getParent() !=
9773                              cast<Instruction>(V)->getParent();
9774                 });
9775               });
9776           if (ArePossiblyReducedInOtherBlock)
9777             return false;
9778           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9779         },
9780         /*LimitForRegisterSize=*/true);
9781     Instructions.clear();
9782   } else {
9783     // Insert in reverse order since the PostponedCmps vector was filled in
9784     // reverse order.
9785     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9786   }
9787   return OpsChanged;
9788 }
9789 
9790 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9791   bool Changed = false;
9792   SmallVector<Value *, 4> Incoming;
9793   SmallPtrSet<Value *, 16> VisitedInstrs;
9794   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9795   // node. Allows better to identify the chains that can be vectorized in the
9796   // better way.
9797   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9798   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9799     assert(isValidElementType(V1->getType()) &&
9800            isValidElementType(V2->getType()) &&
9801            "Expected vectorizable types only.");
9802     // It is fine to compare type IDs here, since we expect only vectorizable
9803     // types, like ints, floats and pointers, we don't care about other type.
9804     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9805       return true;
9806     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
9807       return false;
9808     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9809     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9810     if (Opcodes1.size() < Opcodes2.size())
9811       return true;
9812     if (Opcodes1.size() > Opcodes2.size())
9813       return false;
9814     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9815       // Undefs are compatible with any other value.
9816       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9817         continue;
9818       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9819         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9820           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
9821           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
9822           if (!NodeI1)
9823             return NodeI2 != nullptr;
9824           if (!NodeI2)
9825             return false;
9826           assert((NodeI1 == NodeI2) ==
9827                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9828                  "Different nodes should have different DFS numbers");
9829           if (NodeI1 != NodeI2)
9830             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9831           InstructionsState S = getSameOpcode({I1, I2});
9832           if (S.getOpcode())
9833             continue;
9834           return I1->getOpcode() < I2->getOpcode();
9835         }
9836       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9837         continue;
9838       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
9839         return true;
9840       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
9841         return false;
9842     }
9843     return false;
9844   };
9845   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
9846     if (V1 == V2)
9847       return true;
9848     if (V1->getType() != V2->getType())
9849       return false;
9850     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9851     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9852     if (Opcodes1.size() != Opcodes2.size())
9853       return false;
9854     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9855       // Undefs are compatible with any other value.
9856       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9857         continue;
9858       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9859         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9860           if (I1->getParent() != I2->getParent())
9861             return false;
9862           InstructionsState S = getSameOpcode({I1, I2});
9863           if (S.getOpcode())
9864             continue;
9865           return false;
9866         }
9867       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9868         continue;
9869       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
9870         return false;
9871     }
9872     return true;
9873   };
9874   auto Limit = [&R](Value *V) {
9875     unsigned EltSize = R.getVectorElementSize(V);
9876     return std::max(2U, R.getMaxVecRegSize() / EltSize);
9877   };
9878 
9879   bool HaveVectorizedPhiNodes = false;
9880   do {
9881     // Collect the incoming values from the PHIs.
9882     Incoming.clear();
9883     for (Instruction &I : *BB) {
9884       PHINode *P = dyn_cast<PHINode>(&I);
9885       if (!P)
9886         break;
9887 
9888       // No need to analyze deleted, vectorized and non-vectorizable
9889       // instructions.
9890       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
9891           isValidElementType(P->getType()))
9892         Incoming.push_back(P);
9893     }
9894 
9895     // Find the corresponding non-phi nodes for better matching when trying to
9896     // build the tree.
9897     for (Value *V : Incoming) {
9898       SmallVectorImpl<Value *> &Opcodes =
9899           PHIToOpcodes.try_emplace(V).first->getSecond();
9900       if (!Opcodes.empty())
9901         continue;
9902       SmallVector<Value *, 4> Nodes(1, V);
9903       SmallPtrSet<Value *, 4> Visited;
9904       while (!Nodes.empty()) {
9905         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
9906         if (!Visited.insert(PHI).second)
9907           continue;
9908         for (Value *V : PHI->incoming_values()) {
9909           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
9910             Nodes.push_back(PHI1);
9911             continue;
9912           }
9913           Opcodes.emplace_back(V);
9914         }
9915       }
9916     }
9917 
9918     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
9919         Incoming, Limit, PHICompare, AreCompatiblePHIs,
9920         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9921           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9922         },
9923         /*LimitForRegisterSize=*/true);
9924     Changed |= HaveVectorizedPhiNodes;
9925     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
9926   } while (HaveVectorizedPhiNodes);
9927 
9928   VisitedInstrs.clear();
9929 
9930   SmallVector<Instruction *, 8> PostProcessInstructions;
9931   SmallDenseSet<Instruction *, 4> KeyNodes;
9932   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
9933     // Skip instructions with scalable type. The num of elements is unknown at
9934     // compile-time for scalable type.
9935     if (isa<ScalableVectorType>(it->getType()))
9936       continue;
9937 
9938     // Skip instructions marked for the deletion.
9939     if (R.isDeleted(&*it))
9940       continue;
9941     // We may go through BB multiple times so skip the one we have checked.
9942     if (!VisitedInstrs.insert(&*it).second) {
9943       if (it->use_empty() && KeyNodes.contains(&*it) &&
9944           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9945                                       it->isTerminator())) {
9946         // We would like to start over since some instructions are deleted
9947         // and the iterator may become invalid value.
9948         Changed = true;
9949         it = BB->begin();
9950         e = BB->end();
9951       }
9952       continue;
9953     }
9954 
9955     if (isa<DbgInfoIntrinsic>(it))
9956       continue;
9957 
9958     // Try to vectorize reductions that use PHINodes.
9959     if (PHINode *P = dyn_cast<PHINode>(it)) {
9960       // Check that the PHI is a reduction PHI.
9961       if (P->getNumIncomingValues() == 2) {
9962         // Try to match and vectorize a horizontal reduction.
9963         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
9964                                      TTI)) {
9965           Changed = true;
9966           it = BB->begin();
9967           e = BB->end();
9968           continue;
9969         }
9970       }
9971       // Try to vectorize the incoming values of the PHI, to catch reductions
9972       // that feed into PHIs.
9973       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
9974         // Skip if the incoming block is the current BB for now. Also, bypass
9975         // unreachable IR for efficiency and to avoid crashing.
9976         // TODO: Collect the skipped incoming values and try to vectorize them
9977         // after processing BB.
9978         if (BB == P->getIncomingBlock(I) ||
9979             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
9980           continue;
9981 
9982         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
9983                                             P->getIncomingBlock(I), R, TTI);
9984       }
9985       continue;
9986     }
9987 
9988     // Ran into an instruction without users, like terminator, or function call
9989     // with ignored return value, store. Ignore unused instructions (basing on
9990     // instruction type, except for CallInst and InvokeInst).
9991     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
9992                             isa<InvokeInst>(it))) {
9993       KeyNodes.insert(&*it);
9994       bool OpsChanged = false;
9995       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
9996         for (auto *V : it->operand_values()) {
9997           // Try to match and vectorize a horizontal reduction.
9998           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
9999         }
10000       }
10001       // Start vectorization of post-process list of instructions from the
10002       // top-tree instructions to try to vectorize as many instructions as
10003       // possible.
10004       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10005                                                 it->isTerminator());
10006       if (OpsChanged) {
10007         // We would like to start over since some instructions are deleted
10008         // and the iterator may become invalid value.
10009         Changed = true;
10010         it = BB->begin();
10011         e = BB->end();
10012         continue;
10013       }
10014     }
10015 
10016     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10017         isa<InsertValueInst>(it))
10018       PostProcessInstructions.push_back(&*it);
10019   }
10020 
10021   return Changed;
10022 }
10023 
10024 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10025   auto Changed = false;
10026   for (auto &Entry : GEPs) {
10027     // If the getelementptr list has fewer than two elements, there's nothing
10028     // to do.
10029     if (Entry.second.size() < 2)
10030       continue;
10031 
10032     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10033                       << Entry.second.size() << ".\n");
10034 
10035     // Process the GEP list in chunks suitable for the target's supported
10036     // vector size. If a vector register can't hold 1 element, we are done. We
10037     // are trying to vectorize the index computations, so the maximum number of
10038     // elements is based on the size of the index expression, rather than the
10039     // size of the GEP itself (the target's pointer size).
10040     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10041     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10042     if (MaxVecRegSize < EltSize)
10043       continue;
10044 
10045     unsigned MaxElts = MaxVecRegSize / EltSize;
10046     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10047       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10048       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10049 
10050       // Initialize a set a candidate getelementptrs. Note that we use a
10051       // SetVector here to preserve program order. If the index computations
10052       // are vectorizable and begin with loads, we want to minimize the chance
10053       // of having to reorder them later.
10054       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10055 
10056       // Some of the candidates may have already been vectorized after we
10057       // initially collected them. If so, they are marked as deleted, so remove
10058       // them from the set of candidates.
10059       Candidates.remove_if(
10060           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10061 
10062       // Remove from the set of candidates all pairs of getelementptrs with
10063       // constant differences. Such getelementptrs are likely not good
10064       // candidates for vectorization in a bottom-up phase since one can be
10065       // computed from the other. We also ensure all candidate getelementptr
10066       // indices are unique.
10067       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10068         auto *GEPI = GEPList[I];
10069         if (!Candidates.count(GEPI))
10070           continue;
10071         auto *SCEVI = SE->getSCEV(GEPList[I]);
10072         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10073           auto *GEPJ = GEPList[J];
10074           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10075           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10076             Candidates.remove(GEPI);
10077             Candidates.remove(GEPJ);
10078           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10079             Candidates.remove(GEPJ);
10080           }
10081         }
10082       }
10083 
10084       // We break out of the above computation as soon as we know there are
10085       // fewer than two candidates remaining.
10086       if (Candidates.size() < 2)
10087         continue;
10088 
10089       // Add the single, non-constant index of each candidate to the bundle. We
10090       // ensured the indices met these constraints when we originally collected
10091       // the getelementptrs.
10092       SmallVector<Value *, 16> Bundle(Candidates.size());
10093       auto BundleIndex = 0u;
10094       for (auto *V : Candidates) {
10095         auto *GEP = cast<GetElementPtrInst>(V);
10096         auto *GEPIdx = GEP->idx_begin()->get();
10097         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10098         Bundle[BundleIndex++] = GEPIdx;
10099       }
10100 
10101       // Try and vectorize the indices. We are currently only interested in
10102       // gather-like cases of the form:
10103       //
10104       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10105       //
10106       // where the loads of "a", the loads of "b", and the subtractions can be
10107       // performed in parallel. It's likely that detecting this pattern in a
10108       // bottom-up phase will be simpler and less costly than building a
10109       // full-blown top-down phase beginning at the consecutive loads.
10110       Changed |= tryToVectorizeList(Bundle, R);
10111     }
10112   }
10113   return Changed;
10114 }
10115 
10116 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10117   bool Changed = false;
10118   // Sort by type, base pointers and values operand. Value operands must be
10119   // compatible (have the same opcode, same parent), otherwise it is
10120   // definitely not profitable to try to vectorize them.
10121   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10122     if (V->getPointerOperandType()->getTypeID() <
10123         V2->getPointerOperandType()->getTypeID())
10124       return true;
10125     if (V->getPointerOperandType()->getTypeID() >
10126         V2->getPointerOperandType()->getTypeID())
10127       return false;
10128     // UndefValues are compatible with all other values.
10129     if (isa<UndefValue>(V->getValueOperand()) ||
10130         isa<UndefValue>(V2->getValueOperand()))
10131       return false;
10132     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10133       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10134         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10135             DT->getNode(I1->getParent());
10136         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10137             DT->getNode(I2->getParent());
10138         assert(NodeI1 && "Should only process reachable instructions");
10139         assert(NodeI1 && "Should only process reachable instructions");
10140         assert((NodeI1 == NodeI2) ==
10141                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10142                "Different nodes should have different DFS numbers");
10143         if (NodeI1 != NodeI2)
10144           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10145         InstructionsState S = getSameOpcode({I1, I2});
10146         if (S.getOpcode())
10147           return false;
10148         return I1->getOpcode() < I2->getOpcode();
10149       }
10150     if (isa<Constant>(V->getValueOperand()) &&
10151         isa<Constant>(V2->getValueOperand()))
10152       return false;
10153     return V->getValueOperand()->getValueID() <
10154            V2->getValueOperand()->getValueID();
10155   };
10156 
10157   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10158     if (V1 == V2)
10159       return true;
10160     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10161       return false;
10162     // Undefs are compatible with any other value.
10163     if (isa<UndefValue>(V1->getValueOperand()) ||
10164         isa<UndefValue>(V2->getValueOperand()))
10165       return true;
10166     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10167       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10168         if (I1->getParent() != I2->getParent())
10169           return false;
10170         InstructionsState S = getSameOpcode({I1, I2});
10171         return S.getOpcode() > 0;
10172       }
10173     if (isa<Constant>(V1->getValueOperand()) &&
10174         isa<Constant>(V2->getValueOperand()))
10175       return true;
10176     return V1->getValueOperand()->getValueID() ==
10177            V2->getValueOperand()->getValueID();
10178   };
10179   auto Limit = [&R, this](StoreInst *SI) {
10180     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10181     return R.getMinVF(EltSize);
10182   };
10183 
10184   // Attempt to sort and vectorize each of the store-groups.
10185   for (auto &Pair : Stores) {
10186     if (Pair.second.size() < 2)
10187       continue;
10188 
10189     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10190                       << Pair.second.size() << ".\n");
10191 
10192     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10193       continue;
10194 
10195     Changed |= tryToVectorizeSequence<StoreInst>(
10196         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10197         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10198           return vectorizeStores(Candidates, R);
10199         },
10200         /*LimitForRegisterSize=*/false);
10201   }
10202   return Changed;
10203 }
10204 
10205 char SLPVectorizer::ID = 0;
10206 
10207 static const char lv_name[] = "SLP Vectorizer";
10208 
10209 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10210 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10211 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10212 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10213 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10214 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10215 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10216 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10217 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10218 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10219 
10220 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10221