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