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/MemorySSA.h"
45 #include "llvm/Analysis/MemorySSAUpdater.h"
46 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
47 #include "llvm/Analysis/ScalarEvolution.h"
48 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/TargetTransformInfo.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/Analysis/VectorUtils.h"
53 #include "llvm/IR/Attributes.h"
54 #include "llvm/IR/BasicBlock.h"
55 #include "llvm/IR/Constant.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DebugLoc.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/Dominators.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/IRBuilder.h"
63 #include "llvm/IR/InstrTypes.h"
64 #include "llvm/IR/Instruction.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/Intrinsics.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/Operator.h"
70 #include "llvm/IR/PatternMatch.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/User.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/IR/ValueHandle.h"
76 #include "llvm/IR/Verifier.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 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 static cl::opt<bool> EnableMSSAInSLPVectorizer(
172     "enable-mssa-in-slp-vectorizer", cl::Hidden, cl::init(false),
173     cl::desc("Enable MemorySSA for SLPVectorizer in new pass manager"));
174 
175 // Limit the number of alias checks. The limit is chosen so that
176 // it has no negative effect on the llvm benchmarks.
177 static const unsigned AliasedCheckLimit = 10;
178 
179 // Another limit for the alias checks: The maximum distance between load/store
180 // instructions where alias checks are done.
181 // This limit is useful for very large basic blocks.
182 static const unsigned MaxMemDepDistance = 160;
183 
184 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
185 /// regions to be handled.
186 static const int MinScheduleRegionSize = 16;
187 
188 /// Predicate for the element types that the SLP vectorizer supports.
189 ///
190 /// The most important thing to filter here are types which are invalid in LLVM
191 /// vectors. We also filter target specific types which have absolutely no
192 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
193 /// avoids spending time checking the cost model and realizing that they will
194 /// be inevitably scalarized.
195 static bool isValidElementType(Type *Ty) {
196   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
197          !Ty->isPPC_FP128Ty();
198 }
199 
200 /// \returns True if the value is a constant (but not globals/constant
201 /// expressions).
202 static bool isConstant(Value *V) {
203   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
204 }
205 
206 /// Checks if \p V is one of vector-like instructions, i.e. undef,
207 /// insertelement/extractelement with constant indices for fixed vector type or
208 /// extractvalue instruction.
209 static bool isVectorLikeInstWithConstOps(Value *V) {
210   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
211       !isa<ExtractValueInst, UndefValue>(V))
212     return false;
213   auto *I = dyn_cast<Instruction>(V);
214   if (!I || isa<ExtractValueInst>(I))
215     return true;
216   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
217     return false;
218   if (isa<ExtractElementInst>(I))
219     return isConstant(I->getOperand(1));
220   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
221   return isConstant(I->getOperand(2));
222 }
223 
224 /// \returns true if all of the instructions in \p VL are in the same block or
225 /// false otherwise.
226 static bool allSameBlock(ArrayRef<Value *> VL) {
227   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
228   if (!I0)
229     return false;
230   if (all_of(VL, isVectorLikeInstWithConstOps))
231     return true;
232 
233   BasicBlock *BB = I0->getParent();
234   for (int I = 1, E = VL.size(); I < E; I++) {
235     auto *II = dyn_cast<Instruction>(VL[I]);
236     if (!II)
237       return false;
238 
239     if (BB != II->getParent())
240       return false;
241   }
242   return true;
243 }
244 
245 /// \returns True if all of the values in \p VL are constants (but not
246 /// globals/constant expressions).
247 static bool allConstant(ArrayRef<Value *> VL) {
248   // Constant expressions and globals can't be vectorized like normal integer/FP
249   // constants.
250   return all_of(VL, isConstant);
251 }
252 
253 /// \returns True if all of the values in \p VL are identical or some of them
254 /// are UndefValue.
255 static bool isSplat(ArrayRef<Value *> VL) {
256   Value *FirstNonUndef = nullptr;
257   for (Value *V : VL) {
258     if (isa<UndefValue>(V))
259       continue;
260     if (!FirstNonUndef) {
261       FirstNonUndef = V;
262       continue;
263     }
264     if (V != FirstNonUndef)
265       return false;
266   }
267   return FirstNonUndef != nullptr;
268 }
269 
270 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
271 static bool isCommutative(Instruction *I) {
272   if (auto *Cmp = dyn_cast<CmpInst>(I))
273     return Cmp->isCommutative();
274   if (auto *BO = dyn_cast<BinaryOperator>(I))
275     return BO->isCommutative();
276   // TODO: This should check for generic Instruction::isCommutative(), but
277   //       we need to confirm that the caller code correctly handles Intrinsics
278   //       for example (does not have 2 operands).
279   return false;
280 }
281 
282 /// Checks if the given value is actually an undefined constant vector.
283 static bool isUndefVector(const Value *V) {
284   if (isa<UndefValue>(V))
285     return true;
286   auto *C = dyn_cast<Constant>(V);
287   if (!C)
288     return false;
289   if (!C->containsUndefOrPoisonElement())
290     return false;
291   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
292   if (!VecTy)
293     return false;
294   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
295     if (Constant *Elem = C->getAggregateElement(I))
296       if (!isa<UndefValue>(Elem))
297         return false;
298   }
299   return true;
300 }
301 
302 /// Checks if the vector of instructions can be represented as a shuffle, like:
303 /// %x0 = extractelement <4 x i8> %x, i32 0
304 /// %x3 = extractelement <4 x i8> %x, i32 3
305 /// %y1 = extractelement <4 x i8> %y, i32 1
306 /// %y2 = extractelement <4 x i8> %y, i32 2
307 /// %x0x0 = mul i8 %x0, %x0
308 /// %x3x3 = mul i8 %x3, %x3
309 /// %y1y1 = mul i8 %y1, %y1
310 /// %y2y2 = mul i8 %y2, %y2
311 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
312 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
313 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
314 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
315 /// ret <4 x i8> %ins4
316 /// can be transformed into:
317 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
318 ///                                                         i32 6>
319 /// %2 = mul <4 x i8> %1, %1
320 /// ret <4 x i8> %2
321 /// We convert this initially to something like:
322 /// %x0 = extractelement <4 x i8> %x, i32 0
323 /// %x3 = extractelement <4 x i8> %x, i32 3
324 /// %y1 = extractelement <4 x i8> %y, i32 1
325 /// %y2 = extractelement <4 x i8> %y, i32 2
326 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
327 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
328 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
329 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
330 /// %5 = mul <4 x i8> %4, %4
331 /// %6 = extractelement <4 x i8> %5, i32 0
332 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
333 /// %7 = extractelement <4 x i8> %5, i32 1
334 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
335 /// %8 = extractelement <4 x i8> %5, i32 2
336 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
337 /// %9 = extractelement <4 x i8> %5, i32 3
338 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
339 /// ret <4 x i8> %ins4
340 /// InstCombiner transforms this into a shuffle and vector mul
341 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
342 /// TODO: Can we split off and reuse the shuffle mask detection from
343 /// TargetTransformInfo::getInstructionThroughput?
344 static Optional<TargetTransformInfo::ShuffleKind>
345 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
346   const auto *It =
347       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
348   if (It == VL.end())
349     return None;
350   auto *EI0 = cast<ExtractElementInst>(*It);
351   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
352     return None;
353   unsigned Size =
354       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
355   Value *Vec1 = nullptr;
356   Value *Vec2 = nullptr;
357   enum ShuffleMode { Unknown, Select, Permute };
358   ShuffleMode CommonShuffleMode = Unknown;
359   Mask.assign(VL.size(), UndefMaskElem);
360   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
361     // Undef can be represented as an undef element in a vector.
362     if (isa<UndefValue>(VL[I]))
363       continue;
364     auto *EI = cast<ExtractElementInst>(VL[I]);
365     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
366       return None;
367     auto *Vec = EI->getVectorOperand();
368     // We can extractelement from undef or poison vector.
369     if (isUndefVector(Vec))
370       continue;
371     // All vector operands must have the same number of vector elements.
372     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
373       return None;
374     if (isa<UndefValue>(EI->getIndexOperand()))
375       continue;
376     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
377     if (!Idx)
378       return None;
379     // Undefined behavior if Idx is negative or >= Size.
380     if (Idx->getValue().uge(Size))
381       continue;
382     unsigned IntIdx = Idx->getValue().getZExtValue();
383     Mask[I] = IntIdx;
384     // For correct shuffling we have to have at most 2 different vector operands
385     // in all extractelement instructions.
386     if (!Vec1 || Vec1 == Vec) {
387       Vec1 = Vec;
388     } else if (!Vec2 || Vec2 == Vec) {
389       Vec2 = Vec;
390       Mask[I] += Size;
391     } else {
392       return None;
393     }
394     if (CommonShuffleMode == Permute)
395       continue;
396     // If the extract index is not the same as the operation number, it is a
397     // permutation.
398     if (IntIdx != I) {
399       CommonShuffleMode = Permute;
400       continue;
401     }
402     CommonShuffleMode = Select;
403   }
404   // If we're not crossing lanes in different vectors, consider it as blending.
405   if (CommonShuffleMode == Select && Vec2)
406     return TargetTransformInfo::SK_Select;
407   // If Vec2 was never used, we have a permutation of a single vector, otherwise
408   // we have permutation of 2 vectors.
409   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
410               : TargetTransformInfo::SK_PermuteSingleSrc;
411 }
412 
413 namespace {
414 
415 /// Main data required for vectorization of instructions.
416 struct InstructionsState {
417   /// The very first instruction in the list with the main opcode.
418   Value *OpValue = nullptr;
419 
420   /// The main/alternate instruction.
421   Instruction *MainOp = nullptr;
422   Instruction *AltOp = nullptr;
423 
424   /// The main/alternate opcodes for the list of instructions.
425   unsigned getOpcode() const {
426     return MainOp ? MainOp->getOpcode() : 0;
427   }
428 
429   unsigned getAltOpcode() const {
430     return AltOp ? AltOp->getOpcode() : 0;
431   }
432 
433   /// Some of the instructions in the list have alternate opcodes.
434   bool isAltShuffle() const { return AltOp != MainOp; }
435 
436   bool isOpcodeOrAlt(Instruction *I) const {
437     unsigned CheckedOpcode = I->getOpcode();
438     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
439   }
440 
441   InstructionsState() = delete;
442   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
443       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
444 };
445 
446 } // end anonymous namespace
447 
448 /// Chooses the correct key for scheduling data. If \p Op has the same (or
449 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
450 /// OpValue.
451 static Value *isOneOf(const InstructionsState &S, Value *Op) {
452   auto *I = dyn_cast<Instruction>(Op);
453   if (I && S.isOpcodeOrAlt(I))
454     return Op;
455   return S.OpValue;
456 }
457 
458 /// \returns true if \p Opcode is allowed as part of of the main/alternate
459 /// instruction for SLP vectorization.
460 ///
461 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
462 /// "shuffled out" lane would result in division by zero.
463 static bool isValidForAlternation(unsigned Opcode) {
464   if (Instruction::isIntDivRem(Opcode))
465     return false;
466 
467   return true;
468 }
469 
470 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
471                                        unsigned BaseIndex = 0);
472 
473 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
474 /// compatible instructions or constants, or just some other regular values.
475 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
476                                 Value *Op1) {
477   return (isConstant(BaseOp0) && isConstant(Op0)) ||
478          (isConstant(BaseOp1) && isConstant(Op1)) ||
479          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
480           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
481          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
482          getSameOpcode({BaseOp1, Op1}).getOpcode();
483 }
484 
485 /// \returns analysis of the Instructions in \p VL described in
486 /// InstructionsState, the Opcode that we suppose the whole list
487 /// could be vectorized even if its structure is diverse.
488 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
489                                        unsigned BaseIndex) {
490   // Make sure these are all Instructions.
491   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
492     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
493 
494   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
495   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
496   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
497   CmpInst::Predicate BasePred =
498       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
499               : CmpInst::BAD_ICMP_PREDICATE;
500   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
501   unsigned AltOpcode = Opcode;
502   unsigned AltIndex = BaseIndex;
503 
504   // Check for one alternate opcode from another BinaryOperator.
505   // TODO - generalize to support all operators (types, calls etc.).
506   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
507     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
508     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
509       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
510         continue;
511       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
512           isValidForAlternation(Opcode)) {
513         AltOpcode = InstOpcode;
514         AltIndex = Cnt;
515         continue;
516       }
517     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
518       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
519       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
520       if (Ty0 == Ty1) {
521         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
522           continue;
523         if (Opcode == AltOpcode) {
524           assert(isValidForAlternation(Opcode) &&
525                  isValidForAlternation(InstOpcode) &&
526                  "Cast isn't safe for alternation, logic needs to be updated!");
527           AltOpcode = InstOpcode;
528           AltIndex = Cnt;
529           continue;
530         }
531       }
532     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
533       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
534       auto *Inst = cast<Instruction>(VL[Cnt]);
535       Type *Ty0 = BaseInst->getOperand(0)->getType();
536       Type *Ty1 = Inst->getOperand(0)->getType();
537       if (Ty0 == Ty1) {
538         Value *BaseOp0 = BaseInst->getOperand(0);
539         Value *BaseOp1 = BaseInst->getOperand(1);
540         Value *Op0 = Inst->getOperand(0);
541         Value *Op1 = Inst->getOperand(1);
542         CmpInst::Predicate CurrentPred =
543             cast<CmpInst>(VL[Cnt])->getPredicate();
544         CmpInst::Predicate SwappedCurrentPred =
545             CmpInst::getSwappedPredicate(CurrentPred);
546         // Check for compatible operands. If the corresponding operands are not
547         // compatible - need to perform alternate vectorization.
548         if (InstOpcode == Opcode) {
549           if (BasePred == CurrentPred &&
550               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
551             continue;
552           if (BasePred == SwappedCurrentPred &&
553               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
554             continue;
555           if (E == 2 &&
556               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
557             continue;
558           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
559           CmpInst::Predicate AltPred = AltInst->getPredicate();
560           Value *AltOp0 = AltInst->getOperand(0);
561           Value *AltOp1 = AltInst->getOperand(1);
562           // Check if operands are compatible with alternate operands.
563           if (AltPred == CurrentPred &&
564               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
565             continue;
566           if (AltPred == SwappedCurrentPred &&
567               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
568             continue;
569         }
570         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
571           assert(isValidForAlternation(Opcode) &&
572                  isValidForAlternation(InstOpcode) &&
573                  "Cast isn't safe for alternation, logic needs to be updated!");
574           AltIndex = Cnt;
575           continue;
576         }
577         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
578         CmpInst::Predicate AltPred = AltInst->getPredicate();
579         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
580             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
581           continue;
582       }
583     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
584       continue;
585     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
586   }
587 
588   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
589                            cast<Instruction>(VL[AltIndex]));
590 }
591 
592 /// \returns true if all of the values in \p VL have the same type or false
593 /// otherwise.
594 static bool allSameType(ArrayRef<Value *> VL) {
595   Type *Ty = VL[0]->getType();
596   for (int i = 1, e = VL.size(); i < e; i++)
597     if (VL[i]->getType() != Ty)
598       return false;
599 
600   return true;
601 }
602 
603 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
604 static Optional<unsigned> getExtractIndex(Instruction *E) {
605   unsigned Opcode = E->getOpcode();
606   assert((Opcode == Instruction::ExtractElement ||
607           Opcode == Instruction::ExtractValue) &&
608          "Expected extractelement or extractvalue instruction.");
609   if (Opcode == Instruction::ExtractElement) {
610     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
611     if (!CI)
612       return None;
613     return CI->getZExtValue();
614   }
615   ExtractValueInst *EI = cast<ExtractValueInst>(E);
616   if (EI->getNumIndices() != 1)
617     return None;
618   return *EI->idx_begin();
619 }
620 
621 /// \returns True if in-tree use also needs extract. This refers to
622 /// possible scalar operand in vectorized instruction.
623 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
624                                     TargetLibraryInfo *TLI) {
625   unsigned Opcode = UserInst->getOpcode();
626   switch (Opcode) {
627   case Instruction::Load: {
628     LoadInst *LI = cast<LoadInst>(UserInst);
629     return (LI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Store: {
632     StoreInst *SI = cast<StoreInst>(UserInst);
633     return (SI->getPointerOperand() == Scalar);
634   }
635   case Instruction::Call: {
636     CallInst *CI = cast<CallInst>(UserInst);
637     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
638     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
639       if (hasVectorInstrinsicScalarOpd(ID, i))
640         return (CI->getArgOperand(i) == Scalar);
641     }
642     LLVM_FALLTHROUGH;
643   }
644   default:
645     return false;
646   }
647 }
648 
649 /// \returns the AA location that is being access by the instruction.
650 static MemoryLocation getLocation(Instruction *I) {
651   if (StoreInst *SI = dyn_cast<StoreInst>(I))
652     return MemoryLocation::get(SI);
653   if (LoadInst *LI = dyn_cast<LoadInst>(I))
654     return MemoryLocation::get(LI);
655   return MemoryLocation();
656 }
657 
658 /// \returns True if the instruction is not a volatile or atomic load/store.
659 static bool isSimple(Instruction *I) {
660   if (LoadInst *LI = dyn_cast<LoadInst>(I))
661     return LI->isSimple();
662   if (StoreInst *SI = dyn_cast<StoreInst>(I))
663     return SI->isSimple();
664   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
665     return !MI->isVolatile();
666   return true;
667 }
668 
669 /// Shuffles \p Mask in accordance with the given \p SubMask.
670 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
671   if (SubMask.empty())
672     return;
673   if (Mask.empty()) {
674     Mask.append(SubMask.begin(), SubMask.end());
675     return;
676   }
677   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
678   int TermValue = std::min(Mask.size(), SubMask.size());
679   for (int I = 0, E = SubMask.size(); I < E; ++I) {
680     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
681         Mask[SubMask[I]] >= TermValue)
682       continue;
683     NewMask[I] = Mask[SubMask[I]];
684   }
685   Mask.swap(NewMask);
686 }
687 
688 /// Order may have elements assigned special value (size) which is out of
689 /// bounds. Such indices only appear on places which correspond to undef values
690 /// (see canReuseExtract for details) and used in order to avoid undef values
691 /// have effect on operands ordering.
692 /// The first loop below simply finds all unused indices and then the next loop
693 /// nest assigns these indices for undef values positions.
694 /// As an example below Order has two undef positions and they have assigned
695 /// values 3 and 7 respectively:
696 /// before:  6 9 5 4 9 2 1 0
697 /// after:   6 3 5 4 7 2 1 0
698 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
699   const unsigned Sz = Order.size();
700   SmallBitVector UnusedIndices(Sz, /*t=*/true);
701   SmallBitVector MaskedIndices(Sz);
702   for (unsigned I = 0; I < Sz; ++I) {
703     if (Order[I] < Sz)
704       UnusedIndices.reset(Order[I]);
705     else
706       MaskedIndices.set(I);
707   }
708   if (MaskedIndices.none())
709     return;
710   assert(UnusedIndices.count() == MaskedIndices.count() &&
711          "Non-synced masked/available indices.");
712   int Idx = UnusedIndices.find_first();
713   int MIdx = MaskedIndices.find_first();
714   while (MIdx >= 0) {
715     assert(Idx >= 0 && "Indices must be synced.");
716     Order[MIdx] = Idx;
717     Idx = UnusedIndices.find_next(Idx);
718     MIdx = MaskedIndices.find_next(MIdx);
719   }
720 }
721 
722 namespace llvm {
723 
724 static void inversePermutation(ArrayRef<unsigned> Indices,
725                                SmallVectorImpl<int> &Mask) {
726   Mask.clear();
727   const unsigned E = Indices.size();
728   Mask.resize(E, UndefMaskElem);
729   for (unsigned I = 0; I < E; ++I)
730     Mask[Indices[I]] = I;
731 }
732 
733 /// \returns inserting index of InsertElement or InsertValue instruction,
734 /// using Offset as base offset for index.
735 static Optional<unsigned> getInsertIndex(Value *InsertInst,
736                                          unsigned Offset = 0) {
737   int Index = Offset;
738   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
739     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
740       auto *VT = cast<FixedVectorType>(IE->getType());
741       if (CI->getValue().uge(VT->getNumElements()))
742         return None;
743       Index *= VT->getNumElements();
744       Index += CI->getZExtValue();
745       return Index;
746     }
747     return None;
748   }
749 
750   auto *IV = cast<InsertValueInst>(InsertInst);
751   Type *CurrentType = IV->getType();
752   for (unsigned I : IV->indices()) {
753     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
754       Index *= ST->getNumElements();
755       CurrentType = ST->getElementType(I);
756     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
757       Index *= AT->getNumElements();
758       CurrentType = AT->getElementType();
759     } else {
760       return None;
761     }
762     Index += I;
763   }
764   return Index;
765 }
766 
767 /// Reorders the list of scalars in accordance with the given \p Mask.
768 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
769                            ArrayRef<int> Mask) {
770   assert(!Mask.empty() && "Expected non-empty mask.");
771   SmallVector<Value *> Prev(Scalars.size(),
772                             UndefValue::get(Scalars.front()->getType()));
773   Prev.swap(Scalars);
774   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
775     if (Mask[I] != UndefMaskElem)
776       Scalars[Mask[I]] = Prev[I];
777 }
778 
779 /// Checks if the provided value does not require scheduling. It does not
780 /// require scheduling if this is not an instruction or it is an instruction
781 /// that does not read/write memory and all operands are either not instructions
782 /// or phi nodes or instructions from different blocks.
783 static bool areAllOperandsNonInsts(Value *V) {
784   auto *I = dyn_cast<Instruction>(V);
785   if (!I)
786     return true;
787   return !I->mayReadOrWriteMemory() && all_of(I->operands(), [I](Value *V) {
788     auto *IO = dyn_cast<Instruction>(V);
789     if (!IO)
790       return true;
791     return isa<PHINode>(IO) || IO->getParent() != I->getParent();
792   });
793 }
794 
795 /// Checks if the provided value does not require scheduling. It does not
796 /// require scheduling if this is not an instruction or it is an instruction
797 /// that does not read/write memory and all users are phi nodes or instructions
798 /// from the different blocks.
799 static bool isUsedOutsideBlock(Value *V) {
800   auto *I = dyn_cast<Instruction>(V);
801   if (!I)
802     return true;
803   // Limits the number of uses to save compile time.
804   constexpr int UsesLimit = 8;
805   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
806          all_of(I->users(), [I](User *U) {
807            auto *IU = dyn_cast<Instruction>(U);
808            if (!IU)
809              return true;
810            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
811          });
812 }
813 
814 /// Checks if the specified value does not require scheduling. It does not
815 /// require scheduling if all operands and all users do not need to be scheduled
816 /// in the current basic block.
817 static bool doesNotNeedToBeScheduled(Value *V) {
818   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
819 }
820 
821 /// Checks if the specified array of instructions does not require scheduling.
822 /// It is so if all either instructions have operands that do not require
823 /// scheduling or their users do not require scheduling since they are phis or
824 /// in other basic blocks.
825 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
826   return !VL.empty() &&
827          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
828 }
829 
830 namespace slpvectorizer {
831 
832 /// Bottom Up SLP Vectorizer.
833 class BoUpSLP {
834   struct TreeEntry;
835   struct ScheduleData;
836 
837 public:
838   using ValueList = SmallVector<Value *, 8>;
839   using InstrList = SmallVector<Instruction *, 16>;
840   using ValueSet = SmallPtrSet<Value *, 16>;
841   using StoreList = SmallVector<StoreInst *, 8>;
842   using ExtraValueToDebugLocsMap =
843       MapVector<Value *, SmallVector<Instruction *, 2>>;
844   using OrdersType = SmallVector<unsigned, 4>;
845 
846   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
847           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
848           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
849           MemorySSA *MSSA, const DataLayout *DL, OptimizationRemarkEmitter *ORE)
850       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
851         DT(Dt), AC(AC), DB(DB), MSSA(MSSA), DL(DL), ORE(ORE),
852         Builder(Se->getContext()) {
853     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
854     // Use the vector register size specified by the target unless overridden
855     // by a command-line option.
856     // TODO: It would be better to limit the vectorization factor based on
857     //       data type rather than just register size. For example, x86 AVX has
858     //       256-bit registers, but it does not support integer operations
859     //       at that width (that requires AVX2).
860     if (MaxVectorRegSizeOption.getNumOccurrences())
861       MaxVecRegSize = MaxVectorRegSizeOption;
862     else
863       MaxVecRegSize =
864           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
865               .getFixedSize();
866 
867     if (MinVectorRegSizeOption.getNumOccurrences())
868       MinVecRegSize = MinVectorRegSizeOption;
869     else
870       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
871   }
872 
873   /// Vectorize the tree that starts with the elements in \p VL.
874   /// Returns the vectorized root.
875   Value *vectorizeTree();
876 
877   /// Vectorize the tree but with the list of externally used values \p
878   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
879   /// generated extractvalue instructions.
880   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
881 
882   /// \returns the cost incurred by unwanted spills and fills, caused by
883   /// holding live values over call sites.
884   InstructionCost getSpillCost() const;
885 
886   /// \returns the vectorization cost of the subtree that starts at \p VL.
887   /// A negative number means that this is profitable.
888   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
889 
890   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
891   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
892   void buildTree(ArrayRef<Value *> Roots,
893                  ArrayRef<Value *> UserIgnoreLst = None);
894 
895   /// Builds external uses of the vectorized scalars, i.e. the list of
896   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
897   /// ExternallyUsedValues contains additional list of external uses to handle
898   /// vectorization of reductions.
899   void
900   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
901 
902   /// Clear the internal data structures that are created by 'buildTree'.
903   void deleteTree() {
904     VectorizableTree.clear();
905     ScalarToTreeEntry.clear();
906     MustGather.clear();
907     ExternalUses.clear();
908     for (auto &Iter : BlocksSchedules) {
909       BlockScheduling *BS = Iter.second.get();
910       BS->clear();
911     }
912     MinBWs.clear();
913     InstrElementSize.clear();
914   }
915 
916   unsigned getTreeSize() const { return VectorizableTree.size(); }
917 
918   /// Perform LICM and CSE on the newly generated gather sequences.
919   void optimizeGatherSequence();
920 
921   /// Checks if the specified gather tree entry \p TE can be represented as a
922   /// shuffled vector entry + (possibly) permutation with other gathers. It
923   /// implements the checks only for possibly ordered scalars (Loads,
924   /// ExtractElement, ExtractValue), which can be part of the graph.
925   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
926 
927   /// Gets reordering data for the given tree entry. If the entry is vectorized
928   /// - just return ReorderIndices, otherwise check if the scalars can be
929   /// reordered and return the most optimal order.
930   /// \param TopToBottom If true, include the order of vectorized stores and
931   /// insertelement nodes, otherwise skip them.
932   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
933 
934   /// Reorders the current graph to the most profitable order starting from the
935   /// root node to the leaf nodes. The best order is chosen only from the nodes
936   /// of the same size (vectorization factor). Smaller nodes are considered
937   /// parts of subgraph with smaller VF and they are reordered independently. We
938   /// can make it because we still need to extend smaller nodes to the wider VF
939   /// and we can merge reordering shuffles with the widening shuffles.
940   void reorderTopToBottom();
941 
942   /// Reorders the current graph to the most profitable order starting from
943   /// leaves to the root. It allows to rotate small subgraphs and reduce the
944   /// number of reshuffles if the leaf nodes use the same order. In this case we
945   /// can merge the orders and just shuffle user node instead of shuffling its
946   /// operands. Plus, even the leaf nodes have different orders, it allows to
947   /// sink reordering in the graph closer to the root node and merge it later
948   /// during analysis.
949   void reorderBottomToTop(bool IgnoreReorder = false);
950 
951   /// \return The vector element size in bits to use when vectorizing the
952   /// expression tree ending at \p V. If V is a store, the size is the width of
953   /// the stored value. Otherwise, the size is the width of the largest loaded
954   /// value reaching V. This method is used by the vectorizer to calculate
955   /// vectorization factors.
956   unsigned getVectorElementSize(Value *V);
957 
958   /// Compute the minimum type sizes required to represent the entries in a
959   /// vectorizable tree.
960   void computeMinimumValueSizes();
961 
962   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
963   unsigned getMaxVecRegSize() const {
964     return MaxVecRegSize;
965   }
966 
967   // \returns minimum vector register size as set by cl::opt.
968   unsigned getMinVecRegSize() const {
969     return MinVecRegSize;
970   }
971 
972   unsigned getMinVF(unsigned Sz) const {
973     return std::max(2U, getMinVecRegSize() / Sz);
974   }
975 
976   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
977     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
978       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
979     return MaxVF ? MaxVF : UINT_MAX;
980   }
981 
982   /// Check if homogeneous aggregate is isomorphic to some VectorType.
983   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
984   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
985   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
986   ///
987   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
988   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
989 
990   /// \returns True if the VectorizableTree is both tiny and not fully
991   /// vectorizable. We do not vectorize such trees.
992   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
993 
994   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
995   /// can be load combined in the backend. Load combining may not be allowed in
996   /// the IR optimizer, so we do not want to alter the pattern. For example,
997   /// partially transforming a scalar bswap() pattern into vector code is
998   /// effectively impossible for the backend to undo.
999   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1000   ///       may not be necessary.
1001   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1002 
1003   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1004   /// can be load combined in the backend. Load combining may not be allowed in
1005   /// the IR optimizer, so we do not want to alter the pattern. For example,
1006   /// partially transforming a scalar bswap() pattern into vector code is
1007   /// effectively impossible for the backend to undo.
1008   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1009   ///       may not be necessary.
1010   bool isLoadCombineCandidate() const;
1011 
1012   OptimizationRemarkEmitter *getORE() { return ORE; }
1013 
1014   /// This structure holds any data we need about the edges being traversed
1015   /// during buildTree_rec(). We keep track of:
1016   /// (i) the user TreeEntry index, and
1017   /// (ii) the index of the edge.
1018   struct EdgeInfo {
1019     EdgeInfo() = default;
1020     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1021         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1022     /// The user TreeEntry.
1023     TreeEntry *UserTE = nullptr;
1024     /// The operand index of the use.
1025     unsigned EdgeIdx = UINT_MAX;
1026 #ifndef NDEBUG
1027     friend inline raw_ostream &operator<<(raw_ostream &OS,
1028                                           const BoUpSLP::EdgeInfo &EI) {
1029       EI.dump(OS);
1030       return OS;
1031     }
1032     /// Debug print.
1033     void dump(raw_ostream &OS) const {
1034       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1035          << " EdgeIdx:" << EdgeIdx << "}";
1036     }
1037     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1038 #endif
1039   };
1040 
1041   /// A helper data structure to hold the operands of a vector of instructions.
1042   /// This supports a fixed vector length for all operand vectors.
1043   class VLOperands {
1044     /// For each operand we need (i) the value, and (ii) the opcode that it
1045     /// would be attached to if the expression was in a left-linearized form.
1046     /// This is required to avoid illegal operand reordering.
1047     /// For example:
1048     /// \verbatim
1049     ///                         0 Op1
1050     ///                         |/
1051     /// Op1 Op2   Linearized    + Op2
1052     ///   \ /     ---------->   |/
1053     ///    -                    -
1054     ///
1055     /// Op1 - Op2            (0 + Op1) - Op2
1056     /// \endverbatim
1057     ///
1058     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1059     ///
1060     /// Another way to think of this is to track all the operations across the
1061     /// path from the operand all the way to the root of the tree and to
1062     /// calculate the operation that corresponds to this path. For example, the
1063     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1064     /// corresponding operation is a '-' (which matches the one in the
1065     /// linearized tree, as shown above).
1066     ///
1067     /// For lack of a better term, we refer to this operation as Accumulated
1068     /// Path Operation (APO).
1069     struct OperandData {
1070       OperandData() = default;
1071       OperandData(Value *V, bool APO, bool IsUsed)
1072           : V(V), APO(APO), IsUsed(IsUsed) {}
1073       /// The operand value.
1074       Value *V = nullptr;
1075       /// TreeEntries only allow a single opcode, or an alternate sequence of
1076       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1077       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1078       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1079       /// (e.g., Add/Mul)
1080       bool APO = false;
1081       /// Helper data for the reordering function.
1082       bool IsUsed = false;
1083     };
1084 
1085     /// During operand reordering, we are trying to select the operand at lane
1086     /// that matches best with the operand at the neighboring lane. Our
1087     /// selection is based on the type of value we are looking for. For example,
1088     /// if the neighboring lane has a load, we need to look for a load that is
1089     /// accessing a consecutive address. These strategies are summarized in the
1090     /// 'ReorderingMode' enumerator.
1091     enum class ReorderingMode {
1092       Load,     ///< Matching loads to consecutive memory addresses
1093       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1094       Constant, ///< Matching constants
1095       Splat,    ///< Matching the same instruction multiple times (broadcast)
1096       Failed,   ///< We failed to create a vectorizable group
1097     };
1098 
1099     using OperandDataVec = SmallVector<OperandData, 2>;
1100 
1101     /// A vector of operand vectors.
1102     SmallVector<OperandDataVec, 4> OpsVec;
1103 
1104     const DataLayout &DL;
1105     ScalarEvolution &SE;
1106     const BoUpSLP &R;
1107 
1108     /// \returns the operand data at \p OpIdx and \p Lane.
1109     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1110       return OpsVec[OpIdx][Lane];
1111     }
1112 
1113     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1114     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1115       return OpsVec[OpIdx][Lane];
1116     }
1117 
1118     /// Clears the used flag for all entries.
1119     void clearUsed() {
1120       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1121            OpIdx != NumOperands; ++OpIdx)
1122         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1123              ++Lane)
1124           OpsVec[OpIdx][Lane].IsUsed = false;
1125     }
1126 
1127     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1128     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1129       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1130     }
1131 
1132     // The hard-coded scores listed here are not very important, though it shall
1133     // be higher for better matches to improve the resulting cost. When
1134     // computing the scores of matching one sub-tree with another, we are
1135     // basically counting the number of values that are matching. So even if all
1136     // scores are set to 1, we would still get a decent matching result.
1137     // However, sometimes we have to break ties. For example we may have to
1138     // choose between matching loads vs matching opcodes. This is what these
1139     // scores are helping us with: they provide the order of preference. Also,
1140     // this is important if the scalar is externally used or used in another
1141     // tree entry node in the different lane.
1142 
1143     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1144     static const int ScoreConsecutiveLoads = 4;
1145     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1146     static const int ScoreReversedLoads = 3;
1147     /// ExtractElementInst from same vector and consecutive indexes.
1148     static const int ScoreConsecutiveExtracts = 4;
1149     /// ExtractElementInst from same vector and reversed indices.
1150     static const int ScoreReversedExtracts = 3;
1151     /// Constants.
1152     static const int ScoreConstants = 2;
1153     /// Instructions with the same opcode.
1154     static const int ScoreSameOpcode = 2;
1155     /// Instructions with alt opcodes (e.g, add + sub).
1156     static const int ScoreAltOpcodes = 1;
1157     /// Identical instructions (a.k.a. splat or broadcast).
1158     static const int ScoreSplat = 1;
1159     /// Matching with an undef is preferable to failing.
1160     static const int ScoreUndef = 1;
1161     /// Score for failing to find a decent match.
1162     static const int ScoreFail = 0;
1163     /// Score if all users are vectorized.
1164     static const int ScoreAllUserVectorized = 1;
1165 
1166     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1167     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1168     /// MainAltOps.
1169     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1170                                ScalarEvolution &SE, int NumLanes,
1171                                ArrayRef<Value *> MainAltOps) {
1172       if (V1 == V2)
1173         return VLOperands::ScoreSplat;
1174 
1175       auto *LI1 = dyn_cast<LoadInst>(V1);
1176       auto *LI2 = dyn_cast<LoadInst>(V2);
1177       if (LI1 && LI2) {
1178         if (LI1->getParent() != LI2->getParent())
1179           return VLOperands::ScoreFail;
1180 
1181         Optional<int> Dist = getPointersDiff(
1182             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1183             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1184         if (!Dist || *Dist == 0)
1185           return VLOperands::ScoreFail;
1186         // The distance is too large - still may be profitable to use masked
1187         // loads/gathers.
1188         if (std::abs(*Dist) > NumLanes / 2)
1189           return VLOperands::ScoreAltOpcodes;
1190         // This still will detect consecutive loads, but we might have "holes"
1191         // in some cases. It is ok for non-power-2 vectorization and may produce
1192         // better results. It should not affect current vectorization.
1193         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1194                            : VLOperands::ScoreReversedLoads;
1195       }
1196 
1197       auto *C1 = dyn_cast<Constant>(V1);
1198       auto *C2 = dyn_cast<Constant>(V2);
1199       if (C1 && C2)
1200         return VLOperands::ScoreConstants;
1201 
1202       // Extracts from consecutive indexes of the same vector better score as
1203       // the extracts could be optimized away.
1204       Value *EV1;
1205       ConstantInt *Ex1Idx;
1206       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1207         // Undefs are always profitable for extractelements.
1208         if (isa<UndefValue>(V2))
1209           return VLOperands::ScoreConsecutiveExtracts;
1210         Value *EV2 = nullptr;
1211         ConstantInt *Ex2Idx = nullptr;
1212         if (match(V2,
1213                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1214                                                          m_Undef())))) {
1215           // Undefs are always profitable for extractelements.
1216           if (!Ex2Idx)
1217             return VLOperands::ScoreConsecutiveExtracts;
1218           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1219             return VLOperands::ScoreConsecutiveExtracts;
1220           if (EV2 == EV1) {
1221             int Idx1 = Ex1Idx->getZExtValue();
1222             int Idx2 = Ex2Idx->getZExtValue();
1223             int Dist = Idx2 - Idx1;
1224             // The distance is too large - still may be profitable to use
1225             // shuffles.
1226             if (std::abs(Dist) == 0)
1227               return VLOperands::ScoreSplat;
1228             if (std::abs(Dist) > NumLanes / 2)
1229               return VLOperands::ScoreSameOpcode;
1230             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1231                               : VLOperands::ScoreReversedExtracts;
1232           }
1233           return VLOperands::ScoreAltOpcodes;
1234         }
1235         return VLOperands::ScoreFail;
1236       }
1237 
1238       auto *I1 = dyn_cast<Instruction>(V1);
1239       auto *I2 = dyn_cast<Instruction>(V2);
1240       if (I1 && I2) {
1241         if (I1->getParent() != I2->getParent())
1242           return VLOperands::ScoreFail;
1243         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1244         Ops.push_back(I1);
1245         Ops.push_back(I2);
1246         InstructionsState S = getSameOpcode(Ops);
1247         // Note: Only consider instructions with <= 2 operands to avoid
1248         // complexity explosion.
1249         if (S.getOpcode() &&
1250             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1251              !S.isAltShuffle()) &&
1252             all_of(Ops, [&S](Value *V) {
1253               return cast<Instruction>(V)->getNumOperands() ==
1254                      S.MainOp->getNumOperands();
1255             }))
1256           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1257                                   : VLOperands::ScoreSameOpcode;
1258       }
1259 
1260       if (isa<UndefValue>(V2))
1261         return VLOperands::ScoreUndef;
1262 
1263       return VLOperands::ScoreFail;
1264     }
1265 
1266     /// \param Lane lane of the operands under analysis.
1267     /// \param OpIdx operand index in \p Lane lane we're looking the best
1268     /// candidate for.
1269     /// \param Idx operand index of the current candidate value.
1270     /// \returns The additional score due to possible broadcasting of the
1271     /// elements in the lane. It is more profitable to have power-of-2 unique
1272     /// elements in the lane, it will be vectorized with higher probability
1273     /// after removing duplicates. Currently the SLP vectorizer supports only
1274     /// vectorization of the power-of-2 number of unique scalars.
1275     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1276       Value *IdxLaneV = getData(Idx, Lane).V;
1277       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1278         return 0;
1279       SmallPtrSet<Value *, 4> Uniques;
1280       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1281         if (Ln == Lane)
1282           continue;
1283         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1284         if (!isa<Instruction>(OpIdxLnV))
1285           return 0;
1286         Uniques.insert(OpIdxLnV);
1287       }
1288       int UniquesCount = Uniques.size();
1289       int UniquesCntWithIdxLaneV =
1290           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1291       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1292       int UniquesCntWithOpIdxLaneV =
1293           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1294       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1295         return 0;
1296       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1297               UniquesCntWithOpIdxLaneV) -
1298              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1299     }
1300 
1301     /// \param Lane lane of the operands under analysis.
1302     /// \param OpIdx operand index in \p Lane lane we're looking the best
1303     /// candidate for.
1304     /// \param Idx operand index of the current candidate value.
1305     /// \returns The additional score for the scalar which users are all
1306     /// vectorized.
1307     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1308       Value *IdxLaneV = getData(Idx, Lane).V;
1309       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1310       // Do not care about number of uses for vector-like instructions
1311       // (extractelement/extractvalue with constant indices), they are extracts
1312       // themselves and already externally used. Vectorization of such
1313       // instructions does not add extra extractelement instruction, just may
1314       // remove it.
1315       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1316           isVectorLikeInstWithConstOps(OpIdxLaneV))
1317         return VLOperands::ScoreAllUserVectorized;
1318       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1319       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1320         return 0;
1321       return R.areAllUsersVectorized(IdxLaneI, None)
1322                  ? VLOperands::ScoreAllUserVectorized
1323                  : 0;
1324     }
1325 
1326     /// Go through the operands of \p LHS and \p RHS recursively until \p
1327     /// MaxLevel, and return the cummulative score. For example:
1328     /// \verbatim
1329     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1330     ///     \ /         \ /         \ /        \ /
1331     ///      +           +           +          +
1332     ///     G1          G2          G3         G4
1333     /// \endverbatim
1334     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1335     /// each level recursively, accumulating the score. It starts from matching
1336     /// the additions at level 0, then moves on to the loads (level 1). The
1337     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1338     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1339     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1340     /// Please note that the order of the operands does not matter, as we
1341     /// evaluate the score of all profitable combinations of operands. In
1342     /// other words the score of G1 and G4 is the same as G1 and G2. This
1343     /// heuristic is based on ideas described in:
1344     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1345     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1346     ///   Luís F. W. Góes
1347     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1348                            ArrayRef<Value *> MainAltOps) {
1349 
1350       // Get the shallow score of V1 and V2.
1351       int ShallowScoreAtThisLevel =
1352           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1353 
1354       // If reached MaxLevel,
1355       //  or if V1 and V2 are not instructions,
1356       //  or if they are SPLAT,
1357       //  or if they are not consecutive,
1358       //  or if profitable to vectorize loads or extractelements, early return
1359       //  the current cost.
1360       auto *I1 = dyn_cast<Instruction>(LHS);
1361       auto *I2 = dyn_cast<Instruction>(RHS);
1362       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1363           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1364           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1365             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1366             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1367            ShallowScoreAtThisLevel))
1368         return ShallowScoreAtThisLevel;
1369       assert(I1 && I2 && "Should have early exited.");
1370 
1371       // Contains the I2 operand indexes that got matched with I1 operands.
1372       SmallSet<unsigned, 4> Op2Used;
1373 
1374       // Recursion towards the operands of I1 and I2. We are trying all possible
1375       // operand pairs, and keeping track of the best score.
1376       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1377            OpIdx1 != NumOperands1; ++OpIdx1) {
1378         // Try to pair op1I with the best operand of I2.
1379         int MaxTmpScore = 0;
1380         unsigned MaxOpIdx2 = 0;
1381         bool FoundBest = false;
1382         // If I2 is commutative try all combinations.
1383         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1384         unsigned ToIdx = isCommutative(I2)
1385                              ? I2->getNumOperands()
1386                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1387         assert(FromIdx <= ToIdx && "Bad index");
1388         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1389           // Skip operands already paired with OpIdx1.
1390           if (Op2Used.count(OpIdx2))
1391             continue;
1392           // Recursively calculate the cost at each level
1393           int TmpScore =
1394               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1395                                  CurrLevel + 1, MaxLevel, None);
1396           // Look for the best score.
1397           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1398             MaxTmpScore = TmpScore;
1399             MaxOpIdx2 = OpIdx2;
1400             FoundBest = true;
1401           }
1402         }
1403         if (FoundBest) {
1404           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1405           Op2Used.insert(MaxOpIdx2);
1406           ShallowScoreAtThisLevel += MaxTmpScore;
1407         }
1408       }
1409       return ShallowScoreAtThisLevel;
1410     }
1411 
1412     /// Score scaling factor for fully compatible instructions but with
1413     /// different number of external uses. Allows better selection of the
1414     /// instructions with less external uses.
1415     static const int ScoreScaleFactor = 10;
1416 
1417     /// \Returns the look-ahead score, which tells us how much the sub-trees
1418     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1419     /// score. This helps break ties in an informed way when we cannot decide on
1420     /// the order of the operands by just considering the immediate
1421     /// predecessors.
1422     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1423                           int Lane, unsigned OpIdx, unsigned Idx,
1424                           bool &IsUsed) {
1425       int Score =
1426           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1427       if (Score) {
1428         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1429         if (Score <= -SplatScore) {
1430           // Set the minimum score for splat-like sequence to avoid setting
1431           // failed state.
1432           Score = 1;
1433         } else {
1434           Score += SplatScore;
1435           // Scale score to see the difference between different operands
1436           // and similar operands but all vectorized/not all vectorized
1437           // uses. It does not affect actual selection of the best
1438           // compatible operand in general, just allows to select the
1439           // operand with all vectorized uses.
1440           Score *= ScoreScaleFactor;
1441           Score += getExternalUseScore(Lane, OpIdx, Idx);
1442           IsUsed = true;
1443         }
1444       }
1445       return Score;
1446     }
1447 
1448     /// Best defined scores per lanes between the passes. Used to choose the
1449     /// best operand (with the highest score) between the passes.
1450     /// The key - {Operand Index, Lane}.
1451     /// The value - the best score between the passes for the lane and the
1452     /// operand.
1453     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1454         BestScoresPerLanes;
1455 
1456     // Search all operands in Ops[*][Lane] for the one that matches best
1457     // Ops[OpIdx][LastLane] and return its opreand index.
1458     // If no good match can be found, return None.
1459     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1460                                       ArrayRef<ReorderingMode> ReorderingModes,
1461                                       ArrayRef<Value *> MainAltOps) {
1462       unsigned NumOperands = getNumOperands();
1463 
1464       // The operand of the previous lane at OpIdx.
1465       Value *OpLastLane = getData(OpIdx, LastLane).V;
1466 
1467       // Our strategy mode for OpIdx.
1468       ReorderingMode RMode = ReorderingModes[OpIdx];
1469       if (RMode == ReorderingMode::Failed)
1470         return None;
1471 
1472       // The linearized opcode of the operand at OpIdx, Lane.
1473       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1474 
1475       // The best operand index and its score.
1476       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1477       // are using the score to differentiate between the two.
1478       struct BestOpData {
1479         Optional<unsigned> Idx = None;
1480         unsigned Score = 0;
1481       } BestOp;
1482       BestOp.Score =
1483           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1484               .first->second;
1485 
1486       // Track if the operand must be marked as used. If the operand is set to
1487       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1488       // want to reestimate the operands again on the following iterations).
1489       bool IsUsed =
1490           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1491       // Iterate through all unused operands and look for the best.
1492       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1493         // Get the operand at Idx and Lane.
1494         OperandData &OpData = getData(Idx, Lane);
1495         Value *Op = OpData.V;
1496         bool OpAPO = OpData.APO;
1497 
1498         // Skip already selected operands.
1499         if (OpData.IsUsed)
1500           continue;
1501 
1502         // Skip if we are trying to move the operand to a position with a
1503         // different opcode in the linearized tree form. This would break the
1504         // semantics.
1505         if (OpAPO != OpIdxAPO)
1506           continue;
1507 
1508         // Look for an operand that matches the current mode.
1509         switch (RMode) {
1510         case ReorderingMode::Load:
1511         case ReorderingMode::Constant:
1512         case ReorderingMode::Opcode: {
1513           bool LeftToRight = Lane > LastLane;
1514           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1515           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1516           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1517                                         OpIdx, Idx, IsUsed);
1518           if (Score > static_cast<int>(BestOp.Score)) {
1519             BestOp.Idx = Idx;
1520             BestOp.Score = Score;
1521             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1522           }
1523           break;
1524         }
1525         case ReorderingMode::Splat:
1526           if (Op == OpLastLane)
1527             BestOp.Idx = Idx;
1528           break;
1529         case ReorderingMode::Failed:
1530           llvm_unreachable("Not expected Failed reordering mode.");
1531         }
1532       }
1533 
1534       if (BestOp.Idx) {
1535         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1536         return BestOp.Idx;
1537       }
1538       // If we could not find a good match return None.
1539       return None;
1540     }
1541 
1542     /// Helper for reorderOperandVecs.
1543     /// \returns the lane that we should start reordering from. This is the one
1544     /// which has the least number of operands that can freely move about or
1545     /// less profitable because it already has the most optimal set of operands.
1546     unsigned getBestLaneToStartReordering() const {
1547       unsigned Min = UINT_MAX;
1548       unsigned SameOpNumber = 0;
1549       // std::pair<unsigned, unsigned> is used to implement a simple voting
1550       // algorithm and choose the lane with the least number of operands that
1551       // can freely move about or less profitable because it already has the
1552       // most optimal set of operands. The first unsigned is a counter for
1553       // voting, the second unsigned is the counter of lanes with instructions
1554       // with same/alternate opcodes and same parent basic block.
1555       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1556       // Try to be closer to the original results, if we have multiple lanes
1557       // with same cost. If 2 lanes have the same cost, use the one with the
1558       // lowest index.
1559       for (int I = getNumLanes(); I > 0; --I) {
1560         unsigned Lane = I - 1;
1561         OperandsOrderData NumFreeOpsHash =
1562             getMaxNumOperandsThatCanBeReordered(Lane);
1563         // Compare the number of operands that can move and choose the one with
1564         // the least number.
1565         if (NumFreeOpsHash.NumOfAPOs < Min) {
1566           Min = NumFreeOpsHash.NumOfAPOs;
1567           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1568           HashMap.clear();
1569           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1570         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1571                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1572           // Select the most optimal lane in terms of number of operands that
1573           // should be moved around.
1574           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1575           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1576         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1577                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1578           auto It = HashMap.find(NumFreeOpsHash.Hash);
1579           if (It == HashMap.end())
1580             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1581           else
1582             ++It->second.first;
1583         }
1584       }
1585       // Select the lane with the minimum counter.
1586       unsigned BestLane = 0;
1587       unsigned CntMin = UINT_MAX;
1588       for (const auto &Data : reverse(HashMap)) {
1589         if (Data.second.first < CntMin) {
1590           CntMin = Data.second.first;
1591           BestLane = Data.second.second;
1592         }
1593       }
1594       return BestLane;
1595     }
1596 
1597     /// Data structure that helps to reorder operands.
1598     struct OperandsOrderData {
1599       /// The best number of operands with the same APOs, which can be
1600       /// reordered.
1601       unsigned NumOfAPOs = UINT_MAX;
1602       /// Number of operands with the same/alternate instruction opcode and
1603       /// parent.
1604       unsigned NumOpsWithSameOpcodeParent = 0;
1605       /// Hash for the actual operands ordering.
1606       /// Used to count operands, actually their position id and opcode
1607       /// value. It is used in the voting mechanism to find the lane with the
1608       /// least number of operands that can freely move about or less profitable
1609       /// because it already has the most optimal set of operands. Can be
1610       /// replaced with SmallVector<unsigned> instead but hash code is faster
1611       /// and requires less memory.
1612       unsigned Hash = 0;
1613     };
1614     /// \returns the maximum number of operands that are allowed to be reordered
1615     /// for \p Lane and the number of compatible instructions(with the same
1616     /// parent/opcode). This is used as a heuristic for selecting the first lane
1617     /// to start operand reordering.
1618     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1619       unsigned CntTrue = 0;
1620       unsigned NumOperands = getNumOperands();
1621       // Operands with the same APO can be reordered. We therefore need to count
1622       // how many of them we have for each APO, like this: Cnt[APO] = x.
1623       // Since we only have two APOs, namely true and false, we can avoid using
1624       // a map. Instead we can simply count the number of operands that
1625       // correspond to one of them (in this case the 'true' APO), and calculate
1626       // the other by subtracting it from the total number of operands.
1627       // Operands with the same instruction opcode and parent are more
1628       // profitable since we don't need to move them in many cases, with a high
1629       // probability such lane already can be vectorized effectively.
1630       bool AllUndefs = true;
1631       unsigned NumOpsWithSameOpcodeParent = 0;
1632       Instruction *OpcodeI = nullptr;
1633       BasicBlock *Parent = nullptr;
1634       unsigned Hash = 0;
1635       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1636         const OperandData &OpData = getData(OpIdx, Lane);
1637         if (OpData.APO)
1638           ++CntTrue;
1639         // Use Boyer-Moore majority voting for finding the majority opcode and
1640         // the number of times it occurs.
1641         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1642           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1643               I->getParent() != Parent) {
1644             if (NumOpsWithSameOpcodeParent == 0) {
1645               NumOpsWithSameOpcodeParent = 1;
1646               OpcodeI = I;
1647               Parent = I->getParent();
1648             } else {
1649               --NumOpsWithSameOpcodeParent;
1650             }
1651           } else {
1652             ++NumOpsWithSameOpcodeParent;
1653           }
1654         }
1655         Hash = hash_combine(
1656             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1657         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1658       }
1659       if (AllUndefs)
1660         return {};
1661       OperandsOrderData Data;
1662       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1663       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1664       Data.Hash = Hash;
1665       return Data;
1666     }
1667 
1668     /// Go through the instructions in VL and append their operands.
1669     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1670       assert(!VL.empty() && "Bad VL");
1671       assert((empty() || VL.size() == getNumLanes()) &&
1672              "Expected same number of lanes");
1673       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1674       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1675       OpsVec.resize(NumOperands);
1676       unsigned NumLanes = VL.size();
1677       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1678         OpsVec[OpIdx].resize(NumLanes);
1679         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1680           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1681           // Our tree has just 3 nodes: the root and two operands.
1682           // It is therefore trivial to get the APO. We only need to check the
1683           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1684           // RHS operand. The LHS operand of both add and sub is never attached
1685           // to an inversese operation in the linearized form, therefore its APO
1686           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1687 
1688           // Since operand reordering is performed on groups of commutative
1689           // operations or alternating sequences (e.g., +, -), we can safely
1690           // tell the inverse operations by checking commutativity.
1691           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1692           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1693           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1694                                  APO, false};
1695         }
1696       }
1697     }
1698 
1699     /// \returns the number of operands.
1700     unsigned getNumOperands() const { return OpsVec.size(); }
1701 
1702     /// \returns the number of lanes.
1703     unsigned getNumLanes() const { return OpsVec[0].size(); }
1704 
1705     /// \returns the operand value at \p OpIdx and \p Lane.
1706     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1707       return getData(OpIdx, Lane).V;
1708     }
1709 
1710     /// \returns true if the data structure is empty.
1711     bool empty() const { return OpsVec.empty(); }
1712 
1713     /// Clears the data.
1714     void clear() { OpsVec.clear(); }
1715 
1716     /// \Returns true if there are enough operands identical to \p Op to fill
1717     /// the whole vector.
1718     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1719     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1720       bool OpAPO = getData(OpIdx, Lane).APO;
1721       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1722         if (Ln == Lane)
1723           continue;
1724         // This is set to true if we found a candidate for broadcast at Lane.
1725         bool FoundCandidate = false;
1726         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1727           OperandData &Data = getData(OpI, Ln);
1728           if (Data.APO != OpAPO || Data.IsUsed)
1729             continue;
1730           if (Data.V == Op) {
1731             FoundCandidate = true;
1732             Data.IsUsed = true;
1733             break;
1734           }
1735         }
1736         if (!FoundCandidate)
1737           return false;
1738       }
1739       return true;
1740     }
1741 
1742   public:
1743     /// Initialize with all the operands of the instruction vector \p RootVL.
1744     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1745                ScalarEvolution &SE, const BoUpSLP &R)
1746         : DL(DL), SE(SE), R(R) {
1747       // Append all the operands of RootVL.
1748       appendOperandsOfVL(RootVL);
1749     }
1750 
1751     /// \Returns a value vector with the operands across all lanes for the
1752     /// opearnd at \p OpIdx.
1753     ValueList getVL(unsigned OpIdx) const {
1754       ValueList OpVL(OpsVec[OpIdx].size());
1755       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1756              "Expected same num of lanes across all operands");
1757       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1758         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1759       return OpVL;
1760     }
1761 
1762     // Performs operand reordering for 2 or more operands.
1763     // The original operands are in OrigOps[OpIdx][Lane].
1764     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1765     void reorder() {
1766       unsigned NumOperands = getNumOperands();
1767       unsigned NumLanes = getNumLanes();
1768       // Each operand has its own mode. We are using this mode to help us select
1769       // the instructions for each lane, so that they match best with the ones
1770       // we have selected so far.
1771       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1772 
1773       // This is a greedy single-pass algorithm. We are going over each lane
1774       // once and deciding on the best order right away with no back-tracking.
1775       // However, in order to increase its effectiveness, we start with the lane
1776       // that has operands that can move the least. For example, given the
1777       // following lanes:
1778       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1779       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1780       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1781       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1782       // we will start at Lane 1, since the operands of the subtraction cannot
1783       // be reordered. Then we will visit the rest of the lanes in a circular
1784       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1785 
1786       // Find the first lane that we will start our search from.
1787       unsigned FirstLane = getBestLaneToStartReordering();
1788 
1789       // Initialize the modes.
1790       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1791         Value *OpLane0 = getValue(OpIdx, FirstLane);
1792         // Keep track if we have instructions with all the same opcode on one
1793         // side.
1794         if (isa<LoadInst>(OpLane0))
1795           ReorderingModes[OpIdx] = ReorderingMode::Load;
1796         else if (isa<Instruction>(OpLane0)) {
1797           // Check if OpLane0 should be broadcast.
1798           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1799             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1800           else
1801             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1802         }
1803         else if (isa<Constant>(OpLane0))
1804           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1805         else if (isa<Argument>(OpLane0))
1806           // Our best hope is a Splat. It may save some cost in some cases.
1807           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1808         else
1809           // NOTE: This should be unreachable.
1810           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1811       }
1812 
1813       // Check that we don't have same operands. No need to reorder if operands
1814       // are just perfect diamond or shuffled diamond match. Do not do it only
1815       // for possible broadcasts or non-power of 2 number of scalars (just for
1816       // now).
1817       auto &&SkipReordering = [this]() {
1818         SmallPtrSet<Value *, 4> UniqueValues;
1819         ArrayRef<OperandData> Op0 = OpsVec.front();
1820         for (const OperandData &Data : Op0)
1821           UniqueValues.insert(Data.V);
1822         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1823           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1824                 return !UniqueValues.contains(Data.V);
1825               }))
1826             return false;
1827         }
1828         // TODO: Check if we can remove a check for non-power-2 number of
1829         // scalars after full support of non-power-2 vectorization.
1830         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1831       };
1832 
1833       // If the initial strategy fails for any of the operand indexes, then we
1834       // perform reordering again in a second pass. This helps avoid assigning
1835       // high priority to the failed strategy, and should improve reordering for
1836       // the non-failed operand indexes.
1837       for (int Pass = 0; Pass != 2; ++Pass) {
1838         // Check if no need to reorder operands since they're are perfect or
1839         // shuffled diamond match.
1840         // Need to to do it to avoid extra external use cost counting for
1841         // shuffled matches, which may cause regressions.
1842         if (SkipReordering())
1843           break;
1844         // Skip the second pass if the first pass did not fail.
1845         bool StrategyFailed = false;
1846         // Mark all operand data as free to use.
1847         clearUsed();
1848         // We keep the original operand order for the FirstLane, so reorder the
1849         // rest of the lanes. We are visiting the nodes in a circular fashion,
1850         // using FirstLane as the center point and increasing the radius
1851         // distance.
1852         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1853         for (unsigned I = 0; I < NumOperands; ++I)
1854           MainAltOps[I].push_back(getData(I, FirstLane).V);
1855 
1856         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1857           // Visit the lane on the right and then the lane on the left.
1858           for (int Direction : {+1, -1}) {
1859             int Lane = FirstLane + Direction * Distance;
1860             if (Lane < 0 || Lane >= (int)NumLanes)
1861               continue;
1862             int LastLane = Lane - Direction;
1863             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1864                    "Out of bounds");
1865             // Look for a good match for each operand.
1866             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1867               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1868               Optional<unsigned> BestIdx = getBestOperand(
1869                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1870               // By not selecting a value, we allow the operands that follow to
1871               // select a better matching value. We will get a non-null value in
1872               // the next run of getBestOperand().
1873               if (BestIdx) {
1874                 // Swap the current operand with the one returned by
1875                 // getBestOperand().
1876                 swap(OpIdx, BestIdx.getValue(), Lane);
1877               } else {
1878                 // We failed to find a best operand, set mode to 'Failed'.
1879                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1880                 // Enable the second pass.
1881                 StrategyFailed = true;
1882               }
1883               // Try to get the alternate opcode and follow it during analysis.
1884               if (MainAltOps[OpIdx].size() != 2) {
1885                 OperandData &AltOp = getData(OpIdx, Lane);
1886                 InstructionsState OpS =
1887                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1888                 if (OpS.getOpcode() && OpS.isAltShuffle())
1889                   MainAltOps[OpIdx].push_back(AltOp.V);
1890               }
1891             }
1892           }
1893         }
1894         // Skip second pass if the strategy did not fail.
1895         if (!StrategyFailed)
1896           break;
1897       }
1898     }
1899 
1900 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1901     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1902       switch (RMode) {
1903       case ReorderingMode::Load:
1904         return "Load";
1905       case ReorderingMode::Opcode:
1906         return "Opcode";
1907       case ReorderingMode::Constant:
1908         return "Constant";
1909       case ReorderingMode::Splat:
1910         return "Splat";
1911       case ReorderingMode::Failed:
1912         return "Failed";
1913       }
1914       llvm_unreachable("Unimplemented Reordering Type");
1915     }
1916 
1917     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1918                                                    raw_ostream &OS) {
1919       return OS << getModeStr(RMode);
1920     }
1921 
1922     /// Debug print.
1923     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1924       printMode(RMode, dbgs());
1925     }
1926 
1927     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1928       return printMode(RMode, OS);
1929     }
1930 
1931     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1932       const unsigned Indent = 2;
1933       unsigned Cnt = 0;
1934       for (const OperandDataVec &OpDataVec : OpsVec) {
1935         OS << "Operand " << Cnt++ << "\n";
1936         for (const OperandData &OpData : OpDataVec) {
1937           OS.indent(Indent) << "{";
1938           if (Value *V = OpData.V)
1939             OS << *V;
1940           else
1941             OS << "null";
1942           OS << ", APO:" << OpData.APO << "}\n";
1943         }
1944         OS << "\n";
1945       }
1946       return OS;
1947     }
1948 
1949     /// Debug print.
1950     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1951 #endif
1952   };
1953 
1954   /// Checks if the instruction is marked for deletion.
1955   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1956 
1957   /// Marks values operands for later deletion by replacing them with Undefs.
1958   void eraseInstructions(ArrayRef<Value *> AV);
1959 
1960   ~BoUpSLP();
1961 
1962 private:
1963   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1964   /// reordering (i.e. the operands can be reordered because they have only one
1965   /// user and reordarable).
1966   /// \param NonVectorized List of all gather nodes that require reordering
1967   /// (e.g., gather of extractlements or partially vectorizable loads).
1968   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1969   /// reordering, subset of \p NonVectorized.
1970   bool
1971   canReorderOperands(TreeEntry *UserTE,
1972                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1973                      ArrayRef<TreeEntry *> ReorderableGathers,
1974                      SmallVectorImpl<TreeEntry *> &GatherOps);
1975 
1976   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1977   /// if any. If it is not vectorized (gather node), returns nullptr.
1978   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1979     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1980     TreeEntry *TE = nullptr;
1981     const auto *It = find_if(VL, [this, &TE](Value *V) {
1982       TE = getTreeEntry(V);
1983       return TE;
1984     });
1985     if (It != VL.end() && TE->isSame(VL))
1986       return TE;
1987     return nullptr;
1988   }
1989 
1990   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1991   /// if any. If it is not vectorized (gather node), returns nullptr.
1992   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1993                                         unsigned OpIdx) const {
1994     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1995         const_cast<TreeEntry *>(UserTE), OpIdx);
1996   }
1997 
1998   /// Checks if all users of \p I are the part of the vectorization tree.
1999   bool areAllUsersVectorized(Instruction *I,
2000                              ArrayRef<Value *> VectorizedVals) const;
2001 
2002   /// \returns the cost of the vectorizable entry.
2003   InstructionCost getEntryCost(const TreeEntry *E,
2004                                ArrayRef<Value *> VectorizedVals);
2005 
2006   /// This is the recursive part of buildTree.
2007   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2008                      const EdgeInfo &EI);
2009 
2010   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2011   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2012   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2013   /// returns false, setting \p CurrentOrder to either an empty vector or a
2014   /// non-identity permutation that allows to reuse extract instructions.
2015   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2016                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2017 
2018   /// Vectorize a single entry in the tree.
2019   Value *vectorizeTree(TreeEntry *E);
2020 
2021   /// Vectorize a single entry in the tree, starting in \p VL.
2022   Value *vectorizeTree(ArrayRef<Value *> VL);
2023 
2024   /// Create a new vector from a list of scalar values.  Produces a sequence
2025   /// which exploits values reused across lanes, and arranges the inserts
2026   /// for ease of later optimization.
2027   Value *createBuildVector(ArrayRef<Value *> VL);
2028 
2029   /// \returns the scalarization cost for this type. Scalarization in this
2030   /// context means the creation of vectors from a group of scalars. If \p
2031   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2032   /// vector elements.
2033   InstructionCost getGatherCost(FixedVectorType *Ty,
2034                                 const APInt &ShuffledIndices,
2035                                 bool NeedToShuffle) const;
2036 
2037   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2038   /// tree entries.
2039   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2040   /// previous tree entries. \p Mask is filled with the shuffle mask.
2041   Optional<TargetTransformInfo::ShuffleKind>
2042   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2043                         SmallVectorImpl<const TreeEntry *> &Entries);
2044 
2045   /// \returns the scalarization cost for this list of values. Assuming that
2046   /// this subtree gets vectorized, we may need to extract the values from the
2047   /// roots. This method calculates the cost of extracting the values.
2048   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2049 
2050   /// Set the Builder insert point to one after the last instruction in
2051   /// the bundle
2052   void setInsertPointAfterBundle(const TreeEntry *E);
2053 
2054   /// \returns a vector from a collection of scalars in \p VL.
2055   Value *gather(ArrayRef<Value *> VL);
2056 
2057   /// \returns whether the VectorizableTree is fully vectorizable and will
2058   /// be beneficial even the tree height is tiny.
2059   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2060 
2061   /// Reorder commutative or alt operands to get better probability of
2062   /// generating vectorized code.
2063   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2064                                              SmallVectorImpl<Value *> &Left,
2065                                              SmallVectorImpl<Value *> &Right,
2066                                              const DataLayout &DL,
2067                                              ScalarEvolution &SE,
2068                                              const BoUpSLP &R);
2069   struct TreeEntry {
2070     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2071     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2072 
2073     /// \returns true if the scalars in VL are equal to this entry.
2074     bool isSame(ArrayRef<Value *> VL) const {
2075       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2076         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2077           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2078         return VL.size() == Mask.size() &&
2079                std::equal(VL.begin(), VL.end(), Mask.begin(),
2080                           [Scalars](Value *V, int Idx) {
2081                             return (isa<UndefValue>(V) &&
2082                                     Idx == UndefMaskElem) ||
2083                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2084                           });
2085       };
2086       if (!ReorderIndices.empty()) {
2087         // TODO: implement matching if the nodes are just reordered, still can
2088         // treat the vector as the same if the list of scalars matches VL
2089         // directly, without reordering.
2090         SmallVector<int> Mask;
2091         inversePermutation(ReorderIndices, Mask);
2092         if (VL.size() == Scalars.size())
2093           return IsSame(Scalars, Mask);
2094         if (VL.size() == ReuseShuffleIndices.size()) {
2095           ::addMask(Mask, ReuseShuffleIndices);
2096           return IsSame(Scalars, Mask);
2097         }
2098         return false;
2099       }
2100       return IsSame(Scalars, ReuseShuffleIndices);
2101     }
2102 
2103     /// \returns true if current entry has same operands as \p TE.
2104     bool hasEqualOperands(const TreeEntry &TE) const {
2105       if (TE.getNumOperands() != getNumOperands())
2106         return false;
2107       SmallBitVector Used(getNumOperands());
2108       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2109         unsigned PrevCount = Used.count();
2110         for (unsigned K = 0; K < E; ++K) {
2111           if (Used.test(K))
2112             continue;
2113           if (getOperand(K) == TE.getOperand(I)) {
2114             Used.set(K);
2115             break;
2116           }
2117         }
2118         // Check if we actually found the matching operand.
2119         if (PrevCount == Used.count())
2120           return false;
2121       }
2122       return true;
2123     }
2124 
2125     /// \return Final vectorization factor for the node. Defined by the total
2126     /// number of vectorized scalars, including those, used several times in the
2127     /// entry and counted in the \a ReuseShuffleIndices, if any.
2128     unsigned getVectorFactor() const {
2129       if (!ReuseShuffleIndices.empty())
2130         return ReuseShuffleIndices.size();
2131       return Scalars.size();
2132     };
2133 
2134     /// A vector of scalars.
2135     ValueList Scalars;
2136 
2137     /// The Scalars are vectorized into this value. It is initialized to Null.
2138     Value *VectorizedValue = nullptr;
2139 
2140     /// Do we need to gather this sequence or vectorize it
2141     /// (either with vector instruction or with scatter/gather
2142     /// intrinsics for store/load)?
2143     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2144     EntryState State;
2145 
2146     /// Does this sequence require some shuffling?
2147     SmallVector<int, 4> ReuseShuffleIndices;
2148 
2149     /// Does this entry require reordering?
2150     SmallVector<unsigned, 4> ReorderIndices;
2151 
2152     /// Points back to the VectorizableTree.
2153     ///
2154     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2155     /// to be a pointer and needs to be able to initialize the child iterator.
2156     /// Thus we need a reference back to the container to translate the indices
2157     /// to entries.
2158     VecTreeTy &Container;
2159 
2160     /// The TreeEntry index containing the user of this entry.  We can actually
2161     /// have multiple users so the data structure is not truly a tree.
2162     SmallVector<EdgeInfo, 1> UserTreeIndices;
2163 
2164     /// The index of this treeEntry in VectorizableTree.
2165     int Idx = -1;
2166 
2167   private:
2168     /// The operands of each instruction in each lane Operands[op_index][lane].
2169     /// Note: This helps avoid the replication of the code that performs the
2170     /// reordering of operands during buildTree_rec() and vectorizeTree().
2171     SmallVector<ValueList, 2> Operands;
2172 
2173     /// The main/alternate instruction.
2174     Instruction *MainOp = nullptr;
2175     Instruction *AltOp = nullptr;
2176 
2177   public:
2178     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2179     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2180       if (Operands.size() < OpIdx + 1)
2181         Operands.resize(OpIdx + 1);
2182       assert(Operands[OpIdx].empty() && "Already resized?");
2183       assert(OpVL.size() <= Scalars.size() &&
2184              "Number of operands is greater than the number of scalars.");
2185       Operands[OpIdx].resize(OpVL.size());
2186       copy(OpVL, Operands[OpIdx].begin());
2187     }
2188 
2189     /// Set the operands of this bundle in their original order.
2190     void setOperandsInOrder() {
2191       assert(Operands.empty() && "Already initialized?");
2192       auto *I0 = cast<Instruction>(Scalars[0]);
2193       Operands.resize(I0->getNumOperands());
2194       unsigned NumLanes = Scalars.size();
2195       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2196            OpIdx != NumOperands; ++OpIdx) {
2197         Operands[OpIdx].resize(NumLanes);
2198         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2199           auto *I = cast<Instruction>(Scalars[Lane]);
2200           assert(I->getNumOperands() == NumOperands &&
2201                  "Expected same number of operands");
2202           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2203         }
2204       }
2205     }
2206 
2207     /// Reorders operands of the node to the given mask \p Mask.
2208     void reorderOperands(ArrayRef<int> Mask) {
2209       for (ValueList &Operand : Operands)
2210         reorderScalars(Operand, Mask);
2211     }
2212 
2213     /// \returns the \p OpIdx operand of this TreeEntry.
2214     ValueList &getOperand(unsigned OpIdx) {
2215       assert(OpIdx < Operands.size() && "Off bounds");
2216       return Operands[OpIdx];
2217     }
2218 
2219     /// \returns the \p OpIdx operand of this TreeEntry.
2220     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2221       assert(OpIdx < Operands.size() && "Off bounds");
2222       return Operands[OpIdx];
2223     }
2224 
2225     /// \returns the number of operands.
2226     unsigned getNumOperands() const { return Operands.size(); }
2227 
2228     /// \return the single \p OpIdx operand.
2229     Value *getSingleOperand(unsigned OpIdx) const {
2230       assert(OpIdx < Operands.size() && "Off bounds");
2231       assert(!Operands[OpIdx].empty() && "No operand available");
2232       return Operands[OpIdx][0];
2233     }
2234 
2235     /// Some of the instructions in the list have alternate opcodes.
2236     bool isAltShuffle() const { return MainOp != AltOp; }
2237 
2238     bool isOpcodeOrAlt(Instruction *I) const {
2239       unsigned CheckedOpcode = I->getOpcode();
2240       return (getOpcode() == CheckedOpcode ||
2241               getAltOpcode() == CheckedOpcode);
2242     }
2243 
2244     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2245     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2246     /// \p OpValue.
2247     Value *isOneOf(Value *Op) const {
2248       auto *I = dyn_cast<Instruction>(Op);
2249       if (I && isOpcodeOrAlt(I))
2250         return Op;
2251       return MainOp;
2252     }
2253 
2254     void setOperations(const InstructionsState &S) {
2255       MainOp = S.MainOp;
2256       AltOp = S.AltOp;
2257     }
2258 
2259     Instruction *getMainOp() const {
2260       return MainOp;
2261     }
2262 
2263     Instruction *getAltOp() const {
2264       return AltOp;
2265     }
2266 
2267     /// The main/alternate opcodes for the list of instructions.
2268     unsigned getOpcode() const {
2269       return MainOp ? MainOp->getOpcode() : 0;
2270     }
2271 
2272     unsigned getAltOpcode() const {
2273       return AltOp ? AltOp->getOpcode() : 0;
2274     }
2275 
2276     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2277     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2278     int findLaneForValue(Value *V) const {
2279       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2280       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2281       if (!ReorderIndices.empty())
2282         FoundLane = ReorderIndices[FoundLane];
2283       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2284       if (!ReuseShuffleIndices.empty()) {
2285         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2286                                   find(ReuseShuffleIndices, FoundLane));
2287       }
2288       return FoundLane;
2289     }
2290 
2291 #ifndef NDEBUG
2292     /// Debug printer.
2293     LLVM_DUMP_METHOD void dump() const {
2294       dbgs() << Idx << ".\n";
2295       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2296         dbgs() << "Operand " << OpI << ":\n";
2297         for (const Value *V : Operands[OpI])
2298           dbgs().indent(2) << *V << "\n";
2299       }
2300       dbgs() << "Scalars: \n";
2301       for (Value *V : Scalars)
2302         dbgs().indent(2) << *V << "\n";
2303       dbgs() << "State: ";
2304       switch (State) {
2305       case Vectorize:
2306         dbgs() << "Vectorize\n";
2307         break;
2308       case ScatterVectorize:
2309         dbgs() << "ScatterVectorize\n";
2310         break;
2311       case NeedToGather:
2312         dbgs() << "NeedToGather\n";
2313         break;
2314       }
2315       dbgs() << "MainOp: ";
2316       if (MainOp)
2317         dbgs() << *MainOp << "\n";
2318       else
2319         dbgs() << "NULL\n";
2320       dbgs() << "AltOp: ";
2321       if (AltOp)
2322         dbgs() << *AltOp << "\n";
2323       else
2324         dbgs() << "NULL\n";
2325       dbgs() << "VectorizedValue: ";
2326       if (VectorizedValue)
2327         dbgs() << *VectorizedValue << "\n";
2328       else
2329         dbgs() << "NULL\n";
2330       dbgs() << "ReuseShuffleIndices: ";
2331       if (ReuseShuffleIndices.empty())
2332         dbgs() << "Empty";
2333       else
2334         for (int ReuseIdx : ReuseShuffleIndices)
2335           dbgs() << ReuseIdx << ", ";
2336       dbgs() << "\n";
2337       dbgs() << "ReorderIndices: ";
2338       for (unsigned ReorderIdx : ReorderIndices)
2339         dbgs() << ReorderIdx << ", ";
2340       dbgs() << "\n";
2341       dbgs() << "UserTreeIndices: ";
2342       for (const auto &EInfo : UserTreeIndices)
2343         dbgs() << EInfo << ", ";
2344       dbgs() << "\n";
2345     }
2346 #endif
2347   };
2348 
2349 #ifndef NDEBUG
2350   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2351                      InstructionCost VecCost,
2352                      InstructionCost ScalarCost) const {
2353     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2354     dbgs() << "SLP: Costs:\n";
2355     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2356     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2357     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2358     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2359                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2360   }
2361 #endif
2362 
2363   /// Create a new VectorizableTree entry.
2364   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2365                           const InstructionsState &S,
2366                           const EdgeInfo &UserTreeIdx,
2367                           ArrayRef<int> ReuseShuffleIndices = None,
2368                           ArrayRef<unsigned> ReorderIndices = None) {
2369     TreeEntry::EntryState EntryState =
2370         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2371     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2372                         ReuseShuffleIndices, ReorderIndices);
2373   }
2374 
2375   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2376                           TreeEntry::EntryState EntryState,
2377                           Optional<ScheduleData *> Bundle,
2378                           const InstructionsState &S,
2379                           const EdgeInfo &UserTreeIdx,
2380                           ArrayRef<int> ReuseShuffleIndices = None,
2381                           ArrayRef<unsigned> ReorderIndices = None) {
2382     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2383             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2384            "Need to vectorize gather entry?");
2385     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2386     TreeEntry *Last = VectorizableTree.back().get();
2387     Last->Idx = VectorizableTree.size() - 1;
2388     Last->State = EntryState;
2389     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2390                                      ReuseShuffleIndices.end());
2391     if (ReorderIndices.empty()) {
2392       Last->Scalars.assign(VL.begin(), VL.end());
2393       Last->setOperations(S);
2394     } else {
2395       // Reorder scalars and build final mask.
2396       Last->Scalars.assign(VL.size(), nullptr);
2397       transform(ReorderIndices, Last->Scalars.begin(),
2398                 [VL](unsigned Idx) -> Value * {
2399                   if (Idx >= VL.size())
2400                     return UndefValue::get(VL.front()->getType());
2401                   return VL[Idx];
2402                 });
2403       InstructionsState S = getSameOpcode(Last->Scalars);
2404       Last->setOperations(S);
2405       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2406     }
2407     if (Last->State != TreeEntry::NeedToGather) {
2408       for (Value *V : VL) {
2409         assert(!getTreeEntry(V) && "Scalar already in tree!");
2410         ScalarToTreeEntry[V] = Last;
2411       }
2412       // Update the scheduler bundle to point to this TreeEntry.
2413       ScheduleData *BundleMember = Bundle.getValue();
2414       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2415               isVectorLikeInstWithConstOps(S.MainOp) ||
2416               doesNotNeedToSchedule(VL)) &&
2417              "Bundle and VL out of sync");
2418       if (BundleMember) {
2419         for (Value *V : VL) {
2420           if (doesNotNeedToBeScheduled(V))
2421             continue;
2422           assert(BundleMember && "Unexpected end of bundle.");
2423           BundleMember->TE = Last;
2424           BundleMember = BundleMember->NextInBundle;
2425         }
2426       }
2427       assert(!BundleMember && "Bundle and VL out of sync");
2428     } else {
2429       MustGather.insert(VL.begin(), VL.end());
2430     }
2431 
2432     if (UserTreeIdx.UserTE)
2433       Last->UserTreeIndices.push_back(UserTreeIdx);
2434 
2435     return Last;
2436   }
2437 
2438   /// -- Vectorization State --
2439   /// Holds all of the tree entries.
2440   TreeEntry::VecTreeTy VectorizableTree;
2441 
2442 #ifndef NDEBUG
2443   /// Debug printer.
2444   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2445     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2446       VectorizableTree[Id]->dump();
2447       dbgs() << "\n";
2448     }
2449   }
2450 #endif
2451 
2452   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2453 
2454   const TreeEntry *getTreeEntry(Value *V) const {
2455     return ScalarToTreeEntry.lookup(V);
2456   }
2457 
2458   /// Maps a specific scalar to its tree entry.
2459   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2460 
2461   /// Maps a value to the proposed vectorizable size.
2462   SmallDenseMap<Value *, unsigned> InstrElementSize;
2463 
2464   /// A list of scalars that we found that we need to keep as scalars.
2465   ValueSet MustGather;
2466 
2467   /// This POD struct describes one external user in the vectorized tree.
2468   struct ExternalUser {
2469     ExternalUser(Value *S, llvm::User *U, int L)
2470         : Scalar(S), User(U), Lane(L) {}
2471 
2472     // Which scalar in our function.
2473     Value *Scalar;
2474 
2475     // Which user that uses the scalar.
2476     llvm::User *User;
2477 
2478     // Which lane does the scalar belong to.
2479     int Lane;
2480   };
2481   using UserList = SmallVector<ExternalUser, 16>;
2482 
2483   /// Checks if two instructions may access the same memory.
2484   ///
2485   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2486   /// is invariant in the calling loop.
2487   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2488                  Instruction *Inst2) {
2489     // First check if the result is already in the cache.
2490     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2491     Optional<bool> &result = AliasCache[key];
2492     if (result.hasValue()) {
2493       return result.getValue();
2494     }
2495     bool aliased = true;
2496     if (Loc1.Ptr && isSimple(Inst1))
2497       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2498     // Store the result in the cache.
2499     result = aliased;
2500     return aliased;
2501   }
2502 
2503   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2504 
2505   /// Cache for alias results.
2506   /// TODO: consider moving this to the AliasAnalysis itself.
2507   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2508 
2509   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2510   // globally through SLP because we don't perform any action which
2511   // invalidates capture results.
2512   BatchAAResults BatchAA;
2513 
2514   /// Removes an instruction from its block and eventually deletes it.
2515   /// It's like Instruction::eraseFromParent() except that the actual deletion
2516   /// is delayed until BoUpSLP is destructed.
2517   /// This is required to ensure that there are no incorrect collisions in the
2518   /// AliasCache, which can happen if a new instruction is allocated at the
2519   /// same address as a previously deleted instruction.
2520   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2521     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2522     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2523   }
2524 
2525   /// Temporary store for deleted instructions. Instructions will be deleted
2526   /// eventually when the BoUpSLP is destructed.
2527   DenseMap<Instruction *, bool> DeletedInstructions;
2528 
2529   /// A list of values that need to extracted out of the tree.
2530   /// This list holds pairs of (Internal Scalar : External User). External User
2531   /// can be nullptr, it means that this Internal Scalar will be used later,
2532   /// after vectorization.
2533   UserList ExternalUses;
2534 
2535   /// Values used only by @llvm.assume calls.
2536   SmallPtrSet<const Value *, 32> EphValues;
2537 
2538   /// Holds all of the instructions that we gathered.
2539   SetVector<Instruction *> GatherShuffleSeq;
2540 
2541   /// A list of blocks that we are going to CSE.
2542   SetVector<BasicBlock *> CSEBlocks;
2543 
2544   /// Contains all scheduling relevant data for an instruction.
2545   /// A ScheduleData either represents a single instruction or a member of an
2546   /// instruction bundle (= a group of instructions which is combined into a
2547   /// vector instruction).
2548   struct ScheduleData {
2549     // The initial value for the dependency counters. It means that the
2550     // dependencies are not calculated yet.
2551     enum { InvalidDeps = -1 };
2552 
2553     ScheduleData() = default;
2554 
2555     void init(int BlockSchedulingRegionID, Value *OpVal) {
2556       FirstInBundle = this;
2557       NextInBundle = nullptr;
2558       NextLoadStore = nullptr;
2559       IsScheduled = false;
2560       SchedulingRegionID = BlockSchedulingRegionID;
2561       clearDependencies();
2562       OpValue = OpVal;
2563       TE = nullptr;
2564     }
2565 
2566     /// Verify basic self consistency properties
2567     void verify() {
2568       if (hasValidDependencies()) {
2569         assert(UnscheduledDeps <= Dependencies && "invariant");
2570       } else {
2571         assert(UnscheduledDeps == Dependencies && "invariant");
2572       }
2573 
2574       if (IsScheduled) {
2575         assert(isSchedulingEntity() &&
2576                 "unexpected scheduled state");
2577         for (const ScheduleData *BundleMember = this; BundleMember;
2578              BundleMember = BundleMember->NextInBundle) {
2579           assert(BundleMember->hasValidDependencies() &&
2580                  BundleMember->UnscheduledDeps == 0 &&
2581                  "unexpected scheduled state");
2582           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2583                  "only bundle is marked scheduled");
2584         }
2585       }
2586 
2587       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2588              "all bundle members must be in same basic block");
2589     }
2590 
2591     /// Returns true if the dependency information has been calculated.
2592     /// Note that depenendency validity can vary between instructions within
2593     /// a single bundle.
2594     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2595 
2596     /// Returns true for single instructions and for bundle representatives
2597     /// (= the head of a bundle).
2598     bool isSchedulingEntity() const { return FirstInBundle == this; }
2599 
2600     /// Returns true if it represents an instruction bundle and not only a
2601     /// single instruction.
2602     bool isPartOfBundle() const {
2603       return NextInBundle != nullptr || FirstInBundle != this || TE;
2604     }
2605 
2606     /// Returns true if it is ready for scheduling, i.e. it has no more
2607     /// unscheduled depending instructions/bundles.
2608     bool isReady() const {
2609       assert(isSchedulingEntity() &&
2610              "can't consider non-scheduling entity for ready list");
2611       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2612     }
2613 
2614     /// Modifies the number of unscheduled dependencies for this instruction,
2615     /// and returns the number of remaining dependencies for the containing
2616     /// bundle.
2617     int incrementUnscheduledDeps(int Incr) {
2618       assert(hasValidDependencies() &&
2619              "increment of unscheduled deps would be meaningless");
2620       UnscheduledDeps += Incr;
2621       return FirstInBundle->unscheduledDepsInBundle();
2622     }
2623 
2624     /// Sets the number of unscheduled dependencies to the number of
2625     /// dependencies.
2626     void resetUnscheduledDeps() {
2627       UnscheduledDeps = Dependencies;
2628     }
2629 
2630     /// Clears all dependency information.
2631     void clearDependencies() {
2632       Dependencies = InvalidDeps;
2633       resetUnscheduledDeps();
2634       MemoryDependencies.clear();
2635     }
2636 
2637     int unscheduledDepsInBundle() const {
2638       assert(isSchedulingEntity() && "only meaningful on the bundle");
2639       int Sum = 0;
2640       for (const ScheduleData *BundleMember = this; BundleMember;
2641            BundleMember = BundleMember->NextInBundle) {
2642         if (BundleMember->UnscheduledDeps == InvalidDeps)
2643           return InvalidDeps;
2644         Sum += BundleMember->UnscheduledDeps;
2645       }
2646       return Sum;
2647     }
2648 
2649     void dump(raw_ostream &os) const {
2650       if (!isSchedulingEntity()) {
2651         os << "/ " << *Inst;
2652       } else if (NextInBundle) {
2653         os << '[' << *Inst;
2654         ScheduleData *SD = NextInBundle;
2655         while (SD) {
2656           os << ';' << *SD->Inst;
2657           SD = SD->NextInBundle;
2658         }
2659         os << ']';
2660       } else {
2661         os << *Inst;
2662       }
2663     }
2664 
2665     Instruction *Inst = nullptr;
2666 
2667     /// Opcode of the current instruction in the schedule data.
2668     Value *OpValue = nullptr;
2669 
2670     /// The TreeEntry that this instruction corresponds to.
2671     TreeEntry *TE = nullptr;
2672 
2673     /// Points to the head in an instruction bundle (and always to this for
2674     /// single instructions).
2675     ScheduleData *FirstInBundle = nullptr;
2676 
2677     /// Single linked list of all instructions in a bundle. Null if it is a
2678     /// single instruction.
2679     ScheduleData *NextInBundle = nullptr;
2680 
2681     /// Single linked list of all memory instructions (e.g. load, store, call)
2682     /// in the block - until the end of the scheduling region.
2683     ScheduleData *NextLoadStore = nullptr;
2684 
2685     /// The dependent memory instructions.
2686     /// This list is derived on demand in calculateDependencies().
2687     SmallVector<ScheduleData *, 4> MemoryDependencies;
2688 
2689     /// This ScheduleData is in the current scheduling region if this matches
2690     /// the current SchedulingRegionID of BlockScheduling.
2691     int SchedulingRegionID = 0;
2692 
2693     /// Used for getting a "good" final ordering of instructions.
2694     int SchedulingPriority = 0;
2695 
2696     /// The number of dependencies. Constitutes of the number of users of the
2697     /// instruction plus the number of dependent memory instructions (if any).
2698     /// This value is calculated on demand.
2699     /// If InvalidDeps, the number of dependencies is not calculated yet.
2700     int Dependencies = InvalidDeps;
2701 
2702     /// The number of dependencies minus the number of dependencies of scheduled
2703     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2704     /// for scheduling.
2705     /// Note that this is negative as long as Dependencies is not calculated.
2706     int UnscheduledDeps = InvalidDeps;
2707 
2708     /// True if this instruction is scheduled (or considered as scheduled in the
2709     /// dry-run).
2710     bool IsScheduled = false;
2711   };
2712 
2713 #ifndef NDEBUG
2714   friend inline raw_ostream &operator<<(raw_ostream &os,
2715                                         const BoUpSLP::ScheduleData &SD) {
2716     SD.dump(os);
2717     return os;
2718   }
2719 #endif
2720 
2721   friend struct GraphTraits<BoUpSLP *>;
2722   friend struct DOTGraphTraits<BoUpSLP *>;
2723 
2724   /// Contains all scheduling data for a basic block.
2725   /// It does not schedules instructions, which are not memory read/write
2726   /// instructions and their operands are either constants, or arguments, or
2727   /// phis, or instructions from others blocks, or their users are phis or from
2728   /// the other blocks. The resulting vector instructions can be placed at the
2729   /// beginning of the basic block without scheduling (if operands does not need
2730   /// to be scheduled) or at the end of the block (if users are outside of the
2731   /// block). It allows to save some compile time and memory used by the
2732   /// compiler.
2733   /// ScheduleData is assigned for each instruction in between the boundaries of
2734   /// the tree entry, even for those, which are not part of the graph. It is
2735   /// required to correctly follow the dependencies between the instructions and
2736   /// their correct scheduling. The ScheduleData is not allocated for the
2737   /// instructions, which do not require scheduling, like phis, nodes with
2738   /// extractelements/insertelements only or nodes with instructions, with
2739   /// uses/operands outside of the block.
2740   struct BlockScheduling {
2741     BlockScheduling(BasicBlock *BB)
2742         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2743 
2744     void clear() {
2745       ReadyInsts.clear();
2746       ScheduleStart = nullptr;
2747       ScheduleEnd = nullptr;
2748       FirstLoadStoreInRegion = nullptr;
2749       LastLoadStoreInRegion = nullptr;
2750 
2751       // Reduce the maximum schedule region size by the size of the
2752       // previous scheduling run.
2753       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2754       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2755         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2756       ScheduleRegionSize = 0;
2757 
2758       // Make a new scheduling region, i.e. all existing ScheduleData is not
2759       // in the new region yet.
2760       ++SchedulingRegionID;
2761     }
2762 
2763     ScheduleData *getScheduleData(Instruction *I) {
2764       if (BB != I->getParent())
2765         // Avoid lookup if can't possibly be in map.
2766         return nullptr;
2767       ScheduleData *SD = ScheduleDataMap.lookup(I);
2768       if (SD && isInSchedulingRegion(SD))
2769         return SD;
2770       return nullptr;
2771     }
2772 
2773     ScheduleData *getScheduleData(Value *V) {
2774       if (auto *I = dyn_cast<Instruction>(V))
2775         return getScheduleData(I);
2776       return nullptr;
2777     }
2778 
2779     ScheduleData *getScheduleData(Value *V, Value *Key) {
2780       if (V == Key)
2781         return getScheduleData(V);
2782       auto I = ExtraScheduleDataMap.find(V);
2783       if (I != ExtraScheduleDataMap.end()) {
2784         ScheduleData *SD = I->second.lookup(Key);
2785         if (SD && isInSchedulingRegion(SD))
2786           return SD;
2787       }
2788       return nullptr;
2789     }
2790 
2791     bool isInSchedulingRegion(ScheduleData *SD) const {
2792       return SD->SchedulingRegionID == SchedulingRegionID;
2793     }
2794 
2795     /// Marks an instruction as scheduled and puts all dependent ready
2796     /// instructions into the ready-list.
2797     template <typename ReadyListType>
2798     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2799       SD->IsScheduled = true;
2800       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2801 
2802       for (ScheduleData *BundleMember = SD; BundleMember;
2803            BundleMember = BundleMember->NextInBundle) {
2804         if (BundleMember->Inst != BundleMember->OpValue)
2805           continue;
2806 
2807         // Handle the def-use chain dependencies.
2808 
2809         // Decrement the unscheduled counter and insert to ready list if ready.
2810         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2811           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2812             if (OpDef && OpDef->hasValidDependencies() &&
2813                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2814               // There are no more unscheduled dependencies after
2815               // decrementing, so we can put the dependent instruction
2816               // into the ready list.
2817               ScheduleData *DepBundle = OpDef->FirstInBundle;
2818               assert(!DepBundle->IsScheduled &&
2819                      "already scheduled bundle gets ready");
2820               ReadyList.insert(DepBundle);
2821               LLVM_DEBUG(dbgs()
2822                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2823             }
2824           });
2825         };
2826 
2827         // If BundleMember is a vector bundle, its operands may have been
2828         // reordered during buildTree(). We therefore need to get its operands
2829         // through the TreeEntry.
2830         if (TreeEntry *TE = BundleMember->TE) {
2831           // Need to search for the lane since the tree entry can be reordered.
2832           int Lane = std::distance(TE->Scalars.begin(),
2833                                    find(TE->Scalars, BundleMember->Inst));
2834           assert(Lane >= 0 && "Lane not set");
2835 
2836           // Since vectorization tree is being built recursively this assertion
2837           // ensures that the tree entry has all operands set before reaching
2838           // this code. Couple of exceptions known at the moment are extracts
2839           // where their second (immediate) operand is not added. Since
2840           // immediates do not affect scheduler behavior this is considered
2841           // okay.
2842           auto *In = BundleMember->Inst;
2843           assert(In &&
2844                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2845                   In->getNumOperands() == TE->getNumOperands()) &&
2846                  "Missed TreeEntry operands?");
2847           (void)In; // fake use to avoid build failure when assertions disabled
2848 
2849           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2850                OpIdx != NumOperands; ++OpIdx)
2851             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2852               DecrUnsched(I);
2853         } else {
2854           // If BundleMember is a stand-alone instruction, no operand reordering
2855           // has taken place, so we directly access its operands.
2856           for (Use &U : BundleMember->Inst->operands())
2857             if (auto *I = dyn_cast<Instruction>(U.get()))
2858               DecrUnsched(I);
2859         }
2860         // Handle the memory dependencies.
2861         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2862           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2863             // There are no more unscheduled dependencies after decrementing,
2864             // so we can put the dependent instruction into the ready list.
2865             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2866             assert(!DepBundle->IsScheduled &&
2867                    "already scheduled bundle gets ready");
2868             ReadyList.insert(DepBundle);
2869             LLVM_DEBUG(dbgs()
2870                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2871           }
2872         }
2873       }
2874     }
2875 
2876     /// Verify basic self consistency properties of the data structure.
2877     void verify() {
2878       if (!ScheduleStart)
2879         return;
2880 
2881       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2882              ScheduleStart->comesBefore(ScheduleEnd) &&
2883              "Not a valid scheduling region?");
2884 
2885       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2886         auto *SD = getScheduleData(I);
2887         if (!SD)
2888           continue;
2889         assert(isInSchedulingRegion(SD) &&
2890                "primary schedule data not in window?");
2891         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2892                "entire bundle in window!");
2893         (void)SD;
2894         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2895       }
2896 
2897       for (auto *SD : ReadyInsts) {
2898         assert(SD->isSchedulingEntity() && SD->isReady() &&
2899                "item in ready list not ready?");
2900         (void)SD;
2901       }
2902     }
2903 
2904     void doForAllOpcodes(Value *V,
2905                          function_ref<void(ScheduleData *SD)> Action) {
2906       if (ScheduleData *SD = getScheduleData(V))
2907         Action(SD);
2908       auto I = ExtraScheduleDataMap.find(V);
2909       if (I != ExtraScheduleDataMap.end())
2910         for (auto &P : I->second)
2911           if (isInSchedulingRegion(P.second))
2912             Action(P.second);
2913     }
2914 
2915     /// Put all instructions into the ReadyList which are ready for scheduling.
2916     template <typename ReadyListType>
2917     void initialFillReadyList(ReadyListType &ReadyList) {
2918       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2919         doForAllOpcodes(I, [&](ScheduleData *SD) {
2920           if (SD->isSchedulingEntity() && SD->isReady()) {
2921             ReadyList.insert(SD);
2922             LLVM_DEBUG(dbgs()
2923                        << "SLP:    initially in ready list: " << *SD << "\n");
2924           }
2925         });
2926       }
2927     }
2928 
2929     /// Build a bundle from the ScheduleData nodes corresponding to the
2930     /// scalar instruction for each lane.
2931     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2932 
2933     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2934     /// cyclic dependencies. This is only a dry-run, no instructions are
2935     /// actually moved at this stage.
2936     /// \returns the scheduling bundle. The returned Optional value is non-None
2937     /// if \p VL is allowed to be scheduled.
2938     Optional<ScheduleData *>
2939     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2940                       const InstructionsState &S);
2941 
2942     /// Un-bundles a group of instructions.
2943     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2944 
2945     /// Allocates schedule data chunk.
2946     ScheduleData *allocateScheduleDataChunks();
2947 
2948     /// Extends the scheduling region so that V is inside the region.
2949     /// \returns true if the region size is within the limit.
2950     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2951 
2952     /// Initialize the ScheduleData structures for new instructions in the
2953     /// scheduling region.
2954     void initScheduleData(Instruction *FromI, Instruction *ToI,
2955                           ScheduleData *PrevLoadStore,
2956                           ScheduleData *NextLoadStore);
2957 
2958     /// Updates the dependency information of a bundle and of all instructions/
2959     /// bundles which depend on the original bundle.
2960     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2961                                BoUpSLP *SLP);
2962 
2963     /// Sets all instruction in the scheduling region to un-scheduled.
2964     void resetSchedule();
2965 
2966     BasicBlock *BB;
2967 
2968     /// Simple memory allocation for ScheduleData.
2969     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2970 
2971     /// The size of a ScheduleData array in ScheduleDataChunks.
2972     int ChunkSize;
2973 
2974     /// The allocator position in the current chunk, which is the last entry
2975     /// of ScheduleDataChunks.
2976     int ChunkPos;
2977 
2978     /// Attaches ScheduleData to Instruction.
2979     /// Note that the mapping survives during all vectorization iterations, i.e.
2980     /// ScheduleData structures are recycled.
2981     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2982 
2983     /// Attaches ScheduleData to Instruction with the leading key.
2984     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2985         ExtraScheduleDataMap;
2986 
2987     /// The ready-list for scheduling (only used for the dry-run).
2988     SetVector<ScheduleData *> ReadyInsts;
2989 
2990     /// The first instruction of the scheduling region.
2991     Instruction *ScheduleStart = nullptr;
2992 
2993     /// The first instruction _after_ the scheduling region.
2994     Instruction *ScheduleEnd = nullptr;
2995 
2996     /// The first memory accessing instruction in the scheduling region
2997     /// (can be null).
2998     ScheduleData *FirstLoadStoreInRegion = nullptr;
2999 
3000     /// The last memory accessing instruction in the scheduling region
3001     /// (can be null).
3002     ScheduleData *LastLoadStoreInRegion = nullptr;
3003 
3004     /// The current size of the scheduling region.
3005     int ScheduleRegionSize = 0;
3006 
3007     /// The maximum size allowed for the scheduling region.
3008     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3009 
3010     /// The ID of the scheduling region. For a new vectorization iteration this
3011     /// is incremented which "removes" all ScheduleData from the region.
3012     /// Make sure that the initial SchedulingRegionID is greater than the
3013     /// initial SchedulingRegionID in ScheduleData (which is 0).
3014     int SchedulingRegionID = 1;
3015   };
3016 
3017   /// Attaches the BlockScheduling structures to basic blocks.
3018   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3019 
3020   /// Performs the "real" scheduling. Done before vectorization is actually
3021   /// performed in a basic block.
3022   void scheduleBlock(BlockScheduling *BS);
3023 
3024   /// List of users to ignore during scheduling and that don't need extracting.
3025   ArrayRef<Value *> UserIgnoreList;
3026 
3027   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3028   /// sorted SmallVectors of unsigned.
3029   struct OrdersTypeDenseMapInfo {
3030     static OrdersType getEmptyKey() {
3031       OrdersType V;
3032       V.push_back(~1U);
3033       return V;
3034     }
3035 
3036     static OrdersType getTombstoneKey() {
3037       OrdersType V;
3038       V.push_back(~2U);
3039       return V;
3040     }
3041 
3042     static unsigned getHashValue(const OrdersType &V) {
3043       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3044     }
3045 
3046     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3047       return LHS == RHS;
3048     }
3049   };
3050 
3051   // Analysis and block reference.
3052   Function *F;
3053   ScalarEvolution *SE;
3054   TargetTransformInfo *TTI;
3055   TargetLibraryInfo *TLI;
3056   LoopInfo *LI;
3057   DominatorTree *DT;
3058   AssumptionCache *AC;
3059   DemandedBits *DB;
3060   MemorySSA *MSSA;
3061   const DataLayout *DL;
3062   OptimizationRemarkEmitter *ORE;
3063 
3064   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3065   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3066 
3067   /// Instruction builder to construct the vectorized tree.
3068   IRBuilder<> Builder;
3069 
3070   /// A map of scalar integer values to the smallest bit width with which they
3071   /// can legally be represented. The values map to (width, signed) pairs,
3072   /// where "width" indicates the minimum bit width and "signed" is True if the
3073   /// value must be signed-extended, rather than zero-extended, back to its
3074   /// original width.
3075   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3076 };
3077 
3078 } // end namespace slpvectorizer
3079 
3080 template <> struct GraphTraits<BoUpSLP *> {
3081   using TreeEntry = BoUpSLP::TreeEntry;
3082 
3083   /// NodeRef has to be a pointer per the GraphWriter.
3084   using NodeRef = TreeEntry *;
3085 
3086   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3087 
3088   /// Add the VectorizableTree to the index iterator to be able to return
3089   /// TreeEntry pointers.
3090   struct ChildIteratorType
3091       : public iterator_adaptor_base<
3092             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3093     ContainerTy &VectorizableTree;
3094 
3095     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3096                       ContainerTy &VT)
3097         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3098 
3099     NodeRef operator*() { return I->UserTE; }
3100   };
3101 
3102   static NodeRef getEntryNode(BoUpSLP &R) {
3103     return R.VectorizableTree[0].get();
3104   }
3105 
3106   static ChildIteratorType child_begin(NodeRef N) {
3107     return {N->UserTreeIndices.begin(), N->Container};
3108   }
3109 
3110   static ChildIteratorType child_end(NodeRef N) {
3111     return {N->UserTreeIndices.end(), N->Container};
3112   }
3113 
3114   /// For the node iterator we just need to turn the TreeEntry iterator into a
3115   /// TreeEntry* iterator so that it dereferences to NodeRef.
3116   class nodes_iterator {
3117     using ItTy = ContainerTy::iterator;
3118     ItTy It;
3119 
3120   public:
3121     nodes_iterator(const ItTy &It2) : It(It2) {}
3122     NodeRef operator*() { return It->get(); }
3123     nodes_iterator operator++() {
3124       ++It;
3125       return *this;
3126     }
3127     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3128   };
3129 
3130   static nodes_iterator nodes_begin(BoUpSLP *R) {
3131     return nodes_iterator(R->VectorizableTree.begin());
3132   }
3133 
3134   static nodes_iterator nodes_end(BoUpSLP *R) {
3135     return nodes_iterator(R->VectorizableTree.end());
3136   }
3137 
3138   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3139 };
3140 
3141 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3142   using TreeEntry = BoUpSLP::TreeEntry;
3143 
3144   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3145 
3146   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3147     std::string Str;
3148     raw_string_ostream OS(Str);
3149     if (isSplat(Entry->Scalars))
3150       OS << "<splat> ";
3151     for (auto V : Entry->Scalars) {
3152       OS << *V;
3153       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3154             return EU.Scalar == V;
3155           }))
3156         OS << " <extract>";
3157       OS << "\n";
3158     }
3159     return Str;
3160   }
3161 
3162   static std::string getNodeAttributes(const TreeEntry *Entry,
3163                                        const BoUpSLP *) {
3164     if (Entry->State == TreeEntry::NeedToGather)
3165       return "color=red";
3166     return "";
3167   }
3168 };
3169 
3170 } // end namespace llvm
3171 
3172 BoUpSLP::~BoUpSLP() {
3173   if (MSSA) {
3174     MemorySSAUpdater MSSAU(MSSA);
3175     for (const auto &Pair : DeletedInstructions) {
3176       if (auto *Access = MSSA->getMemoryAccess(Pair.first))
3177         MSSAU.removeMemoryAccess(Access);
3178     }
3179   }
3180   for (const auto &Pair : DeletedInstructions) {
3181     // Replace operands of ignored instructions with Undefs in case if they were
3182     // marked for deletion.
3183     if (Pair.getSecond()) {
3184       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3185       Pair.getFirst()->replaceAllUsesWith(Undef);
3186     }
3187     Pair.getFirst()->dropAllReferences();
3188   }
3189   for (const auto &Pair : DeletedInstructions) {
3190     assert(Pair.getFirst()->use_empty() &&
3191            "trying to erase instruction with users.");
3192     Pair.getFirst()->eraseFromParent();
3193   }
3194 #ifdef EXPENSIVE_CHECKS
3195   // If we could guarantee that this call is not extremely slow, we could
3196   // remove the ifdef limitation (see PR47712).
3197   assert(!verifyFunction(*F, &dbgs()));
3198 #endif
3199 }
3200 
3201 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3202   for (auto *V : AV) {
3203     if (auto *I = dyn_cast<Instruction>(V))
3204       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3205   };
3206 }
3207 
3208 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3209 /// contains original mask for the scalars reused in the node. Procedure
3210 /// transform this mask in accordance with the given \p Mask.
3211 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3212   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3213          "Expected non-empty mask.");
3214   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3215   Prev.swap(Reuses);
3216   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3217     if (Mask[I] != UndefMaskElem)
3218       Reuses[Mask[I]] = Prev[I];
3219 }
3220 
3221 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3222 /// the original order of the scalars. Procedure transforms the provided order
3223 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3224 /// identity order, \p Order is cleared.
3225 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3226   assert(!Mask.empty() && "Expected non-empty mask.");
3227   SmallVector<int> MaskOrder;
3228   if (Order.empty()) {
3229     MaskOrder.resize(Mask.size());
3230     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3231   } else {
3232     inversePermutation(Order, MaskOrder);
3233   }
3234   reorderReuses(MaskOrder, Mask);
3235   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3236     Order.clear();
3237     return;
3238   }
3239   Order.assign(Mask.size(), Mask.size());
3240   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3241     if (MaskOrder[I] != UndefMaskElem)
3242       Order[MaskOrder[I]] = I;
3243   fixupOrderingIndices(Order);
3244 }
3245 
3246 Optional<BoUpSLP::OrdersType>
3247 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3248   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3249   unsigned NumScalars = TE.Scalars.size();
3250   OrdersType CurrentOrder(NumScalars, NumScalars);
3251   SmallVector<int> Positions;
3252   SmallBitVector UsedPositions(NumScalars);
3253   const TreeEntry *STE = nullptr;
3254   // Try to find all gathered scalars that are gets vectorized in other
3255   // vectorize node. Here we can have only one single tree vector node to
3256   // correctly identify order of the gathered scalars.
3257   for (unsigned I = 0; I < NumScalars; ++I) {
3258     Value *V = TE.Scalars[I];
3259     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3260       continue;
3261     if (const auto *LocalSTE = getTreeEntry(V)) {
3262       if (!STE)
3263         STE = LocalSTE;
3264       else if (STE != LocalSTE)
3265         // Take the order only from the single vector node.
3266         return None;
3267       unsigned Lane =
3268           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3269       if (Lane >= NumScalars)
3270         return None;
3271       if (CurrentOrder[Lane] != NumScalars) {
3272         if (Lane != I)
3273           continue;
3274         UsedPositions.reset(CurrentOrder[Lane]);
3275       }
3276       // The partial identity (where only some elements of the gather node are
3277       // in the identity order) is good.
3278       CurrentOrder[Lane] = I;
3279       UsedPositions.set(I);
3280     }
3281   }
3282   // Need to keep the order if we have a vector entry and at least 2 scalars or
3283   // the vectorized entry has just 2 scalars.
3284   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3285     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3286       for (unsigned I = 0; I < NumScalars; ++I)
3287         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3288           return false;
3289       return true;
3290     };
3291     if (IsIdentityOrder(CurrentOrder)) {
3292       CurrentOrder.clear();
3293       return CurrentOrder;
3294     }
3295     auto *It = CurrentOrder.begin();
3296     for (unsigned I = 0; I < NumScalars;) {
3297       if (UsedPositions.test(I)) {
3298         ++I;
3299         continue;
3300       }
3301       if (*It == NumScalars) {
3302         *It = I;
3303         ++I;
3304       }
3305       ++It;
3306     }
3307     return CurrentOrder;
3308   }
3309   return None;
3310 }
3311 
3312 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3313                                                          bool TopToBottom) {
3314   // No need to reorder if need to shuffle reuses, still need to shuffle the
3315   // node.
3316   if (!TE.ReuseShuffleIndices.empty())
3317     return None;
3318   if (TE.State == TreeEntry::Vectorize &&
3319       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3320        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3321       !TE.isAltShuffle())
3322     return TE.ReorderIndices;
3323   if (TE.State == TreeEntry::NeedToGather) {
3324     // TODO: add analysis of other gather nodes with extractelement
3325     // instructions and other values/instructions, not only undefs.
3326     if (((TE.getOpcode() == Instruction::ExtractElement &&
3327           !TE.isAltShuffle()) ||
3328          (all_of(TE.Scalars,
3329                  [](Value *V) {
3330                    return isa<UndefValue, ExtractElementInst>(V);
3331                  }) &&
3332           any_of(TE.Scalars,
3333                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3334         all_of(TE.Scalars,
3335                [](Value *V) {
3336                  auto *EE = dyn_cast<ExtractElementInst>(V);
3337                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3338                }) &&
3339         allSameType(TE.Scalars)) {
3340       // Check that gather of extractelements can be represented as
3341       // just a shuffle of a single vector.
3342       OrdersType CurrentOrder;
3343       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3344       if (Reuse || !CurrentOrder.empty()) {
3345         if (!CurrentOrder.empty())
3346           fixupOrderingIndices(CurrentOrder);
3347         return CurrentOrder;
3348       }
3349     }
3350     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3351       return CurrentOrder;
3352   }
3353   return None;
3354 }
3355 
3356 void BoUpSLP::reorderTopToBottom() {
3357   // Maps VF to the graph nodes.
3358   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3359   // ExtractElement gather nodes which can be vectorized and need to handle
3360   // their ordering.
3361   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3362   // Find all reorderable nodes with the given VF.
3363   // Currently the are vectorized stores,loads,extracts + some gathering of
3364   // extracts.
3365   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3366                                  const std::unique_ptr<TreeEntry> &TE) {
3367     if (Optional<OrdersType> CurrentOrder =
3368             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3369       // Do not include ordering for nodes used in the alt opcode vectorization,
3370       // better to reorder them during bottom-to-top stage. If follow the order
3371       // here, it causes reordering of the whole graph though actually it is
3372       // profitable just to reorder the subgraph that starts from the alternate
3373       // opcode vectorization node. Such nodes already end-up with the shuffle
3374       // instruction and it is just enough to change this shuffle rather than
3375       // rotate the scalars for the whole graph.
3376       unsigned Cnt = 0;
3377       const TreeEntry *UserTE = TE.get();
3378       while (UserTE && Cnt < RecursionMaxDepth) {
3379         if (UserTE->UserTreeIndices.size() != 1)
3380           break;
3381         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3382               return EI.UserTE->State == TreeEntry::Vectorize &&
3383                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3384             }))
3385           return;
3386         if (UserTE->UserTreeIndices.empty())
3387           UserTE = nullptr;
3388         else
3389           UserTE = UserTE->UserTreeIndices.back().UserTE;
3390         ++Cnt;
3391       }
3392       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3393       if (TE->State != TreeEntry::Vectorize)
3394         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3395     }
3396   });
3397 
3398   // Reorder the graph nodes according to their vectorization factor.
3399   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3400        VF /= 2) {
3401     auto It = VFToOrderedEntries.find(VF);
3402     if (It == VFToOrderedEntries.end())
3403       continue;
3404     // Try to find the most profitable order. We just are looking for the most
3405     // used order and reorder scalar elements in the nodes according to this
3406     // mostly used order.
3407     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3408     // All operands are reordered and used only in this node - propagate the
3409     // most used order to the user node.
3410     MapVector<OrdersType, unsigned,
3411               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3412         OrdersUses;
3413     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3414     for (const TreeEntry *OpTE : OrderedEntries) {
3415       // No need to reorder this nodes, still need to extend and to use shuffle,
3416       // just need to merge reordering shuffle and the reuse shuffle.
3417       if (!OpTE->ReuseShuffleIndices.empty())
3418         continue;
3419       // Count number of orders uses.
3420       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3421         if (OpTE->State == TreeEntry::NeedToGather)
3422           return GathersToOrders.find(OpTE)->second;
3423         return OpTE->ReorderIndices;
3424       }();
3425       // Stores actually store the mask, not the order, need to invert.
3426       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3427           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3428         SmallVector<int> Mask;
3429         inversePermutation(Order, Mask);
3430         unsigned E = Order.size();
3431         OrdersType CurrentOrder(E, E);
3432         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3433           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3434         });
3435         fixupOrderingIndices(CurrentOrder);
3436         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3437       } else {
3438         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3439       }
3440     }
3441     // Set order of the user node.
3442     if (OrdersUses.empty())
3443       continue;
3444     // Choose the most used order.
3445     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3446     unsigned Cnt = OrdersUses.front().second;
3447     for (const auto &Pair : drop_begin(OrdersUses)) {
3448       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3449         BestOrder = Pair.first;
3450         Cnt = Pair.second;
3451       }
3452     }
3453     // Set order of the user node.
3454     if (BestOrder.empty())
3455       continue;
3456     SmallVector<int> Mask;
3457     inversePermutation(BestOrder, Mask);
3458     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3459     unsigned E = BestOrder.size();
3460     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3461       return I < E ? static_cast<int>(I) : UndefMaskElem;
3462     });
3463     // Do an actual reordering, if profitable.
3464     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3465       // Just do the reordering for the nodes with the given VF.
3466       if (TE->Scalars.size() != VF) {
3467         if (TE->ReuseShuffleIndices.size() == VF) {
3468           // Need to reorder the reuses masks of the operands with smaller VF to
3469           // be able to find the match between the graph nodes and scalar
3470           // operands of the given node during vectorization/cost estimation.
3471           assert(all_of(TE->UserTreeIndices,
3472                         [VF, &TE](const EdgeInfo &EI) {
3473                           return EI.UserTE->Scalars.size() == VF ||
3474                                  EI.UserTE->Scalars.size() ==
3475                                      TE->Scalars.size();
3476                         }) &&
3477                  "All users must be of VF size.");
3478           // Update ordering of the operands with the smaller VF than the given
3479           // one.
3480           reorderReuses(TE->ReuseShuffleIndices, Mask);
3481         }
3482         continue;
3483       }
3484       if (TE->State == TreeEntry::Vectorize &&
3485           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3486               InsertElementInst>(TE->getMainOp()) &&
3487           !TE->isAltShuffle()) {
3488         // Build correct orders for extract{element,value}, loads and
3489         // stores.
3490         reorderOrder(TE->ReorderIndices, Mask);
3491         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3492           TE->reorderOperands(Mask);
3493       } else {
3494         // Reorder the node and its operands.
3495         TE->reorderOperands(Mask);
3496         assert(TE->ReorderIndices.empty() &&
3497                "Expected empty reorder sequence.");
3498         reorderScalars(TE->Scalars, Mask);
3499       }
3500       if (!TE->ReuseShuffleIndices.empty()) {
3501         // Apply reversed order to keep the original ordering of the reused
3502         // elements to avoid extra reorder indices shuffling.
3503         OrdersType CurrentOrder;
3504         reorderOrder(CurrentOrder, MaskOrder);
3505         SmallVector<int> NewReuses;
3506         inversePermutation(CurrentOrder, NewReuses);
3507         addMask(NewReuses, TE->ReuseShuffleIndices);
3508         TE->ReuseShuffleIndices.swap(NewReuses);
3509       }
3510     }
3511   }
3512 }
3513 
3514 bool BoUpSLP::canReorderOperands(
3515     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3516     ArrayRef<TreeEntry *> ReorderableGathers,
3517     SmallVectorImpl<TreeEntry *> &GatherOps) {
3518   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3519     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3520           return OpData.first == I &&
3521                  OpData.second->State == TreeEntry::Vectorize;
3522         }))
3523       continue;
3524     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3525       // Do not reorder if operand node is used by many user nodes.
3526       if (any_of(TE->UserTreeIndices,
3527                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3528         return false;
3529       // Add the node to the list of the ordered nodes with the identity
3530       // order.
3531       Edges.emplace_back(I, TE);
3532       continue;
3533     }
3534     ArrayRef<Value *> VL = UserTE->getOperand(I);
3535     TreeEntry *Gather = nullptr;
3536     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3537           assert(TE->State != TreeEntry::Vectorize &&
3538                  "Only non-vectorized nodes are expected.");
3539           if (TE->isSame(VL)) {
3540             Gather = TE;
3541             return true;
3542           }
3543           return false;
3544         }) > 1)
3545       return false;
3546     if (Gather)
3547       GatherOps.push_back(Gather);
3548   }
3549   return true;
3550 }
3551 
3552 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3553   SetVector<TreeEntry *> OrderedEntries;
3554   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3555   // Find all reorderable leaf nodes with the given VF.
3556   // Currently the are vectorized loads,extracts without alternate operands +
3557   // some gathering of extracts.
3558   SmallVector<TreeEntry *> NonVectorized;
3559   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3560                               &NonVectorized](
3561                                  const std::unique_ptr<TreeEntry> &TE) {
3562     if (TE->State != TreeEntry::Vectorize)
3563       NonVectorized.push_back(TE.get());
3564     if (Optional<OrdersType> CurrentOrder =
3565             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3566       OrderedEntries.insert(TE.get());
3567       if (TE->State != TreeEntry::Vectorize)
3568         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3569     }
3570   });
3571 
3572   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3573   // I.e., if the node has operands, that are reordered, try to make at least
3574   // one operand order in the natural order and reorder others + reorder the
3575   // user node itself.
3576   SmallPtrSet<const TreeEntry *, 4> Visited;
3577   while (!OrderedEntries.empty()) {
3578     // 1. Filter out only reordered nodes.
3579     // 2. If the entry has multiple uses - skip it and jump to the next node.
3580     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3581     SmallVector<TreeEntry *> Filtered;
3582     for (TreeEntry *TE : OrderedEntries) {
3583       if (!(TE->State == TreeEntry::Vectorize ||
3584             (TE->State == TreeEntry::NeedToGather &&
3585              GathersToOrders.count(TE))) ||
3586           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3587           !all_of(drop_begin(TE->UserTreeIndices),
3588                   [TE](const EdgeInfo &EI) {
3589                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3590                   }) ||
3591           !Visited.insert(TE).second) {
3592         Filtered.push_back(TE);
3593         continue;
3594       }
3595       // Build a map between user nodes and their operands order to speedup
3596       // search. The graph currently does not provide this dependency directly.
3597       for (EdgeInfo &EI : TE->UserTreeIndices) {
3598         TreeEntry *UserTE = EI.UserTE;
3599         auto It = Users.find(UserTE);
3600         if (It == Users.end())
3601           It = Users.insert({UserTE, {}}).first;
3602         It->second.emplace_back(EI.EdgeIdx, TE);
3603       }
3604     }
3605     // Erase filtered entries.
3606     for_each(Filtered,
3607              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3608     for (auto &Data : Users) {
3609       // Check that operands are used only in the User node.
3610       SmallVector<TreeEntry *> GatherOps;
3611       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3612                               GatherOps)) {
3613         for_each(Data.second,
3614                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3615                    OrderedEntries.remove(Op.second);
3616                  });
3617         continue;
3618       }
3619       // All operands are reordered and used only in this node - propagate the
3620       // most used order to the user node.
3621       MapVector<OrdersType, unsigned,
3622                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3623           OrdersUses;
3624       // Do the analysis for each tree entry only once, otherwise the order of
3625       // the same node my be considered several times, though might be not
3626       // profitable.
3627       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3628       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3629       for (const auto &Op : Data.second) {
3630         TreeEntry *OpTE = Op.second;
3631         if (!VisitedOps.insert(OpTE).second)
3632           continue;
3633         if (!OpTE->ReuseShuffleIndices.empty() ||
3634             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3635           continue;
3636         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3637           if (OpTE->State == TreeEntry::NeedToGather)
3638             return GathersToOrders.find(OpTE)->second;
3639           return OpTE->ReorderIndices;
3640         }();
3641         unsigned NumOps = count_if(
3642             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3643               return P.second == OpTE;
3644             });
3645         // Stores actually store the mask, not the order, need to invert.
3646         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3647             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3648           SmallVector<int> Mask;
3649           inversePermutation(Order, Mask);
3650           unsigned E = Order.size();
3651           OrdersType CurrentOrder(E, E);
3652           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3653             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3654           });
3655           fixupOrderingIndices(CurrentOrder);
3656           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3657               NumOps;
3658         } else {
3659           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3660         }
3661         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3662         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3663                                             const TreeEntry *TE) {
3664           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3665               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3666               (IgnoreReorder && TE->Idx == 0))
3667             return true;
3668           if (TE->State == TreeEntry::NeedToGather) {
3669             auto It = GathersToOrders.find(TE);
3670             if (It != GathersToOrders.end())
3671               return !It->second.empty();
3672             return true;
3673           }
3674           return false;
3675         };
3676         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3677           TreeEntry *UserTE = EI.UserTE;
3678           if (!VisitedUsers.insert(UserTE).second)
3679             continue;
3680           // May reorder user node if it requires reordering, has reused
3681           // scalars, is an alternate op vectorize node or its op nodes require
3682           // reordering.
3683           if (AllowsReordering(UserTE))
3684             continue;
3685           // Check if users allow reordering.
3686           // Currently look up just 1 level of operands to avoid increase of
3687           // the compile time.
3688           // Profitable to reorder if definitely more operands allow
3689           // reordering rather than those with natural order.
3690           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3691           if (static_cast<unsigned>(count_if(
3692                   Ops, [UserTE, &AllowsReordering](
3693                            const std::pair<unsigned, TreeEntry *> &Op) {
3694                     return AllowsReordering(Op.second) &&
3695                            all_of(Op.second->UserTreeIndices,
3696                                   [UserTE](const EdgeInfo &EI) {
3697                                     return EI.UserTE == UserTE;
3698                                   });
3699                   })) <= Ops.size() / 2)
3700             ++Res.first->second;
3701         }
3702       }
3703       // If no orders - skip current nodes and jump to the next one, if any.
3704       if (OrdersUses.empty()) {
3705         for_each(Data.second,
3706                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3707                    OrderedEntries.remove(Op.second);
3708                  });
3709         continue;
3710       }
3711       // Choose the best order.
3712       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3713       unsigned Cnt = OrdersUses.front().second;
3714       for (const auto &Pair : drop_begin(OrdersUses)) {
3715         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3716           BestOrder = Pair.first;
3717           Cnt = Pair.second;
3718         }
3719       }
3720       // Set order of the user node (reordering of operands and user nodes).
3721       if (BestOrder.empty()) {
3722         for_each(Data.second,
3723                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3724                    OrderedEntries.remove(Op.second);
3725                  });
3726         continue;
3727       }
3728       // Erase operands from OrderedEntries list and adjust their orders.
3729       VisitedOps.clear();
3730       SmallVector<int> Mask;
3731       inversePermutation(BestOrder, Mask);
3732       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3733       unsigned E = BestOrder.size();
3734       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3735         return I < E ? static_cast<int>(I) : UndefMaskElem;
3736       });
3737       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3738         TreeEntry *TE = Op.second;
3739         OrderedEntries.remove(TE);
3740         if (!VisitedOps.insert(TE).second)
3741           continue;
3742         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3743           // Just reorder reuses indices.
3744           reorderReuses(TE->ReuseShuffleIndices, Mask);
3745           continue;
3746         }
3747         // Gathers are processed separately.
3748         if (TE->State != TreeEntry::Vectorize)
3749           continue;
3750         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3751                 TE->ReorderIndices.empty()) &&
3752                "Non-matching sizes of user/operand entries.");
3753         reorderOrder(TE->ReorderIndices, Mask);
3754       }
3755       // For gathers just need to reorder its scalars.
3756       for (TreeEntry *Gather : GatherOps) {
3757         assert(Gather->ReorderIndices.empty() &&
3758                "Unexpected reordering of gathers.");
3759         if (!Gather->ReuseShuffleIndices.empty()) {
3760           // Just reorder reuses indices.
3761           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3762           continue;
3763         }
3764         reorderScalars(Gather->Scalars, Mask);
3765         OrderedEntries.remove(Gather);
3766       }
3767       // Reorder operands of the user node and set the ordering for the user
3768       // node itself.
3769       if (Data.first->State != TreeEntry::Vectorize ||
3770           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3771               Data.first->getMainOp()) ||
3772           Data.first->isAltShuffle())
3773         Data.first->reorderOperands(Mask);
3774       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3775           Data.first->isAltShuffle()) {
3776         reorderScalars(Data.first->Scalars, Mask);
3777         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3778         if (Data.first->ReuseShuffleIndices.empty() &&
3779             !Data.first->ReorderIndices.empty() &&
3780             !Data.first->isAltShuffle()) {
3781           // Insert user node to the list to try to sink reordering deeper in
3782           // the graph.
3783           OrderedEntries.insert(Data.first);
3784         }
3785       } else {
3786         reorderOrder(Data.first->ReorderIndices, Mask);
3787       }
3788     }
3789   }
3790   // If the reordering is unnecessary, just remove the reorder.
3791   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3792       VectorizableTree.front()->ReuseShuffleIndices.empty())
3793     VectorizableTree.front()->ReorderIndices.clear();
3794 }
3795 
3796 void BoUpSLP::buildExternalUses(
3797     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3798   // Collect the values that we need to extract from the tree.
3799   for (auto &TEPtr : VectorizableTree) {
3800     TreeEntry *Entry = TEPtr.get();
3801 
3802     // No need to handle users of gathered values.
3803     if (Entry->State == TreeEntry::NeedToGather)
3804       continue;
3805 
3806     // For each lane:
3807     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3808       Value *Scalar = Entry->Scalars[Lane];
3809       int FoundLane = Entry->findLaneForValue(Scalar);
3810 
3811       // Check if the scalar is externally used as an extra arg.
3812       auto ExtI = ExternallyUsedValues.find(Scalar);
3813       if (ExtI != ExternallyUsedValues.end()) {
3814         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3815                           << Lane << " from " << *Scalar << ".\n");
3816         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3817       }
3818       for (User *U : Scalar->users()) {
3819         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3820 
3821         Instruction *UserInst = dyn_cast<Instruction>(U);
3822         if (!UserInst)
3823           continue;
3824 
3825         if (isDeleted(UserInst))
3826           continue;
3827 
3828         // Skip in-tree scalars that become vectors
3829         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3830           Value *UseScalar = UseEntry->Scalars[0];
3831           // Some in-tree scalars will remain as scalar in vectorized
3832           // instructions. If that is the case, the one in Lane 0 will
3833           // be used.
3834           if (UseScalar != U ||
3835               UseEntry->State == TreeEntry::ScatterVectorize ||
3836               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3837             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3838                               << ".\n");
3839             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3840             continue;
3841           }
3842         }
3843 
3844         // Ignore users in the user ignore list.
3845         if (is_contained(UserIgnoreList, UserInst))
3846           continue;
3847 
3848         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3849                           << Lane << " from " << *Scalar << ".\n");
3850         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3851       }
3852     }
3853   }
3854 }
3855 
3856 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3857                         ArrayRef<Value *> UserIgnoreLst) {
3858   deleteTree();
3859   UserIgnoreList = UserIgnoreLst;
3860   if (!allSameType(Roots))
3861     return;
3862   buildTree_rec(Roots, 0, EdgeInfo());
3863 }
3864 
3865 namespace {
3866 /// Tracks the state we can represent the loads in the given sequence.
3867 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3868 } // anonymous namespace
3869 
3870 /// Checks if the given array of loads can be represented as a vectorized,
3871 /// scatter or just simple gather.
3872 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3873                                     const TargetTransformInfo &TTI,
3874                                     const DataLayout &DL, ScalarEvolution &SE,
3875                                     SmallVectorImpl<unsigned> &Order,
3876                                     SmallVectorImpl<Value *> &PointerOps) {
3877   // Check that a vectorized load would load the same memory as a scalar
3878   // load. For example, we don't want to vectorize loads that are smaller
3879   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3880   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3881   // from such a struct, we read/write packed bits disagreeing with the
3882   // unvectorized version.
3883   Type *ScalarTy = VL0->getType();
3884 
3885   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3886     return LoadsState::Gather;
3887 
3888   // Make sure all loads in the bundle are simple - we can't vectorize
3889   // atomic or volatile loads.
3890   PointerOps.clear();
3891   PointerOps.resize(VL.size());
3892   auto *POIter = PointerOps.begin();
3893   for (Value *V : VL) {
3894     auto *L = cast<LoadInst>(V);
3895     if (!L->isSimple())
3896       return LoadsState::Gather;
3897     *POIter = L->getPointerOperand();
3898     ++POIter;
3899   }
3900 
3901   Order.clear();
3902   // Check the order of pointer operands.
3903   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3904     Value *Ptr0;
3905     Value *PtrN;
3906     if (Order.empty()) {
3907       Ptr0 = PointerOps.front();
3908       PtrN = PointerOps.back();
3909     } else {
3910       Ptr0 = PointerOps[Order.front()];
3911       PtrN = PointerOps[Order.back()];
3912     }
3913     Optional<int> Diff =
3914         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3915     // Check that the sorted loads are consecutive.
3916     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3917       return LoadsState::Vectorize;
3918     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3919     for (Value *V : VL)
3920       CommonAlignment =
3921           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3922     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3923                                 CommonAlignment))
3924       return LoadsState::ScatterVectorize;
3925   }
3926 
3927   return LoadsState::Gather;
3928 }
3929 
3930 /// \return true if the specified list of values has only one instruction that
3931 /// requires scheduling, false otherwise.
3932 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3933   Value *NeedsScheduling = nullptr;
3934   for (Value *V : VL) {
3935     if (doesNotNeedToBeScheduled(V))
3936       continue;
3937     if (!NeedsScheduling) {
3938       NeedsScheduling = V;
3939       continue;
3940     }
3941     return false;
3942   }
3943   return NeedsScheduling;
3944 }
3945 
3946 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3947                             const EdgeInfo &UserTreeIdx) {
3948   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3949 
3950   SmallVector<int> ReuseShuffleIndicies;
3951   SmallVector<Value *> UniqueValues;
3952   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3953                                 &UserTreeIdx,
3954                                 this](const InstructionsState &S) {
3955     // Check that every instruction appears once in this bundle.
3956     DenseMap<Value *, unsigned> UniquePositions;
3957     for (Value *V : VL) {
3958       if (isConstant(V)) {
3959         ReuseShuffleIndicies.emplace_back(
3960             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3961         UniqueValues.emplace_back(V);
3962         continue;
3963       }
3964       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3965       ReuseShuffleIndicies.emplace_back(Res.first->second);
3966       if (Res.second)
3967         UniqueValues.emplace_back(V);
3968     }
3969     size_t NumUniqueScalarValues = UniqueValues.size();
3970     if (NumUniqueScalarValues == VL.size()) {
3971       ReuseShuffleIndicies.clear();
3972     } else {
3973       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3974       if (NumUniqueScalarValues <= 1 ||
3975           (UniquePositions.size() == 1 && all_of(UniqueValues,
3976                                                  [](Value *V) {
3977                                                    return isa<UndefValue>(V) ||
3978                                                           !isConstant(V);
3979                                                  })) ||
3980           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3981         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3982         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3983         return false;
3984       }
3985       VL = UniqueValues;
3986     }
3987     return true;
3988   };
3989 
3990   InstructionsState S = getSameOpcode(VL);
3991   if (Depth == RecursionMaxDepth) {
3992     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3993     if (TryToFindDuplicates(S))
3994       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3995                    ReuseShuffleIndicies);
3996     return;
3997   }
3998 
3999   // Don't handle scalable vectors
4000   if (S.getOpcode() == Instruction::ExtractElement &&
4001       isa<ScalableVectorType>(
4002           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4003     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4004     if (TryToFindDuplicates(S))
4005       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4006                    ReuseShuffleIndicies);
4007     return;
4008   }
4009 
4010   // Don't handle vectors.
4011   if (S.OpValue->getType()->isVectorTy() &&
4012       !isa<InsertElementInst>(S.OpValue)) {
4013     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4014     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4015     return;
4016   }
4017 
4018   // Avoid attempting to schedule allocas; there are unmodeled dependencies
4019   // for "static" alloca status and for reordering with stacksave calls.
4020   for (Value *V : VL) {
4021     if (isa<AllocaInst>(V)) {
4022       LLVM_DEBUG(dbgs() << "SLP: Gathering due to alloca.\n");
4023       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4024       return;
4025     }
4026   }
4027 
4028   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4029     if (SI->getValueOperand()->getType()->isVectorTy()) {
4030       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4031       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4032       return;
4033     }
4034 
4035   // If all of the operands are identical or constant we have a simple solution.
4036   // If we deal with insert/extract instructions, they all must have constant
4037   // indices, otherwise we should gather them, not try to vectorize.
4038   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4039       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4040        !all_of(VL, isVectorLikeInstWithConstOps))) {
4041     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4042     if (TryToFindDuplicates(S))
4043       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4044                    ReuseShuffleIndicies);
4045     return;
4046   }
4047 
4048   // We now know that this is a vector of instructions of the same type from
4049   // the same block.
4050 
4051   // Don't vectorize ephemeral values.
4052   for (Value *V : VL) {
4053     if (EphValues.count(V)) {
4054       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4055                         << ") is ephemeral.\n");
4056       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4057       return;
4058     }
4059   }
4060 
4061   // Check if this is a duplicate of another entry.
4062   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4063     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4064     if (!E->isSame(VL)) {
4065       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4066       if (TryToFindDuplicates(S))
4067         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4068                      ReuseShuffleIndicies);
4069       return;
4070     }
4071     // Record the reuse of the tree node.  FIXME, currently this is only used to
4072     // properly draw the graph rather than for the actual vectorization.
4073     E->UserTreeIndices.push_back(UserTreeIdx);
4074     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4075                       << ".\n");
4076     return;
4077   }
4078 
4079   // Check that none of the instructions in the bundle are already in the tree.
4080   for (Value *V : VL) {
4081     auto *I = dyn_cast<Instruction>(V);
4082     if (!I)
4083       continue;
4084     if (getTreeEntry(I)) {
4085       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4086                         << ") is already in tree.\n");
4087       if (TryToFindDuplicates(S))
4088         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4089                      ReuseShuffleIndicies);
4090       return;
4091     }
4092   }
4093 
4094   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4095   for (Value *V : VL) {
4096     if (is_contained(UserIgnoreList, V)) {
4097       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4098       if (TryToFindDuplicates(S))
4099         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4100                      ReuseShuffleIndicies);
4101       return;
4102     }
4103   }
4104 
4105   // Check that all of the users of the scalars that we want to vectorize are
4106   // schedulable.
4107   auto *VL0 = cast<Instruction>(S.OpValue);
4108   BasicBlock *BB = VL0->getParent();
4109 
4110   if (!DT->isReachableFromEntry(BB)) {
4111     // Don't go into unreachable blocks. They may contain instructions with
4112     // dependency cycles which confuse the final scheduling.
4113     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4114     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4115     return;
4116   }
4117 
4118   // Check that every instruction appears once in this bundle.
4119   if (!TryToFindDuplicates(S))
4120     return;
4121 
4122   auto &BSRef = BlocksSchedules[BB];
4123   if (!BSRef)
4124     BSRef = std::make_unique<BlockScheduling>(BB);
4125 
4126   BlockScheduling &BS = *BSRef.get();
4127 
4128   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4129 #ifdef EXPENSIVE_CHECKS
4130   // Make sure we didn't break any internal invariants
4131   BS.verify();
4132 #endif
4133   if (!Bundle) {
4134     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4135     assert((!BS.getScheduleData(VL0) ||
4136             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4137            "tryScheduleBundle should cancelScheduling on failure");
4138     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4139                  ReuseShuffleIndicies);
4140     return;
4141   }
4142   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4143 
4144   unsigned ShuffleOrOp = S.isAltShuffle() ?
4145                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4146   switch (ShuffleOrOp) {
4147     case Instruction::PHI: {
4148       auto *PH = cast<PHINode>(VL0);
4149 
4150       // Check for terminator values (e.g. invoke).
4151       for (Value *V : VL)
4152         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4153           Instruction *Term = dyn_cast<Instruction>(Incoming);
4154           if (Term && Term->isTerminator()) {
4155             LLVM_DEBUG(dbgs()
4156                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4157             BS.cancelScheduling(VL, VL0);
4158             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4159                          ReuseShuffleIndicies);
4160             return;
4161           }
4162         }
4163 
4164       TreeEntry *TE =
4165           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4166       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4167 
4168       // Keeps the reordered operands to avoid code duplication.
4169       SmallVector<ValueList, 2> OperandsVec;
4170       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4171         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4172           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4173           TE->setOperand(I, Operands);
4174           OperandsVec.push_back(Operands);
4175           continue;
4176         }
4177         ValueList Operands;
4178         // Prepare the operand vector.
4179         for (Value *V : VL)
4180           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4181               PH->getIncomingBlock(I)));
4182         TE->setOperand(I, Operands);
4183         OperandsVec.push_back(Operands);
4184       }
4185       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4186         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4187       return;
4188     }
4189     case Instruction::ExtractValue:
4190     case Instruction::ExtractElement: {
4191       OrdersType CurrentOrder;
4192       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4193       if (Reuse) {
4194         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4195         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4196                      ReuseShuffleIndicies);
4197         // This is a special case, as it does not gather, but at the same time
4198         // we are not extending buildTree_rec() towards the operands.
4199         ValueList Op0;
4200         Op0.assign(VL.size(), VL0->getOperand(0));
4201         VectorizableTree.back()->setOperand(0, Op0);
4202         return;
4203       }
4204       if (!CurrentOrder.empty()) {
4205         LLVM_DEBUG({
4206           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4207                     "with order";
4208           for (unsigned Idx : CurrentOrder)
4209             dbgs() << " " << Idx;
4210           dbgs() << "\n";
4211         });
4212         fixupOrderingIndices(CurrentOrder);
4213         // Insert new order with initial value 0, if it does not exist,
4214         // otherwise return the iterator to the existing one.
4215         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4216                      ReuseShuffleIndicies, CurrentOrder);
4217         // This is a special case, as it does not gather, but at the same time
4218         // we are not extending buildTree_rec() towards the operands.
4219         ValueList Op0;
4220         Op0.assign(VL.size(), VL0->getOperand(0));
4221         VectorizableTree.back()->setOperand(0, Op0);
4222         return;
4223       }
4224       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4225       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4226                    ReuseShuffleIndicies);
4227       BS.cancelScheduling(VL, VL0);
4228       return;
4229     }
4230     case Instruction::InsertElement: {
4231       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4232 
4233       // Check that we have a buildvector and not a shuffle of 2 or more
4234       // different vectors.
4235       ValueSet SourceVectors;
4236       for (Value *V : VL) {
4237         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4238         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4239       }
4240 
4241       if (count_if(VL, [&SourceVectors](Value *V) {
4242             return !SourceVectors.contains(V);
4243           }) >= 2) {
4244         // Found 2nd source vector - cancel.
4245         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4246                              "different source vectors.\n");
4247         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4248         BS.cancelScheduling(VL, VL0);
4249         return;
4250       }
4251 
4252       auto OrdCompare = [](const std::pair<int, int> &P1,
4253                            const std::pair<int, int> &P2) {
4254         return P1.first > P2.first;
4255       };
4256       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4257                     decltype(OrdCompare)>
4258           Indices(OrdCompare);
4259       for (int I = 0, E = VL.size(); I < E; ++I) {
4260         unsigned Idx = *getInsertIndex(VL[I]);
4261         Indices.emplace(Idx, I);
4262       }
4263       OrdersType CurrentOrder(VL.size(), VL.size());
4264       bool IsIdentity = true;
4265       for (int I = 0, E = VL.size(); I < E; ++I) {
4266         CurrentOrder[Indices.top().second] = I;
4267         IsIdentity &= Indices.top().second == I;
4268         Indices.pop();
4269       }
4270       if (IsIdentity)
4271         CurrentOrder.clear();
4272       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4273                                    None, CurrentOrder);
4274       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4275 
4276       constexpr int NumOps = 2;
4277       ValueList VectorOperands[NumOps];
4278       for (int I = 0; I < NumOps; ++I) {
4279         for (Value *V : VL)
4280           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4281 
4282         TE->setOperand(I, VectorOperands[I]);
4283       }
4284       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4285       return;
4286     }
4287     case Instruction::Load: {
4288       // Check that a vectorized load would load the same memory as a scalar
4289       // load. For example, we don't want to vectorize loads that are smaller
4290       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4291       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4292       // from such a struct, we read/write packed bits disagreeing with the
4293       // unvectorized version.
4294       SmallVector<Value *> PointerOps;
4295       OrdersType CurrentOrder;
4296       TreeEntry *TE = nullptr;
4297       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4298                                 PointerOps)) {
4299       case LoadsState::Vectorize:
4300         if (CurrentOrder.empty()) {
4301           // Original loads are consecutive and does not require reordering.
4302           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4303                             ReuseShuffleIndicies);
4304           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4305         } else {
4306           fixupOrderingIndices(CurrentOrder);
4307           // Need to reorder.
4308           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4309                             ReuseShuffleIndicies, CurrentOrder);
4310           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4311         }
4312         TE->setOperandsInOrder();
4313         break;
4314       case LoadsState::ScatterVectorize:
4315         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4316         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4317                           UserTreeIdx, ReuseShuffleIndicies);
4318         TE->setOperandsInOrder();
4319         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4320         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4321         break;
4322       case LoadsState::Gather:
4323         BS.cancelScheduling(VL, VL0);
4324         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4325                      ReuseShuffleIndicies);
4326 #ifndef NDEBUG
4327         Type *ScalarTy = VL0->getType();
4328         if (DL->getTypeSizeInBits(ScalarTy) !=
4329             DL->getTypeAllocSizeInBits(ScalarTy))
4330           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4331         else if (any_of(VL, [](Value *V) {
4332                    return !cast<LoadInst>(V)->isSimple();
4333                  }))
4334           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4335         else
4336           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4337 #endif // NDEBUG
4338         break;
4339       }
4340       return;
4341     }
4342     case Instruction::ZExt:
4343     case Instruction::SExt:
4344     case Instruction::FPToUI:
4345     case Instruction::FPToSI:
4346     case Instruction::FPExt:
4347     case Instruction::PtrToInt:
4348     case Instruction::IntToPtr:
4349     case Instruction::SIToFP:
4350     case Instruction::UIToFP:
4351     case Instruction::Trunc:
4352     case Instruction::FPTrunc:
4353     case Instruction::BitCast: {
4354       Type *SrcTy = VL0->getOperand(0)->getType();
4355       for (Value *V : VL) {
4356         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4357         if (Ty != SrcTy || !isValidElementType(Ty)) {
4358           BS.cancelScheduling(VL, VL0);
4359           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4360                        ReuseShuffleIndicies);
4361           LLVM_DEBUG(dbgs()
4362                      << "SLP: Gathering casts with different src types.\n");
4363           return;
4364         }
4365       }
4366       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4367                                    ReuseShuffleIndicies);
4368       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4369 
4370       TE->setOperandsInOrder();
4371       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4372         ValueList Operands;
4373         // Prepare the operand vector.
4374         for (Value *V : VL)
4375           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4376 
4377         buildTree_rec(Operands, Depth + 1, {TE, i});
4378       }
4379       return;
4380     }
4381     case Instruction::ICmp:
4382     case Instruction::FCmp: {
4383       // Check that all of the compares have the same predicate.
4384       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4385       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4386       Type *ComparedTy = VL0->getOperand(0)->getType();
4387       for (Value *V : VL) {
4388         CmpInst *Cmp = cast<CmpInst>(V);
4389         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4390             Cmp->getOperand(0)->getType() != ComparedTy) {
4391           BS.cancelScheduling(VL, VL0);
4392           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4393                        ReuseShuffleIndicies);
4394           LLVM_DEBUG(dbgs()
4395                      << "SLP: Gathering cmp with different predicate.\n");
4396           return;
4397         }
4398       }
4399 
4400       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4401                                    ReuseShuffleIndicies);
4402       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4403 
4404       ValueList Left, Right;
4405       if (cast<CmpInst>(VL0)->isCommutative()) {
4406         // Commutative predicate - collect + sort operands of the instructions
4407         // so that each side is more likely to have the same opcode.
4408         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4409         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4410       } else {
4411         // Collect operands - commute if it uses the swapped predicate.
4412         for (Value *V : VL) {
4413           auto *Cmp = cast<CmpInst>(V);
4414           Value *LHS = Cmp->getOperand(0);
4415           Value *RHS = Cmp->getOperand(1);
4416           if (Cmp->getPredicate() != P0)
4417             std::swap(LHS, RHS);
4418           Left.push_back(LHS);
4419           Right.push_back(RHS);
4420         }
4421       }
4422       TE->setOperand(0, Left);
4423       TE->setOperand(1, Right);
4424       buildTree_rec(Left, Depth + 1, {TE, 0});
4425       buildTree_rec(Right, Depth + 1, {TE, 1});
4426       return;
4427     }
4428     case Instruction::Select:
4429     case Instruction::FNeg:
4430     case Instruction::Add:
4431     case Instruction::FAdd:
4432     case Instruction::Sub:
4433     case Instruction::FSub:
4434     case Instruction::Mul:
4435     case Instruction::FMul:
4436     case Instruction::UDiv:
4437     case Instruction::SDiv:
4438     case Instruction::FDiv:
4439     case Instruction::URem:
4440     case Instruction::SRem:
4441     case Instruction::FRem:
4442     case Instruction::Shl:
4443     case Instruction::LShr:
4444     case Instruction::AShr:
4445     case Instruction::And:
4446     case Instruction::Or:
4447     case Instruction::Xor: {
4448       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4449                                    ReuseShuffleIndicies);
4450       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4451 
4452       // Sort operands of the instructions so that each side is more likely to
4453       // have the same opcode.
4454       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4455         ValueList Left, Right;
4456         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4457         TE->setOperand(0, Left);
4458         TE->setOperand(1, Right);
4459         buildTree_rec(Left, Depth + 1, {TE, 0});
4460         buildTree_rec(Right, Depth + 1, {TE, 1});
4461         return;
4462       }
4463 
4464       TE->setOperandsInOrder();
4465       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4466         ValueList Operands;
4467         // Prepare the operand vector.
4468         for (Value *V : VL)
4469           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4470 
4471         buildTree_rec(Operands, Depth + 1, {TE, i});
4472       }
4473       return;
4474     }
4475     case Instruction::GetElementPtr: {
4476       // We don't combine GEPs with complicated (nested) indexing.
4477       for (Value *V : VL) {
4478         if (cast<Instruction>(V)->getNumOperands() != 2) {
4479           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4480           BS.cancelScheduling(VL, VL0);
4481           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4482                        ReuseShuffleIndicies);
4483           return;
4484         }
4485       }
4486 
4487       // We can't combine several GEPs into one vector if they operate on
4488       // different types.
4489       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4490       for (Value *V : VL) {
4491         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4492         if (Ty0 != CurTy) {
4493           LLVM_DEBUG(dbgs()
4494                      << "SLP: not-vectorizable GEP (different types).\n");
4495           BS.cancelScheduling(VL, VL0);
4496           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4497                        ReuseShuffleIndicies);
4498           return;
4499         }
4500       }
4501 
4502       // We don't combine GEPs with non-constant indexes.
4503       Type *Ty1 = VL0->getOperand(1)->getType();
4504       for (Value *V : VL) {
4505         auto Op = cast<Instruction>(V)->getOperand(1);
4506         if (!isa<ConstantInt>(Op) ||
4507             (Op->getType() != Ty1 &&
4508              Op->getType()->getScalarSizeInBits() >
4509                  DL->getIndexSizeInBits(
4510                      V->getType()->getPointerAddressSpace()))) {
4511           LLVM_DEBUG(dbgs()
4512                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4513           BS.cancelScheduling(VL, VL0);
4514           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4515                        ReuseShuffleIndicies);
4516           return;
4517         }
4518       }
4519 
4520       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4521                                    ReuseShuffleIndicies);
4522       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4523       SmallVector<ValueList, 2> Operands(2);
4524       // Prepare the operand vector for pointer operands.
4525       for (Value *V : VL)
4526         Operands.front().push_back(
4527             cast<GetElementPtrInst>(V)->getPointerOperand());
4528       TE->setOperand(0, Operands.front());
4529       // Need to cast all indices to the same type before vectorization to
4530       // avoid crash.
4531       // Required to be able to find correct matches between different gather
4532       // nodes and reuse the vectorized values rather than trying to gather them
4533       // again.
4534       int IndexIdx = 1;
4535       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4536       Type *Ty = all_of(VL,
4537                         [VL0Ty, IndexIdx](Value *V) {
4538                           return VL0Ty == cast<GetElementPtrInst>(V)
4539                                               ->getOperand(IndexIdx)
4540                                               ->getType();
4541                         })
4542                      ? VL0Ty
4543                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4544                                             ->getPointerOperandType()
4545                                             ->getScalarType());
4546       // Prepare the operand vector.
4547       for (Value *V : VL) {
4548         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4549         auto *CI = cast<ConstantInt>(Op);
4550         Operands.back().push_back(ConstantExpr::getIntegerCast(
4551             CI, Ty, CI->getValue().isSignBitSet()));
4552       }
4553       TE->setOperand(IndexIdx, Operands.back());
4554 
4555       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4556         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4557       return;
4558     }
4559     case Instruction::Store: {
4560       // Check if the stores are consecutive or if we need to swizzle them.
4561       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4562       // Avoid types that are padded when being allocated as scalars, while
4563       // being packed together in a vector (such as i1).
4564       if (DL->getTypeSizeInBits(ScalarTy) !=
4565           DL->getTypeAllocSizeInBits(ScalarTy)) {
4566         BS.cancelScheduling(VL, VL0);
4567         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4568                      ReuseShuffleIndicies);
4569         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4570         return;
4571       }
4572       // Make sure all stores in the bundle are simple - we can't vectorize
4573       // atomic or volatile stores.
4574       SmallVector<Value *, 4> PointerOps(VL.size());
4575       ValueList Operands(VL.size());
4576       auto POIter = PointerOps.begin();
4577       auto OIter = Operands.begin();
4578       for (Value *V : VL) {
4579         auto *SI = cast<StoreInst>(V);
4580         if (!SI->isSimple()) {
4581           BS.cancelScheduling(VL, VL0);
4582           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4583                        ReuseShuffleIndicies);
4584           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4585           return;
4586         }
4587         *POIter = SI->getPointerOperand();
4588         *OIter = SI->getValueOperand();
4589         ++POIter;
4590         ++OIter;
4591       }
4592 
4593       OrdersType CurrentOrder;
4594       // Check the order of pointer operands.
4595       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4596         Value *Ptr0;
4597         Value *PtrN;
4598         if (CurrentOrder.empty()) {
4599           Ptr0 = PointerOps.front();
4600           PtrN = PointerOps.back();
4601         } else {
4602           Ptr0 = PointerOps[CurrentOrder.front()];
4603           PtrN = PointerOps[CurrentOrder.back()];
4604         }
4605         Optional<int> Dist =
4606             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4607         // Check that the sorted pointer operands are consecutive.
4608         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4609           if (CurrentOrder.empty()) {
4610             // Original stores are consecutive and does not require reordering.
4611             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4612                                          UserTreeIdx, ReuseShuffleIndicies);
4613             TE->setOperandsInOrder();
4614             buildTree_rec(Operands, Depth + 1, {TE, 0});
4615             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4616           } else {
4617             fixupOrderingIndices(CurrentOrder);
4618             TreeEntry *TE =
4619                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4620                              ReuseShuffleIndicies, CurrentOrder);
4621             TE->setOperandsInOrder();
4622             buildTree_rec(Operands, Depth + 1, {TE, 0});
4623             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4624           }
4625           return;
4626         }
4627       }
4628 
4629       BS.cancelScheduling(VL, VL0);
4630       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4631                    ReuseShuffleIndicies);
4632       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4633       return;
4634     }
4635     case Instruction::Call: {
4636       // Check if the calls are all to the same vectorizable intrinsic or
4637       // library function.
4638       CallInst *CI = cast<CallInst>(VL0);
4639       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4640 
4641       VFShape Shape = VFShape::get(
4642           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4643           false /*HasGlobalPred*/);
4644       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4645 
4646       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4647         BS.cancelScheduling(VL, VL0);
4648         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4649                      ReuseShuffleIndicies);
4650         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4651         return;
4652       }
4653       Function *F = CI->getCalledFunction();
4654       unsigned NumArgs = CI->arg_size();
4655       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4656       for (unsigned j = 0; j != NumArgs; ++j)
4657         if (hasVectorInstrinsicScalarOpd(ID, j))
4658           ScalarArgs[j] = CI->getArgOperand(j);
4659       for (Value *V : VL) {
4660         CallInst *CI2 = dyn_cast<CallInst>(V);
4661         if (!CI2 || CI2->getCalledFunction() != F ||
4662             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4663             (VecFunc &&
4664              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4665             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4666           BS.cancelScheduling(VL, VL0);
4667           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4668                        ReuseShuffleIndicies);
4669           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4670                             << "\n");
4671           return;
4672         }
4673         // Some intrinsics have scalar arguments and should be same in order for
4674         // them to be vectorized.
4675         for (unsigned j = 0; j != NumArgs; ++j) {
4676           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4677             Value *A1J = CI2->getArgOperand(j);
4678             if (ScalarArgs[j] != A1J) {
4679               BS.cancelScheduling(VL, VL0);
4680               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4681                            ReuseShuffleIndicies);
4682               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4683                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4684                                 << "\n");
4685               return;
4686             }
4687           }
4688         }
4689         // Verify that the bundle operands are identical between the two calls.
4690         if (CI->hasOperandBundles() &&
4691             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4692                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4693                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4694           BS.cancelScheduling(VL, VL0);
4695           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4696                        ReuseShuffleIndicies);
4697           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4698                             << *CI << "!=" << *V << '\n');
4699           return;
4700         }
4701       }
4702 
4703       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4704                                    ReuseShuffleIndicies);
4705       TE->setOperandsInOrder();
4706       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4707         // For scalar operands no need to to create an entry since no need to
4708         // vectorize it.
4709         if (hasVectorInstrinsicScalarOpd(ID, i))
4710           continue;
4711         ValueList Operands;
4712         // Prepare the operand vector.
4713         for (Value *V : VL) {
4714           auto *CI2 = cast<CallInst>(V);
4715           Operands.push_back(CI2->getArgOperand(i));
4716         }
4717         buildTree_rec(Operands, Depth + 1, {TE, i});
4718       }
4719       return;
4720     }
4721     case Instruction::ShuffleVector: {
4722       // If this is not an alternate sequence of opcode like add-sub
4723       // then do not vectorize this instruction.
4724       if (!S.isAltShuffle()) {
4725         BS.cancelScheduling(VL, VL0);
4726         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4727                      ReuseShuffleIndicies);
4728         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4729         return;
4730       }
4731       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4732                                    ReuseShuffleIndicies);
4733       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4734 
4735       // Reorder operands if reordering would enable vectorization.
4736       auto *CI = dyn_cast<CmpInst>(VL0);
4737       if (isa<BinaryOperator>(VL0) || CI) {
4738         ValueList Left, Right;
4739         if (!CI || all_of(VL, [](Value *V) {
4740               return cast<CmpInst>(V)->isCommutative();
4741             })) {
4742           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4743         } else {
4744           CmpInst::Predicate P0 = CI->getPredicate();
4745           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4746           assert(P0 != AltP0 &&
4747                  "Expected different main/alternate predicates.");
4748           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4749           Value *BaseOp0 = VL0->getOperand(0);
4750           Value *BaseOp1 = VL0->getOperand(1);
4751           // Collect operands - commute if it uses the swapped predicate or
4752           // alternate operation.
4753           for (Value *V : VL) {
4754             auto *Cmp = cast<CmpInst>(V);
4755             Value *LHS = Cmp->getOperand(0);
4756             Value *RHS = Cmp->getOperand(1);
4757             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4758             if (P0 == AltP0Swapped) {
4759               if (CI != Cmp && S.AltOp != Cmp &&
4760                   ((P0 == CurrentPred &&
4761                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4762                    (AltP0 == CurrentPred &&
4763                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4764                 std::swap(LHS, RHS);
4765             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4766               std::swap(LHS, RHS);
4767             }
4768             Left.push_back(LHS);
4769             Right.push_back(RHS);
4770           }
4771         }
4772         TE->setOperand(0, Left);
4773         TE->setOperand(1, Right);
4774         buildTree_rec(Left, Depth + 1, {TE, 0});
4775         buildTree_rec(Right, Depth + 1, {TE, 1});
4776         return;
4777       }
4778 
4779       TE->setOperandsInOrder();
4780       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4781         ValueList Operands;
4782         // Prepare the operand vector.
4783         for (Value *V : VL)
4784           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4785 
4786         buildTree_rec(Operands, Depth + 1, {TE, i});
4787       }
4788       return;
4789     }
4790     default:
4791       BS.cancelScheduling(VL, VL0);
4792       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4793                    ReuseShuffleIndicies);
4794       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4795       return;
4796   }
4797 }
4798 
4799 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4800   unsigned N = 1;
4801   Type *EltTy = T;
4802 
4803   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4804          isa<VectorType>(EltTy)) {
4805     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4806       // Check that struct is homogeneous.
4807       for (const auto *Ty : ST->elements())
4808         if (Ty != *ST->element_begin())
4809           return 0;
4810       N *= ST->getNumElements();
4811       EltTy = *ST->element_begin();
4812     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4813       N *= AT->getNumElements();
4814       EltTy = AT->getElementType();
4815     } else {
4816       auto *VT = cast<FixedVectorType>(EltTy);
4817       N *= VT->getNumElements();
4818       EltTy = VT->getElementType();
4819     }
4820   }
4821 
4822   if (!isValidElementType(EltTy))
4823     return 0;
4824   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4825   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4826     return 0;
4827   return N;
4828 }
4829 
4830 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4831                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4832   const auto *It = find_if(VL, [](Value *V) {
4833     return isa<ExtractElementInst, ExtractValueInst>(V);
4834   });
4835   assert(It != VL.end() && "Expected at least one extract instruction.");
4836   auto *E0 = cast<Instruction>(*It);
4837   assert(all_of(VL,
4838                 [](Value *V) {
4839                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4840                       V);
4841                 }) &&
4842          "Invalid opcode");
4843   // Check if all of the extracts come from the same vector and from the
4844   // correct offset.
4845   Value *Vec = E0->getOperand(0);
4846 
4847   CurrentOrder.clear();
4848 
4849   // We have to extract from a vector/aggregate with the same number of elements.
4850   unsigned NElts;
4851   if (E0->getOpcode() == Instruction::ExtractValue) {
4852     const DataLayout &DL = E0->getModule()->getDataLayout();
4853     NElts = canMapToVector(Vec->getType(), DL);
4854     if (!NElts)
4855       return false;
4856     // Check if load can be rewritten as load of vector.
4857     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4858     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4859       return false;
4860   } else {
4861     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4862   }
4863 
4864   if (NElts != VL.size())
4865     return false;
4866 
4867   // Check that all of the indices extract from the correct offset.
4868   bool ShouldKeepOrder = true;
4869   unsigned E = VL.size();
4870   // Assign to all items the initial value E + 1 so we can check if the extract
4871   // instruction index was used already.
4872   // Also, later we can check that all the indices are used and we have a
4873   // consecutive access in the extract instructions, by checking that no
4874   // element of CurrentOrder still has value E + 1.
4875   CurrentOrder.assign(E, E);
4876   unsigned I = 0;
4877   for (; I < E; ++I) {
4878     auto *Inst = dyn_cast<Instruction>(VL[I]);
4879     if (!Inst)
4880       continue;
4881     if (Inst->getOperand(0) != Vec)
4882       break;
4883     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4884       if (isa<UndefValue>(EE->getIndexOperand()))
4885         continue;
4886     Optional<unsigned> Idx = getExtractIndex(Inst);
4887     if (!Idx)
4888       break;
4889     const unsigned ExtIdx = *Idx;
4890     if (ExtIdx != I) {
4891       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4892         break;
4893       ShouldKeepOrder = false;
4894       CurrentOrder[ExtIdx] = I;
4895     } else {
4896       if (CurrentOrder[I] != E)
4897         break;
4898       CurrentOrder[I] = I;
4899     }
4900   }
4901   if (I < E) {
4902     CurrentOrder.clear();
4903     return false;
4904   }
4905   if (ShouldKeepOrder)
4906     CurrentOrder.clear();
4907 
4908   return ShouldKeepOrder;
4909 }
4910 
4911 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4912                                     ArrayRef<Value *> VectorizedVals) const {
4913   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4914          all_of(I->users(), [this](User *U) {
4915            return ScalarToTreeEntry.count(U) > 0 ||
4916                   isVectorLikeInstWithConstOps(U) ||
4917                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4918          });
4919 }
4920 
4921 static std::pair<InstructionCost, InstructionCost>
4922 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4923                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4924   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4925 
4926   // Calculate the cost of the scalar and vector calls.
4927   SmallVector<Type *, 4> VecTys;
4928   for (Use &Arg : CI->args())
4929     VecTys.push_back(
4930         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4931   FastMathFlags FMF;
4932   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4933     FMF = FPCI->getFastMathFlags();
4934   SmallVector<const Value *> Arguments(CI->args());
4935   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4936                                     dyn_cast<IntrinsicInst>(CI));
4937   auto IntrinsicCost =
4938     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4939 
4940   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4941                                      VecTy->getNumElements())),
4942                             false /*HasGlobalPred*/);
4943   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4944   auto LibCost = IntrinsicCost;
4945   if (!CI->isNoBuiltin() && VecFunc) {
4946     // Calculate the cost of the vector library call.
4947     // If the corresponding vector call is cheaper, return its cost.
4948     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4949                                     TTI::TCK_RecipThroughput);
4950   }
4951   return {IntrinsicCost, LibCost};
4952 }
4953 
4954 /// Compute the cost of creating a vector of type \p VecTy containing the
4955 /// extracted values from \p VL.
4956 static InstructionCost
4957 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4958                    TargetTransformInfo::ShuffleKind ShuffleKind,
4959                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4960   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4961 
4962   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4963       VecTy->getNumElements() < NumOfParts)
4964     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4965 
4966   bool AllConsecutive = true;
4967   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4968   unsigned Idx = -1;
4969   InstructionCost Cost = 0;
4970 
4971   // Process extracts in blocks of EltsPerVector to check if the source vector
4972   // operand can be re-used directly. If not, add the cost of creating a shuffle
4973   // to extract the values into a vector register.
4974   for (auto *V : VL) {
4975     ++Idx;
4976 
4977     // Need to exclude undefs from analysis.
4978     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4979       continue;
4980 
4981     // Reached the start of a new vector registers.
4982     if (Idx % EltsPerVector == 0) {
4983       AllConsecutive = true;
4984       continue;
4985     }
4986 
4987     // Check all extracts for a vector register on the target directly
4988     // extract values in order.
4989     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4990     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4991       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4992       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4993                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4994     }
4995 
4996     if (AllConsecutive)
4997       continue;
4998 
4999     // Skip all indices, except for the last index per vector block.
5000     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5001       continue;
5002 
5003     // If we have a series of extracts which are not consecutive and hence
5004     // cannot re-use the source vector register directly, compute the shuffle
5005     // cost to extract the a vector with EltsPerVector elements.
5006     Cost += TTI.getShuffleCost(
5007         TargetTransformInfo::SK_PermuteSingleSrc,
5008         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5009   }
5010   return Cost;
5011 }
5012 
5013 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5014 /// operations operands.
5015 static void
5016 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5017                       ArrayRef<int> ReusesIndices,
5018                       const function_ref<bool(Instruction *)> IsAltOp,
5019                       SmallVectorImpl<int> &Mask,
5020                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5021                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5022   unsigned Sz = VL.size();
5023   Mask.assign(Sz, UndefMaskElem);
5024   SmallVector<int> OrderMask;
5025   if (!ReorderIndices.empty())
5026     inversePermutation(ReorderIndices, OrderMask);
5027   for (unsigned I = 0; I < Sz; ++I) {
5028     unsigned Idx = I;
5029     if (!ReorderIndices.empty())
5030       Idx = OrderMask[I];
5031     auto *OpInst = cast<Instruction>(VL[Idx]);
5032     if (IsAltOp(OpInst)) {
5033       Mask[I] = Sz + Idx;
5034       if (AltScalars)
5035         AltScalars->push_back(OpInst);
5036     } else {
5037       Mask[I] = Idx;
5038       if (OpScalars)
5039         OpScalars->push_back(OpInst);
5040     }
5041   }
5042   if (!ReusesIndices.empty()) {
5043     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5044     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5045       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5046     });
5047     Mask.swap(NewMask);
5048   }
5049 }
5050 
5051 /// Checks if the specified instruction \p I is an alternate operation for the
5052 /// given \p MainOp and \p AltOp instructions.
5053 static bool isAlternateInstruction(const Instruction *I,
5054                                    const Instruction *MainOp,
5055                                    const Instruction *AltOp) {
5056   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5057     auto *AltCI0 = cast<CmpInst>(AltOp);
5058     auto *CI = cast<CmpInst>(I);
5059     CmpInst::Predicate P0 = CI0->getPredicate();
5060     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5061     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5062     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5063     CmpInst::Predicate CurrentPred = CI->getPredicate();
5064     if (P0 == AltP0Swapped)
5065       return I == AltCI0 ||
5066              (I != MainOp &&
5067               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5068                                    CI->getOperand(0), CI->getOperand(1)));
5069     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5070   }
5071   return I->getOpcode() == AltOp->getOpcode();
5072 }
5073 
5074 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5075                                       ArrayRef<Value *> VectorizedVals) {
5076   ArrayRef<Value*> VL = E->Scalars;
5077 
5078   Type *ScalarTy = VL[0]->getType();
5079   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5080     ScalarTy = SI->getValueOperand()->getType();
5081   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5082     ScalarTy = CI->getOperand(0)->getType();
5083   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5084     ScalarTy = IE->getOperand(1)->getType();
5085   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5086   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5087 
5088   // If we have computed a smaller type for the expression, update VecTy so
5089   // that the costs will be accurate.
5090   if (MinBWs.count(VL[0]))
5091     VecTy = FixedVectorType::get(
5092         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5093   unsigned EntryVF = E->getVectorFactor();
5094   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5095 
5096   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5097   // FIXME: it tries to fix a problem with MSVC buildbots.
5098   TargetTransformInfo &TTIRef = *TTI;
5099   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5100                                VectorizedVals, E](InstructionCost &Cost) {
5101     DenseMap<Value *, int> ExtractVectorsTys;
5102     SmallPtrSet<Value *, 4> CheckedExtracts;
5103     for (auto *V : VL) {
5104       if (isa<UndefValue>(V))
5105         continue;
5106       // If all users of instruction are going to be vectorized and this
5107       // instruction itself is not going to be vectorized, consider this
5108       // instruction as dead and remove its cost from the final cost of the
5109       // vectorized tree.
5110       // Also, avoid adjusting the cost for extractelements with multiple uses
5111       // in different graph entries.
5112       const TreeEntry *VE = getTreeEntry(V);
5113       if (!CheckedExtracts.insert(V).second ||
5114           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5115           (VE && VE != E))
5116         continue;
5117       auto *EE = cast<ExtractElementInst>(V);
5118       Optional<unsigned> EEIdx = getExtractIndex(EE);
5119       if (!EEIdx)
5120         continue;
5121       unsigned Idx = *EEIdx;
5122       if (TTIRef.getNumberOfParts(VecTy) !=
5123           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5124         auto It =
5125             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5126         It->getSecond() = std::min<int>(It->second, Idx);
5127       }
5128       // Take credit for instruction that will become dead.
5129       if (EE->hasOneUse()) {
5130         Instruction *Ext = EE->user_back();
5131         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5132             all_of(Ext->users(),
5133                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5134           // Use getExtractWithExtendCost() to calculate the cost of
5135           // extractelement/ext pair.
5136           Cost -=
5137               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5138                                               EE->getVectorOperandType(), Idx);
5139           // Add back the cost of s|zext which is subtracted separately.
5140           Cost += TTIRef.getCastInstrCost(
5141               Ext->getOpcode(), Ext->getType(), EE->getType(),
5142               TTI::getCastContextHint(Ext), CostKind, Ext);
5143           continue;
5144         }
5145       }
5146       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5147                                         EE->getVectorOperandType(), Idx);
5148     }
5149     // Add a cost for subvector extracts/inserts if required.
5150     for (const auto &Data : ExtractVectorsTys) {
5151       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5152       unsigned NumElts = VecTy->getNumElements();
5153       if (Data.second % NumElts == 0)
5154         continue;
5155       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5156         unsigned Idx = (Data.second / NumElts) * NumElts;
5157         unsigned EENumElts = EEVTy->getNumElements();
5158         if (Idx + NumElts <= EENumElts) {
5159           Cost +=
5160               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5161                                     EEVTy, None, Idx, VecTy);
5162         } else {
5163           // Need to round up the subvector type vectorization factor to avoid a
5164           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5165           // <= EENumElts.
5166           auto *SubVT =
5167               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5168           Cost +=
5169               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5170                                     EEVTy, None, Idx, SubVT);
5171         }
5172       } else {
5173         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5174                                       VecTy, None, 0, EEVTy);
5175       }
5176     }
5177   };
5178   if (E->State == TreeEntry::NeedToGather) {
5179     if (allConstant(VL))
5180       return 0;
5181     if (isa<InsertElementInst>(VL[0]))
5182       return InstructionCost::getInvalid();
5183     SmallVector<int> Mask;
5184     SmallVector<const TreeEntry *> Entries;
5185     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5186         isGatherShuffledEntry(E, Mask, Entries);
5187     if (Shuffle.hasValue()) {
5188       InstructionCost GatherCost = 0;
5189       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5190         // Perfect match in the graph, will reuse the previously vectorized
5191         // node. Cost is 0.
5192         LLVM_DEBUG(
5193             dbgs()
5194             << "SLP: perfect diamond match for gather bundle that starts with "
5195             << *VL.front() << ".\n");
5196         if (NeedToShuffleReuses)
5197           GatherCost =
5198               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5199                                   FinalVecTy, E->ReuseShuffleIndices);
5200       } else {
5201         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5202                           << " entries for bundle that starts with "
5203                           << *VL.front() << ".\n");
5204         // Detected that instead of gather we can emit a shuffle of single/two
5205         // previously vectorized nodes. Add the cost of the permutation rather
5206         // than gather.
5207         ::addMask(Mask, E->ReuseShuffleIndices);
5208         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5209       }
5210       return GatherCost;
5211     }
5212     if ((E->getOpcode() == Instruction::ExtractElement ||
5213          all_of(E->Scalars,
5214                 [](Value *V) {
5215                   return isa<ExtractElementInst, UndefValue>(V);
5216                 })) &&
5217         allSameType(VL)) {
5218       // Check that gather of extractelements can be represented as just a
5219       // shuffle of a single/two vectors the scalars are extracted from.
5220       SmallVector<int> Mask;
5221       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5222           isFixedVectorShuffle(VL, Mask);
5223       if (ShuffleKind.hasValue()) {
5224         // Found the bunch of extractelement instructions that must be gathered
5225         // into a vector and can be represented as a permutation elements in a
5226         // single input vector or of 2 input vectors.
5227         InstructionCost Cost =
5228             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5229         AdjustExtractsCost(Cost);
5230         if (NeedToShuffleReuses)
5231           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5232                                       FinalVecTy, E->ReuseShuffleIndices);
5233         return Cost;
5234       }
5235     }
5236     if (isSplat(VL)) {
5237       // Found the broadcasting of the single scalar, calculate the cost as the
5238       // broadcast.
5239       assert(VecTy == FinalVecTy &&
5240              "No reused scalars expected for broadcast.");
5241       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5242     }
5243     InstructionCost ReuseShuffleCost = 0;
5244     if (NeedToShuffleReuses)
5245       ReuseShuffleCost = TTI->getShuffleCost(
5246           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5247     // Improve gather cost for gather of loads, if we can group some of the
5248     // loads into vector loads.
5249     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5250         !E->isAltShuffle()) {
5251       BoUpSLP::ValueSet VectorizedLoads;
5252       unsigned StartIdx = 0;
5253       unsigned VF = VL.size() / 2;
5254       unsigned VectorizedCnt = 0;
5255       unsigned ScatterVectorizeCnt = 0;
5256       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5257       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5258         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5259              Cnt += VF) {
5260           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5261           if (!VectorizedLoads.count(Slice.front()) &&
5262               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5263             SmallVector<Value *> PointerOps;
5264             OrdersType CurrentOrder;
5265             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5266                                               *SE, CurrentOrder, PointerOps);
5267             switch (LS) {
5268             case LoadsState::Vectorize:
5269             case LoadsState::ScatterVectorize:
5270               // Mark the vectorized loads so that we don't vectorize them
5271               // again.
5272               if (LS == LoadsState::Vectorize)
5273                 ++VectorizedCnt;
5274               else
5275                 ++ScatterVectorizeCnt;
5276               VectorizedLoads.insert(Slice.begin(), Slice.end());
5277               // If we vectorized initial block, no need to try to vectorize it
5278               // again.
5279               if (Cnt == StartIdx)
5280                 StartIdx += VF;
5281               break;
5282             case LoadsState::Gather:
5283               break;
5284             }
5285           }
5286         }
5287         // Check if the whole array was vectorized already - exit.
5288         if (StartIdx >= VL.size())
5289           break;
5290         // Found vectorizable parts - exit.
5291         if (!VectorizedLoads.empty())
5292           break;
5293       }
5294       if (!VectorizedLoads.empty()) {
5295         InstructionCost GatherCost = 0;
5296         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5297         bool NeedInsertSubvectorAnalysis =
5298             !NumParts || (VL.size() / VF) > NumParts;
5299         // Get the cost for gathered loads.
5300         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5301           if (VectorizedLoads.contains(VL[I]))
5302             continue;
5303           GatherCost += getGatherCost(VL.slice(I, VF));
5304         }
5305         // The cost for vectorized loads.
5306         InstructionCost ScalarsCost = 0;
5307         for (Value *V : VectorizedLoads) {
5308           auto *LI = cast<LoadInst>(V);
5309           ScalarsCost += TTI->getMemoryOpCost(
5310               Instruction::Load, LI->getType(), LI->getAlign(),
5311               LI->getPointerAddressSpace(), CostKind, LI);
5312         }
5313         auto *LI = cast<LoadInst>(E->getMainOp());
5314         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5315         Align Alignment = LI->getAlign();
5316         GatherCost +=
5317             VectorizedCnt *
5318             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5319                                  LI->getPointerAddressSpace(), CostKind, LI);
5320         GatherCost += ScatterVectorizeCnt *
5321                       TTI->getGatherScatterOpCost(
5322                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5323                           /*VariableMask=*/false, Alignment, CostKind, LI);
5324         if (NeedInsertSubvectorAnalysis) {
5325           // Add the cost for the subvectors insert.
5326           for (int I = VF, E = VL.size(); I < E; I += VF)
5327             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5328                                               None, I, LoadTy);
5329         }
5330         return ReuseShuffleCost + GatherCost - ScalarsCost;
5331       }
5332     }
5333     return ReuseShuffleCost + getGatherCost(VL);
5334   }
5335   InstructionCost CommonCost = 0;
5336   SmallVector<int> Mask;
5337   if (!E->ReorderIndices.empty()) {
5338     SmallVector<int> NewMask;
5339     if (E->getOpcode() == Instruction::Store) {
5340       // For stores the order is actually a mask.
5341       NewMask.resize(E->ReorderIndices.size());
5342       copy(E->ReorderIndices, NewMask.begin());
5343     } else {
5344       inversePermutation(E->ReorderIndices, NewMask);
5345     }
5346     ::addMask(Mask, NewMask);
5347   }
5348   if (NeedToShuffleReuses)
5349     ::addMask(Mask, E->ReuseShuffleIndices);
5350   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5351     CommonCost =
5352         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5353   assert((E->State == TreeEntry::Vectorize ||
5354           E->State == TreeEntry::ScatterVectorize) &&
5355          "Unhandled state");
5356   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5357   Instruction *VL0 = E->getMainOp();
5358   unsigned ShuffleOrOp =
5359       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5360   switch (ShuffleOrOp) {
5361     case Instruction::PHI:
5362       return 0;
5363 
5364     case Instruction::ExtractValue:
5365     case Instruction::ExtractElement: {
5366       // The common cost of removal ExtractElement/ExtractValue instructions +
5367       // the cost of shuffles, if required to resuffle the original vector.
5368       if (NeedToShuffleReuses) {
5369         unsigned Idx = 0;
5370         for (unsigned I : E->ReuseShuffleIndices) {
5371           if (ShuffleOrOp == Instruction::ExtractElement) {
5372             auto *EE = cast<ExtractElementInst>(VL[I]);
5373             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5374                                                   EE->getVectorOperandType(),
5375                                                   *getExtractIndex(EE));
5376           } else {
5377             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5378                                                   VecTy, Idx);
5379             ++Idx;
5380           }
5381         }
5382         Idx = EntryVF;
5383         for (Value *V : VL) {
5384           if (ShuffleOrOp == Instruction::ExtractElement) {
5385             auto *EE = cast<ExtractElementInst>(V);
5386             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5387                                                   EE->getVectorOperandType(),
5388                                                   *getExtractIndex(EE));
5389           } else {
5390             --Idx;
5391             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5392                                                   VecTy, Idx);
5393           }
5394         }
5395       }
5396       if (ShuffleOrOp == Instruction::ExtractValue) {
5397         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5398           auto *EI = cast<Instruction>(VL[I]);
5399           // Take credit for instruction that will become dead.
5400           if (EI->hasOneUse()) {
5401             Instruction *Ext = EI->user_back();
5402             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5403                 all_of(Ext->users(),
5404                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5405               // Use getExtractWithExtendCost() to calculate the cost of
5406               // extractelement/ext pair.
5407               CommonCost -= TTI->getExtractWithExtendCost(
5408                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5409               // Add back the cost of s|zext which is subtracted separately.
5410               CommonCost += TTI->getCastInstrCost(
5411                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5412                   TTI::getCastContextHint(Ext), CostKind, Ext);
5413               continue;
5414             }
5415           }
5416           CommonCost -=
5417               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5418         }
5419       } else {
5420         AdjustExtractsCost(CommonCost);
5421       }
5422       return CommonCost;
5423     }
5424     case Instruction::InsertElement: {
5425       assert(E->ReuseShuffleIndices.empty() &&
5426              "Unique insertelements only are expected.");
5427       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5428 
5429       unsigned const NumElts = SrcVecTy->getNumElements();
5430       unsigned const NumScalars = VL.size();
5431       APInt DemandedElts = APInt::getZero(NumElts);
5432       // TODO: Add support for Instruction::InsertValue.
5433       SmallVector<int> Mask;
5434       if (!E->ReorderIndices.empty()) {
5435         inversePermutation(E->ReorderIndices, Mask);
5436         Mask.append(NumElts - NumScalars, UndefMaskElem);
5437       } else {
5438         Mask.assign(NumElts, UndefMaskElem);
5439         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5440       }
5441       unsigned Offset = *getInsertIndex(VL0);
5442       bool IsIdentity = true;
5443       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5444       Mask.swap(PrevMask);
5445       for (unsigned I = 0; I < NumScalars; ++I) {
5446         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5447         DemandedElts.setBit(InsertIdx);
5448         IsIdentity &= InsertIdx - Offset == I;
5449         Mask[InsertIdx - Offset] = I;
5450       }
5451       assert(Offset < NumElts && "Failed to find vector index offset");
5452 
5453       InstructionCost Cost = 0;
5454       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5455                                             /*Insert*/ true, /*Extract*/ false);
5456 
5457       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5458         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5459         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5460         Cost += TTI->getShuffleCost(
5461             TargetTransformInfo::SK_PermuteSingleSrc,
5462             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5463       } else if (!IsIdentity) {
5464         auto *FirstInsert =
5465             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5466               return !is_contained(E->Scalars,
5467                                    cast<Instruction>(V)->getOperand(0));
5468             }));
5469         if (isUndefVector(FirstInsert->getOperand(0))) {
5470           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5471         } else {
5472           SmallVector<int> InsertMask(NumElts);
5473           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5474           for (unsigned I = 0; I < NumElts; I++) {
5475             if (Mask[I] != UndefMaskElem)
5476               InsertMask[Offset + I] = NumElts + I;
5477           }
5478           Cost +=
5479               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5480         }
5481       }
5482 
5483       return Cost;
5484     }
5485     case Instruction::ZExt:
5486     case Instruction::SExt:
5487     case Instruction::FPToUI:
5488     case Instruction::FPToSI:
5489     case Instruction::FPExt:
5490     case Instruction::PtrToInt:
5491     case Instruction::IntToPtr:
5492     case Instruction::SIToFP:
5493     case Instruction::UIToFP:
5494     case Instruction::Trunc:
5495     case Instruction::FPTrunc:
5496     case Instruction::BitCast: {
5497       Type *SrcTy = VL0->getOperand(0)->getType();
5498       InstructionCost ScalarEltCost =
5499           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5500                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5501       if (NeedToShuffleReuses) {
5502         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5503       }
5504 
5505       // Calculate the cost of this instruction.
5506       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5507 
5508       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5509       InstructionCost VecCost = 0;
5510       // Check if the values are candidates to demote.
5511       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5512         VecCost = CommonCost + TTI->getCastInstrCost(
5513                                    E->getOpcode(), VecTy, SrcVecTy,
5514                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5515       }
5516       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5517       return VecCost - ScalarCost;
5518     }
5519     case Instruction::FCmp:
5520     case Instruction::ICmp:
5521     case Instruction::Select: {
5522       // Calculate the cost of this instruction.
5523       InstructionCost ScalarEltCost =
5524           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5525                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5526       if (NeedToShuffleReuses) {
5527         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5528       }
5529       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5530       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5531 
5532       // Check if all entries in VL are either compares or selects with compares
5533       // as condition that have the same predicates.
5534       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5535       bool First = true;
5536       for (auto *V : VL) {
5537         CmpInst::Predicate CurrentPred;
5538         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5539         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5540              !match(V, MatchCmp)) ||
5541             (!First && VecPred != CurrentPred)) {
5542           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5543           break;
5544         }
5545         First = false;
5546         VecPred = CurrentPred;
5547       }
5548 
5549       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5550           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5551       // Check if it is possible and profitable to use min/max for selects in
5552       // VL.
5553       //
5554       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5555       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5556         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5557                                           {VecTy, VecTy});
5558         InstructionCost IntrinsicCost =
5559             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5560         // If the selects are the only uses of the compares, they will be dead
5561         // and we can adjust the cost by removing their cost.
5562         if (IntrinsicAndUse.second)
5563           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5564                                                    MaskTy, VecPred, CostKind);
5565         VecCost = std::min(VecCost, IntrinsicCost);
5566       }
5567       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5568       return CommonCost + VecCost - ScalarCost;
5569     }
5570     case Instruction::FNeg:
5571     case Instruction::Add:
5572     case Instruction::FAdd:
5573     case Instruction::Sub:
5574     case Instruction::FSub:
5575     case Instruction::Mul:
5576     case Instruction::FMul:
5577     case Instruction::UDiv:
5578     case Instruction::SDiv:
5579     case Instruction::FDiv:
5580     case Instruction::URem:
5581     case Instruction::SRem:
5582     case Instruction::FRem:
5583     case Instruction::Shl:
5584     case Instruction::LShr:
5585     case Instruction::AShr:
5586     case Instruction::And:
5587     case Instruction::Or:
5588     case Instruction::Xor: {
5589       // Certain instructions can be cheaper to vectorize if they have a
5590       // constant second vector operand.
5591       TargetTransformInfo::OperandValueKind Op1VK =
5592           TargetTransformInfo::OK_AnyValue;
5593       TargetTransformInfo::OperandValueKind Op2VK =
5594           TargetTransformInfo::OK_UniformConstantValue;
5595       TargetTransformInfo::OperandValueProperties Op1VP =
5596           TargetTransformInfo::OP_None;
5597       TargetTransformInfo::OperandValueProperties Op2VP =
5598           TargetTransformInfo::OP_PowerOf2;
5599 
5600       // If all operands are exactly the same ConstantInt then set the
5601       // operand kind to OK_UniformConstantValue.
5602       // If instead not all operands are constants, then set the operand kind
5603       // to OK_AnyValue. If all operands are constants but not the same,
5604       // then set the operand kind to OK_NonUniformConstantValue.
5605       ConstantInt *CInt0 = nullptr;
5606       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5607         const Instruction *I = cast<Instruction>(VL[i]);
5608         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5609         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5610         if (!CInt) {
5611           Op2VK = TargetTransformInfo::OK_AnyValue;
5612           Op2VP = TargetTransformInfo::OP_None;
5613           break;
5614         }
5615         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5616             !CInt->getValue().isPowerOf2())
5617           Op2VP = TargetTransformInfo::OP_None;
5618         if (i == 0) {
5619           CInt0 = CInt;
5620           continue;
5621         }
5622         if (CInt0 != CInt)
5623           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5624       }
5625 
5626       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5627       InstructionCost ScalarEltCost =
5628           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5629                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5630       if (NeedToShuffleReuses) {
5631         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5632       }
5633       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5634       InstructionCost VecCost =
5635           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5636                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5637       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5638       return CommonCost + VecCost - ScalarCost;
5639     }
5640     case Instruction::GetElementPtr: {
5641       TargetTransformInfo::OperandValueKind Op1VK =
5642           TargetTransformInfo::OK_AnyValue;
5643       TargetTransformInfo::OperandValueKind Op2VK =
5644           TargetTransformInfo::OK_UniformConstantValue;
5645 
5646       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5647           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5648       if (NeedToShuffleReuses) {
5649         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5650       }
5651       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5652       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5653           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5654       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5655       return CommonCost + VecCost - ScalarCost;
5656     }
5657     case Instruction::Load: {
5658       // Cost of wide load - cost of scalar loads.
5659       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5660       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5661           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5662       if (NeedToShuffleReuses) {
5663         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5664       }
5665       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5666       InstructionCost VecLdCost;
5667       if (E->State == TreeEntry::Vectorize) {
5668         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5669                                          CostKind, VL0);
5670       } else {
5671         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5672         Align CommonAlignment = Alignment;
5673         for (Value *V : VL)
5674           CommonAlignment =
5675               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5676         VecLdCost = TTI->getGatherScatterOpCost(
5677             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5678             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5679       }
5680       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5681       return CommonCost + VecLdCost - ScalarLdCost;
5682     }
5683     case Instruction::Store: {
5684       // We know that we can merge the stores. Calculate the cost.
5685       bool IsReorder = !E->ReorderIndices.empty();
5686       auto *SI =
5687           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5688       Align Alignment = SI->getAlign();
5689       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5690           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5691       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5692       InstructionCost VecStCost = TTI->getMemoryOpCost(
5693           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5694       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5695       return CommonCost + VecStCost - ScalarStCost;
5696     }
5697     case Instruction::Call: {
5698       CallInst *CI = cast<CallInst>(VL0);
5699       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5700 
5701       // Calculate the cost of the scalar and vector calls.
5702       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5703       InstructionCost ScalarEltCost =
5704           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5705       if (NeedToShuffleReuses) {
5706         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5707       }
5708       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5709 
5710       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5711       InstructionCost VecCallCost =
5712           std::min(VecCallCosts.first, VecCallCosts.second);
5713 
5714       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5715                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5716                         << " for " << *CI << "\n");
5717 
5718       return CommonCost + VecCallCost - ScalarCallCost;
5719     }
5720     case Instruction::ShuffleVector: {
5721       assert(E->isAltShuffle() &&
5722              ((Instruction::isBinaryOp(E->getOpcode()) &&
5723                Instruction::isBinaryOp(E->getAltOpcode())) ||
5724               (Instruction::isCast(E->getOpcode()) &&
5725                Instruction::isCast(E->getAltOpcode())) ||
5726               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5727              "Invalid Shuffle Vector Operand");
5728       InstructionCost ScalarCost = 0;
5729       if (NeedToShuffleReuses) {
5730         for (unsigned Idx : E->ReuseShuffleIndices) {
5731           Instruction *I = cast<Instruction>(VL[Idx]);
5732           CommonCost -= TTI->getInstructionCost(I, CostKind);
5733         }
5734         for (Value *V : VL) {
5735           Instruction *I = cast<Instruction>(V);
5736           CommonCost += TTI->getInstructionCost(I, CostKind);
5737         }
5738       }
5739       for (Value *V : VL) {
5740         Instruction *I = cast<Instruction>(V);
5741         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5742         ScalarCost += TTI->getInstructionCost(I, CostKind);
5743       }
5744       // VecCost is equal to sum of the cost of creating 2 vectors
5745       // and the cost of creating shuffle.
5746       InstructionCost VecCost = 0;
5747       // Try to find the previous shuffle node with the same operands and same
5748       // main/alternate ops.
5749       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5750         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5751           if (TE.get() == E)
5752             break;
5753           if (TE->isAltShuffle() &&
5754               ((TE->getOpcode() == E->getOpcode() &&
5755                 TE->getAltOpcode() == E->getAltOpcode()) ||
5756                (TE->getOpcode() == E->getAltOpcode() &&
5757                 TE->getAltOpcode() == E->getOpcode())) &&
5758               TE->hasEqualOperands(*E))
5759             return true;
5760         }
5761         return false;
5762       };
5763       if (TryFindNodeWithEqualOperands()) {
5764         LLVM_DEBUG({
5765           dbgs() << "SLP: diamond match for alternate node found.\n";
5766           E->dump();
5767         });
5768         // No need to add new vector costs here since we're going to reuse
5769         // same main/alternate vector ops, just do different shuffling.
5770       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5771         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5772         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5773                                                CostKind);
5774       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5775         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5776                                           Builder.getInt1Ty(),
5777                                           CI0->getPredicate(), CostKind, VL0);
5778         VecCost += TTI->getCmpSelInstrCost(
5779             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5780             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5781             E->getAltOp());
5782       } else {
5783         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5784         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5785         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5786         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5787         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5788                                         TTI::CastContextHint::None, CostKind);
5789         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5790                                          TTI::CastContextHint::None, CostKind);
5791       }
5792 
5793       SmallVector<int> Mask;
5794       buildShuffleEntryMask(
5795           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5796           [E](Instruction *I) {
5797             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5798             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5799           },
5800           Mask);
5801       CommonCost =
5802           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5803       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5804       return CommonCost + VecCost - ScalarCost;
5805     }
5806     default:
5807       llvm_unreachable("Unknown instruction");
5808   }
5809 }
5810 
5811 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5812   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5813                     << VectorizableTree.size() << " is fully vectorizable .\n");
5814 
5815   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5816     SmallVector<int> Mask;
5817     return TE->State == TreeEntry::NeedToGather &&
5818            !any_of(TE->Scalars,
5819                    [this](Value *V) { return EphValues.contains(V); }) &&
5820            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5821             TE->Scalars.size() < Limit ||
5822             ((TE->getOpcode() == Instruction::ExtractElement ||
5823               all_of(TE->Scalars,
5824                      [](Value *V) {
5825                        return isa<ExtractElementInst, UndefValue>(V);
5826                      })) &&
5827              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5828             (TE->State == TreeEntry::NeedToGather &&
5829              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5830   };
5831 
5832   // We only handle trees of heights 1 and 2.
5833   if (VectorizableTree.size() == 1 &&
5834       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5835        (ForReduction &&
5836         AreVectorizableGathers(VectorizableTree[0].get(),
5837                                VectorizableTree[0]->Scalars.size()) &&
5838         VectorizableTree[0]->getVectorFactor() > 2)))
5839     return true;
5840 
5841   if (VectorizableTree.size() != 2)
5842     return false;
5843 
5844   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5845   // with the second gather nodes if they have less scalar operands rather than
5846   // the initial tree element (may be profitable to shuffle the second gather)
5847   // or they are extractelements, which form shuffle.
5848   SmallVector<int> Mask;
5849   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5850       AreVectorizableGathers(VectorizableTree[1].get(),
5851                              VectorizableTree[0]->Scalars.size()))
5852     return true;
5853 
5854   // Gathering cost would be too much for tiny trees.
5855   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5856       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5857        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5858     return false;
5859 
5860   return true;
5861 }
5862 
5863 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5864                                        TargetTransformInfo *TTI,
5865                                        bool MustMatchOrInst) {
5866   // Look past the root to find a source value. Arbitrarily follow the
5867   // path through operand 0 of any 'or'. Also, peek through optional
5868   // shift-left-by-multiple-of-8-bits.
5869   Value *ZextLoad = Root;
5870   const APInt *ShAmtC;
5871   bool FoundOr = false;
5872   while (!isa<ConstantExpr>(ZextLoad) &&
5873          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5874           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5875            ShAmtC->urem(8) == 0))) {
5876     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5877     ZextLoad = BinOp->getOperand(0);
5878     if (BinOp->getOpcode() == Instruction::Or)
5879       FoundOr = true;
5880   }
5881   // Check if the input is an extended load of the required or/shift expression.
5882   Value *Load;
5883   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5884       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5885     return false;
5886 
5887   // Require that the total load bit width is a legal integer type.
5888   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5889   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5890   Type *SrcTy = Load->getType();
5891   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5892   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5893     return false;
5894 
5895   // Everything matched - assume that we can fold the whole sequence using
5896   // load combining.
5897   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5898              << *(cast<Instruction>(Root)) << "\n");
5899 
5900   return true;
5901 }
5902 
5903 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5904   if (RdxKind != RecurKind::Or)
5905     return false;
5906 
5907   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5908   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5909   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5910                                     /* MatchOr */ false);
5911 }
5912 
5913 bool BoUpSLP::isLoadCombineCandidate() const {
5914   // Peek through a final sequence of stores and check if all operations are
5915   // likely to be load-combined.
5916   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5917   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5918     Value *X;
5919     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5920         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5921       return false;
5922   }
5923   return true;
5924 }
5925 
5926 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5927   // No need to vectorize inserts of gathered values.
5928   if (VectorizableTree.size() == 2 &&
5929       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5930       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5931     return true;
5932 
5933   // We can vectorize the tree if its size is greater than or equal to the
5934   // minimum size specified by the MinTreeSize command line option.
5935   if (VectorizableTree.size() >= MinTreeSize)
5936     return false;
5937 
5938   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5939   // can vectorize it if we can prove it fully vectorizable.
5940   if (isFullyVectorizableTinyTree(ForReduction))
5941     return false;
5942 
5943   assert(VectorizableTree.empty()
5944              ? ExternalUses.empty()
5945              : true && "We shouldn't have any external users");
5946 
5947   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5948   // vectorizable.
5949   return true;
5950 }
5951 
5952 InstructionCost BoUpSLP::getSpillCost() const {
5953   // Walk from the bottom of the tree to the top, tracking which values are
5954   // live. When we see a call instruction that is not part of our tree,
5955   // query TTI to see if there is a cost to keeping values live over it
5956   // (for example, if spills and fills are required).
5957   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5958   InstructionCost Cost = 0;
5959 
5960   SmallPtrSet<Instruction*, 4> LiveValues;
5961   Instruction *PrevInst = nullptr;
5962 
5963   // The entries in VectorizableTree are not necessarily ordered by their
5964   // position in basic blocks. Collect them and order them by dominance so later
5965   // instructions are guaranteed to be visited first. For instructions in
5966   // different basic blocks, we only scan to the beginning of the block, so
5967   // their order does not matter, as long as all instructions in a basic block
5968   // are grouped together. Using dominance ensures a deterministic order.
5969   SmallVector<Instruction *, 16> OrderedScalars;
5970   for (const auto &TEPtr : VectorizableTree) {
5971     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5972     if (!Inst)
5973       continue;
5974     OrderedScalars.push_back(Inst);
5975   }
5976   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5977     auto *NodeA = DT->getNode(A->getParent());
5978     auto *NodeB = DT->getNode(B->getParent());
5979     assert(NodeA && "Should only process reachable instructions");
5980     assert(NodeB && "Should only process reachable instructions");
5981     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5982            "Different nodes should have different DFS numbers");
5983     if (NodeA != NodeB)
5984       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5985     return B->comesBefore(A);
5986   });
5987 
5988   for (Instruction *Inst : OrderedScalars) {
5989     if (!PrevInst) {
5990       PrevInst = Inst;
5991       continue;
5992     }
5993 
5994     // Update LiveValues.
5995     LiveValues.erase(PrevInst);
5996     for (auto &J : PrevInst->operands()) {
5997       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5998         LiveValues.insert(cast<Instruction>(&*J));
5999     }
6000 
6001     LLVM_DEBUG({
6002       dbgs() << "SLP: #LV: " << LiveValues.size();
6003       for (auto *X : LiveValues)
6004         dbgs() << " " << X->getName();
6005       dbgs() << ", Looking at ";
6006       Inst->dump();
6007     });
6008 
6009     // Now find the sequence of instructions between PrevInst and Inst.
6010     unsigned NumCalls = 0;
6011     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6012                                  PrevInstIt =
6013                                      PrevInst->getIterator().getReverse();
6014     while (InstIt != PrevInstIt) {
6015       if (PrevInstIt == PrevInst->getParent()->rend()) {
6016         PrevInstIt = Inst->getParent()->rbegin();
6017         continue;
6018       }
6019 
6020       // Debug information does not impact spill cost.
6021       if ((isa<CallInst>(&*PrevInstIt) &&
6022            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6023           &*PrevInstIt != PrevInst)
6024         NumCalls++;
6025 
6026       ++PrevInstIt;
6027     }
6028 
6029     if (NumCalls) {
6030       SmallVector<Type*, 4> V;
6031       for (auto *II : LiveValues) {
6032         auto *ScalarTy = II->getType();
6033         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6034           ScalarTy = VectorTy->getElementType();
6035         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6036       }
6037       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6038     }
6039 
6040     PrevInst = Inst;
6041   }
6042 
6043   return Cost;
6044 }
6045 
6046 /// Check if two insertelement instructions are from the same buildvector.
6047 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6048                                             InsertElementInst *V) {
6049   // Instructions must be from the same basic blocks.
6050   if (VU->getParent() != V->getParent())
6051     return false;
6052   // Checks if 2 insertelements are from the same buildvector.
6053   if (VU->getType() != V->getType())
6054     return false;
6055   // Multiple used inserts are separate nodes.
6056   if (!VU->hasOneUse() && !V->hasOneUse())
6057     return false;
6058   auto *IE1 = VU;
6059   auto *IE2 = V;
6060   // Go through the vector operand of insertelement instructions trying to find
6061   // either VU as the original vector for IE2 or V as the original vector for
6062   // IE1.
6063   do {
6064     if (IE2 == VU || IE1 == V)
6065       return true;
6066     if (IE1) {
6067       if (IE1 != VU && !IE1->hasOneUse())
6068         IE1 = nullptr;
6069       else
6070         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6071     }
6072     if (IE2) {
6073       if (IE2 != V && !IE2->hasOneUse())
6074         IE2 = nullptr;
6075       else
6076         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6077     }
6078   } while (IE1 || IE2);
6079   return false;
6080 }
6081 
6082 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6083   InstructionCost Cost = 0;
6084   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6085                     << VectorizableTree.size() << ".\n");
6086 
6087   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6088 
6089   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6090     TreeEntry &TE = *VectorizableTree[I].get();
6091 
6092     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6093     Cost += C;
6094     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6095                       << " for bundle that starts with " << *TE.Scalars[0]
6096                       << ".\n"
6097                       << "SLP: Current total cost = " << Cost << "\n");
6098   }
6099 
6100   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6101   InstructionCost ExtractCost = 0;
6102   SmallVector<unsigned> VF;
6103   SmallVector<SmallVector<int>> ShuffleMask;
6104   SmallVector<Value *> FirstUsers;
6105   SmallVector<APInt> DemandedElts;
6106   for (ExternalUser &EU : ExternalUses) {
6107     // We only add extract cost once for the same scalar.
6108     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6109         !ExtractCostCalculated.insert(EU.Scalar).second)
6110       continue;
6111 
6112     // Uses by ephemeral values are free (because the ephemeral value will be
6113     // removed prior to code generation, and so the extraction will be
6114     // removed as well).
6115     if (EphValues.count(EU.User))
6116       continue;
6117 
6118     // No extract cost for vector "scalar"
6119     if (isa<FixedVectorType>(EU.Scalar->getType()))
6120       continue;
6121 
6122     // Already counted the cost for external uses when tried to adjust the cost
6123     // for extractelements, no need to add it again.
6124     if (isa<ExtractElementInst>(EU.Scalar))
6125       continue;
6126 
6127     // If found user is an insertelement, do not calculate extract cost but try
6128     // to detect it as a final shuffled/identity match.
6129     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6130       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6131         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6132         if (InsertIdx) {
6133           auto *It = find_if(FirstUsers, [VU](Value *V) {
6134             return areTwoInsertFromSameBuildVector(VU,
6135                                                    cast<InsertElementInst>(V));
6136           });
6137           int VecId = -1;
6138           if (It == FirstUsers.end()) {
6139             VF.push_back(FTy->getNumElements());
6140             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6141             // Find the insertvector, vectorized in tree, if any.
6142             Value *Base = VU;
6143             while (isa<InsertElementInst>(Base)) {
6144               // Build the mask for the vectorized insertelement instructions.
6145               if (const TreeEntry *E = getTreeEntry(Base)) {
6146                 VU = cast<InsertElementInst>(Base);
6147                 do {
6148                   int Idx = E->findLaneForValue(Base);
6149                   ShuffleMask.back()[Idx] = Idx;
6150                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6151                 } while (E == getTreeEntry(Base));
6152                 break;
6153               }
6154               Base = cast<InsertElementInst>(Base)->getOperand(0);
6155             }
6156             FirstUsers.push_back(VU);
6157             DemandedElts.push_back(APInt::getZero(VF.back()));
6158             VecId = FirstUsers.size() - 1;
6159           } else {
6160             VecId = std::distance(FirstUsers.begin(), It);
6161           }
6162           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6163           DemandedElts[VecId].setBit(*InsertIdx);
6164           continue;
6165         }
6166       }
6167     }
6168 
6169     // If we plan to rewrite the tree in a smaller type, we will need to sign
6170     // extend the extracted value back to the original type. Here, we account
6171     // for the extract and the added cost of the sign extend if needed.
6172     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6173     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6174     if (MinBWs.count(ScalarRoot)) {
6175       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6176       auto Extend =
6177           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6178       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6179       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6180                                                    VecTy, EU.Lane);
6181     } else {
6182       ExtractCost +=
6183           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6184     }
6185   }
6186 
6187   InstructionCost SpillCost = getSpillCost();
6188   Cost += SpillCost + ExtractCost;
6189   if (FirstUsers.size() == 1) {
6190     int Limit = ShuffleMask.front().size() * 2;
6191     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6192         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6193       InstructionCost C = TTI->getShuffleCost(
6194           TTI::SK_PermuteSingleSrc,
6195           cast<FixedVectorType>(FirstUsers.front()->getType()),
6196           ShuffleMask.front());
6197       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6198                         << " for final shuffle of insertelement external users "
6199                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6200                         << "SLP: Current total cost = " << Cost << "\n");
6201       Cost += C;
6202     }
6203     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6204         cast<FixedVectorType>(FirstUsers.front()->getType()),
6205         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6206     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6207                       << " for insertelements gather.\n"
6208                       << "SLP: Current total cost = " << Cost << "\n");
6209     Cost -= InsertCost;
6210   } else if (FirstUsers.size() >= 2) {
6211     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6212     // Combined masks of the first 2 vectors.
6213     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6214     copy(ShuffleMask.front(), CombinedMask.begin());
6215     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6216     auto *VecTy = FixedVectorType::get(
6217         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6218         MaxVF);
6219     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6220       if (ShuffleMask[1][I] != UndefMaskElem) {
6221         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6222         CombinedDemandedElts.setBit(I);
6223       }
6224     }
6225     InstructionCost C =
6226         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6227     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6228                       << " for final shuffle of vector node and external "
6229                          "insertelement users "
6230                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6231                       << "SLP: Current total cost = " << Cost << "\n");
6232     Cost += C;
6233     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6234         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6235     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6236                       << " for insertelements gather.\n"
6237                       << "SLP: Current total cost = " << Cost << "\n");
6238     Cost -= InsertCost;
6239     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6240       // Other elements - permutation of 2 vectors (the initial one and the
6241       // next Ith incoming vector).
6242       unsigned VF = ShuffleMask[I].size();
6243       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6244         int Mask = ShuffleMask[I][Idx];
6245         if (Mask != UndefMaskElem)
6246           CombinedMask[Idx] = MaxVF + Mask;
6247         else if (CombinedMask[Idx] != UndefMaskElem)
6248           CombinedMask[Idx] = Idx;
6249       }
6250       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6251         if (CombinedMask[Idx] != UndefMaskElem)
6252           CombinedMask[Idx] = Idx;
6253       InstructionCost C =
6254           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6255       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6256                         << " for final shuffle of vector node and external "
6257                            "insertelement users "
6258                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6259                         << "SLP: Current total cost = " << Cost << "\n");
6260       Cost += C;
6261       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6262           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6263           /*Insert*/ true, /*Extract*/ false);
6264       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6265                         << " for insertelements gather.\n"
6266                         << "SLP: Current total cost = " << Cost << "\n");
6267       Cost -= InsertCost;
6268     }
6269   }
6270 
6271 #ifndef NDEBUG
6272   SmallString<256> Str;
6273   {
6274     raw_svector_ostream OS(Str);
6275     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6276        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6277        << "SLP: Total Cost = " << Cost << ".\n";
6278   }
6279   LLVM_DEBUG(dbgs() << Str);
6280   if (ViewSLPTree)
6281     ViewGraph(this, "SLP" + F->getName(), false, Str);
6282 #endif
6283 
6284   return Cost;
6285 }
6286 
6287 Optional<TargetTransformInfo::ShuffleKind>
6288 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6289                                SmallVectorImpl<const TreeEntry *> &Entries) {
6290   // TODO: currently checking only for Scalars in the tree entry, need to count
6291   // reused elements too for better cost estimation.
6292   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6293   Entries.clear();
6294   // Build a lists of values to tree entries.
6295   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6296   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6297     if (EntryPtr.get() == TE)
6298       break;
6299     if (EntryPtr->State != TreeEntry::NeedToGather)
6300       continue;
6301     for (Value *V : EntryPtr->Scalars)
6302       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6303   }
6304   // Find all tree entries used by the gathered values. If no common entries
6305   // found - not a shuffle.
6306   // Here we build a set of tree nodes for each gathered value and trying to
6307   // find the intersection between these sets. If we have at least one common
6308   // tree node for each gathered value - we have just a permutation of the
6309   // single vector. If we have 2 different sets, we're in situation where we
6310   // have a permutation of 2 input vectors.
6311   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6312   DenseMap<Value *, int> UsedValuesEntry;
6313   for (Value *V : TE->Scalars) {
6314     if (isa<UndefValue>(V))
6315       continue;
6316     // Build a list of tree entries where V is used.
6317     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6318     auto It = ValueToTEs.find(V);
6319     if (It != ValueToTEs.end())
6320       VToTEs = It->second;
6321     if (const TreeEntry *VTE = getTreeEntry(V))
6322       VToTEs.insert(VTE);
6323     if (VToTEs.empty())
6324       return None;
6325     if (UsedTEs.empty()) {
6326       // The first iteration, just insert the list of nodes to vector.
6327       UsedTEs.push_back(VToTEs);
6328     } else {
6329       // Need to check if there are any previously used tree nodes which use V.
6330       // If there are no such nodes, consider that we have another one input
6331       // vector.
6332       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6333       unsigned Idx = 0;
6334       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6335         // Do we have a non-empty intersection of previously listed tree entries
6336         // and tree entries using current V?
6337         set_intersect(VToTEs, Set);
6338         if (!VToTEs.empty()) {
6339           // Yes, write the new subset and continue analysis for the next
6340           // scalar.
6341           Set.swap(VToTEs);
6342           break;
6343         }
6344         VToTEs = SavedVToTEs;
6345         ++Idx;
6346       }
6347       // No non-empty intersection found - need to add a second set of possible
6348       // source vectors.
6349       if (Idx == UsedTEs.size()) {
6350         // If the number of input vectors is greater than 2 - not a permutation,
6351         // fallback to the regular gather.
6352         if (UsedTEs.size() == 2)
6353           return None;
6354         UsedTEs.push_back(SavedVToTEs);
6355         Idx = UsedTEs.size() - 1;
6356       }
6357       UsedValuesEntry.try_emplace(V, Idx);
6358     }
6359   }
6360 
6361   unsigned VF = 0;
6362   if (UsedTEs.size() == 1) {
6363     // Try to find the perfect match in another gather node at first.
6364     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6365       return EntryPtr->isSame(TE->Scalars);
6366     });
6367     if (It != UsedTEs.front().end()) {
6368       Entries.push_back(*It);
6369       std::iota(Mask.begin(), Mask.end(), 0);
6370       return TargetTransformInfo::SK_PermuteSingleSrc;
6371     }
6372     // No perfect match, just shuffle, so choose the first tree node.
6373     Entries.push_back(*UsedTEs.front().begin());
6374   } else {
6375     // Try to find nodes with the same vector factor.
6376     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6377     DenseMap<int, const TreeEntry *> VFToTE;
6378     for (const TreeEntry *TE : UsedTEs.front())
6379       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6380     for (const TreeEntry *TE : UsedTEs.back()) {
6381       auto It = VFToTE.find(TE->getVectorFactor());
6382       if (It != VFToTE.end()) {
6383         VF = It->first;
6384         Entries.push_back(It->second);
6385         Entries.push_back(TE);
6386         break;
6387       }
6388     }
6389     // No 2 source vectors with the same vector factor - give up and do regular
6390     // gather.
6391     if (Entries.empty())
6392       return None;
6393   }
6394 
6395   // Build a shuffle mask for better cost estimation and vector emission.
6396   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6397     Value *V = TE->Scalars[I];
6398     if (isa<UndefValue>(V))
6399       continue;
6400     unsigned Idx = UsedValuesEntry.lookup(V);
6401     const TreeEntry *VTE = Entries[Idx];
6402     int FoundLane = VTE->findLaneForValue(V);
6403     Mask[I] = Idx * VF + FoundLane;
6404     // Extra check required by isSingleSourceMaskImpl function (called by
6405     // ShuffleVectorInst::isSingleSourceMask).
6406     if (Mask[I] >= 2 * E)
6407       return None;
6408   }
6409   switch (Entries.size()) {
6410   case 1:
6411     return TargetTransformInfo::SK_PermuteSingleSrc;
6412   case 2:
6413     return TargetTransformInfo::SK_PermuteTwoSrc;
6414   default:
6415     break;
6416   }
6417   return None;
6418 }
6419 
6420 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6421                                        const APInt &ShuffledIndices,
6422                                        bool NeedToShuffle) const {
6423   InstructionCost Cost =
6424       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6425                                     /*Extract*/ false);
6426   if (NeedToShuffle)
6427     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6428   return Cost;
6429 }
6430 
6431 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6432   // Find the type of the operands in VL.
6433   Type *ScalarTy = VL[0]->getType();
6434   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6435     ScalarTy = SI->getValueOperand()->getType();
6436   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6437   bool DuplicateNonConst = false;
6438   // Find the cost of inserting/extracting values from the vector.
6439   // Check if the same elements are inserted several times and count them as
6440   // shuffle candidates.
6441   APInt ShuffledElements = APInt::getZero(VL.size());
6442   DenseSet<Value *> UniqueElements;
6443   // Iterate in reverse order to consider insert elements with the high cost.
6444   for (unsigned I = VL.size(); I > 0; --I) {
6445     unsigned Idx = I - 1;
6446     // No need to shuffle duplicates for constants.
6447     if (isConstant(VL[Idx])) {
6448       ShuffledElements.setBit(Idx);
6449       continue;
6450     }
6451     if (!UniqueElements.insert(VL[Idx]).second) {
6452       DuplicateNonConst = true;
6453       ShuffledElements.setBit(Idx);
6454     }
6455   }
6456   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6457 }
6458 
6459 // Perform operand reordering on the instructions in VL and return the reordered
6460 // operands in Left and Right.
6461 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6462                                              SmallVectorImpl<Value *> &Left,
6463                                              SmallVectorImpl<Value *> &Right,
6464                                              const DataLayout &DL,
6465                                              ScalarEvolution &SE,
6466                                              const BoUpSLP &R) {
6467   if (VL.empty())
6468     return;
6469   VLOperands Ops(VL, DL, SE, R);
6470   // Reorder the operands in place.
6471   Ops.reorder();
6472   Left = Ops.getVL(0);
6473   Right = Ops.getVL(1);
6474 }
6475 
6476 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6477   // Get the basic block this bundle is in. All instructions in the bundle
6478   // should be in this block.
6479   auto *Front = E->getMainOp();
6480   auto *BB = Front->getParent();
6481   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6482     auto *I = cast<Instruction>(V);
6483     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6484   }));
6485 
6486   auto &&FindLastInst = [E, Front]() {
6487     Instruction *LastInst = Front;
6488     for (Value *V : E->Scalars) {
6489       auto *I = dyn_cast<Instruction>(V);
6490       if (!I)
6491         continue;
6492       if (LastInst->comesBefore(I))
6493         LastInst = I;
6494     }
6495     return LastInst;
6496   };
6497 
6498   auto &&FindFirstInst = [E, Front]() {
6499     Instruction *FirstInst = Front;
6500     for (Value *V : E->Scalars) {
6501       auto *I = dyn_cast<Instruction>(V);
6502       if (!I)
6503         continue;
6504       if (I->comesBefore(FirstInst))
6505         FirstInst = I;
6506     }
6507     return FirstInst;
6508   };
6509 
6510   // Set the insert point to the beginning of the basic block if the entry
6511   // should not be scheduled.
6512   if (E->State != TreeEntry::NeedToGather &&
6513       doesNotNeedToSchedule(E->Scalars)) {
6514     BasicBlock::iterator InsertPt;
6515     if (all_of(E->Scalars, isUsedOutsideBlock))
6516       InsertPt = FindLastInst()->getIterator();
6517     else
6518       InsertPt = FindFirstInst()->getIterator();
6519     Builder.SetInsertPoint(BB, InsertPt);
6520     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6521     return;
6522   }
6523 
6524   // The last instruction in the bundle in program order.
6525   Instruction *LastInst = nullptr;
6526 
6527   // Find the last instruction. The common case should be that BB has been
6528   // scheduled, and the last instruction is VL.back(). So we start with
6529   // VL.back() and iterate over schedule data until we reach the end of the
6530   // bundle. The end of the bundle is marked by null ScheduleData.
6531   if (BlocksSchedules.count(BB)) {
6532     Value *V = E->isOneOf(E->Scalars.back());
6533     if (doesNotNeedToBeScheduled(V))
6534       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6535     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6536     if (Bundle && Bundle->isPartOfBundle())
6537       for (; Bundle; Bundle = Bundle->NextInBundle)
6538         if (Bundle->OpValue == Bundle->Inst)
6539           LastInst = Bundle->Inst;
6540   }
6541 
6542   // LastInst can still be null at this point if there's either not an entry
6543   // for BB in BlocksSchedules or there's no ScheduleData available for
6544   // VL.back(). This can be the case if buildTree_rec aborts for various
6545   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6546   // size is reached, etc.). ScheduleData is initialized in the scheduling
6547   // "dry-run".
6548   //
6549   // If this happens, we can still find the last instruction by brute force. We
6550   // iterate forwards from Front (inclusive) until we either see all
6551   // instructions in the bundle or reach the end of the block. If Front is the
6552   // last instruction in program order, LastInst will be set to Front, and we
6553   // will visit all the remaining instructions in the block.
6554   //
6555   // One of the reasons we exit early from buildTree_rec is to place an upper
6556   // bound on compile-time. Thus, taking an additional compile-time hit here is
6557   // not ideal. However, this should be exceedingly rare since it requires that
6558   // we both exit early from buildTree_rec and that the bundle be out-of-order
6559   // (causing us to iterate all the way to the end of the block).
6560   if (!LastInst)
6561     LastInst = FindLastInst();
6562   assert(LastInst && "Failed to find last instruction in bundle");
6563 
6564   // Set the insertion point after the last instruction in the bundle. Set the
6565   // debug location to Front.
6566   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6567   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6568 }
6569 
6570 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6571   // List of instructions/lanes from current block and/or the blocks which are
6572   // part of the current loop. These instructions will be inserted at the end to
6573   // make it possible to optimize loops and hoist invariant instructions out of
6574   // the loops body with better chances for success.
6575   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6576   SmallSet<int, 4> PostponedIndices;
6577   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6578   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6579     SmallPtrSet<BasicBlock *, 4> Visited;
6580     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6581       InsertBB = InsertBB->getSinglePredecessor();
6582     return InsertBB && InsertBB == InstBB;
6583   };
6584   for (int I = 0, E = VL.size(); I < E; ++I) {
6585     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6586       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6587            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6588           PostponedIndices.insert(I).second)
6589         PostponedInsts.emplace_back(Inst, I);
6590   }
6591 
6592   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6593     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6594     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6595     if (!InsElt)
6596       return Vec;
6597     GatherShuffleSeq.insert(InsElt);
6598     CSEBlocks.insert(InsElt->getParent());
6599     // Add to our 'need-to-extract' list.
6600     if (TreeEntry *Entry = getTreeEntry(V)) {
6601       // Find which lane we need to extract.
6602       unsigned FoundLane = Entry->findLaneForValue(V);
6603       ExternalUses.emplace_back(V, InsElt, FoundLane);
6604     }
6605     return Vec;
6606   };
6607   Value *Val0 =
6608       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6609   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6610   Value *Vec = PoisonValue::get(VecTy);
6611   SmallVector<int> NonConsts;
6612   // Insert constant values at first.
6613   for (int I = 0, E = VL.size(); I < E; ++I) {
6614     if (PostponedIndices.contains(I))
6615       continue;
6616     if (!isConstant(VL[I])) {
6617       NonConsts.push_back(I);
6618       continue;
6619     }
6620     Vec = CreateInsertElement(Vec, VL[I], I);
6621   }
6622   // Insert non-constant values.
6623   for (int I : NonConsts)
6624     Vec = CreateInsertElement(Vec, VL[I], I);
6625   // Append instructions, which are/may be part of the loop, in the end to make
6626   // it possible to hoist non-loop-based instructions.
6627   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6628     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6629 
6630   return Vec;
6631 }
6632 
6633 namespace {
6634 /// Merges shuffle masks and emits final shuffle instruction, if required.
6635 class ShuffleInstructionBuilder {
6636   IRBuilderBase &Builder;
6637   const unsigned VF = 0;
6638   bool IsFinalized = false;
6639   SmallVector<int, 4> Mask;
6640   /// Holds all of the instructions that we gathered.
6641   SetVector<Instruction *> &GatherShuffleSeq;
6642   /// A list of blocks that we are going to CSE.
6643   SetVector<BasicBlock *> &CSEBlocks;
6644 
6645 public:
6646   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6647                             SetVector<Instruction *> &GatherShuffleSeq,
6648                             SetVector<BasicBlock *> &CSEBlocks)
6649       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6650         CSEBlocks(CSEBlocks) {}
6651 
6652   /// Adds a mask, inverting it before applying.
6653   void addInversedMask(ArrayRef<unsigned> SubMask) {
6654     if (SubMask.empty())
6655       return;
6656     SmallVector<int, 4> NewMask;
6657     inversePermutation(SubMask, NewMask);
6658     addMask(NewMask);
6659   }
6660 
6661   /// Functions adds masks, merging them into  single one.
6662   void addMask(ArrayRef<unsigned> SubMask) {
6663     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6664     addMask(NewMask);
6665   }
6666 
6667   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6668 
6669   Value *finalize(Value *V) {
6670     IsFinalized = true;
6671     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6672     if (VF == ValueVF && Mask.empty())
6673       return V;
6674     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6675     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6676     addMask(NormalizedMask);
6677 
6678     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6679       return V;
6680     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6681     if (auto *I = dyn_cast<Instruction>(Vec)) {
6682       GatherShuffleSeq.insert(I);
6683       CSEBlocks.insert(I->getParent());
6684     }
6685     return Vec;
6686   }
6687 
6688   ~ShuffleInstructionBuilder() {
6689     assert((IsFinalized || Mask.empty()) &&
6690            "Shuffle construction must be finalized.");
6691   }
6692 };
6693 } // namespace
6694 
6695 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6696   const unsigned VF = VL.size();
6697   InstructionsState S = getSameOpcode(VL);
6698   if (S.getOpcode()) {
6699     if (TreeEntry *E = getTreeEntry(S.OpValue))
6700       if (E->isSame(VL)) {
6701         Value *V = vectorizeTree(E);
6702         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6703           if (!E->ReuseShuffleIndices.empty()) {
6704             // Reshuffle to get only unique values.
6705             // If some of the scalars are duplicated in the vectorization tree
6706             // entry, we do not vectorize them but instead generate a mask for
6707             // the reuses. But if there are several users of the same entry,
6708             // they may have different vectorization factors. This is especially
6709             // important for PHI nodes. In this case, we need to adapt the
6710             // resulting instruction for the user vectorization factor and have
6711             // to reshuffle it again to take only unique elements of the vector.
6712             // Without this code the function incorrectly returns reduced vector
6713             // instruction with the same elements, not with the unique ones.
6714 
6715             // block:
6716             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6717             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6718             // ... (use %2)
6719             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6720             // br %block
6721             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6722             SmallSet<int, 4> UsedIdxs;
6723             int Pos = 0;
6724             int Sz = VL.size();
6725             for (int Idx : E->ReuseShuffleIndices) {
6726               if (Idx != Sz && Idx != UndefMaskElem &&
6727                   UsedIdxs.insert(Idx).second)
6728                 UniqueIdxs[Idx] = Pos;
6729               ++Pos;
6730             }
6731             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6732                                             "less than original vector size.");
6733             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6734             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6735           } else {
6736             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6737                    "Expected vectorization factor less "
6738                    "than original vector size.");
6739             SmallVector<int> UniformMask(VF, 0);
6740             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6741             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6742           }
6743           if (auto *I = dyn_cast<Instruction>(V)) {
6744             GatherShuffleSeq.insert(I);
6745             CSEBlocks.insert(I->getParent());
6746           }
6747         }
6748         return V;
6749       }
6750   }
6751 
6752   // Can't vectorize this, so simply build a new vector with each lane
6753   // corresponding to the requested value.
6754   return createBuildVector(VL);
6755 }
6756 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6757   unsigned VF = VL.size();
6758   // Exploit possible reuse of values across lanes.
6759   SmallVector<int> ReuseShuffleIndicies;
6760   SmallVector<Value *> UniqueValues;
6761   if (VL.size() > 2) {
6762     DenseMap<Value *, unsigned> UniquePositions;
6763     unsigned NumValues =
6764         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6765                                     return !isa<UndefValue>(V);
6766                                   }).base());
6767     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6768     int UniqueVals = 0;
6769     for (Value *V : VL.drop_back(VL.size() - VF)) {
6770       if (isa<UndefValue>(V)) {
6771         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6772         continue;
6773       }
6774       if (isConstant(V)) {
6775         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6776         UniqueValues.emplace_back(V);
6777         continue;
6778       }
6779       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6780       ReuseShuffleIndicies.emplace_back(Res.first->second);
6781       if (Res.second) {
6782         UniqueValues.emplace_back(V);
6783         ++UniqueVals;
6784       }
6785     }
6786     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6787       // Emit pure splat vector.
6788       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6789                                   UndefMaskElem);
6790     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6791       ReuseShuffleIndicies.clear();
6792       UniqueValues.clear();
6793       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6794     }
6795     UniqueValues.append(VF - UniqueValues.size(),
6796                         PoisonValue::get(VL[0]->getType()));
6797     VL = UniqueValues;
6798   }
6799 
6800   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6801                                            CSEBlocks);
6802   Value *Vec = gather(VL);
6803   if (!ReuseShuffleIndicies.empty()) {
6804     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6805     Vec = ShuffleBuilder.finalize(Vec);
6806   }
6807   return Vec;
6808 }
6809 
6810 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6811   IRBuilder<>::InsertPointGuard Guard(Builder);
6812 
6813   if (E->VectorizedValue) {
6814     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6815     return E->VectorizedValue;
6816   }
6817 
6818   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6819   unsigned VF = E->getVectorFactor();
6820   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6821                                            CSEBlocks);
6822   if (E->State == TreeEntry::NeedToGather) {
6823     if (E->getMainOp())
6824       setInsertPointAfterBundle(E);
6825     Value *Vec;
6826     SmallVector<int> Mask;
6827     SmallVector<const TreeEntry *> Entries;
6828     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6829         isGatherShuffledEntry(E, Mask, Entries);
6830     if (Shuffle.hasValue()) {
6831       assert((Entries.size() == 1 || Entries.size() == 2) &&
6832              "Expected shuffle of 1 or 2 entries.");
6833       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6834                                         Entries.back()->VectorizedValue, Mask);
6835       if (auto *I = dyn_cast<Instruction>(Vec)) {
6836         GatherShuffleSeq.insert(I);
6837         CSEBlocks.insert(I->getParent());
6838       }
6839     } else {
6840       Vec = gather(E->Scalars);
6841     }
6842     if (NeedToShuffleReuses) {
6843       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6844       Vec = ShuffleBuilder.finalize(Vec);
6845     }
6846     E->VectorizedValue = Vec;
6847     return Vec;
6848   }
6849 
6850   assert((E->State == TreeEntry::Vectorize ||
6851           E->State == TreeEntry::ScatterVectorize) &&
6852          "Unhandled state");
6853   unsigned ShuffleOrOp =
6854       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6855   Instruction *VL0 = E->getMainOp();
6856   Type *ScalarTy = VL0->getType();
6857   if (auto *Store = dyn_cast<StoreInst>(VL0))
6858     ScalarTy = Store->getValueOperand()->getType();
6859   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6860     ScalarTy = IE->getOperand(1)->getType();
6861   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6862   switch (ShuffleOrOp) {
6863     case Instruction::PHI: {
6864       assert(
6865           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6866           "PHI reordering is free.");
6867       auto *PH = cast<PHINode>(VL0);
6868       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6869       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6870       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6871       Value *V = NewPhi;
6872 
6873       // Adjust insertion point once all PHI's have been generated.
6874       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6875       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6876 
6877       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6878       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6879       V = ShuffleBuilder.finalize(V);
6880 
6881       E->VectorizedValue = V;
6882 
6883       // PHINodes may have multiple entries from the same block. We want to
6884       // visit every block once.
6885       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6886 
6887       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6888         ValueList Operands;
6889         BasicBlock *IBB = PH->getIncomingBlock(i);
6890 
6891         if (!VisitedBBs.insert(IBB).second) {
6892           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6893           continue;
6894         }
6895 
6896         Builder.SetInsertPoint(IBB->getTerminator());
6897         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6898         Value *Vec = vectorizeTree(E->getOperand(i));
6899         NewPhi->addIncoming(Vec, IBB);
6900       }
6901 
6902       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6903              "Invalid number of incoming values");
6904       return V;
6905     }
6906 
6907     case Instruction::ExtractElement: {
6908       Value *V = E->getSingleOperand(0);
6909       Builder.SetInsertPoint(VL0);
6910       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6911       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6912       V = ShuffleBuilder.finalize(V);
6913       E->VectorizedValue = V;
6914       return V;
6915     }
6916     case Instruction::ExtractValue: {
6917       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6918       Builder.SetInsertPoint(LI);
6919       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6920       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6921       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6922       if (MSSA) {
6923         MemorySSAUpdater MSSAU(MSSA);
6924         auto *Access = MSSA->getMemoryAccess(LI);
6925         assert(Access);
6926         MemoryUseOrDef *NewAccess =
6927           MSSAU.createMemoryAccessBefore(V, Access->getDefiningAccess(),
6928                                          Access);
6929         MSSAU.insertUse(cast<MemoryUse>(NewAccess), true);
6930       }
6931       Value *NewV = propagateMetadata(V, E->Scalars);
6932       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6933       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6934       NewV = ShuffleBuilder.finalize(NewV);
6935       E->VectorizedValue = NewV;
6936       return NewV;
6937     }
6938     case Instruction::InsertElement: {
6939       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6940       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6941       Value *V = vectorizeTree(E->getOperand(1));
6942 
6943       // Create InsertVector shuffle if necessary
6944       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6945         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6946       }));
6947       const unsigned NumElts =
6948           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6949       const unsigned NumScalars = E->Scalars.size();
6950 
6951       unsigned Offset = *getInsertIndex(VL0);
6952       assert(Offset < NumElts && "Failed to find vector index offset");
6953 
6954       // Create shuffle to resize vector
6955       SmallVector<int> Mask;
6956       if (!E->ReorderIndices.empty()) {
6957         inversePermutation(E->ReorderIndices, Mask);
6958         Mask.append(NumElts - NumScalars, UndefMaskElem);
6959       } else {
6960         Mask.assign(NumElts, UndefMaskElem);
6961         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6962       }
6963       // Create InsertVector shuffle if necessary
6964       bool IsIdentity = true;
6965       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6966       Mask.swap(PrevMask);
6967       for (unsigned I = 0; I < NumScalars; ++I) {
6968         Value *Scalar = E->Scalars[PrevMask[I]];
6969         unsigned InsertIdx = *getInsertIndex(Scalar);
6970         IsIdentity &= InsertIdx - Offset == I;
6971         Mask[InsertIdx - Offset] = I;
6972       }
6973       if (!IsIdentity || NumElts != NumScalars) {
6974         V = Builder.CreateShuffleVector(V, Mask);
6975         if (auto *I = dyn_cast<Instruction>(V)) {
6976           GatherShuffleSeq.insert(I);
6977           CSEBlocks.insert(I->getParent());
6978         }
6979       }
6980 
6981       if ((!IsIdentity || Offset != 0 ||
6982            !isUndefVector(FirstInsert->getOperand(0))) &&
6983           NumElts != NumScalars) {
6984         SmallVector<int> InsertMask(NumElts);
6985         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6986         for (unsigned I = 0; I < NumElts; I++) {
6987           if (Mask[I] != UndefMaskElem)
6988             InsertMask[Offset + I] = NumElts + I;
6989         }
6990 
6991         V = Builder.CreateShuffleVector(
6992             FirstInsert->getOperand(0), V, InsertMask,
6993             cast<Instruction>(E->Scalars.back())->getName());
6994         if (auto *I = dyn_cast<Instruction>(V)) {
6995           GatherShuffleSeq.insert(I);
6996           CSEBlocks.insert(I->getParent());
6997         }
6998       }
6999 
7000       ++NumVectorInstructions;
7001       E->VectorizedValue = V;
7002       return V;
7003     }
7004     case Instruction::ZExt:
7005     case Instruction::SExt:
7006     case Instruction::FPToUI:
7007     case Instruction::FPToSI:
7008     case Instruction::FPExt:
7009     case Instruction::PtrToInt:
7010     case Instruction::IntToPtr:
7011     case Instruction::SIToFP:
7012     case Instruction::UIToFP:
7013     case Instruction::Trunc:
7014     case Instruction::FPTrunc:
7015     case Instruction::BitCast: {
7016       setInsertPointAfterBundle(E);
7017 
7018       Value *InVec = vectorizeTree(E->getOperand(0));
7019 
7020       if (E->VectorizedValue) {
7021         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7022         return E->VectorizedValue;
7023       }
7024 
7025       auto *CI = cast<CastInst>(VL0);
7026       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7027       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7028       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7029       V = ShuffleBuilder.finalize(V);
7030 
7031       E->VectorizedValue = V;
7032       ++NumVectorInstructions;
7033       return V;
7034     }
7035     case Instruction::FCmp:
7036     case Instruction::ICmp: {
7037       setInsertPointAfterBundle(E);
7038 
7039       Value *L = vectorizeTree(E->getOperand(0));
7040       Value *R = vectorizeTree(E->getOperand(1));
7041 
7042       if (E->VectorizedValue) {
7043         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7044         return E->VectorizedValue;
7045       }
7046 
7047       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7048       Value *V = Builder.CreateCmp(P0, L, R);
7049       propagateIRFlags(V, E->Scalars, VL0);
7050       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7051       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7052       V = ShuffleBuilder.finalize(V);
7053 
7054       E->VectorizedValue = V;
7055       ++NumVectorInstructions;
7056       return V;
7057     }
7058     case Instruction::Select: {
7059       setInsertPointAfterBundle(E);
7060 
7061       Value *Cond = vectorizeTree(E->getOperand(0));
7062       Value *True = vectorizeTree(E->getOperand(1));
7063       Value *False = vectorizeTree(E->getOperand(2));
7064 
7065       if (E->VectorizedValue) {
7066         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7067         return E->VectorizedValue;
7068       }
7069 
7070       Value *V = Builder.CreateSelect(Cond, True, False);
7071       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7072       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7073       V = ShuffleBuilder.finalize(V);
7074 
7075       E->VectorizedValue = V;
7076       ++NumVectorInstructions;
7077       return V;
7078     }
7079     case Instruction::FNeg: {
7080       setInsertPointAfterBundle(E);
7081 
7082       Value *Op = vectorizeTree(E->getOperand(0));
7083 
7084       if (E->VectorizedValue) {
7085         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7086         return E->VectorizedValue;
7087       }
7088 
7089       Value *V = Builder.CreateUnOp(
7090           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7091       propagateIRFlags(V, E->Scalars, VL0);
7092       if (auto *I = dyn_cast<Instruction>(V))
7093         V = propagateMetadata(I, E->Scalars);
7094 
7095       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7096       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7097       V = ShuffleBuilder.finalize(V);
7098 
7099       E->VectorizedValue = V;
7100       ++NumVectorInstructions;
7101 
7102       return V;
7103     }
7104     case Instruction::Add:
7105     case Instruction::FAdd:
7106     case Instruction::Sub:
7107     case Instruction::FSub:
7108     case Instruction::Mul:
7109     case Instruction::FMul:
7110     case Instruction::UDiv:
7111     case Instruction::SDiv:
7112     case Instruction::FDiv:
7113     case Instruction::URem:
7114     case Instruction::SRem:
7115     case Instruction::FRem:
7116     case Instruction::Shl:
7117     case Instruction::LShr:
7118     case Instruction::AShr:
7119     case Instruction::And:
7120     case Instruction::Or:
7121     case Instruction::Xor: {
7122       setInsertPointAfterBundle(E);
7123 
7124       Value *LHS = vectorizeTree(E->getOperand(0));
7125       Value *RHS = vectorizeTree(E->getOperand(1));
7126 
7127       if (E->VectorizedValue) {
7128         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7129         return E->VectorizedValue;
7130       }
7131 
7132       Value *V = Builder.CreateBinOp(
7133           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7134           RHS);
7135       propagateIRFlags(V, E->Scalars, VL0);
7136       if (auto *I = dyn_cast<Instruction>(V))
7137         V = propagateMetadata(I, E->Scalars);
7138 
7139       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7140       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7141       V = ShuffleBuilder.finalize(V);
7142 
7143       E->VectorizedValue = V;
7144       ++NumVectorInstructions;
7145 
7146       return V;
7147     }
7148     case Instruction::Load: {
7149       // Loads are inserted at the head of the tree because we don't want to
7150       // sink them all the way down past store instructions.
7151       setInsertPointAfterBundle(E);
7152 
7153       LoadInst *LI = cast<LoadInst>(VL0);
7154       Instruction *NewLI;
7155       unsigned AS = LI->getPointerAddressSpace();
7156       Value *PO = LI->getPointerOperand();
7157       if (E->State == TreeEntry::Vectorize) {
7158         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7159         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7160 
7161         // The pointer operand uses an in-tree scalar so we add the new BitCast
7162         // or LoadInst to ExternalUses list to make sure that an extract will
7163         // be generated in the future.
7164         if (TreeEntry *Entry = getTreeEntry(PO)) {
7165           // Find which lane we need to extract.
7166           unsigned FoundLane = Entry->findLaneForValue(PO);
7167           ExternalUses.emplace_back(
7168               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7169         }
7170       } else {
7171         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7172         Value *VecPtr = vectorizeTree(E->getOperand(0));
7173         // Use the minimum alignment of the gathered loads.
7174         Align CommonAlignment = LI->getAlign();
7175         for (Value *V : E->Scalars)
7176           CommonAlignment =
7177               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7178         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7179       }
7180 
7181       if (MSSA) {
7182         MemorySSAUpdater MSSAU(MSSA);
7183         auto *Access = MSSA->getMemoryAccess(LI);
7184         assert(Access);
7185         MemoryUseOrDef *NewAccess =
7186           MSSAU.createMemoryAccessAfter(NewLI, Access->getDefiningAccess(),
7187                                         Access);
7188         MSSAU.insertUse(cast<MemoryUse>(NewAccess), true);
7189       }
7190 
7191       Value *V = propagateMetadata(NewLI, E->Scalars);
7192 
7193       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7194       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7195       V = ShuffleBuilder.finalize(V);
7196       E->VectorizedValue = V;
7197       ++NumVectorInstructions;
7198       return V;
7199     }
7200     case Instruction::Store: {
7201       auto *SI = cast<StoreInst>(VL0);
7202       unsigned AS = SI->getPointerAddressSpace();
7203 
7204       setInsertPointAfterBundle(E);
7205 
7206       Value *VecValue = vectorizeTree(E->getOperand(0));
7207       ShuffleBuilder.addMask(E->ReorderIndices);
7208       VecValue = ShuffleBuilder.finalize(VecValue);
7209 
7210       Value *ScalarPtr = SI->getPointerOperand();
7211       Value *VecPtr = Builder.CreateBitCast(
7212           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7213       StoreInst *ST =
7214           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7215 
7216       if (MSSA) {
7217         MemorySSAUpdater MSSAU(MSSA);
7218         auto *Access = MSSA->getMemoryAccess(SI);
7219         assert(Access);
7220         MemoryUseOrDef *NewAccess =
7221           MSSAU.createMemoryAccessAfter(ST, Access->getDefiningAccess(),
7222                                         Access);
7223         MSSAU.insertDef(cast<MemoryDef>(NewAccess), true);
7224       }
7225 
7226       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7227       // StoreInst to ExternalUses to make sure that an extract will be
7228       // generated in the future.
7229       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7230         // Find which lane we need to extract.
7231         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7232         ExternalUses.push_back(ExternalUser(
7233             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7234             FoundLane));
7235       }
7236 
7237       Value *V = propagateMetadata(ST, E->Scalars);
7238 
7239       E->VectorizedValue = V;
7240       ++NumVectorInstructions;
7241       return V;
7242     }
7243     case Instruction::GetElementPtr: {
7244       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7245       setInsertPointAfterBundle(E);
7246 
7247       Value *Op0 = vectorizeTree(E->getOperand(0));
7248 
7249       SmallVector<Value *> OpVecs;
7250       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7251         Value *OpVec = vectorizeTree(E->getOperand(J));
7252         OpVecs.push_back(OpVec);
7253       }
7254 
7255       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7256       if (Instruction *I = dyn_cast<Instruction>(V))
7257         V = propagateMetadata(I, E->Scalars);
7258 
7259       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7260       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7261       V = ShuffleBuilder.finalize(V);
7262 
7263       E->VectorizedValue = V;
7264       ++NumVectorInstructions;
7265 
7266       return V;
7267     }
7268     case Instruction::Call: {
7269       CallInst *CI = cast<CallInst>(VL0);
7270       setInsertPointAfterBundle(E);
7271 
7272       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7273       if (Function *FI = CI->getCalledFunction())
7274         IID = FI->getIntrinsicID();
7275 
7276       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7277 
7278       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7279       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7280                           VecCallCosts.first <= VecCallCosts.second;
7281 
7282       Value *ScalarArg = nullptr;
7283       std::vector<Value *> OpVecs;
7284       SmallVector<Type *, 2> TysForDecl =
7285           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7286       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7287         ValueList OpVL;
7288         // Some intrinsics have scalar arguments. This argument should not be
7289         // vectorized.
7290         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7291           CallInst *CEI = cast<CallInst>(VL0);
7292           ScalarArg = CEI->getArgOperand(j);
7293           OpVecs.push_back(CEI->getArgOperand(j));
7294           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7295             TysForDecl.push_back(ScalarArg->getType());
7296           continue;
7297         }
7298 
7299         Value *OpVec = vectorizeTree(E->getOperand(j));
7300         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7301         OpVecs.push_back(OpVec);
7302       }
7303 
7304       Function *CF;
7305       if (!UseIntrinsic) {
7306         VFShape Shape =
7307             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7308                                   VecTy->getNumElements())),
7309                          false /*HasGlobalPred*/);
7310         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7311       } else {
7312         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7313       }
7314 
7315       SmallVector<OperandBundleDef, 1> OpBundles;
7316       CI->getOperandBundlesAsDefs(OpBundles);
7317       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7318 
7319       // The scalar argument uses an in-tree scalar so we add the new vectorized
7320       // call to ExternalUses list to make sure that an extract will be
7321       // generated in the future.
7322       if (ScalarArg) {
7323         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7324           // Find which lane we need to extract.
7325           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7326           ExternalUses.push_back(
7327               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7328         }
7329       }
7330 
7331       propagateIRFlags(V, E->Scalars, VL0);
7332       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7333       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7334       V = ShuffleBuilder.finalize(V);
7335 
7336       E->VectorizedValue = V;
7337       ++NumVectorInstructions;
7338       return V;
7339     }
7340     case Instruction::ShuffleVector: {
7341       assert(E->isAltShuffle() &&
7342              ((Instruction::isBinaryOp(E->getOpcode()) &&
7343                Instruction::isBinaryOp(E->getAltOpcode())) ||
7344               (Instruction::isCast(E->getOpcode()) &&
7345                Instruction::isCast(E->getAltOpcode())) ||
7346               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7347              "Invalid Shuffle Vector Operand");
7348 
7349       Value *LHS = nullptr, *RHS = nullptr;
7350       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7351         setInsertPointAfterBundle(E);
7352         LHS = vectorizeTree(E->getOperand(0));
7353         RHS = vectorizeTree(E->getOperand(1));
7354       } else {
7355         setInsertPointAfterBundle(E);
7356         LHS = vectorizeTree(E->getOperand(0));
7357       }
7358 
7359       if (E->VectorizedValue) {
7360         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7361         return E->VectorizedValue;
7362       }
7363 
7364       Value *V0, *V1;
7365       if (Instruction::isBinaryOp(E->getOpcode())) {
7366         V0 = Builder.CreateBinOp(
7367             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7368         V1 = Builder.CreateBinOp(
7369             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7370       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7371         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7372         auto *AltCI = cast<CmpInst>(E->getAltOp());
7373         CmpInst::Predicate AltPred = AltCI->getPredicate();
7374         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7375       } else {
7376         V0 = Builder.CreateCast(
7377             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7378         V1 = Builder.CreateCast(
7379             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7380       }
7381       // Add V0 and V1 to later analysis to try to find and remove matching
7382       // instruction, if any.
7383       for (Value *V : {V0, V1}) {
7384         if (auto *I = dyn_cast<Instruction>(V)) {
7385           GatherShuffleSeq.insert(I);
7386           CSEBlocks.insert(I->getParent());
7387         }
7388       }
7389 
7390       // Create shuffle to take alternate operations from the vector.
7391       // Also, gather up main and alt scalar ops to propagate IR flags to
7392       // each vector operation.
7393       ValueList OpScalars, AltScalars;
7394       SmallVector<int> Mask;
7395       buildShuffleEntryMask(
7396           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7397           [E](Instruction *I) {
7398             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7399             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7400           },
7401           Mask, &OpScalars, &AltScalars);
7402 
7403       propagateIRFlags(V0, OpScalars);
7404       propagateIRFlags(V1, AltScalars);
7405 
7406       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7407       if (auto *I = dyn_cast<Instruction>(V)) {
7408         V = propagateMetadata(I, E->Scalars);
7409         GatherShuffleSeq.insert(I);
7410         CSEBlocks.insert(I->getParent());
7411       }
7412       V = ShuffleBuilder.finalize(V);
7413 
7414       E->VectorizedValue = V;
7415       ++NumVectorInstructions;
7416 
7417       return V;
7418     }
7419     default:
7420     llvm_unreachable("unknown inst");
7421   }
7422   return nullptr;
7423 }
7424 
7425 Value *BoUpSLP::vectorizeTree() {
7426   ExtraValueToDebugLocsMap ExternallyUsedValues;
7427   return vectorizeTree(ExternallyUsedValues);
7428 }
7429 
7430 Value *
7431 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7432   // All blocks must be scheduled before any instructions are inserted.
7433   for (auto &BSIter : BlocksSchedules) {
7434     scheduleBlock(BSIter.second.get());
7435   }
7436 
7437   Builder.SetInsertPoint(&F->getEntryBlock().front());
7438   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7439 
7440   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7441   // vectorized root. InstCombine will then rewrite the entire expression. We
7442   // sign extend the extracted values below.
7443   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7444   if (MinBWs.count(ScalarRoot)) {
7445     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7446       // If current instr is a phi and not the last phi, insert it after the
7447       // last phi node.
7448       if (isa<PHINode>(I))
7449         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7450       else
7451         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7452     }
7453     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7454     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7455     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7456     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7457     VectorizableTree[0]->VectorizedValue = Trunc;
7458   }
7459 
7460   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7461                     << " values .\n");
7462 
7463   // Extract all of the elements with the external uses.
7464   for (const auto &ExternalUse : ExternalUses) {
7465     Value *Scalar = ExternalUse.Scalar;
7466     llvm::User *User = ExternalUse.User;
7467 
7468     // Skip users that we already RAUW. This happens when one instruction
7469     // has multiple uses of the same value.
7470     if (User && !is_contained(Scalar->users(), User))
7471       continue;
7472     TreeEntry *E = getTreeEntry(Scalar);
7473     assert(E && "Invalid scalar");
7474     assert(E->State != TreeEntry::NeedToGather &&
7475            "Extracting from a gather list");
7476 
7477     Value *Vec = E->VectorizedValue;
7478     assert(Vec && "Can't find vectorizable value");
7479 
7480     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7481     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7482       if (Scalar->getType() != Vec->getType()) {
7483         Value *Ex;
7484         // "Reuse" the existing extract to improve final codegen.
7485         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7486           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7487                                             ES->getOperand(1));
7488         } else {
7489           Ex = Builder.CreateExtractElement(Vec, Lane);
7490         }
7491         // If necessary, sign-extend or zero-extend ScalarRoot
7492         // to the larger type.
7493         if (!MinBWs.count(ScalarRoot))
7494           return Ex;
7495         if (MinBWs[ScalarRoot].second)
7496           return Builder.CreateSExt(Ex, Scalar->getType());
7497         return Builder.CreateZExt(Ex, Scalar->getType());
7498       }
7499       assert(isa<FixedVectorType>(Scalar->getType()) &&
7500              isa<InsertElementInst>(Scalar) &&
7501              "In-tree scalar of vector type is not insertelement?");
7502       return Vec;
7503     };
7504     // If User == nullptr, the Scalar is used as extra arg. Generate
7505     // ExtractElement instruction and update the record for this scalar in
7506     // ExternallyUsedValues.
7507     if (!User) {
7508       assert(ExternallyUsedValues.count(Scalar) &&
7509              "Scalar with nullptr as an external user must be registered in "
7510              "ExternallyUsedValues map");
7511       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7512         Builder.SetInsertPoint(VecI->getParent(),
7513                                std::next(VecI->getIterator()));
7514       } else {
7515         Builder.SetInsertPoint(&F->getEntryBlock().front());
7516       }
7517       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7518       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7519       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7520       auto It = ExternallyUsedValues.find(Scalar);
7521       assert(It != ExternallyUsedValues.end() &&
7522              "Externally used scalar is not found in ExternallyUsedValues");
7523       NewInstLocs.append(It->second);
7524       ExternallyUsedValues.erase(Scalar);
7525       // Required to update internally referenced instructions.
7526       Scalar->replaceAllUsesWith(NewInst);
7527       continue;
7528     }
7529 
7530     // Generate extracts for out-of-tree users.
7531     // Find the insertion point for the extractelement lane.
7532     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7533       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7534         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7535           if (PH->getIncomingValue(i) == Scalar) {
7536             Instruction *IncomingTerminator =
7537                 PH->getIncomingBlock(i)->getTerminator();
7538             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7539               Builder.SetInsertPoint(VecI->getParent(),
7540                                      std::next(VecI->getIterator()));
7541             } else {
7542               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7543             }
7544             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7545             CSEBlocks.insert(PH->getIncomingBlock(i));
7546             PH->setOperand(i, NewInst);
7547           }
7548         }
7549       } else {
7550         Builder.SetInsertPoint(cast<Instruction>(User));
7551         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7552         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7553         User->replaceUsesOfWith(Scalar, NewInst);
7554       }
7555     } else {
7556       Builder.SetInsertPoint(&F->getEntryBlock().front());
7557       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7558       CSEBlocks.insert(&F->getEntryBlock());
7559       User->replaceUsesOfWith(Scalar, NewInst);
7560     }
7561 
7562     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7563   }
7564 
7565   // For each vectorized value:
7566   for (auto &TEPtr : VectorizableTree) {
7567     TreeEntry *Entry = TEPtr.get();
7568 
7569     // No need to handle users of gathered values.
7570     if (Entry->State == TreeEntry::NeedToGather)
7571       continue;
7572 
7573     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7574 
7575     // For each lane:
7576     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7577       Value *Scalar = Entry->Scalars[Lane];
7578 
7579 #ifndef NDEBUG
7580       Type *Ty = Scalar->getType();
7581       if (!Ty->isVoidTy()) {
7582         for (User *U : Scalar->users()) {
7583           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7584 
7585           // It is legal to delete users in the ignorelist.
7586           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7587                   (isa_and_nonnull<Instruction>(U) &&
7588                    isDeleted(cast<Instruction>(U)))) &&
7589                  "Deleting out-of-tree value");
7590         }
7591       }
7592 #endif
7593       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7594       eraseInstruction(cast<Instruction>(Scalar));
7595     }
7596   }
7597 
7598   Builder.ClearInsertionPoint();
7599   InstrElementSize.clear();
7600 
7601   return VectorizableTree[0]->VectorizedValue;
7602 }
7603 
7604 void BoUpSLP::optimizeGatherSequence() {
7605   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7606                     << " gather sequences instructions.\n");
7607   // LICM InsertElementInst sequences.
7608   for (Instruction *I : GatherShuffleSeq) {
7609     if (isDeleted(I))
7610       continue;
7611 
7612     // Check if this block is inside a loop.
7613     Loop *L = LI->getLoopFor(I->getParent());
7614     if (!L)
7615       continue;
7616 
7617     // Check if it has a preheader.
7618     BasicBlock *PreHeader = L->getLoopPreheader();
7619     if (!PreHeader)
7620       continue;
7621 
7622     // If the vector or the element that we insert into it are
7623     // instructions that are defined in this basic block then we can't
7624     // hoist this instruction.
7625     if (any_of(I->operands(), [L](Value *V) {
7626           auto *OpI = dyn_cast<Instruction>(V);
7627           return OpI && L->contains(OpI);
7628         }))
7629       continue;
7630 
7631     // We can hoist this instruction. Move it to the pre-header.
7632     I->moveBefore(PreHeader->getTerminator());
7633   }
7634 
7635   // Make a list of all reachable blocks in our CSE queue.
7636   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7637   CSEWorkList.reserve(CSEBlocks.size());
7638   for (BasicBlock *BB : CSEBlocks)
7639     if (DomTreeNode *N = DT->getNode(BB)) {
7640       assert(DT->isReachableFromEntry(N));
7641       CSEWorkList.push_back(N);
7642     }
7643 
7644   // Sort blocks by domination. This ensures we visit a block after all blocks
7645   // dominating it are visited.
7646   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7647     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7648            "Different nodes should have different DFS numbers");
7649     return A->getDFSNumIn() < B->getDFSNumIn();
7650   });
7651 
7652   // Less defined shuffles can be replaced by the more defined copies.
7653   // Between two shuffles one is less defined if it has the same vector operands
7654   // and its mask indeces are the same as in the first one or undefs. E.g.
7655   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7656   // poison, <0, 0, 0, 0>.
7657   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7658                                            SmallVectorImpl<int> &NewMask) {
7659     if (I1->getType() != I2->getType())
7660       return false;
7661     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7662     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7663     if (!SI1 || !SI2)
7664       return I1->isIdenticalTo(I2);
7665     if (SI1->isIdenticalTo(SI2))
7666       return true;
7667     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7668       if (SI1->getOperand(I) != SI2->getOperand(I))
7669         return false;
7670     // Check if the second instruction is more defined than the first one.
7671     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7672     ArrayRef<int> SM1 = SI1->getShuffleMask();
7673     // Count trailing undefs in the mask to check the final number of used
7674     // registers.
7675     unsigned LastUndefsCnt = 0;
7676     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7677       if (SM1[I] == UndefMaskElem)
7678         ++LastUndefsCnt;
7679       else
7680         LastUndefsCnt = 0;
7681       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7682           NewMask[I] != SM1[I])
7683         return false;
7684       if (NewMask[I] == UndefMaskElem)
7685         NewMask[I] = SM1[I];
7686     }
7687     // Check if the last undefs actually change the final number of used vector
7688     // registers.
7689     return SM1.size() - LastUndefsCnt > 1 &&
7690            TTI->getNumberOfParts(SI1->getType()) ==
7691                TTI->getNumberOfParts(
7692                    FixedVectorType::get(SI1->getType()->getElementType(),
7693                                         SM1.size() - LastUndefsCnt));
7694   };
7695   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7696   // instructions. TODO: We can further optimize this scan if we split the
7697   // instructions into different buckets based on the insert lane.
7698   SmallVector<Instruction *, 16> Visited;
7699   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7700     assert(*I &&
7701            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7702            "Worklist not sorted properly!");
7703     BasicBlock *BB = (*I)->getBlock();
7704     // For all instructions in blocks containing gather sequences:
7705     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7706       if (isDeleted(&In))
7707         continue;
7708       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7709           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7710         continue;
7711 
7712       // Check if we can replace this instruction with any of the
7713       // visited instructions.
7714       bool Replaced = false;
7715       for (Instruction *&V : Visited) {
7716         SmallVector<int> NewMask;
7717         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7718             DT->dominates(V->getParent(), In.getParent())) {
7719           In.replaceAllUsesWith(V);
7720           eraseInstruction(&In);
7721           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7722             if (!NewMask.empty())
7723               SI->setShuffleMask(NewMask);
7724           Replaced = true;
7725           break;
7726         }
7727         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7728             GatherShuffleSeq.contains(V) &&
7729             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7730             DT->dominates(In.getParent(), V->getParent())) {
7731           In.moveAfter(V);
7732           V->replaceAllUsesWith(&In);
7733           eraseInstruction(V);
7734           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7735             if (!NewMask.empty())
7736               SI->setShuffleMask(NewMask);
7737           V = &In;
7738           Replaced = true;
7739           break;
7740         }
7741       }
7742       if (!Replaced) {
7743         assert(!is_contained(Visited, &In));
7744         Visited.push_back(&In);
7745       }
7746     }
7747   }
7748   CSEBlocks.clear();
7749   GatherShuffleSeq.clear();
7750 }
7751 
7752 BoUpSLP::ScheduleData *
7753 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7754   ScheduleData *Bundle = nullptr;
7755   ScheduleData *PrevInBundle = nullptr;
7756   for (Value *V : VL) {
7757     if (doesNotNeedToBeScheduled(V))
7758       continue;
7759     ScheduleData *BundleMember = getScheduleData(V);
7760     assert(BundleMember &&
7761            "no ScheduleData for bundle member "
7762            "(maybe not in same basic block)");
7763     assert(BundleMember->isSchedulingEntity() &&
7764            "bundle member already part of other bundle");
7765     if (PrevInBundle) {
7766       PrevInBundle->NextInBundle = BundleMember;
7767     } else {
7768       Bundle = BundleMember;
7769     }
7770 
7771     // Group the instructions to a bundle.
7772     BundleMember->FirstInBundle = Bundle;
7773     PrevInBundle = BundleMember;
7774   }
7775   assert(Bundle && "Failed to find schedule bundle");
7776   return Bundle;
7777 }
7778 
7779 // Groups the instructions to a bundle (which is then a single scheduling entity)
7780 // and schedules instructions until the bundle gets ready.
7781 Optional<BoUpSLP::ScheduleData *>
7782 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7783                                             const InstructionsState &S) {
7784   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7785   // instructions.
7786   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7787       doesNotNeedToSchedule(VL))
7788     return nullptr;
7789 
7790   // Initialize the instruction bundle.
7791   Instruction *OldScheduleEnd = ScheduleEnd;
7792   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7793 
7794   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7795                                                          ScheduleData *Bundle) {
7796     // The scheduling region got new instructions at the lower end (or it is a
7797     // new region for the first bundle). This makes it necessary to
7798     // recalculate all dependencies.
7799     // It is seldom that this needs to be done a second time after adding the
7800     // initial bundle to the region.
7801     if (ScheduleEnd != OldScheduleEnd) {
7802       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7803         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7804       ReSchedule = true;
7805     }
7806     if (Bundle) {
7807       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7808                         << " in block " << BB->getName() << "\n");
7809       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7810     }
7811 
7812     if (ReSchedule) {
7813       resetSchedule();
7814       initialFillReadyList(ReadyInsts);
7815     }
7816 
7817     // Now try to schedule the new bundle or (if no bundle) just calculate
7818     // dependencies. As soon as the bundle is "ready" it means that there are no
7819     // cyclic dependencies and we can schedule it. Note that's important that we
7820     // don't "schedule" the bundle yet (see cancelScheduling).
7821     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7822            !ReadyInsts.empty()) {
7823       ScheduleData *Picked = ReadyInsts.pop_back_val();
7824       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7825              "must be ready to schedule");
7826       schedule(Picked, ReadyInsts);
7827     }
7828   };
7829 
7830   // Make sure that the scheduling region contains all
7831   // instructions of the bundle.
7832   for (Value *V : VL) {
7833     if (doesNotNeedToBeScheduled(V))
7834       continue;
7835     if (!extendSchedulingRegion(V, S)) {
7836       // If the scheduling region got new instructions at the lower end (or it
7837       // is a new region for the first bundle). This makes it necessary to
7838       // recalculate all dependencies.
7839       // Otherwise the compiler may crash trying to incorrectly calculate
7840       // dependencies and emit instruction in the wrong order at the actual
7841       // scheduling.
7842       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7843       return None;
7844     }
7845   }
7846 
7847   bool ReSchedule = false;
7848   for (Value *V : VL) {
7849     if (doesNotNeedToBeScheduled(V))
7850       continue;
7851     ScheduleData *BundleMember = getScheduleData(V);
7852     assert(BundleMember &&
7853            "no ScheduleData for bundle member (maybe not in same basic block)");
7854 
7855     // Make sure we don't leave the pieces of the bundle in the ready list when
7856     // whole bundle might not be ready.
7857     ReadyInsts.remove(BundleMember);
7858 
7859     if (!BundleMember->IsScheduled)
7860       continue;
7861     // A bundle member was scheduled as single instruction before and now
7862     // needs to be scheduled as part of the bundle. We just get rid of the
7863     // existing schedule.
7864     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7865                       << " was already scheduled\n");
7866     ReSchedule = true;
7867   }
7868 
7869   auto *Bundle = buildBundle(VL);
7870   TryScheduleBundleImpl(ReSchedule, Bundle);
7871   if (!Bundle->isReady()) {
7872     cancelScheduling(VL, S.OpValue);
7873     return None;
7874   }
7875   return Bundle;
7876 }
7877 
7878 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7879                                                 Value *OpValue) {
7880   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7881       doesNotNeedToSchedule(VL))
7882     return;
7883 
7884   if (doesNotNeedToBeScheduled(OpValue))
7885     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7886   ScheduleData *Bundle = getScheduleData(OpValue);
7887   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7888   assert(!Bundle->IsScheduled &&
7889          "Can't cancel bundle which is already scheduled");
7890   assert(Bundle->isSchedulingEntity() &&
7891          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7892          "tried to unbundle something which is not a bundle");
7893 
7894   // Remove the bundle from the ready list.
7895   if (Bundle->isReady())
7896     ReadyInsts.remove(Bundle);
7897 
7898   // Un-bundle: make single instructions out of the bundle.
7899   ScheduleData *BundleMember = Bundle;
7900   while (BundleMember) {
7901     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7902     BundleMember->FirstInBundle = BundleMember;
7903     ScheduleData *Next = BundleMember->NextInBundle;
7904     BundleMember->NextInBundle = nullptr;
7905     BundleMember->TE = nullptr;
7906     if (BundleMember->unscheduledDepsInBundle() == 0) {
7907       ReadyInsts.insert(BundleMember);
7908     }
7909     BundleMember = Next;
7910   }
7911 }
7912 
7913 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7914   // Allocate a new ScheduleData for the instruction.
7915   if (ChunkPos >= ChunkSize) {
7916     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7917     ChunkPos = 0;
7918   }
7919   return &(ScheduleDataChunks.back()[ChunkPos++]);
7920 }
7921 
7922 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7923                                                       const InstructionsState &S) {
7924   if (getScheduleData(V, isOneOf(S, V)))
7925     return true;
7926   Instruction *I = dyn_cast<Instruction>(V);
7927   assert(I && "bundle member must be an instruction");
7928   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7929          !doesNotNeedToBeScheduled(I) &&
7930          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7931          "be scheduled");
7932   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7933     ScheduleData *ISD = getScheduleData(I);
7934     if (!ISD)
7935       return false;
7936     assert(isInSchedulingRegion(ISD) &&
7937            "ScheduleData not in scheduling region");
7938     ScheduleData *SD = allocateScheduleDataChunks();
7939     SD->Inst = I;
7940     SD->init(SchedulingRegionID, S.OpValue);
7941     ExtraScheduleDataMap[I][S.OpValue] = SD;
7942     return true;
7943   };
7944   if (CheckScheduleForI(I))
7945     return true;
7946   if (!ScheduleStart) {
7947     // It's the first instruction in the new region.
7948     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7949     ScheduleStart = I;
7950     ScheduleEnd = I->getNextNode();
7951     if (isOneOf(S, I) != I)
7952       CheckScheduleForI(I);
7953     assert(ScheduleEnd && "tried to vectorize a terminator?");
7954     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7955     return true;
7956   }
7957   // Search up and down at the same time, because we don't know if the new
7958   // instruction is above or below the existing scheduling region.
7959   BasicBlock::reverse_iterator UpIter =
7960       ++ScheduleStart->getIterator().getReverse();
7961   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7962   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7963   BasicBlock::iterator LowerEnd = BB->end();
7964   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7965          &*DownIter != I) {
7966     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7967       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7968       return false;
7969     }
7970 
7971     ++UpIter;
7972     ++DownIter;
7973   }
7974   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7975     assert(I->getParent() == ScheduleStart->getParent() &&
7976            "Instruction is in wrong basic block.");
7977     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7978     ScheduleStart = I;
7979     if (isOneOf(S, I) != I)
7980       CheckScheduleForI(I);
7981     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7982                       << "\n");
7983     return true;
7984   }
7985   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7986          "Expected to reach top of the basic block or instruction down the "
7987          "lower end.");
7988   assert(I->getParent() == ScheduleEnd->getParent() &&
7989          "Instruction is in wrong basic block.");
7990   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7991                    nullptr);
7992   ScheduleEnd = I->getNextNode();
7993   if (isOneOf(S, I) != I)
7994     CheckScheduleForI(I);
7995   assert(ScheduleEnd && "tried to vectorize a terminator?");
7996   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7997   return true;
7998 }
7999 
8000 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8001                                                 Instruction *ToI,
8002                                                 ScheduleData *PrevLoadStore,
8003                                                 ScheduleData *NextLoadStore) {
8004   ScheduleData *CurrentLoadStore = PrevLoadStore;
8005   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8006     // No need to allocate data for non-schedulable instructions.
8007     if (doesNotNeedToBeScheduled(I))
8008       continue;
8009     ScheduleData *SD = ScheduleDataMap.lookup(I);
8010     if (!SD) {
8011       SD = allocateScheduleDataChunks();
8012       ScheduleDataMap[I] = SD;
8013       SD->Inst = I;
8014     }
8015     assert(!isInSchedulingRegion(SD) &&
8016            "new ScheduleData already in scheduling region");
8017     SD->init(SchedulingRegionID, I);
8018 
8019     if (I->mayReadOrWriteMemory() &&
8020         (!isa<IntrinsicInst>(I) ||
8021          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8022           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8023               Intrinsic::pseudoprobe))) {
8024       // Update the linked list of memory accessing instructions.
8025       if (CurrentLoadStore) {
8026         CurrentLoadStore->NextLoadStore = SD;
8027       } else {
8028         FirstLoadStoreInRegion = SD;
8029       }
8030       CurrentLoadStore = SD;
8031     }
8032   }
8033   if (NextLoadStore) {
8034     if (CurrentLoadStore)
8035       CurrentLoadStore->NextLoadStore = NextLoadStore;
8036   } else {
8037     LastLoadStoreInRegion = CurrentLoadStore;
8038   }
8039 }
8040 
8041 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8042                                                      bool InsertInReadyList,
8043                                                      BoUpSLP *SLP) {
8044   assert(SD->isSchedulingEntity());
8045 
8046   SmallVector<ScheduleData *, 10> WorkList;
8047   WorkList.push_back(SD);
8048 
8049   while (!WorkList.empty()) {
8050     ScheduleData *SD = WorkList.pop_back_val();
8051     for (ScheduleData *BundleMember = SD; BundleMember;
8052          BundleMember = BundleMember->NextInBundle) {
8053       assert(isInSchedulingRegion(BundleMember));
8054       if (BundleMember->hasValidDependencies())
8055         continue;
8056 
8057       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8058                  << "\n");
8059       BundleMember->Dependencies = 0;
8060       BundleMember->resetUnscheduledDeps();
8061 
8062       // Handle def-use chain dependencies.
8063       if (BundleMember->OpValue != BundleMember->Inst) {
8064         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8065           BundleMember->Dependencies++;
8066           ScheduleData *DestBundle = UseSD->FirstInBundle;
8067           if (!DestBundle->IsScheduled)
8068             BundleMember->incrementUnscheduledDeps(1);
8069           if (!DestBundle->hasValidDependencies())
8070             WorkList.push_back(DestBundle);
8071         }
8072       } else {
8073         for (User *U : BundleMember->Inst->users()) {
8074           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8075             BundleMember->Dependencies++;
8076             ScheduleData *DestBundle = UseSD->FirstInBundle;
8077             if (!DestBundle->IsScheduled)
8078               BundleMember->incrementUnscheduledDeps(1);
8079             if (!DestBundle->hasValidDependencies())
8080               WorkList.push_back(DestBundle);
8081           }
8082         }
8083       }
8084 
8085       // Handle the memory dependencies (if any).
8086       ScheduleData *DepDest = BundleMember->NextLoadStore;
8087       if (!DepDest)
8088         continue;
8089       Instruction *SrcInst = BundleMember->Inst;
8090       assert(SrcInst->mayReadOrWriteMemory() &&
8091              "NextLoadStore list for non memory effecting bundle?");
8092       MemoryLocation SrcLoc = getLocation(SrcInst);
8093       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8094       unsigned numAliased = 0;
8095       unsigned DistToSrc = 1;
8096 
8097       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8098         assert(isInSchedulingRegion(DepDest));
8099 
8100         // We have two limits to reduce the complexity:
8101         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8102         //    SLP->isAliased (which is the expensive part in this loop).
8103         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8104         //    the whole loop (even if the loop is fast, it's quadratic).
8105         //    It's important for the loop break condition (see below) to
8106         //    check this limit even between two read-only instructions.
8107         if (DistToSrc >= MaxMemDepDistance ||
8108             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8109              (numAliased >= AliasedCheckLimit ||
8110               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8111 
8112           // We increment the counter only if the locations are aliased
8113           // (instead of counting all alias checks). This gives a better
8114           // balance between reduced runtime and accurate dependencies.
8115           numAliased++;
8116 
8117           DepDest->MemoryDependencies.push_back(BundleMember);
8118           BundleMember->Dependencies++;
8119           ScheduleData *DestBundle = DepDest->FirstInBundle;
8120           if (!DestBundle->IsScheduled) {
8121             BundleMember->incrementUnscheduledDeps(1);
8122           }
8123           if (!DestBundle->hasValidDependencies()) {
8124             WorkList.push_back(DestBundle);
8125           }
8126         }
8127 
8128         // Example, explaining the loop break condition: Let's assume our
8129         // starting instruction is i0 and MaxMemDepDistance = 3.
8130         //
8131         //                      +--------v--v--v
8132         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8133         //             +--------^--^--^
8134         //
8135         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8136         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8137         // Previously we already added dependencies from i3 to i6,i7,i8
8138         // (because of MaxMemDepDistance). As we added a dependency from
8139         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8140         // and we can abort this loop at i6.
8141         if (DistToSrc >= 2 * MaxMemDepDistance)
8142           break;
8143         DistToSrc++;
8144       }
8145     }
8146     if (InsertInReadyList && SD->isReady()) {
8147       ReadyInsts.insert(SD);
8148       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8149                         << "\n");
8150     }
8151   }
8152 }
8153 
8154 void BoUpSLP::BlockScheduling::resetSchedule() {
8155   assert(ScheduleStart &&
8156          "tried to reset schedule on block which has not been scheduled");
8157   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8158     doForAllOpcodes(I, [&](ScheduleData *SD) {
8159       assert(isInSchedulingRegion(SD) &&
8160              "ScheduleData not in scheduling region");
8161       SD->IsScheduled = false;
8162       SD->resetUnscheduledDeps();
8163     });
8164   }
8165   ReadyInsts.clear();
8166 }
8167 
8168 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8169   if (!BS->ScheduleStart)
8170     return;
8171 
8172   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8173 
8174   BS->resetSchedule();
8175 
8176   // For the real scheduling we use a more sophisticated ready-list: it is
8177   // sorted by the original instruction location. This lets the final schedule
8178   // be as  close as possible to the original instruction order.
8179   struct ScheduleDataCompare {
8180     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8181       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8182     }
8183   };
8184   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8185 
8186   // Ensure that all dependency data is updated and fill the ready-list with
8187   // initial instructions.
8188   int Idx = 0;
8189   int NumToSchedule = 0;
8190   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8191        I = I->getNextNode()) {
8192     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8193       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8194       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8195               SD->isPartOfBundle() ==
8196                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8197              "scheduler and vectorizer bundle mismatch");
8198       SD->FirstInBundle->SchedulingPriority = Idx++;
8199       if (SD->isSchedulingEntity()) {
8200         BS->calculateDependencies(SD, false, this);
8201         NumToSchedule++;
8202       }
8203     });
8204   }
8205   BS->initialFillReadyList(ReadyInsts);
8206 
8207   Instruction *LastScheduledInst = BS->ScheduleEnd;
8208   MemoryAccess *MemInsertPt = nullptr;
8209   if (MSSA) {
8210     for (auto I = LastScheduledInst->getIterator(); I != BS->BB->end(); I++) {
8211       if (auto *Access = MSSA->getMemoryAccess(&*I)) {
8212         MemInsertPt = Access;
8213         break;
8214       }
8215     }
8216   }
8217 
8218   // Do the "real" scheduling.
8219   while (!ReadyInsts.empty()) {
8220     ScheduleData *picked = *ReadyInsts.begin();
8221     ReadyInsts.erase(ReadyInsts.begin());
8222 
8223     // Move the scheduled instruction(s) to their dedicated places, if not
8224     // there yet.
8225     for (ScheduleData *BundleMember = picked; BundleMember;
8226          BundleMember = BundleMember->NextInBundle) {
8227       Instruction *pickedInst = BundleMember->Inst;
8228       if (pickedInst->getNextNode() != LastScheduledInst) {
8229         pickedInst->moveBefore(LastScheduledInst);
8230         if (MSSA) {
8231           MemorySSAUpdater MSSAU(MSSA);
8232           if (auto *Access = MSSA->getMemoryAccess(pickedInst)) {
8233             if (MemInsertPt)
8234               MSSAU.moveBefore(Access, cast<MemoryUseOrDef>(MemInsertPt));
8235             else
8236               MSSAU.moveToPlace(Access, BS->BB,
8237                                 MemorySSA::InsertionPlace::End);
8238           }
8239         }
8240       }
8241 
8242       LastScheduledInst = pickedInst;
8243       if (MSSA)
8244         if (auto *Access = MSSA->getMemoryAccess(LastScheduledInst))
8245           MemInsertPt = Access;
8246     }
8247 
8248     BS->schedule(picked, ReadyInsts);
8249     NumToSchedule--;
8250   }
8251   assert(NumToSchedule == 0 && "could not schedule all instructions");
8252 
8253   // Check that we didn't break any of our invariants.
8254 #ifdef EXPENSIVE_CHECKS
8255   BS->verify();
8256 #endif
8257 
8258 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8259   // Check that all schedulable entities got scheduled
8260   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8261     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8262       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8263         assert(SD->IsScheduled && "must be scheduled at this point");
8264       }
8265     });
8266   }
8267 #endif
8268 
8269   // Avoid duplicate scheduling of the block.
8270   BS->ScheduleStart = nullptr;
8271 }
8272 
8273 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8274   // If V is a store, just return the width of the stored value (or value
8275   // truncated just before storing) without traversing the expression tree.
8276   // This is the common case.
8277   if (auto *Store = dyn_cast<StoreInst>(V)) {
8278     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8279       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8280     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8281   }
8282 
8283   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8284     return getVectorElementSize(IEI->getOperand(1));
8285 
8286   auto E = InstrElementSize.find(V);
8287   if (E != InstrElementSize.end())
8288     return E->second;
8289 
8290   // If V is not a store, we can traverse the expression tree to find loads
8291   // that feed it. The type of the loaded value may indicate a more suitable
8292   // width than V's type. We want to base the vector element size on the width
8293   // of memory operations where possible.
8294   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8295   SmallPtrSet<Instruction *, 16> Visited;
8296   if (auto *I = dyn_cast<Instruction>(V)) {
8297     Worklist.emplace_back(I, I->getParent());
8298     Visited.insert(I);
8299   }
8300 
8301   // Traverse the expression tree in bottom-up order looking for loads. If we
8302   // encounter an instruction we don't yet handle, we give up.
8303   auto Width = 0u;
8304   while (!Worklist.empty()) {
8305     Instruction *I;
8306     BasicBlock *Parent;
8307     std::tie(I, Parent) = Worklist.pop_back_val();
8308 
8309     // We should only be looking at scalar instructions here. If the current
8310     // instruction has a vector type, skip.
8311     auto *Ty = I->getType();
8312     if (isa<VectorType>(Ty))
8313       continue;
8314 
8315     // If the current instruction is a load, update MaxWidth to reflect the
8316     // width of the loaded value.
8317     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8318         isa<ExtractValueInst>(I))
8319       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8320 
8321     // Otherwise, we need to visit the operands of the instruction. We only
8322     // handle the interesting cases from buildTree here. If an operand is an
8323     // instruction we haven't yet visited and from the same basic block as the
8324     // user or the use is a PHI node, we add it to the worklist.
8325     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8326              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8327              isa<UnaryOperator>(I)) {
8328       for (Use &U : I->operands())
8329         if (auto *J = dyn_cast<Instruction>(U.get()))
8330           if (Visited.insert(J).second &&
8331               (isa<PHINode>(I) || J->getParent() == Parent))
8332             Worklist.emplace_back(J, J->getParent());
8333     } else {
8334       break;
8335     }
8336   }
8337 
8338   // If we didn't encounter a memory access in the expression tree, or if we
8339   // gave up for some reason, just return the width of V. Otherwise, return the
8340   // maximum width we found.
8341   if (!Width) {
8342     if (auto *CI = dyn_cast<CmpInst>(V))
8343       V = CI->getOperand(0);
8344     Width = DL->getTypeSizeInBits(V->getType());
8345   }
8346 
8347   for (Instruction *I : Visited)
8348     InstrElementSize[I] = Width;
8349 
8350   return Width;
8351 }
8352 
8353 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8354 // smaller type with a truncation. We collect the values that will be demoted
8355 // in ToDemote and additional roots that require investigating in Roots.
8356 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8357                                   SmallVectorImpl<Value *> &ToDemote,
8358                                   SmallVectorImpl<Value *> &Roots) {
8359   // We can always demote constants.
8360   if (isa<Constant>(V)) {
8361     ToDemote.push_back(V);
8362     return true;
8363   }
8364 
8365   // If the value is not an instruction in the expression with only one use, it
8366   // cannot be demoted.
8367   auto *I = dyn_cast<Instruction>(V);
8368   if (!I || !I->hasOneUse() || !Expr.count(I))
8369     return false;
8370 
8371   switch (I->getOpcode()) {
8372 
8373   // We can always demote truncations and extensions. Since truncations can
8374   // seed additional demotion, we save the truncated value.
8375   case Instruction::Trunc:
8376     Roots.push_back(I->getOperand(0));
8377     break;
8378   case Instruction::ZExt:
8379   case Instruction::SExt:
8380     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8381         isa<InsertElementInst>(I->getOperand(0)))
8382       return false;
8383     break;
8384 
8385   // We can demote certain binary operations if we can demote both of their
8386   // operands.
8387   case Instruction::Add:
8388   case Instruction::Sub:
8389   case Instruction::Mul:
8390   case Instruction::And:
8391   case Instruction::Or:
8392   case Instruction::Xor:
8393     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8394         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8395       return false;
8396     break;
8397 
8398   // We can demote selects if we can demote their true and false values.
8399   case Instruction::Select: {
8400     SelectInst *SI = cast<SelectInst>(I);
8401     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8402         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8403       return false;
8404     break;
8405   }
8406 
8407   // We can demote phis if we can demote all their incoming operands. Note that
8408   // we don't need to worry about cycles since we ensure single use above.
8409   case Instruction::PHI: {
8410     PHINode *PN = cast<PHINode>(I);
8411     for (Value *IncValue : PN->incoming_values())
8412       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8413         return false;
8414     break;
8415   }
8416 
8417   // Otherwise, conservatively give up.
8418   default:
8419     return false;
8420   }
8421 
8422   // Record the value that we can demote.
8423   ToDemote.push_back(V);
8424   return true;
8425 }
8426 
8427 void BoUpSLP::computeMinimumValueSizes() {
8428   // If there are no external uses, the expression tree must be rooted by a
8429   // store. We can't demote in-memory values, so there is nothing to do here.
8430   if (ExternalUses.empty())
8431     return;
8432 
8433   // We only attempt to truncate integer expressions.
8434   auto &TreeRoot = VectorizableTree[0]->Scalars;
8435   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8436   if (!TreeRootIT)
8437     return;
8438 
8439   // If the expression is not rooted by a store, these roots should have
8440   // external uses. We will rely on InstCombine to rewrite the expression in
8441   // the narrower type. However, InstCombine only rewrites single-use values.
8442   // This means that if a tree entry other than a root is used externally, it
8443   // must have multiple uses and InstCombine will not rewrite it. The code
8444   // below ensures that only the roots are used externally.
8445   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8446   for (auto &EU : ExternalUses)
8447     if (!Expr.erase(EU.Scalar))
8448       return;
8449   if (!Expr.empty())
8450     return;
8451 
8452   // Collect the scalar values of the vectorizable expression. We will use this
8453   // context to determine which values can be demoted. If we see a truncation,
8454   // we mark it as seeding another demotion.
8455   for (auto &EntryPtr : VectorizableTree)
8456     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8457 
8458   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8459   // have a single external user that is not in the vectorizable tree.
8460   for (auto *Root : TreeRoot)
8461     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8462       return;
8463 
8464   // Conservatively determine if we can actually truncate the roots of the
8465   // expression. Collect the values that can be demoted in ToDemote and
8466   // additional roots that require investigating in Roots.
8467   SmallVector<Value *, 32> ToDemote;
8468   SmallVector<Value *, 4> Roots;
8469   for (auto *Root : TreeRoot)
8470     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8471       return;
8472 
8473   // The maximum bit width required to represent all the values that can be
8474   // demoted without loss of precision. It would be safe to truncate the roots
8475   // of the expression to this width.
8476   auto MaxBitWidth = 8u;
8477 
8478   // We first check if all the bits of the roots are demanded. If they're not,
8479   // we can truncate the roots to this narrower type.
8480   for (auto *Root : TreeRoot) {
8481     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8482     MaxBitWidth = std::max<unsigned>(
8483         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8484   }
8485 
8486   // True if the roots can be zero-extended back to their original type, rather
8487   // than sign-extended. We know that if the leading bits are not demanded, we
8488   // can safely zero-extend. So we initialize IsKnownPositive to True.
8489   bool IsKnownPositive = true;
8490 
8491   // If all the bits of the roots are demanded, we can try a little harder to
8492   // compute a narrower type. This can happen, for example, if the roots are
8493   // getelementptr indices. InstCombine promotes these indices to the pointer
8494   // width. Thus, all their bits are technically demanded even though the
8495   // address computation might be vectorized in a smaller type.
8496   //
8497   // We start by looking at each entry that can be demoted. We compute the
8498   // maximum bit width required to store the scalar by using ValueTracking to
8499   // compute the number of high-order bits we can truncate.
8500   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8501       llvm::all_of(TreeRoot, [](Value *R) {
8502         assert(R->hasOneUse() && "Root should have only one use!");
8503         return isa<GetElementPtrInst>(R->user_back());
8504       })) {
8505     MaxBitWidth = 8u;
8506 
8507     // Determine if the sign bit of all the roots is known to be zero. If not,
8508     // IsKnownPositive is set to False.
8509     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8510       KnownBits Known = computeKnownBits(R, *DL);
8511       return Known.isNonNegative();
8512     });
8513 
8514     // Determine the maximum number of bits required to store the scalar
8515     // values.
8516     for (auto *Scalar : ToDemote) {
8517       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8518       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8519       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8520     }
8521 
8522     // If we can't prove that the sign bit is zero, we must add one to the
8523     // maximum bit width to account for the unknown sign bit. This preserves
8524     // the existing sign bit so we can safely sign-extend the root back to the
8525     // original type. Otherwise, if we know the sign bit is zero, we will
8526     // zero-extend the root instead.
8527     //
8528     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8529     //        one to the maximum bit width will yield a larger-than-necessary
8530     //        type. In general, we need to add an extra bit only if we can't
8531     //        prove that the upper bit of the original type is equal to the
8532     //        upper bit of the proposed smaller type. If these two bits are the
8533     //        same (either zero or one) we know that sign-extending from the
8534     //        smaller type will result in the same value. Here, since we can't
8535     //        yet prove this, we are just making the proposed smaller type
8536     //        larger to ensure correctness.
8537     if (!IsKnownPositive)
8538       ++MaxBitWidth;
8539   }
8540 
8541   // Round MaxBitWidth up to the next power-of-two.
8542   if (!isPowerOf2_64(MaxBitWidth))
8543     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8544 
8545   // If the maximum bit width we compute is less than the with of the roots'
8546   // type, we can proceed with the narrowing. Otherwise, do nothing.
8547   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8548     return;
8549 
8550   // If we can truncate the root, we must collect additional values that might
8551   // be demoted as a result. That is, those seeded by truncations we will
8552   // modify.
8553   while (!Roots.empty())
8554     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8555 
8556   // Finally, map the values we can demote to the maximum bit with we computed.
8557   for (auto *Scalar : ToDemote)
8558     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8559 }
8560 
8561 namespace {
8562 
8563 /// The SLPVectorizer Pass.
8564 struct SLPVectorizer : public FunctionPass {
8565   SLPVectorizerPass Impl;
8566 
8567   /// Pass identification, replacement for typeid
8568   static char ID;
8569 
8570   explicit SLPVectorizer() : FunctionPass(ID) {
8571     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8572   }
8573 
8574   bool doInitialization(Module &M) override { return false; }
8575 
8576   bool runOnFunction(Function &F) override {
8577     if (skipFunction(F))
8578       return false;
8579 
8580     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8581     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8582     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8583     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8584     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8585     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8586     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8587     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8588     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8589     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8590 
8591     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, /*MSSA*/nullptr, ORE);
8592   }
8593 
8594   void getAnalysisUsage(AnalysisUsage &AU) const override {
8595     FunctionPass::getAnalysisUsage(AU);
8596     AU.addRequired<AssumptionCacheTracker>();
8597     AU.addRequired<ScalarEvolutionWrapperPass>();
8598     AU.addRequired<AAResultsWrapperPass>();
8599     AU.addRequired<TargetTransformInfoWrapperPass>();
8600     AU.addRequired<LoopInfoWrapperPass>();
8601     AU.addRequired<DominatorTreeWrapperPass>();
8602     AU.addRequired<DemandedBitsWrapperPass>();
8603     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8604     AU.addRequired<InjectTLIMappingsLegacy>();
8605     AU.addPreserved<LoopInfoWrapperPass>();
8606     AU.addPreserved<DominatorTreeWrapperPass>();
8607     AU.addPreserved<AAResultsWrapperPass>();
8608     AU.addPreserved<GlobalsAAWrapperPass>();
8609     AU.setPreservesCFG();
8610   }
8611 };
8612 
8613 } // end anonymous namespace
8614 
8615 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8616   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8617   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8618   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8619   auto *AA = &AM.getResult<AAManager>(F);
8620   auto *LI = &AM.getResult<LoopAnalysis>(F);
8621   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8622   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8623   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8624   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8625   auto *MSSA = EnableMSSAInSLPVectorizer ?
8626     &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : (MemorySSA*)nullptr;
8627 
8628   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, MSSA, ORE);
8629   if (!Changed)
8630     return PreservedAnalyses::all();
8631 
8632   PreservedAnalyses PA;
8633   PA.preserveSet<CFGAnalyses>();
8634   if (MSSA) {
8635 #ifdef EXPENSIVE_CHECKS
8636     MSSA->verifyMemorySSA();
8637 #endif
8638     PA.preserve<MemorySSAAnalysis>();
8639   }
8640   return PA;
8641 }
8642 
8643 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8644                                 TargetTransformInfo *TTI_,
8645                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8646                                 LoopInfo *LI_, DominatorTree *DT_,
8647                                 AssumptionCache *AC_, DemandedBits *DB_,
8648                                 MemorySSA *MSSA,
8649                                 OptimizationRemarkEmitter *ORE_) {
8650   if (!RunSLPVectorization)
8651     return false;
8652   SE = SE_;
8653   TTI = TTI_;
8654   TLI = TLI_;
8655   AA = AA_;
8656   LI = LI_;
8657   DT = DT_;
8658   AC = AC_;
8659   DB = DB_;
8660   DL = &F.getParent()->getDataLayout();
8661 
8662   Stores.clear();
8663   GEPs.clear();
8664   bool Changed = false;
8665 
8666   // If the target claims to have no vector registers don't attempt
8667   // vectorization.
8668   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8669     LLVM_DEBUG(
8670         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8671     return false;
8672   }
8673 
8674   // Don't vectorize when the attribute NoImplicitFloat is used.
8675   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8676     return false;
8677 
8678   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8679 
8680   // Use the bottom up slp vectorizer to construct chains that start with
8681   // store instructions.
8682   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, MSSA, DL, ORE_);
8683 
8684   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8685   // delete instructions.
8686 
8687   // Update DFS numbers now so that we can use them for ordering.
8688   DT->updateDFSNumbers();
8689 
8690   // Scan the blocks in the function in post order.
8691   for (auto BB : post_order(&F.getEntryBlock())) {
8692     collectSeedInstructions(BB);
8693 
8694     // Vectorize trees that end at stores.
8695     if (!Stores.empty()) {
8696       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8697                         << " underlying objects.\n");
8698       Changed |= vectorizeStoreChains(R);
8699     }
8700 
8701     // Vectorize trees that end at reductions.
8702     Changed |= vectorizeChainsInBlock(BB, R);
8703 
8704     // Vectorize the index computations of getelementptr instructions. This
8705     // is primarily intended to catch gather-like idioms ending at
8706     // non-consecutive loads.
8707     if (!GEPs.empty()) {
8708       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8709                         << " underlying objects.\n");
8710       Changed |= vectorizeGEPIndices(BB, R);
8711     }
8712   }
8713 
8714   if (Changed) {
8715     R.optimizeGatherSequence();
8716     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8717   }
8718   return Changed;
8719 }
8720 
8721 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8722                                             unsigned Idx) {
8723   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8724                     << "\n");
8725   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8726   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8727   unsigned VF = Chain.size();
8728 
8729   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8730     return false;
8731 
8732   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8733                     << "\n");
8734 
8735   R.buildTree(Chain);
8736   if (R.isTreeTinyAndNotFullyVectorizable())
8737     return false;
8738   if (R.isLoadCombineCandidate())
8739     return false;
8740   R.reorderTopToBottom();
8741   R.reorderBottomToTop();
8742   R.buildExternalUses();
8743 
8744   R.computeMinimumValueSizes();
8745 
8746   InstructionCost Cost = R.getTreeCost();
8747 
8748   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8749   if (Cost < -SLPCostThreshold) {
8750     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8751 
8752     using namespace ore;
8753 
8754     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8755                                         cast<StoreInst>(Chain[0]))
8756                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8757                      << " and with tree size "
8758                      << NV("TreeSize", R.getTreeSize()));
8759 
8760     R.vectorizeTree();
8761     return true;
8762   }
8763 
8764   return false;
8765 }
8766 
8767 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8768                                         BoUpSLP &R) {
8769   // We may run into multiple chains that merge into a single chain. We mark the
8770   // stores that we vectorized so that we don't visit the same store twice.
8771   BoUpSLP::ValueSet VectorizedStores;
8772   bool Changed = false;
8773 
8774   int E = Stores.size();
8775   SmallBitVector Tails(E, false);
8776   int MaxIter = MaxStoreLookup.getValue();
8777   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8778       E, std::make_pair(E, INT_MAX));
8779   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8780   int IterCnt;
8781   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8782                                   &CheckedPairs,
8783                                   &ConsecutiveChain](int K, int Idx) {
8784     if (IterCnt >= MaxIter)
8785       return true;
8786     if (CheckedPairs[Idx].test(K))
8787       return ConsecutiveChain[K].second == 1 &&
8788              ConsecutiveChain[K].first == Idx;
8789     ++IterCnt;
8790     CheckedPairs[Idx].set(K);
8791     CheckedPairs[K].set(Idx);
8792     Optional<int> Diff = getPointersDiff(
8793         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8794         Stores[Idx]->getValueOperand()->getType(),
8795         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8796     if (!Diff || *Diff == 0)
8797       return false;
8798     int Val = *Diff;
8799     if (Val < 0) {
8800       if (ConsecutiveChain[Idx].second > -Val) {
8801         Tails.set(K);
8802         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8803       }
8804       return false;
8805     }
8806     if (ConsecutiveChain[K].second <= Val)
8807       return false;
8808 
8809     Tails.set(Idx);
8810     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8811     return Val == 1;
8812   };
8813   // Do a quadratic search on all of the given stores in reverse order and find
8814   // all of the pairs of stores that follow each other.
8815   for (int Idx = E - 1; Idx >= 0; --Idx) {
8816     // If a store has multiple consecutive store candidates, search according
8817     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8818     // This is because usually pairing with immediate succeeding or preceding
8819     // candidate create the best chance to find slp vectorization opportunity.
8820     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8821     IterCnt = 0;
8822     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8823       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8824           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8825         break;
8826   }
8827 
8828   // Tracks if we tried to vectorize stores starting from the given tail
8829   // already.
8830   SmallBitVector TriedTails(E, false);
8831   // For stores that start but don't end a link in the chain:
8832   for (int Cnt = E; Cnt > 0; --Cnt) {
8833     int I = Cnt - 1;
8834     if (ConsecutiveChain[I].first == E || Tails.test(I))
8835       continue;
8836     // We found a store instr that starts a chain. Now follow the chain and try
8837     // to vectorize it.
8838     BoUpSLP::ValueList Operands;
8839     // Collect the chain into a list.
8840     while (I != E && !VectorizedStores.count(Stores[I])) {
8841       Operands.push_back(Stores[I]);
8842       Tails.set(I);
8843       if (ConsecutiveChain[I].second != 1) {
8844         // Mark the new end in the chain and go back, if required. It might be
8845         // required if the original stores come in reversed order, for example.
8846         if (ConsecutiveChain[I].first != E &&
8847             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8848             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8849           TriedTails.set(I);
8850           Tails.reset(ConsecutiveChain[I].first);
8851           if (Cnt < ConsecutiveChain[I].first + 2)
8852             Cnt = ConsecutiveChain[I].first + 2;
8853         }
8854         break;
8855       }
8856       // Move to the next value in the chain.
8857       I = ConsecutiveChain[I].first;
8858     }
8859     assert(!Operands.empty() && "Expected non-empty list of stores.");
8860 
8861     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8862     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8863     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8864 
8865     unsigned MinVF = R.getMinVF(EltSize);
8866     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8867                               MaxElts);
8868 
8869     // FIXME: Is division-by-2 the correct step? Should we assert that the
8870     // register size is a power-of-2?
8871     unsigned StartIdx = 0;
8872     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8873       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8874         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8875         if (!VectorizedStores.count(Slice.front()) &&
8876             !VectorizedStores.count(Slice.back()) &&
8877             vectorizeStoreChain(Slice, R, Cnt)) {
8878           // Mark the vectorized stores so that we don't vectorize them again.
8879           VectorizedStores.insert(Slice.begin(), Slice.end());
8880           Changed = true;
8881           // If we vectorized initial block, no need to try to vectorize it
8882           // again.
8883           if (Cnt == StartIdx)
8884             StartIdx += Size;
8885           Cnt += Size;
8886           continue;
8887         }
8888         ++Cnt;
8889       }
8890       // Check if the whole array was vectorized already - exit.
8891       if (StartIdx >= Operands.size())
8892         break;
8893     }
8894   }
8895 
8896   return Changed;
8897 }
8898 
8899 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8900   // Initialize the collections. We will make a single pass over the block.
8901   Stores.clear();
8902   GEPs.clear();
8903 
8904   // Visit the store and getelementptr instructions in BB and organize them in
8905   // Stores and GEPs according to the underlying objects of their pointer
8906   // operands.
8907   for (Instruction &I : *BB) {
8908     // Ignore store instructions that are volatile or have a pointer operand
8909     // that doesn't point to a scalar type.
8910     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8911       if (!SI->isSimple())
8912         continue;
8913       if (!isValidElementType(SI->getValueOperand()->getType()))
8914         continue;
8915       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8916     }
8917 
8918     // Ignore getelementptr instructions that have more than one index, a
8919     // constant index, or a pointer operand that doesn't point to a scalar
8920     // type.
8921     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8922       auto Idx = GEP->idx_begin()->get();
8923       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8924         continue;
8925       if (!isValidElementType(Idx->getType()))
8926         continue;
8927       if (GEP->getType()->isVectorTy())
8928         continue;
8929       GEPs[GEP->getPointerOperand()].push_back(GEP);
8930     }
8931   }
8932 }
8933 
8934 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8935   if (!A || !B)
8936     return false;
8937   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8938     return false;
8939   Value *VL[] = {A, B};
8940   return tryToVectorizeList(VL, R);
8941 }
8942 
8943 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8944                                            bool LimitForRegisterSize) {
8945   if (VL.size() < 2)
8946     return false;
8947 
8948   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8949                     << VL.size() << ".\n");
8950 
8951   // Check that all of the parts are instructions of the same type,
8952   // we permit an alternate opcode via InstructionsState.
8953   InstructionsState S = getSameOpcode(VL);
8954   if (!S.getOpcode())
8955     return false;
8956 
8957   Instruction *I0 = cast<Instruction>(S.OpValue);
8958   // Make sure invalid types (including vector type) are rejected before
8959   // determining vectorization factor for scalar instructions.
8960   for (Value *V : VL) {
8961     Type *Ty = V->getType();
8962     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8963       // NOTE: the following will give user internal llvm type name, which may
8964       // not be useful.
8965       R.getORE()->emit([&]() {
8966         std::string type_str;
8967         llvm::raw_string_ostream rso(type_str);
8968         Ty->print(rso);
8969         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8970                << "Cannot SLP vectorize list: type "
8971                << rso.str() + " is unsupported by vectorizer";
8972       });
8973       return false;
8974     }
8975   }
8976 
8977   unsigned Sz = R.getVectorElementSize(I0);
8978   unsigned MinVF = R.getMinVF(Sz);
8979   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8980   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8981   if (MaxVF < 2) {
8982     R.getORE()->emit([&]() {
8983       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8984              << "Cannot SLP vectorize list: vectorization factor "
8985              << "less than 2 is not supported";
8986     });
8987     return false;
8988   }
8989 
8990   bool Changed = false;
8991   bool CandidateFound = false;
8992   InstructionCost MinCost = SLPCostThreshold.getValue();
8993   Type *ScalarTy = VL[0]->getType();
8994   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8995     ScalarTy = IE->getOperand(1)->getType();
8996 
8997   unsigned NextInst = 0, MaxInst = VL.size();
8998   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8999     // No actual vectorization should happen, if number of parts is the same as
9000     // provided vectorization factor (i.e. the scalar type is used for vector
9001     // code during codegen).
9002     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9003     if (TTI->getNumberOfParts(VecTy) == VF)
9004       continue;
9005     for (unsigned I = NextInst; I < MaxInst; ++I) {
9006       unsigned OpsWidth = 0;
9007 
9008       if (I + VF > MaxInst)
9009         OpsWidth = MaxInst - I;
9010       else
9011         OpsWidth = VF;
9012 
9013       if (!isPowerOf2_32(OpsWidth))
9014         continue;
9015 
9016       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9017           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9018         break;
9019 
9020       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9021       // Check that a previous iteration of this loop did not delete the Value.
9022       if (llvm::any_of(Ops, [&R](Value *V) {
9023             auto *I = dyn_cast<Instruction>(V);
9024             return I && R.isDeleted(I);
9025           }))
9026         continue;
9027 
9028       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9029                         << "\n");
9030 
9031       R.buildTree(Ops);
9032       if (R.isTreeTinyAndNotFullyVectorizable())
9033         continue;
9034       R.reorderTopToBottom();
9035       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9036       R.buildExternalUses();
9037 
9038       R.computeMinimumValueSizes();
9039       InstructionCost Cost = R.getTreeCost();
9040       CandidateFound = true;
9041       MinCost = std::min(MinCost, Cost);
9042 
9043       if (Cost < -SLPCostThreshold) {
9044         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9045         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9046                                                     cast<Instruction>(Ops[0]))
9047                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9048                                  << " and with tree size "
9049                                  << ore::NV("TreeSize", R.getTreeSize()));
9050 
9051         R.vectorizeTree();
9052         // Move to the next bundle.
9053         I += VF - 1;
9054         NextInst = I + 1;
9055         Changed = true;
9056       }
9057     }
9058   }
9059 
9060   if (!Changed && CandidateFound) {
9061     R.getORE()->emit([&]() {
9062       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9063              << "List vectorization was possible but not beneficial with cost "
9064              << ore::NV("Cost", MinCost) << " >= "
9065              << ore::NV("Treshold", -SLPCostThreshold);
9066     });
9067   } else if (!Changed) {
9068     R.getORE()->emit([&]() {
9069       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9070              << "Cannot SLP vectorize list: vectorization was impossible"
9071              << " with available vectorization factors";
9072     });
9073   }
9074   return Changed;
9075 }
9076 
9077 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9078   if (!I)
9079     return false;
9080 
9081   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9082     return false;
9083 
9084   Value *P = I->getParent();
9085 
9086   // Vectorize in current basic block only.
9087   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9088   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9089   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9090     return false;
9091 
9092   // Try to vectorize V.
9093   if (tryToVectorizePair(Op0, Op1, R))
9094     return true;
9095 
9096   auto *A = dyn_cast<BinaryOperator>(Op0);
9097   auto *B = dyn_cast<BinaryOperator>(Op1);
9098   // Try to skip B.
9099   if (B && B->hasOneUse()) {
9100     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9101     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9102     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9103       return true;
9104     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9105       return true;
9106   }
9107 
9108   // Try to skip A.
9109   if (A && A->hasOneUse()) {
9110     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9111     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9112     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9113       return true;
9114     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9115       return true;
9116   }
9117   return false;
9118 }
9119 
9120 namespace {
9121 
9122 /// Model horizontal reductions.
9123 ///
9124 /// A horizontal reduction is a tree of reduction instructions that has values
9125 /// that can be put into a vector as its leaves. For example:
9126 ///
9127 /// mul mul mul mul
9128 ///  \  /    \  /
9129 ///   +       +
9130 ///    \     /
9131 ///       +
9132 /// This tree has "mul" as its leaf values and "+" as its reduction
9133 /// instructions. A reduction can feed into a store or a binary operation
9134 /// feeding a phi.
9135 ///    ...
9136 ///    \  /
9137 ///     +
9138 ///     |
9139 ///  phi +=
9140 ///
9141 ///  Or:
9142 ///    ...
9143 ///    \  /
9144 ///     +
9145 ///     |
9146 ///   *p =
9147 ///
9148 class HorizontalReduction {
9149   using ReductionOpsType = SmallVector<Value *, 16>;
9150   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9151   ReductionOpsListType ReductionOps;
9152   SmallVector<Value *, 32> ReducedVals;
9153   // Use map vector to make stable output.
9154   MapVector<Instruction *, Value *> ExtraArgs;
9155   WeakTrackingVH ReductionRoot;
9156   /// The type of reduction operation.
9157   RecurKind RdxKind;
9158 
9159   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9160 
9161   static bool isCmpSelMinMax(Instruction *I) {
9162     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9163            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9164   }
9165 
9166   // And/or are potentially poison-safe logical patterns like:
9167   // select x, y, false
9168   // select x, true, y
9169   static bool isBoolLogicOp(Instruction *I) {
9170     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9171            match(I, m_LogicalOr(m_Value(), m_Value()));
9172   }
9173 
9174   /// Checks if instruction is associative and can be vectorized.
9175   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9176     if (Kind == RecurKind::None)
9177       return false;
9178 
9179     // Integer ops that map to select instructions or intrinsics are fine.
9180     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9181         isBoolLogicOp(I))
9182       return true;
9183 
9184     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9185       // FP min/max are associative except for NaN and -0.0. We do not
9186       // have to rule out -0.0 here because the intrinsic semantics do not
9187       // specify a fixed result for it.
9188       return I->getFastMathFlags().noNaNs();
9189     }
9190 
9191     return I->isAssociative();
9192   }
9193 
9194   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9195     // Poison-safe 'or' takes the form: select X, true, Y
9196     // To make that work with the normal operand processing, we skip the
9197     // true value operand.
9198     // TODO: Change the code and data structures to handle this without a hack.
9199     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9200       return I->getOperand(2);
9201     return I->getOperand(Index);
9202   }
9203 
9204   /// Checks if the ParentStackElem.first should be marked as a reduction
9205   /// operation with an extra argument or as extra argument itself.
9206   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9207                     Value *ExtraArg) {
9208     if (ExtraArgs.count(ParentStackElem.first)) {
9209       ExtraArgs[ParentStackElem.first] = nullptr;
9210       // We ran into something like:
9211       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9212       // The whole ParentStackElem.first should be considered as an extra value
9213       // in this case.
9214       // Do not perform analysis of remaining operands of ParentStackElem.first
9215       // instruction, this whole instruction is an extra argument.
9216       ParentStackElem.second = INVALID_OPERAND_INDEX;
9217     } else {
9218       // We ran into something like:
9219       // ParentStackElem.first += ... + ExtraArg + ...
9220       ExtraArgs[ParentStackElem.first] = ExtraArg;
9221     }
9222   }
9223 
9224   /// Creates reduction operation with the current opcode.
9225   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9226                          Value *RHS, const Twine &Name, bool UseSelect) {
9227     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9228     switch (Kind) {
9229     case RecurKind::Or:
9230       if (UseSelect &&
9231           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9232         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9233       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9234                                  Name);
9235     case RecurKind::And:
9236       if (UseSelect &&
9237           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9238         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9239       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9240                                  Name);
9241     case RecurKind::Add:
9242     case RecurKind::Mul:
9243     case RecurKind::Xor:
9244     case RecurKind::FAdd:
9245     case RecurKind::FMul:
9246       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9247                                  Name);
9248     case RecurKind::FMax:
9249       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9250     case RecurKind::FMin:
9251       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9252     case RecurKind::SMax:
9253       if (UseSelect) {
9254         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9255         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9256       }
9257       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9258     case RecurKind::SMin:
9259       if (UseSelect) {
9260         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9261         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9262       }
9263       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9264     case RecurKind::UMax:
9265       if (UseSelect) {
9266         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9267         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9268       }
9269       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9270     case RecurKind::UMin:
9271       if (UseSelect) {
9272         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9273         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9274       }
9275       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9276     default:
9277       llvm_unreachable("Unknown reduction operation.");
9278     }
9279   }
9280 
9281   /// Creates reduction operation with the current opcode with the IR flags
9282   /// from \p ReductionOps.
9283   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9284                          Value *RHS, const Twine &Name,
9285                          const ReductionOpsListType &ReductionOps) {
9286     bool UseSelect = ReductionOps.size() == 2 ||
9287                      // Logical or/and.
9288                      (ReductionOps.size() == 1 &&
9289                       isa<SelectInst>(ReductionOps.front().front()));
9290     assert((!UseSelect || ReductionOps.size() != 2 ||
9291             isa<SelectInst>(ReductionOps[1][0])) &&
9292            "Expected cmp + select pairs for reduction");
9293     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9294     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9295       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9296         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9297         propagateIRFlags(Op, ReductionOps[1]);
9298         return Op;
9299       }
9300     }
9301     propagateIRFlags(Op, ReductionOps[0]);
9302     return Op;
9303   }
9304 
9305   /// Creates reduction operation with the current opcode with the IR flags
9306   /// from \p I.
9307   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9308                          Value *RHS, const Twine &Name, Instruction *I) {
9309     auto *SelI = dyn_cast<SelectInst>(I);
9310     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9311     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9312       if (auto *Sel = dyn_cast<SelectInst>(Op))
9313         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9314     }
9315     propagateIRFlags(Op, I);
9316     return Op;
9317   }
9318 
9319   static RecurKind getRdxKind(Instruction *I) {
9320     assert(I && "Expected instruction for reduction matching");
9321     if (match(I, m_Add(m_Value(), m_Value())))
9322       return RecurKind::Add;
9323     if (match(I, m_Mul(m_Value(), m_Value())))
9324       return RecurKind::Mul;
9325     if (match(I, m_And(m_Value(), m_Value())) ||
9326         match(I, m_LogicalAnd(m_Value(), m_Value())))
9327       return RecurKind::And;
9328     if (match(I, m_Or(m_Value(), m_Value())) ||
9329         match(I, m_LogicalOr(m_Value(), m_Value())))
9330       return RecurKind::Or;
9331     if (match(I, m_Xor(m_Value(), m_Value())))
9332       return RecurKind::Xor;
9333     if (match(I, m_FAdd(m_Value(), m_Value())))
9334       return RecurKind::FAdd;
9335     if (match(I, m_FMul(m_Value(), m_Value())))
9336       return RecurKind::FMul;
9337 
9338     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9339       return RecurKind::FMax;
9340     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9341       return RecurKind::FMin;
9342 
9343     // This matches either cmp+select or intrinsics. SLP is expected to handle
9344     // either form.
9345     // TODO: If we are canonicalizing to intrinsics, we can remove several
9346     //       special-case paths that deal with selects.
9347     if (match(I, m_SMax(m_Value(), m_Value())))
9348       return RecurKind::SMax;
9349     if (match(I, m_SMin(m_Value(), m_Value())))
9350       return RecurKind::SMin;
9351     if (match(I, m_UMax(m_Value(), m_Value())))
9352       return RecurKind::UMax;
9353     if (match(I, m_UMin(m_Value(), m_Value())))
9354       return RecurKind::UMin;
9355 
9356     if (auto *Select = dyn_cast<SelectInst>(I)) {
9357       // Try harder: look for min/max pattern based on instructions producing
9358       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9359       // During the intermediate stages of SLP, it's very common to have
9360       // pattern like this (since optimizeGatherSequence is run only once
9361       // at the end):
9362       // %1 = extractelement <2 x i32> %a, i32 0
9363       // %2 = extractelement <2 x i32> %a, i32 1
9364       // %cond = icmp sgt i32 %1, %2
9365       // %3 = extractelement <2 x i32> %a, i32 0
9366       // %4 = extractelement <2 x i32> %a, i32 1
9367       // %select = select i1 %cond, i32 %3, i32 %4
9368       CmpInst::Predicate Pred;
9369       Instruction *L1;
9370       Instruction *L2;
9371 
9372       Value *LHS = Select->getTrueValue();
9373       Value *RHS = Select->getFalseValue();
9374       Value *Cond = Select->getCondition();
9375 
9376       // TODO: Support inverse predicates.
9377       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9378         if (!isa<ExtractElementInst>(RHS) ||
9379             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9380           return RecurKind::None;
9381       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9382         if (!isa<ExtractElementInst>(LHS) ||
9383             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9384           return RecurKind::None;
9385       } else {
9386         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9387           return RecurKind::None;
9388         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9389             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9390             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9391           return RecurKind::None;
9392       }
9393 
9394       switch (Pred) {
9395       default:
9396         return RecurKind::None;
9397       case CmpInst::ICMP_SGT:
9398       case CmpInst::ICMP_SGE:
9399         return RecurKind::SMax;
9400       case CmpInst::ICMP_SLT:
9401       case CmpInst::ICMP_SLE:
9402         return RecurKind::SMin;
9403       case CmpInst::ICMP_UGT:
9404       case CmpInst::ICMP_UGE:
9405         return RecurKind::UMax;
9406       case CmpInst::ICMP_ULT:
9407       case CmpInst::ICMP_ULE:
9408         return RecurKind::UMin;
9409       }
9410     }
9411     return RecurKind::None;
9412   }
9413 
9414   /// Get the index of the first operand.
9415   static unsigned getFirstOperandIndex(Instruction *I) {
9416     return isCmpSelMinMax(I) ? 1 : 0;
9417   }
9418 
9419   /// Total number of operands in the reduction operation.
9420   static unsigned getNumberOfOperands(Instruction *I) {
9421     return isCmpSelMinMax(I) ? 3 : 2;
9422   }
9423 
9424   /// Checks if the instruction is in basic block \p BB.
9425   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9426   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9427     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9428       auto *Sel = cast<SelectInst>(I);
9429       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9430       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9431     }
9432     return I->getParent() == BB;
9433   }
9434 
9435   /// Expected number of uses for reduction operations/reduced values.
9436   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9437     if (IsCmpSelMinMax) {
9438       // SelectInst must be used twice while the condition op must have single
9439       // use only.
9440       if (auto *Sel = dyn_cast<SelectInst>(I))
9441         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9442       return I->hasNUses(2);
9443     }
9444 
9445     // Arithmetic reduction operation must be used once only.
9446     return I->hasOneUse();
9447   }
9448 
9449   /// Initializes the list of reduction operations.
9450   void initReductionOps(Instruction *I) {
9451     if (isCmpSelMinMax(I))
9452       ReductionOps.assign(2, ReductionOpsType());
9453     else
9454       ReductionOps.assign(1, ReductionOpsType());
9455   }
9456 
9457   /// Add all reduction operations for the reduction instruction \p I.
9458   void addReductionOps(Instruction *I) {
9459     if (isCmpSelMinMax(I)) {
9460       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9461       ReductionOps[1].emplace_back(I);
9462     } else {
9463       ReductionOps[0].emplace_back(I);
9464     }
9465   }
9466 
9467   static Value *getLHS(RecurKind Kind, Instruction *I) {
9468     if (Kind == RecurKind::None)
9469       return nullptr;
9470     return I->getOperand(getFirstOperandIndex(I));
9471   }
9472   static Value *getRHS(RecurKind Kind, Instruction *I) {
9473     if (Kind == RecurKind::None)
9474       return nullptr;
9475     return I->getOperand(getFirstOperandIndex(I) + 1);
9476   }
9477 
9478 public:
9479   HorizontalReduction() = default;
9480 
9481   /// Try to find a reduction tree.
9482   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9483     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9484            "Phi needs to use the binary operator");
9485     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9486             isa<IntrinsicInst>(Inst)) &&
9487            "Expected binop, select, or intrinsic for reduction matching");
9488     RdxKind = getRdxKind(Inst);
9489 
9490     // We could have a initial reductions that is not an add.
9491     //  r *= v1 + v2 + v3 + v4
9492     // In such a case start looking for a tree rooted in the first '+'.
9493     if (Phi) {
9494       if (getLHS(RdxKind, Inst) == Phi) {
9495         Phi = nullptr;
9496         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9497         if (!Inst)
9498           return false;
9499         RdxKind = getRdxKind(Inst);
9500       } else if (getRHS(RdxKind, Inst) == Phi) {
9501         Phi = nullptr;
9502         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9503         if (!Inst)
9504           return false;
9505         RdxKind = getRdxKind(Inst);
9506       }
9507     }
9508 
9509     if (!isVectorizable(RdxKind, Inst))
9510       return false;
9511 
9512     // Analyze "regular" integer/FP types for reductions - no target-specific
9513     // types or pointers.
9514     Type *Ty = Inst->getType();
9515     if (!isValidElementType(Ty) || Ty->isPointerTy())
9516       return false;
9517 
9518     // Though the ultimate reduction may have multiple uses, its condition must
9519     // have only single use.
9520     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9521       if (!Sel->getCondition()->hasOneUse())
9522         return false;
9523 
9524     ReductionRoot = Inst;
9525 
9526     // The opcode for leaf values that we perform a reduction on.
9527     // For example: load(x) + load(y) + load(z) + fptoui(w)
9528     // The leaf opcode for 'w' does not match, so we don't include it as a
9529     // potential candidate for the reduction.
9530     unsigned LeafOpcode = 0;
9531 
9532     // Post-order traverse the reduction tree starting at Inst. We only handle
9533     // true trees containing binary operators or selects.
9534     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9535     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9536     initReductionOps(Inst);
9537     while (!Stack.empty()) {
9538       Instruction *TreeN = Stack.back().first;
9539       unsigned EdgeToVisit = Stack.back().second++;
9540       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9541       bool IsReducedValue = TreeRdxKind != RdxKind;
9542 
9543       // Postorder visit.
9544       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9545         if (IsReducedValue)
9546           ReducedVals.push_back(TreeN);
9547         else {
9548           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9549           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9550             // Check if TreeN is an extra argument of its parent operation.
9551             if (Stack.size() <= 1) {
9552               // TreeN can't be an extra argument as it is a root reduction
9553               // operation.
9554               return false;
9555             }
9556             // Yes, TreeN is an extra argument, do not add it to a list of
9557             // reduction operations.
9558             // Stack[Stack.size() - 2] always points to the parent operation.
9559             markExtraArg(Stack[Stack.size() - 2], TreeN);
9560             ExtraArgs.erase(TreeN);
9561           } else
9562             addReductionOps(TreeN);
9563         }
9564         // Retract.
9565         Stack.pop_back();
9566         continue;
9567       }
9568 
9569       // Visit operands.
9570       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9571       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9572       if (!EdgeInst) {
9573         // Edge value is not a reduction instruction or a leaf instruction.
9574         // (It may be a constant, function argument, or something else.)
9575         markExtraArg(Stack.back(), EdgeVal);
9576         continue;
9577       }
9578       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9579       // Continue analysis if the next operand is a reduction operation or
9580       // (possibly) a leaf value. If the leaf value opcode is not set,
9581       // the first met operation != reduction operation is considered as the
9582       // leaf opcode.
9583       // Only handle trees in the current basic block.
9584       // Each tree node needs to have minimal number of users except for the
9585       // ultimate reduction.
9586       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9587       if (EdgeInst != Phi && EdgeInst != Inst &&
9588           hasSameParent(EdgeInst, Inst->getParent()) &&
9589           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9590           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9591         if (IsRdxInst) {
9592           // We need to be able to reassociate the reduction operations.
9593           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9594             // I is an extra argument for TreeN (its parent operation).
9595             markExtraArg(Stack.back(), EdgeInst);
9596             continue;
9597           }
9598         } else if (!LeafOpcode) {
9599           LeafOpcode = EdgeInst->getOpcode();
9600         }
9601         Stack.push_back(
9602             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9603         continue;
9604       }
9605       // I is an extra argument for TreeN (its parent operation).
9606       markExtraArg(Stack.back(), EdgeInst);
9607     }
9608     return true;
9609   }
9610 
9611   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9612   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9613     // If there are a sufficient number of reduction values, reduce
9614     // to a nearby power-of-2. We can safely generate oversized
9615     // vectors and rely on the backend to split them to legal sizes.
9616     unsigned NumReducedVals = ReducedVals.size();
9617     if (NumReducedVals < 4)
9618       return nullptr;
9619 
9620     // Intersect the fast-math-flags from all reduction operations.
9621     FastMathFlags RdxFMF;
9622     RdxFMF.set();
9623     for (ReductionOpsType &RdxOp : ReductionOps) {
9624       for (Value *RdxVal : RdxOp) {
9625         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9626           RdxFMF &= FPMO->getFastMathFlags();
9627       }
9628     }
9629 
9630     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9631     Builder.setFastMathFlags(RdxFMF);
9632 
9633     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9634     // The same extra argument may be used several times, so log each attempt
9635     // to use it.
9636     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9637       assert(Pair.first && "DebugLoc must be set.");
9638       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9639     }
9640 
9641     // The compare instruction of a min/max is the insertion point for new
9642     // instructions and may be replaced with a new compare instruction.
9643     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9644       assert(isa<SelectInst>(RdxRootInst) &&
9645              "Expected min/max reduction to have select root instruction");
9646       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9647       assert(isa<Instruction>(ScalarCond) &&
9648              "Expected min/max reduction to have compare condition");
9649       return cast<Instruction>(ScalarCond);
9650     };
9651 
9652     // The reduction root is used as the insertion point for new instructions,
9653     // so set it as externally used to prevent it from being deleted.
9654     ExternallyUsedValues[ReductionRoot];
9655     SmallVector<Value *, 16> IgnoreList;
9656     for (ReductionOpsType &RdxOp : ReductionOps)
9657       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9658 
9659     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9660     if (NumReducedVals > ReduxWidth) {
9661       // In the loop below, we are building a tree based on a window of
9662       // 'ReduxWidth' values.
9663       // If the operands of those values have common traits (compare predicate,
9664       // constant operand, etc), then we want to group those together to
9665       // minimize the cost of the reduction.
9666 
9667       // TODO: This should be extended to count common operands for
9668       //       compares and binops.
9669 
9670       // Step 1: Count the number of times each compare predicate occurs.
9671       SmallDenseMap<unsigned, unsigned> PredCountMap;
9672       for (Value *RdxVal : ReducedVals) {
9673         CmpInst::Predicate Pred;
9674         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9675           ++PredCountMap[Pred];
9676       }
9677       // Step 2: Sort the values so the most common predicates come first.
9678       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9679         CmpInst::Predicate PredA, PredB;
9680         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9681             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9682           return PredCountMap[PredA] > PredCountMap[PredB];
9683         }
9684         return false;
9685       });
9686     }
9687 
9688     Value *VectorizedTree = nullptr;
9689     unsigned i = 0;
9690     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9691       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9692       V.buildTree(VL, IgnoreList);
9693       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9694         break;
9695       if (V.isLoadCombineReductionCandidate(RdxKind))
9696         break;
9697       V.reorderTopToBottom();
9698       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9699       V.buildExternalUses(ExternallyUsedValues);
9700 
9701       // For a poison-safe boolean logic reduction, do not replace select
9702       // instructions with logic ops. All reduced values will be frozen (see
9703       // below) to prevent leaking poison.
9704       if (isa<SelectInst>(ReductionRoot) &&
9705           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9706           NumReducedVals != ReduxWidth)
9707         break;
9708 
9709       V.computeMinimumValueSizes();
9710 
9711       // Estimate cost.
9712       InstructionCost TreeCost =
9713           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9714       InstructionCost ReductionCost =
9715           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9716       InstructionCost Cost = TreeCost + ReductionCost;
9717       if (!Cost.isValid()) {
9718         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9719         return nullptr;
9720       }
9721       if (Cost >= -SLPCostThreshold) {
9722         V.getORE()->emit([&]() {
9723           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9724                                           cast<Instruction>(VL[0]))
9725                  << "Vectorizing horizontal reduction is possible"
9726                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9727                  << " and threshold "
9728                  << ore::NV("Threshold", -SLPCostThreshold);
9729         });
9730         break;
9731       }
9732 
9733       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9734                         << Cost << ". (HorRdx)\n");
9735       V.getORE()->emit([&]() {
9736         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9737                                   cast<Instruction>(VL[0]))
9738                << "Vectorized horizontal reduction with cost "
9739                << ore::NV("Cost", Cost) << " and with tree size "
9740                << ore::NV("TreeSize", V.getTreeSize());
9741       });
9742 
9743       // Vectorize a tree.
9744       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9745       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9746 
9747       // Emit a reduction. If the root is a select (min/max idiom), the insert
9748       // point is the compare condition of that select.
9749       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9750       if (isCmpSelMinMax(RdxRootInst))
9751         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9752       else
9753         Builder.SetInsertPoint(RdxRootInst);
9754 
9755       // To prevent poison from leaking across what used to be sequential, safe,
9756       // scalar boolean logic operations, the reduction operand must be frozen.
9757       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9758         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9759 
9760       Value *ReducedSubTree =
9761           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9762 
9763       if (!VectorizedTree) {
9764         // Initialize the final value in the reduction.
9765         VectorizedTree = ReducedSubTree;
9766       } else {
9767         // Update the final value in the reduction.
9768         Builder.SetCurrentDebugLocation(Loc);
9769         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9770                                   ReducedSubTree, "op.rdx", ReductionOps);
9771       }
9772       i += ReduxWidth;
9773       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9774     }
9775 
9776     if (VectorizedTree) {
9777       // Finish the reduction.
9778       for (; i < NumReducedVals; ++i) {
9779         auto *I = cast<Instruction>(ReducedVals[i]);
9780         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9781         VectorizedTree =
9782             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9783       }
9784       for (auto &Pair : ExternallyUsedValues) {
9785         // Add each externally used value to the final reduction.
9786         for (auto *I : Pair.second) {
9787           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9788           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9789                                     Pair.first, "op.extra", I);
9790         }
9791       }
9792 
9793       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9794 
9795       // Mark all scalar reduction ops for deletion, they are replaced by the
9796       // vector reductions.
9797       V.eraseInstructions(IgnoreList);
9798     }
9799     return VectorizedTree;
9800   }
9801 
9802   unsigned numReductionValues() const { return ReducedVals.size(); }
9803 
9804 private:
9805   /// Calculate the cost of a reduction.
9806   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9807                                    Value *FirstReducedVal, unsigned ReduxWidth,
9808                                    FastMathFlags FMF) {
9809     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9810     Type *ScalarTy = FirstReducedVal->getType();
9811     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9812     InstructionCost VectorCost, ScalarCost;
9813     switch (RdxKind) {
9814     case RecurKind::Add:
9815     case RecurKind::Mul:
9816     case RecurKind::Or:
9817     case RecurKind::And:
9818     case RecurKind::Xor:
9819     case RecurKind::FAdd:
9820     case RecurKind::FMul: {
9821       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9822       VectorCost =
9823           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9824       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9825       break;
9826     }
9827     case RecurKind::FMax:
9828     case RecurKind::FMin: {
9829       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9830       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9831       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9832                                                /*IsUnsigned=*/false, CostKind);
9833       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9834       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9835                                            SclCondTy, RdxPred, CostKind) +
9836                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9837                                            SclCondTy, RdxPred, CostKind);
9838       break;
9839     }
9840     case RecurKind::SMax:
9841     case RecurKind::SMin:
9842     case RecurKind::UMax:
9843     case RecurKind::UMin: {
9844       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9845       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9846       bool IsUnsigned =
9847           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9848       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9849                                                CostKind);
9850       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9851       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9852                                            SclCondTy, RdxPred, CostKind) +
9853                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9854                                            SclCondTy, RdxPred, CostKind);
9855       break;
9856     }
9857     default:
9858       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9859     }
9860 
9861     // Scalar cost is repeated for N-1 elements.
9862     ScalarCost *= (ReduxWidth - 1);
9863     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9864                       << " for reduction that starts with " << *FirstReducedVal
9865                       << " (It is a splitting reduction)\n");
9866     return VectorCost - ScalarCost;
9867   }
9868 
9869   /// Emit a horizontal reduction of the vectorized value.
9870   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9871                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9872     assert(VectorizedValue && "Need to have a vectorized tree node");
9873     assert(isPowerOf2_32(ReduxWidth) &&
9874            "We only handle power-of-two reductions for now");
9875     assert(RdxKind != RecurKind::FMulAdd &&
9876            "A call to the llvm.fmuladd intrinsic is not handled yet");
9877 
9878     ++NumVectorInstructions;
9879     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9880   }
9881 };
9882 
9883 } // end anonymous namespace
9884 
9885 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9886   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9887     return cast<FixedVectorType>(IE->getType())->getNumElements();
9888 
9889   unsigned AggregateSize = 1;
9890   auto *IV = cast<InsertValueInst>(InsertInst);
9891   Type *CurrentType = IV->getType();
9892   do {
9893     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9894       for (auto *Elt : ST->elements())
9895         if (Elt != ST->getElementType(0)) // check homogeneity
9896           return None;
9897       AggregateSize *= ST->getNumElements();
9898       CurrentType = ST->getElementType(0);
9899     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9900       AggregateSize *= AT->getNumElements();
9901       CurrentType = AT->getElementType();
9902     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9903       AggregateSize *= VT->getNumElements();
9904       return AggregateSize;
9905     } else if (CurrentType->isSingleValueType()) {
9906       return AggregateSize;
9907     } else {
9908       return None;
9909     }
9910   } while (true);
9911 }
9912 
9913 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9914                                    TargetTransformInfo *TTI,
9915                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9916                                    SmallVectorImpl<Value *> &InsertElts,
9917                                    unsigned OperandOffset) {
9918   do {
9919     Value *InsertedOperand = LastInsertInst->getOperand(1);
9920     Optional<unsigned> OperandIndex =
9921         getInsertIndex(LastInsertInst, OperandOffset);
9922     if (!OperandIndex)
9923       return;
9924     if (isa<InsertElementInst>(InsertedOperand) ||
9925         isa<InsertValueInst>(InsertedOperand)) {
9926       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9927                              BuildVectorOpds, InsertElts, *OperandIndex);
9928 
9929     } else {
9930       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9931       InsertElts[*OperandIndex] = LastInsertInst;
9932     }
9933     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9934   } while (LastInsertInst != nullptr &&
9935            (isa<InsertValueInst>(LastInsertInst) ||
9936             isa<InsertElementInst>(LastInsertInst)) &&
9937            LastInsertInst->hasOneUse());
9938 }
9939 
9940 /// Recognize construction of vectors like
9941 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9942 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9943 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9944 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9945 ///  starting from the last insertelement or insertvalue instruction.
9946 ///
9947 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9948 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9949 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9950 ///
9951 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9952 ///
9953 /// \return true if it matches.
9954 static bool findBuildAggregate(Instruction *LastInsertInst,
9955                                TargetTransformInfo *TTI,
9956                                SmallVectorImpl<Value *> &BuildVectorOpds,
9957                                SmallVectorImpl<Value *> &InsertElts) {
9958 
9959   assert((isa<InsertElementInst>(LastInsertInst) ||
9960           isa<InsertValueInst>(LastInsertInst)) &&
9961          "Expected insertelement or insertvalue instruction!");
9962 
9963   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9964          "Expected empty result vectors!");
9965 
9966   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9967   if (!AggregateSize)
9968     return false;
9969   BuildVectorOpds.resize(*AggregateSize);
9970   InsertElts.resize(*AggregateSize);
9971 
9972   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9973   llvm::erase_value(BuildVectorOpds, nullptr);
9974   llvm::erase_value(InsertElts, nullptr);
9975   if (BuildVectorOpds.size() >= 2)
9976     return true;
9977 
9978   return false;
9979 }
9980 
9981 /// Try and get a reduction value from a phi node.
9982 ///
9983 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9984 /// if they come from either \p ParentBB or a containing loop latch.
9985 ///
9986 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9987 /// if not possible.
9988 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9989                                 BasicBlock *ParentBB, LoopInfo *LI) {
9990   // There are situations where the reduction value is not dominated by the
9991   // reduction phi. Vectorizing such cases has been reported to cause
9992   // miscompiles. See PR25787.
9993   auto DominatedReduxValue = [&](Value *R) {
9994     return isa<Instruction>(R) &&
9995            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9996   };
9997 
9998   Value *Rdx = nullptr;
9999 
10000   // Return the incoming value if it comes from the same BB as the phi node.
10001   if (P->getIncomingBlock(0) == ParentBB) {
10002     Rdx = P->getIncomingValue(0);
10003   } else if (P->getIncomingBlock(1) == ParentBB) {
10004     Rdx = P->getIncomingValue(1);
10005   }
10006 
10007   if (Rdx && DominatedReduxValue(Rdx))
10008     return Rdx;
10009 
10010   // Otherwise, check whether we have a loop latch to look at.
10011   Loop *BBL = LI->getLoopFor(ParentBB);
10012   if (!BBL)
10013     return nullptr;
10014   BasicBlock *BBLatch = BBL->getLoopLatch();
10015   if (!BBLatch)
10016     return nullptr;
10017 
10018   // There is a loop latch, return the incoming value if it comes from
10019   // that. This reduction pattern occasionally turns up.
10020   if (P->getIncomingBlock(0) == BBLatch) {
10021     Rdx = P->getIncomingValue(0);
10022   } else if (P->getIncomingBlock(1) == BBLatch) {
10023     Rdx = P->getIncomingValue(1);
10024   }
10025 
10026   if (Rdx && DominatedReduxValue(Rdx))
10027     return Rdx;
10028 
10029   return nullptr;
10030 }
10031 
10032 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10033   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10034     return true;
10035   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10036     return true;
10037   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10038     return true;
10039   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10040     return true;
10041   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10042     return true;
10043   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10044     return true;
10045   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10046     return true;
10047   return false;
10048 }
10049 
10050 /// Attempt to reduce a horizontal reduction.
10051 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10052 /// with reduction operators \a Root (or one of its operands) in a basic block
10053 /// \a BB, then check if it can be done. If horizontal reduction is not found
10054 /// and root instruction is a binary operation, vectorization of the operands is
10055 /// attempted.
10056 /// \returns true if a horizontal reduction was matched and reduced or operands
10057 /// of one of the binary instruction were vectorized.
10058 /// \returns false if a horizontal reduction was not matched (or not possible)
10059 /// or no vectorization of any binary operation feeding \a Root instruction was
10060 /// performed.
10061 static bool tryToVectorizeHorReductionOrInstOperands(
10062     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10063     TargetTransformInfo *TTI,
10064     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10065   if (!ShouldVectorizeHor)
10066     return false;
10067 
10068   if (!Root)
10069     return false;
10070 
10071   if (Root->getParent() != BB || isa<PHINode>(Root))
10072     return false;
10073   // Start analysis starting from Root instruction. If horizontal reduction is
10074   // found, try to vectorize it. If it is not a horizontal reduction or
10075   // vectorization is not possible or not effective, and currently analyzed
10076   // instruction is a binary operation, try to vectorize the operands, using
10077   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10078   // the same procedure considering each operand as a possible root of the
10079   // horizontal reduction.
10080   // Interrupt the process if the Root instruction itself was vectorized or all
10081   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10082   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10083   // CmpInsts so we can skip extra attempts in
10084   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10085   std::queue<std::pair<Instruction *, unsigned>> Stack;
10086   Stack.emplace(Root, 0);
10087   SmallPtrSet<Value *, 8> VisitedInstrs;
10088   SmallVector<WeakTrackingVH> PostponedInsts;
10089   bool Res = false;
10090   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10091                                      Value *&B1) -> Value * {
10092     bool IsBinop = matchRdxBop(Inst, B0, B1);
10093     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10094     if (IsBinop || IsSelect) {
10095       HorizontalReduction HorRdx;
10096       if (HorRdx.matchAssociativeReduction(P, Inst))
10097         return HorRdx.tryToReduce(R, TTI);
10098     }
10099     return nullptr;
10100   };
10101   while (!Stack.empty()) {
10102     Instruction *Inst;
10103     unsigned Level;
10104     std::tie(Inst, Level) = Stack.front();
10105     Stack.pop();
10106     // Do not try to analyze instruction that has already been vectorized.
10107     // This may happen when we vectorize instruction operands on a previous
10108     // iteration while stack was populated before that happened.
10109     if (R.isDeleted(Inst))
10110       continue;
10111     Value *B0 = nullptr, *B1 = nullptr;
10112     if (Value *V = TryToReduce(Inst, B0, B1)) {
10113       Res = true;
10114       // Set P to nullptr to avoid re-analysis of phi node in
10115       // matchAssociativeReduction function unless this is the root node.
10116       P = nullptr;
10117       if (auto *I = dyn_cast<Instruction>(V)) {
10118         // Try to find another reduction.
10119         Stack.emplace(I, Level);
10120         continue;
10121       }
10122     } else {
10123       bool IsBinop = B0 && B1;
10124       if (P && IsBinop) {
10125         Inst = dyn_cast<Instruction>(B0);
10126         if (Inst == P)
10127           Inst = dyn_cast<Instruction>(B1);
10128         if (!Inst) {
10129           // Set P to nullptr to avoid re-analysis of phi node in
10130           // matchAssociativeReduction function unless this is the root node.
10131           P = nullptr;
10132           continue;
10133         }
10134       }
10135       // Set P to nullptr to avoid re-analysis of phi node in
10136       // matchAssociativeReduction function unless this is the root node.
10137       P = nullptr;
10138       // Do not try to vectorize CmpInst operands, this is done separately.
10139       // Final attempt for binop args vectorization should happen after the loop
10140       // to try to find reductions.
10141       if (!isa<CmpInst>(Inst))
10142         PostponedInsts.push_back(Inst);
10143     }
10144 
10145     // Try to vectorize operands.
10146     // Continue analysis for the instruction from the same basic block only to
10147     // save compile time.
10148     if (++Level < RecursionMaxDepth)
10149       for (auto *Op : Inst->operand_values())
10150         if (VisitedInstrs.insert(Op).second)
10151           if (auto *I = dyn_cast<Instruction>(Op))
10152             // Do not try to vectorize CmpInst operands,  this is done
10153             // separately.
10154             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10155                 I->getParent() == BB)
10156               Stack.emplace(I, Level);
10157   }
10158   // Try to vectorized binops where reductions were not found.
10159   for (Value *V : PostponedInsts)
10160     if (auto *Inst = dyn_cast<Instruction>(V))
10161       if (!R.isDeleted(Inst))
10162         Res |= Vectorize(Inst, R);
10163   return Res;
10164 }
10165 
10166 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10167                                                  BasicBlock *BB, BoUpSLP &R,
10168                                                  TargetTransformInfo *TTI) {
10169   auto *I = dyn_cast_or_null<Instruction>(V);
10170   if (!I)
10171     return false;
10172 
10173   if (!isa<BinaryOperator>(I))
10174     P = nullptr;
10175   // Try to match and vectorize a horizontal reduction.
10176   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10177     return tryToVectorize(I, R);
10178   };
10179   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10180                                                   ExtraVectorization);
10181 }
10182 
10183 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10184                                                  BasicBlock *BB, BoUpSLP &R) {
10185   const DataLayout &DL = BB->getModule()->getDataLayout();
10186   if (!R.canMapToVector(IVI->getType(), DL))
10187     return false;
10188 
10189   SmallVector<Value *, 16> BuildVectorOpds;
10190   SmallVector<Value *, 16> BuildVectorInsts;
10191   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10192     return false;
10193 
10194   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10195   // Aggregate value is unlikely to be processed in vector register.
10196   return tryToVectorizeList(BuildVectorOpds, R);
10197 }
10198 
10199 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10200                                                    BasicBlock *BB, BoUpSLP &R) {
10201   SmallVector<Value *, 16> BuildVectorInsts;
10202   SmallVector<Value *, 16> BuildVectorOpds;
10203   SmallVector<int> Mask;
10204   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10205       (llvm::all_of(
10206            BuildVectorOpds,
10207            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10208        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10209     return false;
10210 
10211   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10212   return tryToVectorizeList(BuildVectorInsts, R);
10213 }
10214 
10215 template <typename T>
10216 static bool
10217 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10218                        function_ref<unsigned(T *)> Limit,
10219                        function_ref<bool(T *, T *)> Comparator,
10220                        function_ref<bool(T *, T *)> AreCompatible,
10221                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10222                        bool LimitForRegisterSize) {
10223   bool Changed = false;
10224   // Sort by type, parent, operands.
10225   stable_sort(Incoming, Comparator);
10226 
10227   // Try to vectorize elements base on their type.
10228   SmallVector<T *> Candidates;
10229   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10230     // Look for the next elements with the same type, parent and operand
10231     // kinds.
10232     auto *SameTypeIt = IncIt;
10233     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10234       ++SameTypeIt;
10235 
10236     // Try to vectorize them.
10237     unsigned NumElts = (SameTypeIt - IncIt);
10238     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10239                       << NumElts << ")\n");
10240     // The vectorization is a 3-state attempt:
10241     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10242     // size of maximal register at first.
10243     // 2. Try to vectorize remaining instructions with the same type, if
10244     // possible. This may result in the better vectorization results rather than
10245     // if we try just to vectorize instructions with the same/alternate opcodes.
10246     // 3. Final attempt to try to vectorize all instructions with the
10247     // same/alternate ops only, this may result in some extra final
10248     // vectorization.
10249     if (NumElts > 1 &&
10250         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10251       // Success start over because instructions might have been changed.
10252       Changed = true;
10253     } else if (NumElts < Limit(*IncIt) &&
10254                (Candidates.empty() ||
10255                 Candidates.front()->getType() == (*IncIt)->getType())) {
10256       Candidates.append(IncIt, std::next(IncIt, NumElts));
10257     }
10258     // Final attempt to vectorize instructions with the same types.
10259     if (Candidates.size() > 1 &&
10260         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10261       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10262         // Success start over because instructions might have been changed.
10263         Changed = true;
10264       } else if (LimitForRegisterSize) {
10265         // Try to vectorize using small vectors.
10266         for (auto *It = Candidates.begin(), *End = Candidates.end();
10267              It != End;) {
10268           auto *SameTypeIt = It;
10269           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10270             ++SameTypeIt;
10271           unsigned NumElts = (SameTypeIt - It);
10272           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10273                                             /*LimitForRegisterSize=*/false))
10274             Changed = true;
10275           It = SameTypeIt;
10276         }
10277       }
10278       Candidates.clear();
10279     }
10280 
10281     // Start over at the next instruction of a different type (or the end).
10282     IncIt = SameTypeIt;
10283   }
10284   return Changed;
10285 }
10286 
10287 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10288 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10289 /// operands. If IsCompatibility is false, function implements strict weak
10290 /// ordering relation between two cmp instructions, returning true if the first
10291 /// instruction is "less" than the second, i.e. its predicate is less than the
10292 /// predicate of the second or the operands IDs are less than the operands IDs
10293 /// of the second cmp instruction.
10294 template <bool IsCompatibility>
10295 static bool compareCmp(Value *V, Value *V2,
10296                        function_ref<bool(Instruction *)> IsDeleted) {
10297   auto *CI1 = cast<CmpInst>(V);
10298   auto *CI2 = cast<CmpInst>(V2);
10299   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10300     return false;
10301   if (CI1->getOperand(0)->getType()->getTypeID() <
10302       CI2->getOperand(0)->getType()->getTypeID())
10303     return !IsCompatibility;
10304   if (CI1->getOperand(0)->getType()->getTypeID() >
10305       CI2->getOperand(0)->getType()->getTypeID())
10306     return false;
10307   CmpInst::Predicate Pred1 = CI1->getPredicate();
10308   CmpInst::Predicate Pred2 = CI2->getPredicate();
10309   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10310   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10311   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10312   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10313   if (BasePred1 < BasePred2)
10314     return !IsCompatibility;
10315   if (BasePred1 > BasePred2)
10316     return false;
10317   // Compare operands.
10318   bool LEPreds = Pred1 <= Pred2;
10319   bool GEPreds = Pred1 >= Pred2;
10320   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10321     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10322     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10323     if (Op1->getValueID() < Op2->getValueID())
10324       return !IsCompatibility;
10325     if (Op1->getValueID() > Op2->getValueID())
10326       return false;
10327     if (auto *I1 = dyn_cast<Instruction>(Op1))
10328       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10329         if (I1->getParent() != I2->getParent())
10330           return false;
10331         InstructionsState S = getSameOpcode({I1, I2});
10332         if (S.getOpcode())
10333           continue;
10334         return false;
10335       }
10336   }
10337   return IsCompatibility;
10338 }
10339 
10340 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10341     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10342     bool AtTerminator) {
10343   bool OpsChanged = false;
10344   SmallVector<Instruction *, 4> PostponedCmps;
10345   for (auto *I : reverse(Instructions)) {
10346     if (R.isDeleted(I))
10347       continue;
10348     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10349       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10350     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10351       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10352     else if (isa<CmpInst>(I))
10353       PostponedCmps.push_back(I);
10354   }
10355   if (AtTerminator) {
10356     // Try to find reductions first.
10357     for (Instruction *I : PostponedCmps) {
10358       if (R.isDeleted(I))
10359         continue;
10360       for (Value *Op : I->operands())
10361         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10362     }
10363     // Try to vectorize operands as vector bundles.
10364     for (Instruction *I : PostponedCmps) {
10365       if (R.isDeleted(I))
10366         continue;
10367       OpsChanged |= tryToVectorize(I, R);
10368     }
10369     // Try to vectorize list of compares.
10370     // Sort by type, compare predicate, etc.
10371     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10372       return compareCmp<false>(V, V2,
10373                                [&R](Instruction *I) { return R.isDeleted(I); });
10374     };
10375 
10376     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10377       if (V1 == V2)
10378         return true;
10379       return compareCmp<true>(V1, V2,
10380                               [&R](Instruction *I) { return R.isDeleted(I); });
10381     };
10382     auto Limit = [&R](Value *V) {
10383       unsigned EltSize = R.getVectorElementSize(V);
10384       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10385     };
10386 
10387     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10388     OpsChanged |= tryToVectorizeSequence<Value>(
10389         Vals, Limit, CompareSorter, AreCompatibleCompares,
10390         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10391           // Exclude possible reductions from other blocks.
10392           bool ArePossiblyReducedInOtherBlock =
10393               any_of(Candidates, [](Value *V) {
10394                 return any_of(V->users(), [V](User *U) {
10395                   return isa<SelectInst>(U) &&
10396                          cast<SelectInst>(U)->getParent() !=
10397                              cast<Instruction>(V)->getParent();
10398                 });
10399               });
10400           if (ArePossiblyReducedInOtherBlock)
10401             return false;
10402           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10403         },
10404         /*LimitForRegisterSize=*/true);
10405     Instructions.clear();
10406   } else {
10407     // Insert in reverse order since the PostponedCmps vector was filled in
10408     // reverse order.
10409     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10410   }
10411   return OpsChanged;
10412 }
10413 
10414 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10415   bool Changed = false;
10416   SmallVector<Value *, 4> Incoming;
10417   SmallPtrSet<Value *, 16> VisitedInstrs;
10418   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10419   // node. Allows better to identify the chains that can be vectorized in the
10420   // better way.
10421   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10422   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10423     assert(isValidElementType(V1->getType()) &&
10424            isValidElementType(V2->getType()) &&
10425            "Expected vectorizable types only.");
10426     // It is fine to compare type IDs here, since we expect only vectorizable
10427     // types, like ints, floats and pointers, we don't care about other type.
10428     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10429       return true;
10430     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10431       return false;
10432     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10433     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10434     if (Opcodes1.size() < Opcodes2.size())
10435       return true;
10436     if (Opcodes1.size() > Opcodes2.size())
10437       return false;
10438     Optional<bool> ConstOrder;
10439     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10440       // Undefs are compatible with any other value.
10441       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10442         if (!ConstOrder)
10443           ConstOrder =
10444               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10445         continue;
10446       }
10447       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10448         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10449           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10450           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10451           if (!NodeI1)
10452             return NodeI2 != nullptr;
10453           if (!NodeI2)
10454             return false;
10455           assert((NodeI1 == NodeI2) ==
10456                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10457                  "Different nodes should have different DFS numbers");
10458           if (NodeI1 != NodeI2)
10459             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10460           InstructionsState S = getSameOpcode({I1, I2});
10461           if (S.getOpcode())
10462             continue;
10463           return I1->getOpcode() < I2->getOpcode();
10464         }
10465       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10466         if (!ConstOrder)
10467           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10468         continue;
10469       }
10470       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10471         return true;
10472       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10473         return false;
10474     }
10475     return ConstOrder && *ConstOrder;
10476   };
10477   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10478     if (V1 == V2)
10479       return true;
10480     if (V1->getType() != V2->getType())
10481       return false;
10482     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10483     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10484     if (Opcodes1.size() != Opcodes2.size())
10485       return false;
10486     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10487       // Undefs are compatible with any other value.
10488       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10489         continue;
10490       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10491         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10492           if (I1->getParent() != I2->getParent())
10493             return false;
10494           InstructionsState S = getSameOpcode({I1, I2});
10495           if (S.getOpcode())
10496             continue;
10497           return false;
10498         }
10499       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10500         continue;
10501       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10502         return false;
10503     }
10504     return true;
10505   };
10506   auto Limit = [&R](Value *V) {
10507     unsigned EltSize = R.getVectorElementSize(V);
10508     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10509   };
10510 
10511   bool HaveVectorizedPhiNodes = false;
10512   do {
10513     // Collect the incoming values from the PHIs.
10514     Incoming.clear();
10515     for (Instruction &I : *BB) {
10516       PHINode *P = dyn_cast<PHINode>(&I);
10517       if (!P)
10518         break;
10519 
10520       // No need to analyze deleted, vectorized and non-vectorizable
10521       // instructions.
10522       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10523           isValidElementType(P->getType()))
10524         Incoming.push_back(P);
10525     }
10526 
10527     // Find the corresponding non-phi nodes for better matching when trying to
10528     // build the tree.
10529     for (Value *V : Incoming) {
10530       SmallVectorImpl<Value *> &Opcodes =
10531           PHIToOpcodes.try_emplace(V).first->getSecond();
10532       if (!Opcodes.empty())
10533         continue;
10534       SmallVector<Value *, 4> Nodes(1, V);
10535       SmallPtrSet<Value *, 4> Visited;
10536       while (!Nodes.empty()) {
10537         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10538         if (!Visited.insert(PHI).second)
10539           continue;
10540         for (Value *V : PHI->incoming_values()) {
10541           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10542             Nodes.push_back(PHI1);
10543             continue;
10544           }
10545           Opcodes.emplace_back(V);
10546         }
10547       }
10548     }
10549 
10550     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10551         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10552         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10553           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10554         },
10555         /*LimitForRegisterSize=*/true);
10556     Changed |= HaveVectorizedPhiNodes;
10557     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10558   } while (HaveVectorizedPhiNodes);
10559 
10560   VisitedInstrs.clear();
10561 
10562   SmallVector<Instruction *, 8> PostProcessInstructions;
10563   SmallDenseSet<Instruction *, 4> KeyNodes;
10564   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10565     // Skip instructions with scalable type. The num of elements is unknown at
10566     // compile-time for scalable type.
10567     if (isa<ScalableVectorType>(it->getType()))
10568       continue;
10569 
10570     // Skip instructions marked for the deletion.
10571     if (R.isDeleted(&*it))
10572       continue;
10573     // We may go through BB multiple times so skip the one we have checked.
10574     if (!VisitedInstrs.insert(&*it).second) {
10575       if (it->use_empty() && KeyNodes.contains(&*it) &&
10576           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10577                                       it->isTerminator())) {
10578         // We would like to start over since some instructions are deleted
10579         // and the iterator may become invalid value.
10580         Changed = true;
10581         it = BB->begin();
10582         e = BB->end();
10583       }
10584       continue;
10585     }
10586 
10587     if (isa<DbgInfoIntrinsic>(it))
10588       continue;
10589 
10590     // Try to vectorize reductions that use PHINodes.
10591     if (PHINode *P = dyn_cast<PHINode>(it)) {
10592       // Check that the PHI is a reduction PHI.
10593       if (P->getNumIncomingValues() == 2) {
10594         // Try to match and vectorize a horizontal reduction.
10595         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10596                                      TTI)) {
10597           Changed = true;
10598           it = BB->begin();
10599           e = BB->end();
10600           continue;
10601         }
10602       }
10603       // Try to vectorize the incoming values of the PHI, to catch reductions
10604       // that feed into PHIs.
10605       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10606         // Skip if the incoming block is the current BB for now. Also, bypass
10607         // unreachable IR for efficiency and to avoid crashing.
10608         // TODO: Collect the skipped incoming values and try to vectorize them
10609         // after processing BB.
10610         if (BB == P->getIncomingBlock(I) ||
10611             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10612           continue;
10613 
10614         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10615                                             P->getIncomingBlock(I), R, TTI);
10616       }
10617       continue;
10618     }
10619 
10620     // Ran into an instruction without users, like terminator, or function call
10621     // with ignored return value, store. Ignore unused instructions (basing on
10622     // instruction type, except for CallInst and InvokeInst).
10623     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10624                             isa<InvokeInst>(it))) {
10625       KeyNodes.insert(&*it);
10626       bool OpsChanged = false;
10627       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10628         for (auto *V : it->operand_values()) {
10629           // Try to match and vectorize a horizontal reduction.
10630           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10631         }
10632       }
10633       // Start vectorization of post-process list of instructions from the
10634       // top-tree instructions to try to vectorize as many instructions as
10635       // possible.
10636       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10637                                                 it->isTerminator());
10638       if (OpsChanged) {
10639         // We would like to start over since some instructions are deleted
10640         // and the iterator may become invalid value.
10641         Changed = true;
10642         it = BB->begin();
10643         e = BB->end();
10644         continue;
10645       }
10646     }
10647 
10648     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10649         isa<InsertValueInst>(it))
10650       PostProcessInstructions.push_back(&*it);
10651   }
10652 
10653   return Changed;
10654 }
10655 
10656 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10657   auto Changed = false;
10658   for (auto &Entry : GEPs) {
10659     // If the getelementptr list has fewer than two elements, there's nothing
10660     // to do.
10661     if (Entry.second.size() < 2)
10662       continue;
10663 
10664     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10665                       << Entry.second.size() << ".\n");
10666 
10667     // Process the GEP list in chunks suitable for the target's supported
10668     // vector size. If a vector register can't hold 1 element, we are done. We
10669     // are trying to vectorize the index computations, so the maximum number of
10670     // elements is based on the size of the index expression, rather than the
10671     // size of the GEP itself (the target's pointer size).
10672     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10673     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10674     if (MaxVecRegSize < EltSize)
10675       continue;
10676 
10677     unsigned MaxElts = MaxVecRegSize / EltSize;
10678     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10679       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10680       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10681 
10682       // Initialize a set a candidate getelementptrs. Note that we use a
10683       // SetVector here to preserve program order. If the index computations
10684       // are vectorizable and begin with loads, we want to minimize the chance
10685       // of having to reorder them later.
10686       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10687 
10688       // Some of the candidates may have already been vectorized after we
10689       // initially collected them. If so, they are marked as deleted, so remove
10690       // them from the set of candidates.
10691       Candidates.remove_if(
10692           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10693 
10694       // Remove from the set of candidates all pairs of getelementptrs with
10695       // constant differences. Such getelementptrs are likely not good
10696       // candidates for vectorization in a bottom-up phase since one can be
10697       // computed from the other. We also ensure all candidate getelementptr
10698       // indices are unique.
10699       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10700         auto *GEPI = GEPList[I];
10701         if (!Candidates.count(GEPI))
10702           continue;
10703         auto *SCEVI = SE->getSCEV(GEPList[I]);
10704         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10705           auto *GEPJ = GEPList[J];
10706           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10707           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10708             Candidates.remove(GEPI);
10709             Candidates.remove(GEPJ);
10710           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10711             Candidates.remove(GEPJ);
10712           }
10713         }
10714       }
10715 
10716       // We break out of the above computation as soon as we know there are
10717       // fewer than two candidates remaining.
10718       if (Candidates.size() < 2)
10719         continue;
10720 
10721       // Add the single, non-constant index of each candidate to the bundle. We
10722       // ensured the indices met these constraints when we originally collected
10723       // the getelementptrs.
10724       SmallVector<Value *, 16> Bundle(Candidates.size());
10725       auto BundleIndex = 0u;
10726       for (auto *V : Candidates) {
10727         auto *GEP = cast<GetElementPtrInst>(V);
10728         auto *GEPIdx = GEP->idx_begin()->get();
10729         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10730         Bundle[BundleIndex++] = GEPIdx;
10731       }
10732 
10733       // Try and vectorize the indices. We are currently only interested in
10734       // gather-like cases of the form:
10735       //
10736       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10737       //
10738       // where the loads of "a", the loads of "b", and the subtractions can be
10739       // performed in parallel. It's likely that detecting this pattern in a
10740       // bottom-up phase will be simpler and less costly than building a
10741       // full-blown top-down phase beginning at the consecutive loads.
10742       Changed |= tryToVectorizeList(Bundle, R);
10743     }
10744   }
10745   return Changed;
10746 }
10747 
10748 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10749   bool Changed = false;
10750   // Sort by type, base pointers and values operand. Value operands must be
10751   // compatible (have the same opcode, same parent), otherwise it is
10752   // definitely not profitable to try to vectorize them.
10753   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10754     if (V->getPointerOperandType()->getTypeID() <
10755         V2->getPointerOperandType()->getTypeID())
10756       return true;
10757     if (V->getPointerOperandType()->getTypeID() >
10758         V2->getPointerOperandType()->getTypeID())
10759       return false;
10760     // UndefValues are compatible with all other values.
10761     if (isa<UndefValue>(V->getValueOperand()) ||
10762         isa<UndefValue>(V2->getValueOperand()))
10763       return false;
10764     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10765       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10766         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10767             DT->getNode(I1->getParent());
10768         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10769             DT->getNode(I2->getParent());
10770         assert(NodeI1 && "Should only process reachable instructions");
10771         assert(NodeI1 && "Should only process reachable instructions");
10772         assert((NodeI1 == NodeI2) ==
10773                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10774                "Different nodes should have different DFS numbers");
10775         if (NodeI1 != NodeI2)
10776           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10777         InstructionsState S = getSameOpcode({I1, I2});
10778         if (S.getOpcode())
10779           return false;
10780         return I1->getOpcode() < I2->getOpcode();
10781       }
10782     if (isa<Constant>(V->getValueOperand()) &&
10783         isa<Constant>(V2->getValueOperand()))
10784       return false;
10785     return V->getValueOperand()->getValueID() <
10786            V2->getValueOperand()->getValueID();
10787   };
10788 
10789   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10790     if (V1 == V2)
10791       return true;
10792     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10793       return false;
10794     // Undefs are compatible with any other value.
10795     if (isa<UndefValue>(V1->getValueOperand()) ||
10796         isa<UndefValue>(V2->getValueOperand()))
10797       return true;
10798     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10799       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10800         if (I1->getParent() != I2->getParent())
10801           return false;
10802         InstructionsState S = getSameOpcode({I1, I2});
10803         return S.getOpcode() > 0;
10804       }
10805     if (isa<Constant>(V1->getValueOperand()) &&
10806         isa<Constant>(V2->getValueOperand()))
10807       return true;
10808     return V1->getValueOperand()->getValueID() ==
10809            V2->getValueOperand()->getValueID();
10810   };
10811   auto Limit = [&R, this](StoreInst *SI) {
10812     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10813     return R.getMinVF(EltSize);
10814   };
10815 
10816   // Attempt to sort and vectorize each of the store-groups.
10817   for (auto &Pair : Stores) {
10818     if (Pair.second.size() < 2)
10819       continue;
10820 
10821     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10822                       << Pair.second.size() << ".\n");
10823 
10824     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10825       continue;
10826 
10827     Changed |= tryToVectorizeSequence<StoreInst>(
10828         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10829         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10830           return vectorizeStores(Candidates, R);
10831         },
10832         /*LimitForRegisterSize=*/false);
10833   }
10834   return Changed;
10835 }
10836 
10837 char SLPVectorizer::ID = 0;
10838 
10839 static const char lv_name[] = "SLP Vectorizer";
10840 
10841 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10842 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10843 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10844 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10845 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10846 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10847 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10848 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10849 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10850 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10851 
10852 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10853