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