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();
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() 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() 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() {
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           continue;
2955         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
2956           if (OpTE->State == TreeEntry::NeedToGather)
2957             return GathersToOrders.find(OpTE)->second;
2958           return OpTE->ReorderIndices;
2959         }();
2960         // Stores actually store the mask, not the order, need to invert.
2961         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
2962             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
2963           SmallVector<int> Mask;
2964           inversePermutation(Order, Mask);
2965           unsigned E = Order.size();
2966           OrdersType CurrentOrder(E, E);
2967           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
2968             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
2969           });
2970           fixupOrderingIndices(CurrentOrder);
2971           ++OrdersUses.try_emplace(CurrentOrder).first->getSecond();
2972         } else {
2973           ++OrdersUses.try_emplace(Order).first->getSecond();
2974         }
2975         if (VisitedOps.insert(OpTE).second)
2976           OrdersUses.try_emplace({}, 0).first->getSecond() +=
2977               OpTE->UserTreeIndices.size();
2978         --OrdersUses[{}];
2979       }
2980       // If no orders - skip current nodes and jump to the next one, if any.
2981       if (OrdersUses.empty()) {
2982         for_each(Data.second,
2983                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
2984                    OrderedEntries.remove(Op.second);
2985                  });
2986         continue;
2987       }
2988       // Choose the best order.
2989       ArrayRef<unsigned> BestOrder = OrdersUses.begin()->first;
2990       unsigned Cnt = OrdersUses.begin()->second;
2991       for (const auto &Pair : llvm::drop_begin(OrdersUses)) {
2992         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
2993           BestOrder = Pair.first;
2994           Cnt = Pair.second;
2995         }
2996       }
2997       // Set order of the user node (reordering of operands and user nodes).
2998       if (BestOrder.empty()) {
2999         for_each(Data.second,
3000                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3001                    OrderedEntries.remove(Op.second);
3002                  });
3003         continue;
3004       }
3005       // Erase operands from OrderedEntries list and adjust their orders.
3006       VisitedOps.clear();
3007       SmallVector<int> Mask;
3008       inversePermutation(BestOrder, Mask);
3009       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3010       unsigned E = BestOrder.size();
3011       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3012         return I < E ? static_cast<int>(I) : UndefMaskElem;
3013       });
3014       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3015         TreeEntry *TE = Op.second;
3016         OrderedEntries.remove(TE);
3017         if (!VisitedOps.insert(TE).second)
3018           continue;
3019         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3020           // Just reorder reuses indices.
3021           reorderReuses(TE->ReuseShuffleIndices, Mask);
3022           continue;
3023         }
3024         // Gathers are processed separately.
3025         if (TE->State != TreeEntry::Vectorize)
3026           continue;
3027         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3028                 TE->ReorderIndices.empty()) &&
3029                "Non-matching sizes of user/operand entries.");
3030         reorderOrder(TE->ReorderIndices, Mask);
3031       }
3032       // For gathers just need to reorder its scalars.
3033       for (TreeEntry *Gather : GatherOps) {
3034         if (!Gather->ReuseShuffleIndices.empty())
3035           continue;
3036         assert(Gather->ReorderIndices.empty() &&
3037                "Unexpected reordering of gathers.");
3038         reorderScalars(Gather->Scalars, Mask);
3039         OrderedEntries.remove(Gather);
3040       }
3041       // Reorder operands of the user node and set the ordering for the user
3042       // node itself.
3043       if (Data.first->State != TreeEntry::Vectorize ||
3044           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3045               Data.first->getMainOp()) ||
3046           Data.first->isAltShuffle())
3047         Data.first->reorderOperands(Mask);
3048       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3049           Data.first->isAltShuffle()) {
3050         reorderScalars(Data.first->Scalars, Mask);
3051         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3052         if (Data.first->ReuseShuffleIndices.empty() &&
3053             !Data.first->ReorderIndices.empty() &&
3054             !Data.first->isAltShuffle()) {
3055           // Insert user node to the list to try to sink reordering deeper in
3056           // the graph.
3057           OrderedEntries.insert(Data.first);
3058         }
3059       } else {
3060         reorderOrder(Data.first->ReorderIndices, Mask);
3061       }
3062     }
3063   }
3064 }
3065 
3066 void BoUpSLP::buildExternalUses(
3067     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3068   // Collect the values that we need to extract from the tree.
3069   for (auto &TEPtr : VectorizableTree) {
3070     TreeEntry *Entry = TEPtr.get();
3071 
3072     // No need to handle users of gathered values.
3073     if (Entry->State == TreeEntry::NeedToGather)
3074       continue;
3075 
3076     // For each lane:
3077     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3078       Value *Scalar = Entry->Scalars[Lane];
3079       int FoundLane = Entry->findLaneForValue(Scalar);
3080 
3081       // Check if the scalar is externally used as an extra arg.
3082       auto ExtI = ExternallyUsedValues.find(Scalar);
3083       if (ExtI != ExternallyUsedValues.end()) {
3084         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3085                           << Lane << " from " << *Scalar << ".\n");
3086         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3087       }
3088       for (User *U : Scalar->users()) {
3089         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3090 
3091         Instruction *UserInst = dyn_cast<Instruction>(U);
3092         if (!UserInst)
3093           continue;
3094 
3095         if (isDeleted(UserInst))
3096           continue;
3097 
3098         // Skip in-tree scalars that become vectors
3099         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3100           Value *UseScalar = UseEntry->Scalars[0];
3101           // Some in-tree scalars will remain as scalar in vectorized
3102           // instructions. If that is the case, the one in Lane 0 will
3103           // be used.
3104           if (UseScalar != U ||
3105               UseEntry->State == TreeEntry::ScatterVectorize ||
3106               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3107             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3108                               << ".\n");
3109             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3110             continue;
3111           }
3112         }
3113 
3114         // Ignore users in the user ignore list.
3115         if (is_contained(UserIgnoreList, UserInst))
3116           continue;
3117 
3118         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3119                           << Lane << " from " << *Scalar << ".\n");
3120         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3121       }
3122     }
3123   }
3124 }
3125 
3126 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3127                         ArrayRef<Value *> UserIgnoreLst) {
3128   deleteTree();
3129   UserIgnoreList = UserIgnoreLst;
3130   if (!allSameType(Roots))
3131     return;
3132   buildTree_rec(Roots, 0, EdgeInfo());
3133 }
3134 
3135 namespace {
3136 /// Tracks the state we can represent the loads in the given sequence.
3137 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3138 } // anonymous namespace
3139 
3140 /// Checks if the given array of loads can be represented as a vectorized,
3141 /// scatter or just simple gather.
3142 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3143                                     const TargetTransformInfo &TTI,
3144                                     const DataLayout &DL, ScalarEvolution &SE,
3145                                     SmallVectorImpl<unsigned> &Order,
3146                                     SmallVectorImpl<Value *> &PointerOps) {
3147   // Check that a vectorized load would load the same memory as a scalar
3148   // load. For example, we don't want to vectorize loads that are smaller
3149   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3150   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3151   // from such a struct, we read/write packed bits disagreeing with the
3152   // unvectorized version.
3153   Type *ScalarTy = VL0->getType();
3154 
3155   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3156     return LoadsState::Gather;
3157 
3158   // Make sure all loads in the bundle are simple - we can't vectorize
3159   // atomic or volatile loads.
3160   PointerOps.clear();
3161   PointerOps.resize(VL.size());
3162   auto *POIter = PointerOps.begin();
3163   for (Value *V : VL) {
3164     auto *L = cast<LoadInst>(V);
3165     if (!L->isSimple())
3166       return LoadsState::Gather;
3167     *POIter = L->getPointerOperand();
3168     ++POIter;
3169   }
3170 
3171   Order.clear();
3172   // Check the order of pointer operands.
3173   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3174     Value *Ptr0;
3175     Value *PtrN;
3176     if (Order.empty()) {
3177       Ptr0 = PointerOps.front();
3178       PtrN = PointerOps.back();
3179     } else {
3180       Ptr0 = PointerOps[Order.front()];
3181       PtrN = PointerOps[Order.back()];
3182     }
3183     Optional<int> Diff =
3184         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3185     // Check that the sorted loads are consecutive.
3186     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3187       return LoadsState::Vectorize;
3188     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3189     for (Value *V : VL)
3190       CommonAlignment =
3191           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3192     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3193                                 CommonAlignment))
3194       return LoadsState::ScatterVectorize;
3195   }
3196 
3197   return LoadsState::Gather;
3198 }
3199 
3200 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3201                             const EdgeInfo &UserTreeIdx) {
3202   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3203 
3204   SmallVector<int> ReuseShuffleIndicies;
3205   SmallVector<Value *> UniqueValues;
3206   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3207                                 &UserTreeIdx,
3208                                 this](const InstructionsState &S) {
3209     // Check that every instruction appears once in this bundle.
3210     DenseMap<Value *, unsigned> UniquePositions;
3211     for (Value *V : VL) {
3212       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3213       ReuseShuffleIndicies.emplace_back(isa<UndefValue>(V) ? -1
3214                                                            : Res.first->second);
3215       if (Res.second)
3216         UniqueValues.emplace_back(V);
3217     }
3218     size_t NumUniqueScalarValues = UniqueValues.size();
3219     if (NumUniqueScalarValues == VL.size()) {
3220       ReuseShuffleIndicies.clear();
3221     } else {
3222       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3223       if (NumUniqueScalarValues <= 1 ||
3224           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3225         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3226         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3227         return false;
3228       }
3229       VL = UniqueValues;
3230     }
3231     return true;
3232   };
3233 
3234   InstructionsState S = getSameOpcode(VL);
3235   if (Depth == RecursionMaxDepth) {
3236     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3237     if (TryToFindDuplicates(S))
3238       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3239                    ReuseShuffleIndicies);
3240     return;
3241   }
3242 
3243   // Don't handle scalable vectors
3244   if (S.getOpcode() == Instruction::ExtractElement &&
3245       isa<ScalableVectorType>(
3246           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3247     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3248     if (TryToFindDuplicates(S))
3249       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3250                    ReuseShuffleIndicies);
3251     return;
3252   }
3253 
3254   // Don't handle vectors.
3255   if (S.OpValue->getType()->isVectorTy() &&
3256       !isa<InsertElementInst>(S.OpValue)) {
3257     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3258     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3259     return;
3260   }
3261 
3262   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3263     if (SI->getValueOperand()->getType()->isVectorTy()) {
3264       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3265       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3266       return;
3267     }
3268 
3269   // If all of the operands are identical or constant we have a simple solution.
3270   // If we deal with insert/extract instructions, they all must have constant
3271   // indices, otherwise we should gather them, not try to vectorize.
3272   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3273       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3274        !all_of(VL, isVectorLikeInstWithConstOps))) {
3275     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3276     if (TryToFindDuplicates(S))
3277       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3278                    ReuseShuffleIndicies);
3279     return;
3280   }
3281 
3282   // We now know that this is a vector of instructions of the same type from
3283   // the same block.
3284 
3285   // Don't vectorize ephemeral values.
3286   for (Value *V : VL) {
3287     if (EphValues.count(V)) {
3288       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3289                         << ") is ephemeral.\n");
3290       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3291       return;
3292     }
3293   }
3294 
3295   // Check if this is a duplicate of another entry.
3296   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3297     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3298     if (!E->isSame(VL)) {
3299       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3300       if (TryToFindDuplicates(S))
3301         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3302                      ReuseShuffleIndicies);
3303       return;
3304     }
3305     // Record the reuse of the tree node.  FIXME, currently this is only used to
3306     // properly draw the graph rather than for the actual vectorization.
3307     E->UserTreeIndices.push_back(UserTreeIdx);
3308     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3309                       << ".\n");
3310     return;
3311   }
3312 
3313   // Check that none of the instructions in the bundle are already in the tree.
3314   for (Value *V : VL) {
3315     auto *I = dyn_cast<Instruction>(V);
3316     if (!I)
3317       continue;
3318     if (getTreeEntry(I)) {
3319       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3320                         << ") is already in tree.\n");
3321       if (TryToFindDuplicates(S))
3322         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3323                      ReuseShuffleIndicies);
3324       return;
3325     }
3326   }
3327 
3328   // If any of the scalars is marked as a value that needs to stay scalar, then
3329   // we need to gather the scalars.
3330   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3331   for (Value *V : VL) {
3332     if (MustGather.count(V) || is_contained(UserIgnoreList, V)) {
3333       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3334       if (TryToFindDuplicates(S))
3335         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3336                      ReuseShuffleIndicies);
3337       return;
3338     }
3339   }
3340 
3341   // Check that all of the users of the scalars that we want to vectorize are
3342   // schedulable.
3343   auto *VL0 = cast<Instruction>(S.OpValue);
3344   BasicBlock *BB = VL0->getParent();
3345 
3346   if (!DT->isReachableFromEntry(BB)) {
3347     // Don't go into unreachable blocks. They may contain instructions with
3348     // dependency cycles which confuse the final scheduling.
3349     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3350     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3351     return;
3352   }
3353 
3354   // Check that every instruction appears once in this bundle.
3355   if (!TryToFindDuplicates(S))
3356     return;
3357 
3358   auto &BSRef = BlocksSchedules[BB];
3359   if (!BSRef)
3360     BSRef = std::make_unique<BlockScheduling>(BB);
3361 
3362   BlockScheduling &BS = *BSRef.get();
3363 
3364   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3365   if (!Bundle) {
3366     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3367     assert((!BS.getScheduleData(VL0) ||
3368             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3369            "tryScheduleBundle should cancelScheduling on failure");
3370     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3371                  ReuseShuffleIndicies);
3372     return;
3373   }
3374   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3375 
3376   unsigned ShuffleOrOp = S.isAltShuffle() ?
3377                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3378   switch (ShuffleOrOp) {
3379     case Instruction::PHI: {
3380       auto *PH = cast<PHINode>(VL0);
3381 
3382       // Check for terminator values (e.g. invoke).
3383       for (Value *V : VL)
3384         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3385           Instruction *Term = dyn_cast<Instruction>(
3386               cast<PHINode>(V)->getIncomingValueForBlock(
3387                   PH->getIncomingBlock(I)));
3388           if (Term && Term->isTerminator()) {
3389             LLVM_DEBUG(dbgs()
3390                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3391             BS.cancelScheduling(VL, VL0);
3392             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3393                          ReuseShuffleIndicies);
3394             return;
3395           }
3396         }
3397 
3398       TreeEntry *TE =
3399           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3400       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3401 
3402       // Keeps the reordered operands to avoid code duplication.
3403       SmallVector<ValueList, 2> OperandsVec;
3404       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3405         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3406           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3407           TE->setOperand(I, Operands);
3408           OperandsVec.push_back(Operands);
3409           continue;
3410         }
3411         ValueList Operands;
3412         // Prepare the operand vector.
3413         for (Value *V : VL)
3414           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3415               PH->getIncomingBlock(I)));
3416         TE->setOperand(I, Operands);
3417         OperandsVec.push_back(Operands);
3418       }
3419       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3420         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3421       return;
3422     }
3423     case Instruction::ExtractValue:
3424     case Instruction::ExtractElement: {
3425       OrdersType CurrentOrder;
3426       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3427       if (Reuse) {
3428         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3429         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3430                      ReuseShuffleIndicies);
3431         // This is a special case, as it does not gather, but at the same time
3432         // we are not extending buildTree_rec() towards the operands.
3433         ValueList Op0;
3434         Op0.assign(VL.size(), VL0->getOperand(0));
3435         VectorizableTree.back()->setOperand(0, Op0);
3436         return;
3437       }
3438       if (!CurrentOrder.empty()) {
3439         LLVM_DEBUG({
3440           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3441                     "with order";
3442           for (unsigned Idx : CurrentOrder)
3443             dbgs() << " " << Idx;
3444           dbgs() << "\n";
3445         });
3446         fixupOrderingIndices(CurrentOrder);
3447         // Insert new order with initial value 0, if it does not exist,
3448         // otherwise return the iterator to the existing one.
3449         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3450                      ReuseShuffleIndicies, CurrentOrder);
3451         // This is a special case, as it does not gather, but at the same time
3452         // we are not extending buildTree_rec() towards the operands.
3453         ValueList Op0;
3454         Op0.assign(VL.size(), VL0->getOperand(0));
3455         VectorizableTree.back()->setOperand(0, Op0);
3456         return;
3457       }
3458       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3459       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3460                    ReuseShuffleIndicies);
3461       BS.cancelScheduling(VL, VL0);
3462       return;
3463     }
3464     case Instruction::InsertElement: {
3465       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3466 
3467       // Check that we have a buildvector and not a shuffle of 2 or more
3468       // different vectors.
3469       ValueSet SourceVectors;
3470       int MinIdx = std::numeric_limits<int>::max();
3471       for (Value *V : VL) {
3472         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3473         Optional<int> Idx = *getInsertIndex(V, 0);
3474         if (!Idx || *Idx == UndefMaskElem)
3475           continue;
3476         MinIdx = std::min(MinIdx, *Idx);
3477       }
3478 
3479       if (count_if(VL, [&SourceVectors](Value *V) {
3480             return !SourceVectors.contains(V);
3481           }) >= 2) {
3482         // Found 2nd source vector - cancel.
3483         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3484                              "different source vectors.\n");
3485         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3486         BS.cancelScheduling(VL, VL0);
3487         return;
3488       }
3489 
3490       auto OrdCompare = [](const std::pair<int, int> &P1,
3491                            const std::pair<int, int> &P2) {
3492         return P1.first > P2.first;
3493       };
3494       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3495                     decltype(OrdCompare)>
3496           Indices(OrdCompare);
3497       for (int I = 0, E = VL.size(); I < E; ++I) {
3498         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3499         if (!Idx || *Idx == UndefMaskElem)
3500           continue;
3501         Indices.emplace(*Idx, I);
3502       }
3503       OrdersType CurrentOrder(VL.size(), VL.size());
3504       bool IsIdentity = true;
3505       for (int I = 0, E = VL.size(); I < E; ++I) {
3506         CurrentOrder[Indices.top().second] = I;
3507         IsIdentity &= Indices.top().second == I;
3508         Indices.pop();
3509       }
3510       if (IsIdentity)
3511         CurrentOrder.clear();
3512       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3513                                    None, CurrentOrder);
3514       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3515 
3516       constexpr int NumOps = 2;
3517       ValueList VectorOperands[NumOps];
3518       for (int I = 0; I < NumOps; ++I) {
3519         for (Value *V : VL)
3520           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3521 
3522         TE->setOperand(I, VectorOperands[I]);
3523       }
3524       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3525       return;
3526     }
3527     case Instruction::Load: {
3528       // Check that a vectorized load would load the same memory as a scalar
3529       // load. For example, we don't want to vectorize loads that are smaller
3530       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3531       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3532       // from such a struct, we read/write packed bits disagreeing with the
3533       // unvectorized version.
3534       SmallVector<Value *> PointerOps;
3535       OrdersType CurrentOrder;
3536       TreeEntry *TE = nullptr;
3537       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3538                                 PointerOps)) {
3539       case LoadsState::Vectorize:
3540         if (CurrentOrder.empty()) {
3541           // Original loads are consecutive and does not require reordering.
3542           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3543                             ReuseShuffleIndicies);
3544           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3545         } else {
3546           fixupOrderingIndices(CurrentOrder);
3547           // Need to reorder.
3548           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3549                             ReuseShuffleIndicies, CurrentOrder);
3550           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
3551         }
3552         TE->setOperandsInOrder();
3553         break;
3554       case LoadsState::ScatterVectorize:
3555         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3556         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
3557                           UserTreeIdx, ReuseShuffleIndicies);
3558         TE->setOperandsInOrder();
3559         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
3560         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
3561         break;
3562       case LoadsState::Gather:
3563         BS.cancelScheduling(VL, VL0);
3564         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3565                      ReuseShuffleIndicies);
3566 #ifndef NDEBUG
3567         Type *ScalarTy = VL0->getType();
3568         if (DL->getTypeSizeInBits(ScalarTy) !=
3569             DL->getTypeAllocSizeInBits(ScalarTy))
3570           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
3571         else if (any_of(VL, [](Value *V) {
3572                    return !cast<LoadInst>(V)->isSimple();
3573                  }))
3574           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
3575         else
3576           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
3577 #endif // NDEBUG
3578         break;
3579       }
3580       return;
3581     }
3582     case Instruction::ZExt:
3583     case Instruction::SExt:
3584     case Instruction::FPToUI:
3585     case Instruction::FPToSI:
3586     case Instruction::FPExt:
3587     case Instruction::PtrToInt:
3588     case Instruction::IntToPtr:
3589     case Instruction::SIToFP:
3590     case Instruction::UIToFP:
3591     case Instruction::Trunc:
3592     case Instruction::FPTrunc:
3593     case Instruction::BitCast: {
3594       Type *SrcTy = VL0->getOperand(0)->getType();
3595       for (Value *V : VL) {
3596         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
3597         if (Ty != SrcTy || !isValidElementType(Ty)) {
3598           BS.cancelScheduling(VL, VL0);
3599           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3600                        ReuseShuffleIndicies);
3601           LLVM_DEBUG(dbgs()
3602                      << "SLP: Gathering casts with different src types.\n");
3603           return;
3604         }
3605       }
3606       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3607                                    ReuseShuffleIndicies);
3608       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
3609 
3610       TE->setOperandsInOrder();
3611       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3612         ValueList Operands;
3613         // Prepare the operand vector.
3614         for (Value *V : VL)
3615           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3616 
3617         buildTree_rec(Operands, Depth + 1, {TE, i});
3618       }
3619       return;
3620     }
3621     case Instruction::ICmp:
3622     case Instruction::FCmp: {
3623       // Check that all of the compares have the same predicate.
3624       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3625       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
3626       Type *ComparedTy = VL0->getOperand(0)->getType();
3627       for (Value *V : VL) {
3628         CmpInst *Cmp = cast<CmpInst>(V);
3629         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
3630             Cmp->getOperand(0)->getType() != ComparedTy) {
3631           BS.cancelScheduling(VL, VL0);
3632           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3633                        ReuseShuffleIndicies);
3634           LLVM_DEBUG(dbgs()
3635                      << "SLP: Gathering cmp with different predicate.\n");
3636           return;
3637         }
3638       }
3639 
3640       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3641                                    ReuseShuffleIndicies);
3642       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
3643 
3644       ValueList Left, Right;
3645       if (cast<CmpInst>(VL0)->isCommutative()) {
3646         // Commutative predicate - collect + sort operands of the instructions
3647         // so that each side is more likely to have the same opcode.
3648         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
3649         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3650       } else {
3651         // Collect operands - commute if it uses the swapped predicate.
3652         for (Value *V : VL) {
3653           auto *Cmp = cast<CmpInst>(V);
3654           Value *LHS = Cmp->getOperand(0);
3655           Value *RHS = Cmp->getOperand(1);
3656           if (Cmp->getPredicate() != P0)
3657             std::swap(LHS, RHS);
3658           Left.push_back(LHS);
3659           Right.push_back(RHS);
3660         }
3661       }
3662       TE->setOperand(0, Left);
3663       TE->setOperand(1, Right);
3664       buildTree_rec(Left, Depth + 1, {TE, 0});
3665       buildTree_rec(Right, Depth + 1, {TE, 1});
3666       return;
3667     }
3668     case Instruction::Select:
3669     case Instruction::FNeg:
3670     case Instruction::Add:
3671     case Instruction::FAdd:
3672     case Instruction::Sub:
3673     case Instruction::FSub:
3674     case Instruction::Mul:
3675     case Instruction::FMul:
3676     case Instruction::UDiv:
3677     case Instruction::SDiv:
3678     case Instruction::FDiv:
3679     case Instruction::URem:
3680     case Instruction::SRem:
3681     case Instruction::FRem:
3682     case Instruction::Shl:
3683     case Instruction::LShr:
3684     case Instruction::AShr:
3685     case Instruction::And:
3686     case Instruction::Or:
3687     case Instruction::Xor: {
3688       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3689                                    ReuseShuffleIndicies);
3690       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
3691 
3692       // Sort operands of the instructions so that each side is more likely to
3693       // have the same opcode.
3694       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
3695         ValueList Left, Right;
3696         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3697         TE->setOperand(0, Left);
3698         TE->setOperand(1, Right);
3699         buildTree_rec(Left, Depth + 1, {TE, 0});
3700         buildTree_rec(Right, Depth + 1, {TE, 1});
3701         return;
3702       }
3703 
3704       TE->setOperandsInOrder();
3705       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3706         ValueList Operands;
3707         // Prepare the operand vector.
3708         for (Value *V : VL)
3709           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3710 
3711         buildTree_rec(Operands, Depth + 1, {TE, i});
3712       }
3713       return;
3714     }
3715     case Instruction::GetElementPtr: {
3716       // We don't combine GEPs with complicated (nested) indexing.
3717       for (Value *V : VL) {
3718         if (cast<Instruction>(V)->getNumOperands() != 2) {
3719           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
3720           BS.cancelScheduling(VL, VL0);
3721           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3722                        ReuseShuffleIndicies);
3723           return;
3724         }
3725       }
3726 
3727       // We can't combine several GEPs into one vector if they operate on
3728       // different types.
3729       Type *Ty0 = VL0->getOperand(0)->getType();
3730       for (Value *V : VL) {
3731         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
3732         if (Ty0 != CurTy) {
3733           LLVM_DEBUG(dbgs()
3734                      << "SLP: not-vectorizable GEP (different types).\n");
3735           BS.cancelScheduling(VL, VL0);
3736           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3737                        ReuseShuffleIndicies);
3738           return;
3739         }
3740       }
3741 
3742       // We don't combine GEPs with non-constant indexes.
3743       Type *Ty1 = VL0->getOperand(1)->getType();
3744       for (Value *V : VL) {
3745         auto Op = cast<Instruction>(V)->getOperand(1);
3746         if (!isa<ConstantInt>(Op) ||
3747             (Op->getType() != Ty1 &&
3748              Op->getType()->getScalarSizeInBits() >
3749                  DL->getIndexSizeInBits(
3750                      V->getType()->getPointerAddressSpace()))) {
3751           LLVM_DEBUG(dbgs()
3752                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
3753           BS.cancelScheduling(VL, VL0);
3754           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3755                        ReuseShuffleIndicies);
3756           return;
3757         }
3758       }
3759 
3760       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3761                                    ReuseShuffleIndicies);
3762       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
3763       TE->setOperandsInOrder();
3764       for (unsigned i = 0, e = 2; i < e; ++i) {
3765         ValueList Operands;
3766         // Prepare the operand vector.
3767         for (Value *V : VL)
3768           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3769 
3770         buildTree_rec(Operands, Depth + 1, {TE, i});
3771       }
3772       return;
3773     }
3774     case Instruction::Store: {
3775       // Check if the stores are consecutive or if we need to swizzle them.
3776       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
3777       // Avoid types that are padded when being allocated as scalars, while
3778       // being packed together in a vector (such as i1).
3779       if (DL->getTypeSizeInBits(ScalarTy) !=
3780           DL->getTypeAllocSizeInBits(ScalarTy)) {
3781         BS.cancelScheduling(VL, VL0);
3782         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3783                      ReuseShuffleIndicies);
3784         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
3785         return;
3786       }
3787       // Make sure all stores in the bundle are simple - we can't vectorize
3788       // atomic or volatile stores.
3789       SmallVector<Value *, 4> PointerOps(VL.size());
3790       ValueList Operands(VL.size());
3791       auto POIter = PointerOps.begin();
3792       auto OIter = Operands.begin();
3793       for (Value *V : VL) {
3794         auto *SI = cast<StoreInst>(V);
3795         if (!SI->isSimple()) {
3796           BS.cancelScheduling(VL, VL0);
3797           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3798                        ReuseShuffleIndicies);
3799           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
3800           return;
3801         }
3802         *POIter = SI->getPointerOperand();
3803         *OIter = SI->getValueOperand();
3804         ++POIter;
3805         ++OIter;
3806       }
3807 
3808       OrdersType CurrentOrder;
3809       // Check the order of pointer operands.
3810       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
3811         Value *Ptr0;
3812         Value *PtrN;
3813         if (CurrentOrder.empty()) {
3814           Ptr0 = PointerOps.front();
3815           PtrN = PointerOps.back();
3816         } else {
3817           Ptr0 = PointerOps[CurrentOrder.front()];
3818           PtrN = PointerOps[CurrentOrder.back()];
3819         }
3820         Optional<int> Dist =
3821             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
3822         // Check that the sorted pointer operands are consecutive.
3823         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
3824           if (CurrentOrder.empty()) {
3825             // Original stores are consecutive and does not require reordering.
3826             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
3827                                          UserTreeIdx, ReuseShuffleIndicies);
3828             TE->setOperandsInOrder();
3829             buildTree_rec(Operands, Depth + 1, {TE, 0});
3830             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
3831           } else {
3832             fixupOrderingIndices(CurrentOrder);
3833             TreeEntry *TE =
3834                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3835                              ReuseShuffleIndicies, CurrentOrder);
3836             TE->setOperandsInOrder();
3837             buildTree_rec(Operands, Depth + 1, {TE, 0});
3838             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
3839           }
3840           return;
3841         }
3842       }
3843 
3844       BS.cancelScheduling(VL, VL0);
3845       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3846                    ReuseShuffleIndicies);
3847       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
3848       return;
3849     }
3850     case Instruction::Call: {
3851       // Check if the calls are all to the same vectorizable intrinsic or
3852       // library function.
3853       CallInst *CI = cast<CallInst>(VL0);
3854       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3855 
3856       VFShape Shape = VFShape::get(
3857           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
3858           false /*HasGlobalPred*/);
3859       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3860 
3861       if (!VecFunc && !isTriviallyVectorizable(ID)) {
3862         BS.cancelScheduling(VL, VL0);
3863         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3864                      ReuseShuffleIndicies);
3865         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
3866         return;
3867       }
3868       Function *F = CI->getCalledFunction();
3869       unsigned NumArgs = CI->arg_size();
3870       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
3871       for (unsigned j = 0; j != NumArgs; ++j)
3872         if (hasVectorInstrinsicScalarOpd(ID, j))
3873           ScalarArgs[j] = CI->getArgOperand(j);
3874       for (Value *V : VL) {
3875         CallInst *CI2 = dyn_cast<CallInst>(V);
3876         if (!CI2 || CI2->getCalledFunction() != F ||
3877             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
3878             (VecFunc &&
3879              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
3880             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
3881           BS.cancelScheduling(VL, VL0);
3882           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3883                        ReuseShuffleIndicies);
3884           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
3885                             << "\n");
3886           return;
3887         }
3888         // Some intrinsics have scalar arguments and should be same in order for
3889         // them to be vectorized.
3890         for (unsigned j = 0; j != NumArgs; ++j) {
3891           if (hasVectorInstrinsicScalarOpd(ID, j)) {
3892             Value *A1J = CI2->getArgOperand(j);
3893             if (ScalarArgs[j] != A1J) {
3894               BS.cancelScheduling(VL, VL0);
3895               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3896                            ReuseShuffleIndicies);
3897               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
3898                                 << " argument " << ScalarArgs[j] << "!=" << A1J
3899                                 << "\n");
3900               return;
3901             }
3902           }
3903         }
3904         // Verify that the bundle operands are identical between the two calls.
3905         if (CI->hasOperandBundles() &&
3906             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
3907                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
3908                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
3909           BS.cancelScheduling(VL, VL0);
3910           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3911                        ReuseShuffleIndicies);
3912           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
3913                             << *CI << "!=" << *V << '\n');
3914           return;
3915         }
3916       }
3917 
3918       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3919                                    ReuseShuffleIndicies);
3920       TE->setOperandsInOrder();
3921       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
3922         ValueList Operands;
3923         // Prepare the operand vector.
3924         for (Value *V : VL) {
3925           auto *CI2 = cast<CallInst>(V);
3926           Operands.push_back(CI2->getArgOperand(i));
3927         }
3928         buildTree_rec(Operands, Depth + 1, {TE, i});
3929       }
3930       return;
3931     }
3932     case Instruction::ShuffleVector: {
3933       // If this is not an alternate sequence of opcode like add-sub
3934       // then do not vectorize this instruction.
3935       if (!S.isAltShuffle()) {
3936         BS.cancelScheduling(VL, VL0);
3937         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3938                      ReuseShuffleIndicies);
3939         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
3940         return;
3941       }
3942       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3943                                    ReuseShuffleIndicies);
3944       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
3945 
3946       // Reorder operands if reordering would enable vectorization.
3947       if (isa<BinaryOperator>(VL0)) {
3948         ValueList Left, Right;
3949         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3950         TE->setOperand(0, Left);
3951         TE->setOperand(1, Right);
3952         buildTree_rec(Left, Depth + 1, {TE, 0});
3953         buildTree_rec(Right, Depth + 1, {TE, 1});
3954         return;
3955       }
3956 
3957       TE->setOperandsInOrder();
3958       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3959         ValueList Operands;
3960         // Prepare the operand vector.
3961         for (Value *V : VL)
3962           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3963 
3964         buildTree_rec(Operands, Depth + 1, {TE, i});
3965       }
3966       return;
3967     }
3968     default:
3969       BS.cancelScheduling(VL, VL0);
3970       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3971                    ReuseShuffleIndicies);
3972       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
3973       return;
3974   }
3975 }
3976 
3977 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
3978   unsigned N = 1;
3979   Type *EltTy = T;
3980 
3981   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
3982          isa<VectorType>(EltTy)) {
3983     if (auto *ST = dyn_cast<StructType>(EltTy)) {
3984       // Check that struct is homogeneous.
3985       for (const auto *Ty : ST->elements())
3986         if (Ty != *ST->element_begin())
3987           return 0;
3988       N *= ST->getNumElements();
3989       EltTy = *ST->element_begin();
3990     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
3991       N *= AT->getNumElements();
3992       EltTy = AT->getElementType();
3993     } else {
3994       auto *VT = cast<FixedVectorType>(EltTy);
3995       N *= VT->getNumElements();
3996       EltTy = VT->getElementType();
3997     }
3998   }
3999 
4000   if (!isValidElementType(EltTy))
4001     return 0;
4002   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4003   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4004     return 0;
4005   return N;
4006 }
4007 
4008 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4009                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4010   Instruction *E0 = cast<Instruction>(OpValue);
4011   assert(E0->getOpcode() == Instruction::ExtractElement ||
4012          E0->getOpcode() == Instruction::ExtractValue);
4013   assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
4014   // Check if all of the extracts come from the same vector and from the
4015   // correct offset.
4016   Value *Vec = E0->getOperand(0);
4017 
4018   CurrentOrder.clear();
4019 
4020   // We have to extract from a vector/aggregate with the same number of elements.
4021   unsigned NElts;
4022   if (E0->getOpcode() == Instruction::ExtractValue) {
4023     const DataLayout &DL = E0->getModule()->getDataLayout();
4024     NElts = canMapToVector(Vec->getType(), DL);
4025     if (!NElts)
4026       return false;
4027     // Check if load can be rewritten as load of vector.
4028     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4029     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4030       return false;
4031   } else {
4032     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4033   }
4034 
4035   if (NElts != VL.size())
4036     return false;
4037 
4038   // Check that all of the indices extract from the correct offset.
4039   bool ShouldKeepOrder = true;
4040   unsigned E = VL.size();
4041   // Assign to all items the initial value E + 1 so we can check if the extract
4042   // instruction index was used already.
4043   // Also, later we can check that all the indices are used and we have a
4044   // consecutive access in the extract instructions, by checking that no
4045   // element of CurrentOrder still has value E + 1.
4046   CurrentOrder.assign(E, E + 1);
4047   unsigned I = 0;
4048   for (; I < E; ++I) {
4049     auto *Inst = cast<Instruction>(VL[I]);
4050     if (Inst->getOperand(0) != Vec)
4051       break;
4052     Optional<unsigned> Idx = getExtractIndex(Inst);
4053     if (!Idx)
4054       break;
4055     const unsigned ExtIdx = *Idx;
4056     if (ExtIdx != I) {
4057       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
4058         break;
4059       ShouldKeepOrder = false;
4060       CurrentOrder[ExtIdx] = I;
4061     } else {
4062       if (CurrentOrder[I] != E + 1)
4063         break;
4064       CurrentOrder[I] = I;
4065     }
4066   }
4067   if (I < E) {
4068     CurrentOrder.clear();
4069     return false;
4070   }
4071 
4072   return ShouldKeepOrder;
4073 }
4074 
4075 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4076                                     ArrayRef<Value *> VectorizedVals) const {
4077   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4078          llvm::all_of(I->users(), [this](User *U) {
4079            return ScalarToTreeEntry.count(U) > 0;
4080          });
4081 }
4082 
4083 static std::pair<InstructionCost, InstructionCost>
4084 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4085                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4086   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4087 
4088   // Calculate the cost of the scalar and vector calls.
4089   SmallVector<Type *, 4> VecTys;
4090   for (Use &Arg : CI->args())
4091     VecTys.push_back(
4092         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4093   FastMathFlags FMF;
4094   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4095     FMF = FPCI->getFastMathFlags();
4096   SmallVector<const Value *> Arguments(CI->args());
4097   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4098                                     dyn_cast<IntrinsicInst>(CI));
4099   auto IntrinsicCost =
4100     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4101 
4102   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4103                                      VecTy->getNumElements())),
4104                             false /*HasGlobalPred*/);
4105   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4106   auto LibCost = IntrinsicCost;
4107   if (!CI->isNoBuiltin() && VecFunc) {
4108     // Calculate the cost of the vector library call.
4109     // If the corresponding vector call is cheaper, return its cost.
4110     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4111                                     TTI::TCK_RecipThroughput);
4112   }
4113   return {IntrinsicCost, LibCost};
4114 }
4115 
4116 /// Compute the cost of creating a vector of type \p VecTy containing the
4117 /// extracted values from \p VL.
4118 static InstructionCost
4119 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4120                    TargetTransformInfo::ShuffleKind ShuffleKind,
4121                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4122   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4123 
4124   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4125       VecTy->getNumElements() < NumOfParts)
4126     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4127 
4128   bool AllConsecutive = true;
4129   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4130   unsigned Idx = -1;
4131   InstructionCost Cost = 0;
4132 
4133   // Process extracts in blocks of EltsPerVector to check if the source vector
4134   // operand can be re-used directly. If not, add the cost of creating a shuffle
4135   // to extract the values into a vector register.
4136   for (auto *V : VL) {
4137     ++Idx;
4138 
4139     // Reached the start of a new vector registers.
4140     if (Idx % EltsPerVector == 0) {
4141       AllConsecutive = true;
4142       continue;
4143     }
4144 
4145     // Check all extracts for a vector register on the target directly
4146     // extract values in order.
4147     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4148     unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4149     AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4150                       CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4151 
4152     if (AllConsecutive)
4153       continue;
4154 
4155     // Skip all indices, except for the last index per vector block.
4156     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4157       continue;
4158 
4159     // If we have a series of extracts which are not consecutive and hence
4160     // cannot re-use the source vector register directly, compute the shuffle
4161     // cost to extract the a vector with EltsPerVector elements.
4162     Cost += TTI.getShuffleCost(
4163         TargetTransformInfo::SK_PermuteSingleSrc,
4164         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4165   }
4166   return Cost;
4167 }
4168 
4169 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4170 /// operations operands.
4171 static void
4172 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4173                      ArrayRef<int> ReusesIndices,
4174                      const function_ref<bool(Instruction *)> IsAltOp,
4175                      SmallVectorImpl<int> &Mask,
4176                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4177                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4178   unsigned Sz = VL.size();
4179   Mask.assign(Sz, UndefMaskElem);
4180   SmallVector<int> OrderMask;
4181   if (!ReorderIndices.empty())
4182     inversePermutation(ReorderIndices, OrderMask);
4183   for (unsigned I = 0; I < Sz; ++I) {
4184     unsigned Idx = I;
4185     if (!ReorderIndices.empty())
4186       Idx = OrderMask[I];
4187     auto *OpInst = cast<Instruction>(VL[Idx]);
4188     if (IsAltOp(OpInst)) {
4189       Mask[I] = Sz + Idx;
4190       if (AltScalars)
4191         AltScalars->push_back(OpInst);
4192     } else {
4193       Mask[I] = Idx;
4194       if (OpScalars)
4195         OpScalars->push_back(OpInst);
4196     }
4197   }
4198   if (!ReusesIndices.empty()) {
4199     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4200     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4201       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4202     });
4203     Mask.swap(NewMask);
4204   }
4205 }
4206 
4207 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4208                                       ArrayRef<Value *> VectorizedVals) {
4209   ArrayRef<Value*> VL = E->Scalars;
4210 
4211   Type *ScalarTy = VL[0]->getType();
4212   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4213     ScalarTy = SI->getValueOperand()->getType();
4214   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4215     ScalarTy = CI->getOperand(0)->getType();
4216   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4217     ScalarTy = IE->getOperand(1)->getType();
4218   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4219   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4220 
4221   // If we have computed a smaller type for the expression, update VecTy so
4222   // that the costs will be accurate.
4223   if (MinBWs.count(VL[0]))
4224     VecTy = FixedVectorType::get(
4225         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4226   auto *FinalVecTy = VecTy;
4227 
4228   unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
4229   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4230   if (NeedToShuffleReuses)
4231     FinalVecTy =
4232         FixedVectorType::get(VecTy->getElementType(), ReuseShuffleNumbers);
4233   // FIXME: it tries to fix a problem with MSVC buildbots.
4234   TargetTransformInfo &TTIRef = *TTI;
4235   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4236                                VectorizedVals](InstructionCost &Cost,
4237                                                bool IsGather) {
4238     DenseMap<Value *, int> ExtractVectorsTys;
4239     for (auto *V : VL) {
4240       // If all users of instruction are going to be vectorized and this
4241       // instruction itself is not going to be vectorized, consider this
4242       // instruction as dead and remove its cost from the final cost of the
4243       // vectorized tree.
4244       if (!areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4245           (IsGather && ScalarToTreeEntry.count(V)))
4246         continue;
4247       auto *EE = cast<ExtractElementInst>(V);
4248       unsigned Idx = *getExtractIndex(EE);
4249       if (TTIRef.getNumberOfParts(VecTy) !=
4250           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4251         auto It =
4252             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4253         It->getSecond() = std::min<int>(It->second, Idx);
4254       }
4255       // Take credit for instruction that will become dead.
4256       if (EE->hasOneUse()) {
4257         Instruction *Ext = EE->user_back();
4258         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4259             all_of(Ext->users(),
4260                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4261           // Use getExtractWithExtendCost() to calculate the cost of
4262           // extractelement/ext pair.
4263           Cost -=
4264               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4265                                               EE->getVectorOperandType(), Idx);
4266           // Add back the cost of s|zext which is subtracted separately.
4267           Cost += TTIRef.getCastInstrCost(
4268               Ext->getOpcode(), Ext->getType(), EE->getType(),
4269               TTI::getCastContextHint(Ext), CostKind, Ext);
4270           continue;
4271         }
4272       }
4273       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4274                                         EE->getVectorOperandType(), Idx);
4275     }
4276     // Add a cost for subvector extracts/inserts if required.
4277     for (const auto &Data : ExtractVectorsTys) {
4278       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4279       unsigned NumElts = VecTy->getNumElements();
4280       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4281         unsigned Idx = (Data.second / NumElts) * NumElts;
4282         unsigned EENumElts = EEVTy->getNumElements();
4283         if (Idx + NumElts <= EENumElts) {
4284           Cost +=
4285               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4286                                     EEVTy, None, Idx, VecTy);
4287         } else {
4288           // Need to round up the subvector type vectorization factor to avoid a
4289           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4290           // <= EENumElts.
4291           auto *SubVT =
4292               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4293           Cost +=
4294               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4295                                     EEVTy, None, Idx, SubVT);
4296         }
4297       } else {
4298         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4299                                       VecTy, None, 0, EEVTy);
4300       }
4301     }
4302   };
4303   if (E->State == TreeEntry::NeedToGather) {
4304     if (allConstant(VL))
4305       return 0;
4306     if (isa<InsertElementInst>(VL[0]))
4307       return InstructionCost::getInvalid();
4308     SmallVector<int> Mask;
4309     SmallVector<const TreeEntry *> Entries;
4310     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4311         isGatherShuffledEntry(E, Mask, Entries);
4312     if (Shuffle.hasValue()) {
4313       InstructionCost GatherCost = 0;
4314       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4315         // Perfect match in the graph, will reuse the previously vectorized
4316         // node. Cost is 0.
4317         LLVM_DEBUG(
4318             dbgs()
4319             << "SLP: perfect diamond match for gather bundle that starts with "
4320             << *VL.front() << ".\n");
4321         if (NeedToShuffleReuses)
4322           GatherCost =
4323               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4324                                   FinalVecTy, E->ReuseShuffleIndices);
4325       } else {
4326         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4327                           << " entries for bundle that starts with "
4328                           << *VL.front() << ".\n");
4329         // Detected that instead of gather we can emit a shuffle of single/two
4330         // previously vectorized nodes. Add the cost of the permutation rather
4331         // than gather.
4332         ::addMask(Mask, E->ReuseShuffleIndices);
4333         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4334       }
4335       return GatherCost;
4336     }
4337     if (isSplat(VL)) {
4338       // Found the broadcasting of the single scalar, calculate the cost as the
4339       // broadcast.
4340       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4341     }
4342     if (E->getOpcode() == Instruction::ExtractElement && allSameType(VL) &&
4343         allSameBlock(VL) &&
4344         !isa<ScalableVectorType>(
4345             cast<ExtractElementInst>(E->getMainOp())->getVectorOperandType())) {
4346       // Check that gather of extractelements can be represented as just a
4347       // shuffle of a single/two vectors the scalars are extracted from.
4348       SmallVector<int> Mask;
4349       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4350           isFixedVectorShuffle(VL, Mask);
4351       if (ShuffleKind.hasValue()) {
4352         // Found the bunch of extractelement instructions that must be gathered
4353         // into a vector and can be represented as a permutation elements in a
4354         // single input vector or of 2 input vectors.
4355         InstructionCost Cost =
4356             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4357         AdjustExtractsCost(Cost, /*IsGather=*/true);
4358         if (NeedToShuffleReuses)
4359           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4360                                       FinalVecTy, E->ReuseShuffleIndices);
4361         return Cost;
4362       }
4363     }
4364     InstructionCost ReuseShuffleCost = 0;
4365     if (NeedToShuffleReuses)
4366       ReuseShuffleCost = TTI->getShuffleCost(
4367           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4368     // Improve gather cost for gather of loads, if we can group some of the
4369     // loads into vector loads.
4370     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4371         !E->isAltShuffle()) {
4372       BoUpSLP::ValueSet VectorizedLoads;
4373       unsigned StartIdx = 0;
4374       unsigned VF = VL.size() / 2;
4375       unsigned VectorizedCnt = 0;
4376       unsigned ScatterVectorizeCnt = 0;
4377       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4378       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4379         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4380              Cnt += VF) {
4381           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4382           if (!VectorizedLoads.count(Slice.front()) &&
4383               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4384             SmallVector<Value *> PointerOps;
4385             OrdersType CurrentOrder;
4386             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4387                                               *SE, CurrentOrder, PointerOps);
4388             switch (LS) {
4389             case LoadsState::Vectorize:
4390             case LoadsState::ScatterVectorize:
4391               // Mark the vectorized loads so that we don't vectorize them
4392               // again.
4393               if (LS == LoadsState::Vectorize)
4394                 ++VectorizedCnt;
4395               else
4396                 ++ScatterVectorizeCnt;
4397               VectorizedLoads.insert(Slice.begin(), Slice.end());
4398               // If we vectorized initial block, no need to try to vectorize it
4399               // again.
4400               if (Cnt == StartIdx)
4401                 StartIdx += VF;
4402               break;
4403             case LoadsState::Gather:
4404               break;
4405             }
4406           }
4407         }
4408         // Check if the whole array was vectorized already - exit.
4409         if (StartIdx >= VL.size())
4410           break;
4411         // Found vectorizable parts - exit.
4412         if (!VectorizedLoads.empty())
4413           break;
4414       }
4415       if (!VectorizedLoads.empty()) {
4416         InstructionCost GatherCost = 0;
4417         // Get the cost for gathered loads.
4418         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4419           if (VectorizedLoads.contains(VL[I]))
4420             continue;
4421           GatherCost += getGatherCost(VL.slice(I, VF));
4422         }
4423         // The cost for vectorized loads.
4424         InstructionCost ScalarsCost = 0;
4425         for (Value *V : VectorizedLoads) {
4426           auto *LI = cast<LoadInst>(V);
4427           ScalarsCost += TTI->getMemoryOpCost(
4428               Instruction::Load, LI->getType(), LI->getAlign(),
4429               LI->getPointerAddressSpace(), CostKind, LI);
4430         }
4431         auto *LI = cast<LoadInst>(E->getMainOp());
4432         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4433         Align Alignment = LI->getAlign();
4434         GatherCost +=
4435             VectorizedCnt *
4436             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4437                                  LI->getPointerAddressSpace(), CostKind, LI);
4438         GatherCost += ScatterVectorizeCnt *
4439                       TTI->getGatherScatterOpCost(
4440                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4441                           /*VariableMask=*/false, Alignment, CostKind, LI);
4442         // Add the cost for the subvectors shuffling.
4443         GatherCost += ((VL.size() - VF) / VF) *
4444                       TTI->getShuffleCost(TTI::SK_Select, VecTy);
4445         return ReuseShuffleCost + GatherCost - ScalarsCost;
4446       }
4447     }
4448     return ReuseShuffleCost + getGatherCost(VL);
4449   }
4450   InstructionCost CommonCost = 0;
4451   SmallVector<int> Mask;
4452   if (!E->ReorderIndices.empty()) {
4453     SmallVector<int> NewMask;
4454     if (E->getOpcode() == Instruction::Store) {
4455       // For stores the order is actually a mask.
4456       NewMask.resize(E->ReorderIndices.size());
4457       copy(E->ReorderIndices, NewMask.begin());
4458     } else {
4459       inversePermutation(E->ReorderIndices, NewMask);
4460     }
4461     ::addMask(Mask, NewMask);
4462   }
4463   if (NeedToShuffleReuses)
4464     ::addMask(Mask, E->ReuseShuffleIndices);
4465   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
4466     CommonCost =
4467         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
4468   assert((E->State == TreeEntry::Vectorize ||
4469           E->State == TreeEntry::ScatterVectorize) &&
4470          "Unhandled state");
4471   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
4472   Instruction *VL0 = E->getMainOp();
4473   unsigned ShuffleOrOp =
4474       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4475   switch (ShuffleOrOp) {
4476     case Instruction::PHI:
4477       return 0;
4478 
4479     case Instruction::ExtractValue:
4480     case Instruction::ExtractElement: {
4481       // The common cost of removal ExtractElement/ExtractValue instructions +
4482       // the cost of shuffles, if required to resuffle the original vector.
4483       if (NeedToShuffleReuses) {
4484         unsigned Idx = 0;
4485         for (unsigned I : E->ReuseShuffleIndices) {
4486           if (ShuffleOrOp == Instruction::ExtractElement) {
4487             auto *EE = cast<ExtractElementInst>(VL[I]);
4488             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4489                                                   EE->getVectorOperandType(),
4490                                                   *getExtractIndex(EE));
4491           } else {
4492             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4493                                                   VecTy, Idx);
4494             ++Idx;
4495           }
4496         }
4497         Idx = ReuseShuffleNumbers;
4498         for (Value *V : VL) {
4499           if (ShuffleOrOp == Instruction::ExtractElement) {
4500             auto *EE = cast<ExtractElementInst>(V);
4501             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4502                                                   EE->getVectorOperandType(),
4503                                                   *getExtractIndex(EE));
4504           } else {
4505             --Idx;
4506             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4507                                                   VecTy, Idx);
4508           }
4509         }
4510       }
4511       if (ShuffleOrOp == Instruction::ExtractValue) {
4512         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
4513           auto *EI = cast<Instruction>(VL[I]);
4514           // Take credit for instruction that will become dead.
4515           if (EI->hasOneUse()) {
4516             Instruction *Ext = EI->user_back();
4517             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4518                 all_of(Ext->users(),
4519                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
4520               // Use getExtractWithExtendCost() to calculate the cost of
4521               // extractelement/ext pair.
4522               CommonCost -= TTI->getExtractWithExtendCost(
4523                   Ext->getOpcode(), Ext->getType(), VecTy, I);
4524               // Add back the cost of s|zext which is subtracted separately.
4525               CommonCost += TTI->getCastInstrCost(
4526                   Ext->getOpcode(), Ext->getType(), EI->getType(),
4527                   TTI::getCastContextHint(Ext), CostKind, Ext);
4528               continue;
4529             }
4530           }
4531           CommonCost -=
4532               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
4533         }
4534       } else {
4535         AdjustExtractsCost(CommonCost, /*IsGather=*/false);
4536       }
4537       return CommonCost;
4538     }
4539     case Instruction::InsertElement: {
4540       assert(E->ReuseShuffleIndices.empty() &&
4541              "Unique insertelements only are expected.");
4542       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
4543 
4544       unsigned const NumElts = SrcVecTy->getNumElements();
4545       unsigned const NumScalars = VL.size();
4546       APInt DemandedElts = APInt::getZero(NumElts);
4547       // TODO: Add support for Instruction::InsertValue.
4548       SmallVector<int> Mask;
4549       if (!E->ReorderIndices.empty()) {
4550         inversePermutation(E->ReorderIndices, Mask);
4551         Mask.append(NumElts - NumScalars, UndefMaskElem);
4552       } else {
4553         Mask.assign(NumElts, UndefMaskElem);
4554         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
4555       }
4556       unsigned Offset = *getInsertIndex(VL0, 0);
4557       bool IsIdentity = true;
4558       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
4559       Mask.swap(PrevMask);
4560       for (unsigned I = 0; I < NumScalars; ++I) {
4561         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
4562         if (!InsertIdx || *InsertIdx == UndefMaskElem)
4563           continue;
4564         DemandedElts.setBit(*InsertIdx);
4565         IsIdentity &= *InsertIdx - Offset == I;
4566         Mask[*InsertIdx - Offset] = I;
4567       }
4568       assert(Offset < NumElts && "Failed to find vector index offset");
4569 
4570       InstructionCost Cost = 0;
4571       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
4572                                             /*Insert*/ true, /*Extract*/ false);
4573 
4574       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
4575         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
4576         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
4577         Cost += TTI->getShuffleCost(
4578             TargetTransformInfo::SK_PermuteSingleSrc,
4579             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
4580       } else if (!IsIdentity) {
4581         auto *FirstInsert =
4582             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
4583               return !is_contained(E->Scalars,
4584                                    cast<Instruction>(V)->getOperand(0));
4585             }));
4586         if (isa<UndefValue>(FirstInsert->getOperand(0))) {
4587           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
4588         } else {
4589           SmallVector<int> InsertMask(NumElts);
4590           std::iota(InsertMask.begin(), InsertMask.end(), 0);
4591           for (unsigned I = 0; I < NumElts; I++) {
4592             if (Mask[I] != UndefMaskElem)
4593               InsertMask[Offset + I] = NumElts + I;
4594           }
4595           Cost +=
4596               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
4597         }
4598       }
4599 
4600       return Cost;
4601     }
4602     case Instruction::ZExt:
4603     case Instruction::SExt:
4604     case Instruction::FPToUI:
4605     case Instruction::FPToSI:
4606     case Instruction::FPExt:
4607     case Instruction::PtrToInt:
4608     case Instruction::IntToPtr:
4609     case Instruction::SIToFP:
4610     case Instruction::UIToFP:
4611     case Instruction::Trunc:
4612     case Instruction::FPTrunc:
4613     case Instruction::BitCast: {
4614       Type *SrcTy = VL0->getOperand(0)->getType();
4615       InstructionCost ScalarEltCost =
4616           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
4617                                 TTI::getCastContextHint(VL0), CostKind, VL0);
4618       if (NeedToShuffleReuses) {
4619         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4620       }
4621 
4622       // Calculate the cost of this instruction.
4623       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
4624 
4625       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
4626       InstructionCost VecCost = 0;
4627       // Check if the values are candidates to demote.
4628       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
4629         VecCost = CommonCost + TTI->getCastInstrCost(
4630                                    E->getOpcode(), VecTy, SrcVecTy,
4631                                    TTI::getCastContextHint(VL0), CostKind, VL0);
4632       }
4633       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4634       return VecCost - ScalarCost;
4635     }
4636     case Instruction::FCmp:
4637     case Instruction::ICmp:
4638     case Instruction::Select: {
4639       // Calculate the cost of this instruction.
4640       InstructionCost ScalarEltCost =
4641           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
4642                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
4643       if (NeedToShuffleReuses) {
4644         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4645       }
4646       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
4647       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4648 
4649       // Check if all entries in VL are either compares or selects with compares
4650       // as condition that have the same predicates.
4651       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
4652       bool First = true;
4653       for (auto *V : VL) {
4654         CmpInst::Predicate CurrentPred;
4655         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
4656         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
4657              !match(V, MatchCmp)) ||
4658             (!First && VecPred != CurrentPred)) {
4659           VecPred = CmpInst::BAD_ICMP_PREDICATE;
4660           break;
4661         }
4662         First = false;
4663         VecPred = CurrentPred;
4664       }
4665 
4666       InstructionCost VecCost = TTI->getCmpSelInstrCost(
4667           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
4668       // Check if it is possible and profitable to use min/max for selects in
4669       // VL.
4670       //
4671       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
4672       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
4673         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
4674                                           {VecTy, VecTy});
4675         InstructionCost IntrinsicCost =
4676             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4677         // If the selects are the only uses of the compares, they will be dead
4678         // and we can adjust the cost by removing their cost.
4679         if (IntrinsicAndUse.second)
4680           IntrinsicCost -=
4681               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
4682                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
4683         VecCost = std::min(VecCost, IntrinsicCost);
4684       }
4685       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4686       return CommonCost + VecCost - ScalarCost;
4687     }
4688     case Instruction::FNeg:
4689     case Instruction::Add:
4690     case Instruction::FAdd:
4691     case Instruction::Sub:
4692     case Instruction::FSub:
4693     case Instruction::Mul:
4694     case Instruction::FMul:
4695     case Instruction::UDiv:
4696     case Instruction::SDiv:
4697     case Instruction::FDiv:
4698     case Instruction::URem:
4699     case Instruction::SRem:
4700     case Instruction::FRem:
4701     case Instruction::Shl:
4702     case Instruction::LShr:
4703     case Instruction::AShr:
4704     case Instruction::And:
4705     case Instruction::Or:
4706     case Instruction::Xor: {
4707       // Certain instructions can be cheaper to vectorize if they have a
4708       // constant second vector operand.
4709       TargetTransformInfo::OperandValueKind Op1VK =
4710           TargetTransformInfo::OK_AnyValue;
4711       TargetTransformInfo::OperandValueKind Op2VK =
4712           TargetTransformInfo::OK_UniformConstantValue;
4713       TargetTransformInfo::OperandValueProperties Op1VP =
4714           TargetTransformInfo::OP_None;
4715       TargetTransformInfo::OperandValueProperties Op2VP =
4716           TargetTransformInfo::OP_PowerOf2;
4717 
4718       // If all operands are exactly the same ConstantInt then set the
4719       // operand kind to OK_UniformConstantValue.
4720       // If instead not all operands are constants, then set the operand kind
4721       // to OK_AnyValue. If all operands are constants but not the same,
4722       // then set the operand kind to OK_NonUniformConstantValue.
4723       ConstantInt *CInt0 = nullptr;
4724       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
4725         const Instruction *I = cast<Instruction>(VL[i]);
4726         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
4727         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
4728         if (!CInt) {
4729           Op2VK = TargetTransformInfo::OK_AnyValue;
4730           Op2VP = TargetTransformInfo::OP_None;
4731           break;
4732         }
4733         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
4734             !CInt->getValue().isPowerOf2())
4735           Op2VP = TargetTransformInfo::OP_None;
4736         if (i == 0) {
4737           CInt0 = CInt;
4738           continue;
4739         }
4740         if (CInt0 != CInt)
4741           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4742       }
4743 
4744       SmallVector<const Value *, 4> Operands(VL0->operand_values());
4745       InstructionCost ScalarEltCost =
4746           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
4747                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4748       if (NeedToShuffleReuses) {
4749         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4750       }
4751       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4752       InstructionCost VecCost =
4753           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
4754                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4755       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4756       return CommonCost + VecCost - ScalarCost;
4757     }
4758     case Instruction::GetElementPtr: {
4759       TargetTransformInfo::OperandValueKind Op1VK =
4760           TargetTransformInfo::OK_AnyValue;
4761       TargetTransformInfo::OperandValueKind Op2VK =
4762           TargetTransformInfo::OK_UniformConstantValue;
4763 
4764       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
4765           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
4766       if (NeedToShuffleReuses) {
4767         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4768       }
4769       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4770       InstructionCost VecCost = TTI->getArithmeticInstrCost(
4771           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
4772       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4773       return CommonCost + VecCost - ScalarCost;
4774     }
4775     case Instruction::Load: {
4776       // Cost of wide load - cost of scalar loads.
4777       Align Alignment = cast<LoadInst>(VL0)->getAlign();
4778       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
4779           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
4780       if (NeedToShuffleReuses) {
4781         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4782       }
4783       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
4784       InstructionCost VecLdCost;
4785       if (E->State == TreeEntry::Vectorize) {
4786         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
4787                                          CostKind, VL0);
4788       } else {
4789         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
4790         Align CommonAlignment = Alignment;
4791         for (Value *V : VL)
4792           CommonAlignment =
4793               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4794         VecLdCost = TTI->getGatherScatterOpCost(
4795             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
4796             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
4797       }
4798       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
4799       return CommonCost + VecLdCost - ScalarLdCost;
4800     }
4801     case Instruction::Store: {
4802       // We know that we can merge the stores. Calculate the cost.
4803       bool IsReorder = !E->ReorderIndices.empty();
4804       auto *SI =
4805           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
4806       Align Alignment = SI->getAlign();
4807       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
4808           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
4809       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
4810       InstructionCost VecStCost = TTI->getMemoryOpCost(
4811           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
4812       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
4813       return CommonCost + VecStCost - ScalarStCost;
4814     }
4815     case Instruction::Call: {
4816       CallInst *CI = cast<CallInst>(VL0);
4817       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4818 
4819       // Calculate the cost of the scalar and vector calls.
4820       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
4821       InstructionCost ScalarEltCost =
4822           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4823       if (NeedToShuffleReuses) {
4824         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4825       }
4826       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
4827 
4828       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4829       InstructionCost VecCallCost =
4830           std::min(VecCallCosts.first, VecCallCosts.second);
4831 
4832       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
4833                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
4834                         << " for " << *CI << "\n");
4835 
4836       return CommonCost + VecCallCost - ScalarCallCost;
4837     }
4838     case Instruction::ShuffleVector: {
4839       assert(E->isAltShuffle() &&
4840              ((Instruction::isBinaryOp(E->getOpcode()) &&
4841                Instruction::isBinaryOp(E->getAltOpcode())) ||
4842               (Instruction::isCast(E->getOpcode()) &&
4843                Instruction::isCast(E->getAltOpcode()))) &&
4844              "Invalid Shuffle Vector Operand");
4845       InstructionCost ScalarCost = 0;
4846       if (NeedToShuffleReuses) {
4847         for (unsigned Idx : E->ReuseShuffleIndices) {
4848           Instruction *I = cast<Instruction>(VL[Idx]);
4849           CommonCost -= TTI->getInstructionCost(I, CostKind);
4850         }
4851         for (Value *V : VL) {
4852           Instruction *I = cast<Instruction>(V);
4853           CommonCost += TTI->getInstructionCost(I, CostKind);
4854         }
4855       }
4856       for (Value *V : VL) {
4857         Instruction *I = cast<Instruction>(V);
4858         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
4859         ScalarCost += TTI->getInstructionCost(I, CostKind);
4860       }
4861       // VecCost is equal to sum of the cost of creating 2 vectors
4862       // and the cost of creating shuffle.
4863       InstructionCost VecCost = 0;
4864       if (Instruction::isBinaryOp(E->getOpcode())) {
4865         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
4866         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
4867                                                CostKind);
4868       } else {
4869         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
4870         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
4871         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
4872         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
4873         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
4874                                         TTI::CastContextHint::None, CostKind);
4875         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
4876                                          TTI::CastContextHint::None, CostKind);
4877       }
4878 
4879       SmallVector<int> Mask;
4880       buildSuffleEntryMask(
4881           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
4882           [E](Instruction *I) {
4883             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
4884             return I->getOpcode() == E->getAltOpcode();
4885           },
4886           Mask);
4887       CommonCost =
4888           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
4889       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4890       return CommonCost + VecCost - ScalarCost;
4891     }
4892     default:
4893       llvm_unreachable("Unknown instruction");
4894   }
4895 }
4896 
4897 bool BoUpSLP::isFullyVectorizableTinyTree() const {
4898   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
4899                     << VectorizableTree.size() << " is fully vectorizable .\n");
4900 
4901   // We only handle trees of heights 1 and 2.
4902   if (VectorizableTree.size() == 1 &&
4903       VectorizableTree[0]->State == TreeEntry::Vectorize)
4904     return true;
4905 
4906   if (VectorizableTree.size() != 2)
4907     return false;
4908 
4909   // Handle splat and all-constants stores. Also try to vectorize tiny trees
4910   // with the second gather nodes if they have less scalar operands rather than
4911   // the initial tree element (may be profitable to shuffle the second gather)
4912   // or they are extractelements, which form shuffle.
4913   SmallVector<int> Mask;
4914   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
4915       (allConstant(VectorizableTree[1]->Scalars) ||
4916        isSplat(VectorizableTree[1]->Scalars) ||
4917        (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
4918         VectorizableTree[1]->Scalars.size() <
4919             VectorizableTree[0]->Scalars.size()) ||
4920        (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
4921         VectorizableTree[1]->getOpcode() == Instruction::ExtractElement &&
4922         isFixedVectorShuffle(VectorizableTree[1]->Scalars, Mask))))
4923     return true;
4924 
4925   // Gathering cost would be too much for tiny trees.
4926   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
4927       VectorizableTree[1]->State == TreeEntry::NeedToGather)
4928     return false;
4929 
4930   return true;
4931 }
4932 
4933 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
4934                                        TargetTransformInfo *TTI,
4935                                        bool MustMatchOrInst) {
4936   // Look past the root to find a source value. Arbitrarily follow the
4937   // path through operand 0 of any 'or'. Also, peek through optional
4938   // shift-left-by-multiple-of-8-bits.
4939   Value *ZextLoad = Root;
4940   const APInt *ShAmtC;
4941   bool FoundOr = false;
4942   while (!isa<ConstantExpr>(ZextLoad) &&
4943          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
4944           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
4945            ShAmtC->urem(8) == 0))) {
4946     auto *BinOp = cast<BinaryOperator>(ZextLoad);
4947     ZextLoad = BinOp->getOperand(0);
4948     if (BinOp->getOpcode() == Instruction::Or)
4949       FoundOr = true;
4950   }
4951   // Check if the input is an extended load of the required or/shift expression.
4952   Value *LoadPtr;
4953   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
4954       !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
4955     return false;
4956 
4957   // Require that the total load bit width is a legal integer type.
4958   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
4959   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
4960   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
4961   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
4962   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
4963     return false;
4964 
4965   // Everything matched - assume that we can fold the whole sequence using
4966   // load combining.
4967   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
4968              << *(cast<Instruction>(Root)) << "\n");
4969 
4970   return true;
4971 }
4972 
4973 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
4974   if (RdxKind != RecurKind::Or)
4975     return false;
4976 
4977   unsigned NumElts = VectorizableTree[0]->Scalars.size();
4978   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
4979   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
4980                                     /* MatchOr */ false);
4981 }
4982 
4983 bool BoUpSLP::isLoadCombineCandidate() const {
4984   // Peek through a final sequence of stores and check if all operations are
4985   // likely to be load-combined.
4986   unsigned NumElts = VectorizableTree[0]->Scalars.size();
4987   for (Value *Scalar : VectorizableTree[0]->Scalars) {
4988     Value *X;
4989     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
4990         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
4991       return false;
4992   }
4993   return true;
4994 }
4995 
4996 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
4997   // No need to vectorize inserts of gathered values.
4998   if (VectorizableTree.size() == 2 &&
4999       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5000       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5001     return true;
5002 
5003   // We can vectorize the tree if its size is greater than or equal to the
5004   // minimum size specified by the MinTreeSize command line option.
5005   if (VectorizableTree.size() >= MinTreeSize)
5006     return false;
5007 
5008   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5009   // can vectorize it if we can prove it fully vectorizable.
5010   if (isFullyVectorizableTinyTree())
5011     return false;
5012 
5013   assert(VectorizableTree.empty()
5014              ? ExternalUses.empty()
5015              : true && "We shouldn't have any external users");
5016 
5017   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5018   // vectorizable.
5019   return true;
5020 }
5021 
5022 InstructionCost BoUpSLP::getSpillCost() const {
5023   // Walk from the bottom of the tree to the top, tracking which values are
5024   // live. When we see a call instruction that is not part of our tree,
5025   // query TTI to see if there is a cost to keeping values live over it
5026   // (for example, if spills and fills are required).
5027   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5028   InstructionCost Cost = 0;
5029 
5030   SmallPtrSet<Instruction*, 4> LiveValues;
5031   Instruction *PrevInst = nullptr;
5032 
5033   // The entries in VectorizableTree are not necessarily ordered by their
5034   // position in basic blocks. Collect them and order them by dominance so later
5035   // instructions are guaranteed to be visited first. For instructions in
5036   // different basic blocks, we only scan to the beginning of the block, so
5037   // their order does not matter, as long as all instructions in a basic block
5038   // are grouped together. Using dominance ensures a deterministic order.
5039   SmallVector<Instruction *, 16> OrderedScalars;
5040   for (const auto &TEPtr : VectorizableTree) {
5041     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5042     if (!Inst)
5043       continue;
5044     OrderedScalars.push_back(Inst);
5045   }
5046   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5047     auto *NodeA = DT->getNode(A->getParent());
5048     auto *NodeB = DT->getNode(B->getParent());
5049     assert(NodeA && "Should only process reachable instructions");
5050     assert(NodeB && "Should only process reachable instructions");
5051     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5052            "Different nodes should have different DFS numbers");
5053     if (NodeA != NodeB)
5054       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5055     return B->comesBefore(A);
5056   });
5057 
5058   for (Instruction *Inst : OrderedScalars) {
5059     if (!PrevInst) {
5060       PrevInst = Inst;
5061       continue;
5062     }
5063 
5064     // Update LiveValues.
5065     LiveValues.erase(PrevInst);
5066     for (auto &J : PrevInst->operands()) {
5067       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5068         LiveValues.insert(cast<Instruction>(&*J));
5069     }
5070 
5071     LLVM_DEBUG({
5072       dbgs() << "SLP: #LV: " << LiveValues.size();
5073       for (auto *X : LiveValues)
5074         dbgs() << " " << X->getName();
5075       dbgs() << ", Looking at ";
5076       Inst->dump();
5077     });
5078 
5079     // Now find the sequence of instructions between PrevInst and Inst.
5080     unsigned NumCalls = 0;
5081     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5082                                  PrevInstIt =
5083                                      PrevInst->getIterator().getReverse();
5084     while (InstIt != PrevInstIt) {
5085       if (PrevInstIt == PrevInst->getParent()->rend()) {
5086         PrevInstIt = Inst->getParent()->rbegin();
5087         continue;
5088       }
5089 
5090       // Debug information does not impact spill cost.
5091       if ((isa<CallInst>(&*PrevInstIt) &&
5092            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5093           &*PrevInstIt != PrevInst)
5094         NumCalls++;
5095 
5096       ++PrevInstIt;
5097     }
5098 
5099     if (NumCalls) {
5100       SmallVector<Type*, 4> V;
5101       for (auto *II : LiveValues) {
5102         auto *ScalarTy = II->getType();
5103         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5104           ScalarTy = VectorTy->getElementType();
5105         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5106       }
5107       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5108     }
5109 
5110     PrevInst = Inst;
5111   }
5112 
5113   return Cost;
5114 }
5115 
5116 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5117   InstructionCost Cost = 0;
5118   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5119                     << VectorizableTree.size() << ".\n");
5120 
5121   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5122 
5123   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5124     TreeEntry &TE = *VectorizableTree[I].get();
5125 
5126     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5127     Cost += C;
5128     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5129                       << " for bundle that starts with " << *TE.Scalars[0]
5130                       << ".\n"
5131                       << "SLP: Current total cost = " << Cost << "\n");
5132   }
5133 
5134   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5135   InstructionCost ExtractCost = 0;
5136   SmallVector<unsigned> VF;
5137   SmallVector<SmallVector<int>> ShuffleMask;
5138   SmallVector<Value *> FirstUsers;
5139   SmallVector<APInt> DemandedElts;
5140   for (ExternalUser &EU : ExternalUses) {
5141     // We only add extract cost once for the same scalar.
5142     if (!ExtractCostCalculated.insert(EU.Scalar).second)
5143       continue;
5144 
5145     // Uses by ephemeral values are free (because the ephemeral value will be
5146     // removed prior to code generation, and so the extraction will be
5147     // removed as well).
5148     if (EphValues.count(EU.User))
5149       continue;
5150 
5151     // No extract cost for vector "scalar"
5152     if (isa<FixedVectorType>(EU.Scalar->getType()))
5153       continue;
5154 
5155     // Already counted the cost for external uses when tried to adjust the cost
5156     // for extractelements, no need to add it again.
5157     if (isa<ExtractElementInst>(EU.Scalar))
5158       continue;
5159 
5160     // If found user is an insertelement, do not calculate extract cost but try
5161     // to detect it as a final shuffled/identity match.
5162     if (EU.User && isa<InsertElementInst>(EU.User)) {
5163       if (auto *FTy = dyn_cast<FixedVectorType>(EU.User->getType())) {
5164         Optional<int> InsertIdx = getInsertIndex(EU.User, 0);
5165         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5166           continue;
5167         Value *VU = EU.User;
5168         auto *It = find_if(FirstUsers, [VU](Value *V) {
5169           // Checks if 2 insertelements are from the same buildvector.
5170           if (VU->getType() != V->getType())
5171             return false;
5172           auto *IE1 = cast<InsertElementInst>(VU);
5173           auto *IE2 = cast<InsertElementInst>(V);
5174           // Go though of insertelement instructions trying to find either VU as
5175           // the original vector for IE2 or V as the original vector for IE1.
5176           do {
5177             if (IE1 == VU || IE2 == V)
5178               return true;
5179             if (IE1)
5180               IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5181             if (IE2)
5182               IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5183           } while (IE1 || IE2);
5184           return false;
5185         });
5186         int VecId = -1;
5187         if (It == FirstUsers.end()) {
5188           VF.push_back(FTy->getNumElements());
5189           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5190           FirstUsers.push_back(EU.User);
5191           DemandedElts.push_back(APInt::getZero(VF.back()));
5192           VecId = FirstUsers.size() - 1;
5193         } else {
5194           VecId = std::distance(FirstUsers.begin(), It);
5195         }
5196         int Idx = *InsertIdx;
5197         ShuffleMask[VecId][Idx] = EU.Lane;
5198         DemandedElts[VecId].setBit(Idx);
5199       }
5200     }
5201 
5202     // If we plan to rewrite the tree in a smaller type, we will need to sign
5203     // extend the extracted value back to the original type. Here, we account
5204     // for the extract and the added cost of the sign extend if needed.
5205     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5206     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5207     if (MinBWs.count(ScalarRoot)) {
5208       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5209       auto Extend =
5210           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5211       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5212       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5213                                                    VecTy, EU.Lane);
5214     } else {
5215       ExtractCost +=
5216           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5217     }
5218   }
5219 
5220   InstructionCost SpillCost = getSpillCost();
5221   Cost += SpillCost + ExtractCost;
5222   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
5223     // For the very first element - simple shuffle of the source vector.
5224     int Limit = ShuffleMask[I].size() * 2;
5225     if (I == 0 &&
5226         all_of(ShuffleMask[I], [Limit](int Idx) { return Idx < Limit; }) &&
5227         !ShuffleVectorInst::isIdentityMask(ShuffleMask[I])) {
5228       InstructionCost C = TTI->getShuffleCost(
5229           TTI::SK_PermuteSingleSrc,
5230           cast<FixedVectorType>(FirstUsers[I]->getType()), ShuffleMask[I]);
5231       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5232                         << " for final shuffle of insertelement external users "
5233                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5234                         << "SLP: Current total cost = " << Cost << "\n");
5235       Cost += C;
5236       continue;
5237     }
5238     // Other elements - permutation of 2 vectors (the initial one and the next
5239     // Ith incoming vector).
5240     unsigned VF = ShuffleMask[I].size();
5241     for (unsigned Idx = 0; Idx < VF; ++Idx) {
5242       int &Mask = ShuffleMask[I][Idx];
5243       Mask = Mask == UndefMaskElem ? Idx : VF + Mask;
5244     }
5245     InstructionCost C = TTI->getShuffleCost(
5246         TTI::SK_PermuteTwoSrc, cast<FixedVectorType>(FirstUsers[I]->getType()),
5247         ShuffleMask[I]);
5248     LLVM_DEBUG(
5249         dbgs()
5250         << "SLP: Adding cost " << C
5251         << " for final shuffle of vector node and external insertelement users "
5252         << *VectorizableTree.front()->Scalars.front() << ".\n"
5253         << "SLP: Current total cost = " << Cost << "\n");
5254     Cost += C;
5255     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5256         cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5257         /*Insert*/ true,
5258         /*Extract*/ false);
5259     Cost -= InsertCost;
5260     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5261                       << " for insertelements gather.\n"
5262                       << "SLP: Current total cost = " << Cost << "\n");
5263   }
5264 
5265 #ifndef NDEBUG
5266   SmallString<256> Str;
5267   {
5268     raw_svector_ostream OS(Str);
5269     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5270        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5271        << "SLP: Total Cost = " << Cost << ".\n";
5272   }
5273   LLVM_DEBUG(dbgs() << Str);
5274   if (ViewSLPTree)
5275     ViewGraph(this, "SLP" + F->getName(), false, Str);
5276 #endif
5277 
5278   return Cost;
5279 }
5280 
5281 Optional<TargetTransformInfo::ShuffleKind>
5282 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5283                                SmallVectorImpl<const TreeEntry *> &Entries) {
5284   // TODO: currently checking only for Scalars in the tree entry, need to count
5285   // reused elements too for better cost estimation.
5286   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5287   Entries.clear();
5288   // Build a lists of values to tree entries.
5289   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5290   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5291     if (EntryPtr.get() == TE)
5292       break;
5293     if (EntryPtr->State != TreeEntry::NeedToGather)
5294       continue;
5295     for (Value *V : EntryPtr->Scalars)
5296       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5297   }
5298   // Find all tree entries used by the gathered values. If no common entries
5299   // found - not a shuffle.
5300   // Here we build a set of tree nodes for each gathered value and trying to
5301   // find the intersection between these sets. If we have at least one common
5302   // tree node for each gathered value - we have just a permutation of the
5303   // single vector. If we have 2 different sets, we're in situation where we
5304   // have a permutation of 2 input vectors.
5305   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5306   DenseMap<Value *, int> UsedValuesEntry;
5307   for (Value *V : TE->Scalars) {
5308     if (isa<UndefValue>(V))
5309       continue;
5310     // Build a list of tree entries where V is used.
5311     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5312     auto It = ValueToTEs.find(V);
5313     if (It != ValueToTEs.end())
5314       VToTEs = It->second;
5315     if (const TreeEntry *VTE = getTreeEntry(V))
5316       VToTEs.insert(VTE);
5317     if (VToTEs.empty())
5318       return None;
5319     if (UsedTEs.empty()) {
5320       // The first iteration, just insert the list of nodes to vector.
5321       UsedTEs.push_back(VToTEs);
5322     } else {
5323       // Need to check if there are any previously used tree nodes which use V.
5324       // If there are no such nodes, consider that we have another one input
5325       // vector.
5326       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
5327       unsigned Idx = 0;
5328       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
5329         // Do we have a non-empty intersection of previously listed tree entries
5330         // and tree entries using current V?
5331         set_intersect(VToTEs, Set);
5332         if (!VToTEs.empty()) {
5333           // Yes, write the new subset and continue analysis for the next
5334           // scalar.
5335           Set.swap(VToTEs);
5336           break;
5337         }
5338         VToTEs = SavedVToTEs;
5339         ++Idx;
5340       }
5341       // No non-empty intersection found - need to add a second set of possible
5342       // source vectors.
5343       if (Idx == UsedTEs.size()) {
5344         // If the number of input vectors is greater than 2 - not a permutation,
5345         // fallback to the regular gather.
5346         if (UsedTEs.size() == 2)
5347           return None;
5348         UsedTEs.push_back(SavedVToTEs);
5349         Idx = UsedTEs.size() - 1;
5350       }
5351       UsedValuesEntry.try_emplace(V, Idx);
5352     }
5353   }
5354 
5355   unsigned VF = 0;
5356   if (UsedTEs.size() == 1) {
5357     // Try to find the perfect match in another gather node at first.
5358     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
5359       return EntryPtr->isSame(TE->Scalars);
5360     });
5361     if (It != UsedTEs.front().end()) {
5362       Entries.push_back(*It);
5363       std::iota(Mask.begin(), Mask.end(), 0);
5364       return TargetTransformInfo::SK_PermuteSingleSrc;
5365     }
5366     // No perfect match, just shuffle, so choose the first tree node.
5367     Entries.push_back(*UsedTEs.front().begin());
5368   } else {
5369     // Try to find nodes with the same vector factor.
5370     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
5371     // FIXME: Shall be replaced by GetVF function once non-power-2 patch is
5372     // landed.
5373     auto &&GetVF = [](const TreeEntry *TE) {
5374       if (!TE->ReuseShuffleIndices.empty())
5375         return TE->ReuseShuffleIndices.size();
5376       return TE->Scalars.size();
5377     };
5378     DenseMap<int, const TreeEntry *> VFToTE;
5379     for (const TreeEntry *TE : UsedTEs.front())
5380       VFToTE.try_emplace(GetVF(TE), TE);
5381     for (const TreeEntry *TE : UsedTEs.back()) {
5382       auto It = VFToTE.find(GetVF(TE));
5383       if (It != VFToTE.end()) {
5384         VF = It->first;
5385         Entries.push_back(It->second);
5386         Entries.push_back(TE);
5387         break;
5388       }
5389     }
5390     // No 2 source vectors with the same vector factor - give up and do regular
5391     // gather.
5392     if (Entries.empty())
5393       return None;
5394   }
5395 
5396   // Build a shuffle mask for better cost estimation and vector emission.
5397   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
5398     Value *V = TE->Scalars[I];
5399     if (isa<UndefValue>(V))
5400       continue;
5401     unsigned Idx = UsedValuesEntry.lookup(V);
5402     const TreeEntry *VTE = Entries[Idx];
5403     int FoundLane = VTE->findLaneForValue(V);
5404     Mask[I] = Idx * VF + FoundLane;
5405     // Extra check required by isSingleSourceMaskImpl function (called by
5406     // ShuffleVectorInst::isSingleSourceMask).
5407     if (Mask[I] >= 2 * E)
5408       return None;
5409   }
5410   switch (Entries.size()) {
5411   case 1:
5412     return TargetTransformInfo::SK_PermuteSingleSrc;
5413   case 2:
5414     return TargetTransformInfo::SK_PermuteTwoSrc;
5415   default:
5416     break;
5417   }
5418   return None;
5419 }
5420 
5421 InstructionCost
5422 BoUpSLP::getGatherCost(FixedVectorType *Ty,
5423                        const DenseSet<unsigned> &ShuffledIndices) const {
5424   unsigned NumElts = Ty->getNumElements();
5425   APInt DemandedElts = APInt::getZero(NumElts);
5426   for (unsigned I = 0; I < NumElts; ++I)
5427     if (!ShuffledIndices.count(I))
5428       DemandedElts.setBit(I);
5429   InstructionCost Cost =
5430       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
5431                                     /*Extract*/ false);
5432   if (!ShuffledIndices.empty())
5433     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
5434   return Cost;
5435 }
5436 
5437 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
5438   // Find the type of the operands in VL.
5439   Type *ScalarTy = VL[0]->getType();
5440   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5441     ScalarTy = SI->getValueOperand()->getType();
5442   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5443   // Find the cost of inserting/extracting values from the vector.
5444   // Check if the same elements are inserted several times and count them as
5445   // shuffle candidates.
5446   DenseSet<unsigned> ShuffledElements;
5447   DenseSet<Value *> UniqueElements;
5448   // Iterate in reverse order to consider insert elements with the high cost.
5449   for (unsigned I = VL.size(); I > 0; --I) {
5450     unsigned Idx = I - 1;
5451     if (isConstant(VL[Idx]))
5452       continue;
5453     if (!UniqueElements.insert(VL[Idx]).second)
5454       ShuffledElements.insert(Idx);
5455   }
5456   return getGatherCost(VecTy, ShuffledElements);
5457 }
5458 
5459 // Perform operand reordering on the instructions in VL and return the reordered
5460 // operands in Left and Right.
5461 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
5462                                              SmallVectorImpl<Value *> &Left,
5463                                              SmallVectorImpl<Value *> &Right,
5464                                              const DataLayout &DL,
5465                                              ScalarEvolution &SE,
5466                                              const BoUpSLP &R) {
5467   if (VL.empty())
5468     return;
5469   VLOperands Ops(VL, DL, SE, R);
5470   // Reorder the operands in place.
5471   Ops.reorder();
5472   Left = Ops.getVL(0);
5473   Right = Ops.getVL(1);
5474 }
5475 
5476 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
5477   // Get the basic block this bundle is in. All instructions in the bundle
5478   // should be in this block.
5479   auto *Front = E->getMainOp();
5480   auto *BB = Front->getParent();
5481   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
5482     auto *I = cast<Instruction>(V);
5483     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
5484   }));
5485 
5486   // The last instruction in the bundle in program order.
5487   Instruction *LastInst = nullptr;
5488 
5489   // Find the last instruction. The common case should be that BB has been
5490   // scheduled, and the last instruction is VL.back(). So we start with
5491   // VL.back() and iterate over schedule data until we reach the end of the
5492   // bundle. The end of the bundle is marked by null ScheduleData.
5493   if (BlocksSchedules.count(BB)) {
5494     auto *Bundle =
5495         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
5496     if (Bundle && Bundle->isPartOfBundle())
5497       for (; Bundle; Bundle = Bundle->NextInBundle)
5498         if (Bundle->OpValue == Bundle->Inst)
5499           LastInst = Bundle->Inst;
5500   }
5501 
5502   // LastInst can still be null at this point if there's either not an entry
5503   // for BB in BlocksSchedules or there's no ScheduleData available for
5504   // VL.back(). This can be the case if buildTree_rec aborts for various
5505   // reasons (e.g., the maximum recursion depth is reached, the maximum region
5506   // size is reached, etc.). ScheduleData is initialized in the scheduling
5507   // "dry-run".
5508   //
5509   // If this happens, we can still find the last instruction by brute force. We
5510   // iterate forwards from Front (inclusive) until we either see all
5511   // instructions in the bundle or reach the end of the block. If Front is the
5512   // last instruction in program order, LastInst will be set to Front, and we
5513   // will visit all the remaining instructions in the block.
5514   //
5515   // One of the reasons we exit early from buildTree_rec is to place an upper
5516   // bound on compile-time. Thus, taking an additional compile-time hit here is
5517   // not ideal. However, this should be exceedingly rare since it requires that
5518   // we both exit early from buildTree_rec and that the bundle be out-of-order
5519   // (causing us to iterate all the way to the end of the block).
5520   if (!LastInst) {
5521     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
5522     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
5523       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
5524         LastInst = &I;
5525       if (Bundle.empty())
5526         break;
5527     }
5528   }
5529   assert(LastInst && "Failed to find last instruction in bundle");
5530 
5531   // Set the insertion point after the last instruction in the bundle. Set the
5532   // debug location to Front.
5533   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
5534   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
5535 }
5536 
5537 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
5538   // List of instructions/lanes from current block and/or the blocks which are
5539   // part of the current loop. These instructions will be inserted at the end to
5540   // make it possible to optimize loops and hoist invariant instructions out of
5541   // the loops body with better chances for success.
5542   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
5543   SmallSet<int, 4> PostponedIndices;
5544   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
5545   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
5546     SmallPtrSet<BasicBlock *, 4> Visited;
5547     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
5548       InsertBB = InsertBB->getSinglePredecessor();
5549     return InsertBB && InsertBB == InstBB;
5550   };
5551   for (int I = 0, E = VL.size(); I < E; ++I) {
5552     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
5553       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
5554            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
5555           PostponedIndices.insert(I).second)
5556         PostponedInsts.emplace_back(Inst, I);
5557   }
5558 
5559   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
5560     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
5561     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
5562     if (!InsElt)
5563       return Vec;
5564     GatherSeq.insert(InsElt);
5565     CSEBlocks.insert(InsElt->getParent());
5566     // Add to our 'need-to-extract' list.
5567     if (TreeEntry *Entry = getTreeEntry(V)) {
5568       // Find which lane we need to extract.
5569       unsigned FoundLane = Entry->findLaneForValue(V);
5570       ExternalUses.emplace_back(V, InsElt, FoundLane);
5571     }
5572     return Vec;
5573   };
5574   Value *Val0 =
5575       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
5576   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
5577   Value *Vec = PoisonValue::get(VecTy);
5578   SmallVector<int> NonConsts;
5579   // Insert constant values at first.
5580   for (int I = 0, E = VL.size(); I < E; ++I) {
5581     if (PostponedIndices.contains(I))
5582       continue;
5583     if (!isConstant(VL[I])) {
5584       NonConsts.push_back(I);
5585       continue;
5586     }
5587     Vec = CreateInsertElement(Vec, VL[I], I);
5588   }
5589   // Insert non-constant values.
5590   for (int I : NonConsts)
5591     Vec = CreateInsertElement(Vec, VL[I], I);
5592   // Append instructions, which are/may be part of the loop, in the end to make
5593   // it possible to hoist non-loop-based instructions.
5594   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
5595     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
5596 
5597   return Vec;
5598 }
5599 
5600 namespace {
5601 /// Merges shuffle masks and emits final shuffle instruction, if required.
5602 class ShuffleInstructionBuilder {
5603   IRBuilderBase &Builder;
5604   const unsigned VF = 0;
5605   bool IsFinalized = false;
5606   SmallVector<int, 4> Mask;
5607 
5608 public:
5609   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF)
5610       : Builder(Builder), VF(VF) {}
5611 
5612   /// Adds a mask, inverting it before applying.
5613   void addInversedMask(ArrayRef<unsigned> SubMask) {
5614     if (SubMask.empty())
5615       return;
5616     SmallVector<int, 4> NewMask;
5617     inversePermutation(SubMask, NewMask);
5618     addMask(NewMask);
5619   }
5620 
5621   /// Functions adds masks, merging them into  single one.
5622   void addMask(ArrayRef<unsigned> SubMask) {
5623     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
5624     addMask(NewMask);
5625   }
5626 
5627   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
5628 
5629   Value *finalize(Value *V) {
5630     IsFinalized = true;
5631     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
5632     if (VF == ValueVF && Mask.empty())
5633       return V;
5634     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
5635     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
5636     addMask(NormalizedMask);
5637 
5638     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
5639       return V;
5640     return Builder.CreateShuffleVector(V, Mask, "shuffle");
5641   }
5642 
5643   ~ShuffleInstructionBuilder() {
5644     assert((IsFinalized || Mask.empty()) &&
5645            "Shuffle construction must be finalized.");
5646   }
5647 };
5648 } // namespace
5649 
5650 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
5651   unsigned VF = VL.size();
5652   InstructionsState S = getSameOpcode(VL);
5653   if (S.getOpcode()) {
5654     if (TreeEntry *E = getTreeEntry(S.OpValue))
5655       if (E->isSame(VL)) {
5656         Value *V = vectorizeTree(E);
5657         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
5658           if (!E->ReuseShuffleIndices.empty()) {
5659             // Reshuffle to get only unique values.
5660             // If some of the scalars are duplicated in the vectorization tree
5661             // entry, we do not vectorize them but instead generate a mask for
5662             // the reuses. But if there are several users of the same entry,
5663             // they may have different vectorization factors. This is especially
5664             // important for PHI nodes. In this case, we need to adapt the
5665             // resulting instruction for the user vectorization factor and have
5666             // to reshuffle it again to take only unique elements of the vector.
5667             // Without this code the function incorrectly returns reduced vector
5668             // instruction with the same elements, not with the unique ones.
5669 
5670             // block:
5671             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
5672             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
5673             // ... (use %2)
5674             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
5675             // br %block
5676             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
5677             SmallSet<int, 4> UsedIdxs;
5678             int Pos = 0;
5679             int Sz = VL.size();
5680             for (int Idx : E->ReuseShuffleIndices) {
5681               if (Idx != Sz && Idx != UndefMaskElem &&
5682                   UsedIdxs.insert(Idx).second)
5683                 UniqueIdxs[Idx] = Pos;
5684               ++Pos;
5685             }
5686             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
5687                                             "less than original vector size.");
5688             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
5689             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
5690           } else {
5691             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
5692                    "Expected vectorization factor less "
5693                    "than original vector size.");
5694             SmallVector<int> UniformMask(VF, 0);
5695             std::iota(UniformMask.begin(), UniformMask.end(), 0);
5696             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
5697           }
5698         }
5699         return V;
5700       }
5701   }
5702 
5703   // Check that every instruction appears once in this bundle.
5704   SmallVector<int> ReuseShuffleIndicies;
5705   SmallVector<Value *> UniqueValues;
5706   if (VL.size() > 2) {
5707     DenseMap<Value *, unsigned> UniquePositions;
5708     unsigned NumValues =
5709         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
5710                                     return !isa<UndefValue>(V);
5711                                   }).base());
5712     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
5713     int UniqueVals = 0;
5714     for (Value *V : VL.drop_back(VL.size() - VF)) {
5715       if (isa<UndefValue>(V)) {
5716         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
5717         continue;
5718       }
5719       if (isConstant(V)) {
5720         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
5721         UniqueValues.emplace_back(V);
5722         continue;
5723       }
5724       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
5725       ReuseShuffleIndicies.emplace_back(Res.first->second);
5726       if (Res.second) {
5727         UniqueValues.emplace_back(V);
5728         ++UniqueVals;
5729       }
5730     }
5731     if (UniqueVals == 1 && UniqueValues.size() == 1) {
5732       // Emit pure splat vector.
5733       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
5734                                   UndefMaskElem);
5735     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
5736       ReuseShuffleIndicies.clear();
5737       UniqueValues.clear();
5738       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
5739     }
5740     UniqueValues.append(VF - UniqueValues.size(),
5741                         PoisonValue::get(VL[0]->getType()));
5742     VL = UniqueValues;
5743   }
5744 
5745   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF);
5746   Value *Vec = gather(VL);
5747   if (!ReuseShuffleIndicies.empty()) {
5748     ShuffleBuilder.addMask(ReuseShuffleIndicies);
5749     Vec = ShuffleBuilder.finalize(Vec);
5750     if (auto *I = dyn_cast<Instruction>(Vec)) {
5751       GatherSeq.insert(I);
5752       CSEBlocks.insert(I->getParent());
5753     }
5754   }
5755   return Vec;
5756 }
5757 
5758 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
5759   IRBuilder<>::InsertPointGuard Guard(Builder);
5760 
5761   if (E->VectorizedValue) {
5762     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
5763     return E->VectorizedValue;
5764   }
5765 
5766   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5767   unsigned VF = E->Scalars.size();
5768   if (NeedToShuffleReuses)
5769     VF = E->ReuseShuffleIndices.size();
5770   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF);
5771   if (E->State == TreeEntry::NeedToGather) {
5772     setInsertPointAfterBundle(E);
5773     Value *Vec;
5774     SmallVector<int> Mask;
5775     SmallVector<const TreeEntry *> Entries;
5776     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5777         isGatherShuffledEntry(E, Mask, Entries);
5778     if (Shuffle.hasValue()) {
5779       assert((Entries.size() == 1 || Entries.size() == 2) &&
5780              "Expected shuffle of 1 or 2 entries.");
5781       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
5782                                         Entries.back()->VectorizedValue, Mask);
5783     } else {
5784       Vec = gather(E->Scalars);
5785     }
5786     if (NeedToShuffleReuses) {
5787       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5788       Vec = ShuffleBuilder.finalize(Vec);
5789       if (auto *I = dyn_cast<Instruction>(Vec)) {
5790         GatherSeq.insert(I);
5791         CSEBlocks.insert(I->getParent());
5792       }
5793     }
5794     E->VectorizedValue = Vec;
5795     return Vec;
5796   }
5797 
5798   assert((E->State == TreeEntry::Vectorize ||
5799           E->State == TreeEntry::ScatterVectorize) &&
5800          "Unhandled state");
5801   unsigned ShuffleOrOp =
5802       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5803   Instruction *VL0 = E->getMainOp();
5804   Type *ScalarTy = VL0->getType();
5805   if (auto *Store = dyn_cast<StoreInst>(VL0))
5806     ScalarTy = Store->getValueOperand()->getType();
5807   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
5808     ScalarTy = IE->getOperand(1)->getType();
5809   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
5810   switch (ShuffleOrOp) {
5811     case Instruction::PHI: {
5812       assert(
5813           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
5814           "PHI reordering is free.");
5815       auto *PH = cast<PHINode>(VL0);
5816       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
5817       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
5818       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
5819       Value *V = NewPhi;
5820       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5821       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5822       V = ShuffleBuilder.finalize(V);
5823 
5824       E->VectorizedValue = V;
5825 
5826       // PHINodes may have multiple entries from the same block. We want to
5827       // visit every block once.
5828       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
5829 
5830       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
5831         ValueList Operands;
5832         BasicBlock *IBB = PH->getIncomingBlock(i);
5833 
5834         if (!VisitedBBs.insert(IBB).second) {
5835           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
5836           continue;
5837         }
5838 
5839         Builder.SetInsertPoint(IBB->getTerminator());
5840         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
5841         Value *Vec = vectorizeTree(E->getOperand(i));
5842         NewPhi->addIncoming(Vec, IBB);
5843       }
5844 
5845       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
5846              "Invalid number of incoming values");
5847       return V;
5848     }
5849 
5850     case Instruction::ExtractElement: {
5851       Value *V = E->getSingleOperand(0);
5852       Builder.SetInsertPoint(VL0);
5853       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5854       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5855       V = ShuffleBuilder.finalize(V);
5856       E->VectorizedValue = V;
5857       return V;
5858     }
5859     case Instruction::ExtractValue: {
5860       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
5861       Builder.SetInsertPoint(LI);
5862       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
5863       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
5864       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
5865       Value *NewV = propagateMetadata(V, E->Scalars);
5866       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5867       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5868       NewV = ShuffleBuilder.finalize(NewV);
5869       E->VectorizedValue = NewV;
5870       return NewV;
5871     }
5872     case Instruction::InsertElement: {
5873       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
5874       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
5875       Value *V = vectorizeTree(E->getOperand(1));
5876 
5877       // Create InsertVector shuffle if necessary
5878       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5879         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
5880       }));
5881       const unsigned NumElts =
5882           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
5883       const unsigned NumScalars = E->Scalars.size();
5884 
5885       unsigned Offset = *getInsertIndex(VL0, 0);
5886       assert(Offset < NumElts && "Failed to find vector index offset");
5887 
5888       // Create shuffle to resize vector
5889       SmallVector<int> Mask;
5890       if (!E->ReorderIndices.empty()) {
5891         inversePermutation(E->ReorderIndices, Mask);
5892         Mask.append(NumElts - NumScalars, UndefMaskElem);
5893       } else {
5894         Mask.assign(NumElts, UndefMaskElem);
5895         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5896       }
5897       // Create InsertVector shuffle if necessary
5898       bool IsIdentity = true;
5899       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5900       Mask.swap(PrevMask);
5901       for (unsigned I = 0; I < NumScalars; ++I) {
5902         Value *Scalar = E->Scalars[PrevMask[I]];
5903         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
5904         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5905           continue;
5906         IsIdentity &= *InsertIdx - Offset == I;
5907         Mask[*InsertIdx - Offset] = I;
5908       }
5909       if (!IsIdentity || NumElts != NumScalars)
5910         V = Builder.CreateShuffleVector(V, Mask);
5911 
5912       if ((!IsIdentity || Offset != 0 ||
5913            !isa<UndefValue>(FirstInsert->getOperand(0))) &&
5914           NumElts != NumScalars) {
5915         SmallVector<int> InsertMask(NumElts);
5916         std::iota(InsertMask.begin(), InsertMask.end(), 0);
5917         for (unsigned I = 0; I < NumElts; I++) {
5918           if (Mask[I] != UndefMaskElem)
5919             InsertMask[Offset + I] = NumElts + I;
5920         }
5921 
5922         V = Builder.CreateShuffleVector(
5923             FirstInsert->getOperand(0), V, InsertMask,
5924             cast<Instruction>(E->Scalars.back())->getName());
5925       }
5926 
5927       ++NumVectorInstructions;
5928       E->VectorizedValue = V;
5929       return V;
5930     }
5931     case Instruction::ZExt:
5932     case Instruction::SExt:
5933     case Instruction::FPToUI:
5934     case Instruction::FPToSI:
5935     case Instruction::FPExt:
5936     case Instruction::PtrToInt:
5937     case Instruction::IntToPtr:
5938     case Instruction::SIToFP:
5939     case Instruction::UIToFP:
5940     case Instruction::Trunc:
5941     case Instruction::FPTrunc:
5942     case Instruction::BitCast: {
5943       setInsertPointAfterBundle(E);
5944 
5945       Value *InVec = vectorizeTree(E->getOperand(0));
5946 
5947       if (E->VectorizedValue) {
5948         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
5949         return E->VectorizedValue;
5950       }
5951 
5952       auto *CI = cast<CastInst>(VL0);
5953       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
5954       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5955       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5956       V = ShuffleBuilder.finalize(V);
5957 
5958       E->VectorizedValue = V;
5959       ++NumVectorInstructions;
5960       return V;
5961     }
5962     case Instruction::FCmp:
5963     case Instruction::ICmp: {
5964       setInsertPointAfterBundle(E);
5965 
5966       Value *L = vectorizeTree(E->getOperand(0));
5967       Value *R = vectorizeTree(E->getOperand(1));
5968 
5969       if (E->VectorizedValue) {
5970         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
5971         return E->VectorizedValue;
5972       }
5973 
5974       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
5975       Value *V = Builder.CreateCmp(P0, L, R);
5976       propagateIRFlags(V, E->Scalars, VL0);
5977       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5978       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5979       V = ShuffleBuilder.finalize(V);
5980 
5981       E->VectorizedValue = V;
5982       ++NumVectorInstructions;
5983       return V;
5984     }
5985     case Instruction::Select: {
5986       setInsertPointAfterBundle(E);
5987 
5988       Value *Cond = vectorizeTree(E->getOperand(0));
5989       Value *True = vectorizeTree(E->getOperand(1));
5990       Value *False = vectorizeTree(E->getOperand(2));
5991 
5992       if (E->VectorizedValue) {
5993         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
5994         return E->VectorizedValue;
5995       }
5996 
5997       Value *V = Builder.CreateSelect(Cond, True, False);
5998       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5999       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6000       V = ShuffleBuilder.finalize(V);
6001 
6002       E->VectorizedValue = V;
6003       ++NumVectorInstructions;
6004       return V;
6005     }
6006     case Instruction::FNeg: {
6007       setInsertPointAfterBundle(E);
6008 
6009       Value *Op = vectorizeTree(E->getOperand(0));
6010 
6011       if (E->VectorizedValue) {
6012         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6013         return E->VectorizedValue;
6014       }
6015 
6016       Value *V = Builder.CreateUnOp(
6017           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6018       propagateIRFlags(V, E->Scalars, VL0);
6019       if (auto *I = dyn_cast<Instruction>(V))
6020         V = propagateMetadata(I, E->Scalars);
6021 
6022       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6023       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6024       V = ShuffleBuilder.finalize(V);
6025 
6026       E->VectorizedValue = V;
6027       ++NumVectorInstructions;
6028 
6029       return V;
6030     }
6031     case Instruction::Add:
6032     case Instruction::FAdd:
6033     case Instruction::Sub:
6034     case Instruction::FSub:
6035     case Instruction::Mul:
6036     case Instruction::FMul:
6037     case Instruction::UDiv:
6038     case Instruction::SDiv:
6039     case Instruction::FDiv:
6040     case Instruction::URem:
6041     case Instruction::SRem:
6042     case Instruction::FRem:
6043     case Instruction::Shl:
6044     case Instruction::LShr:
6045     case Instruction::AShr:
6046     case Instruction::And:
6047     case Instruction::Or:
6048     case Instruction::Xor: {
6049       setInsertPointAfterBundle(E);
6050 
6051       Value *LHS = vectorizeTree(E->getOperand(0));
6052       Value *RHS = vectorizeTree(E->getOperand(1));
6053 
6054       if (E->VectorizedValue) {
6055         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6056         return E->VectorizedValue;
6057       }
6058 
6059       Value *V = Builder.CreateBinOp(
6060           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6061           RHS);
6062       propagateIRFlags(V, E->Scalars, VL0);
6063       if (auto *I = dyn_cast<Instruction>(V))
6064         V = propagateMetadata(I, E->Scalars);
6065 
6066       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6067       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6068       V = ShuffleBuilder.finalize(V);
6069 
6070       E->VectorizedValue = V;
6071       ++NumVectorInstructions;
6072 
6073       return V;
6074     }
6075     case Instruction::Load: {
6076       // Loads are inserted at the head of the tree because we don't want to
6077       // sink them all the way down past store instructions.
6078       setInsertPointAfterBundle(E);
6079 
6080       LoadInst *LI = cast<LoadInst>(VL0);
6081       Instruction *NewLI;
6082       unsigned AS = LI->getPointerAddressSpace();
6083       Value *PO = LI->getPointerOperand();
6084       if (E->State == TreeEntry::Vectorize) {
6085 
6086         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6087 
6088         // The pointer operand uses an in-tree scalar so we add the new BitCast
6089         // to ExternalUses list to make sure that an extract will be generated
6090         // in the future.
6091         if (TreeEntry *Entry = getTreeEntry(PO)) {
6092           // Find which lane we need to extract.
6093           unsigned FoundLane = Entry->findLaneForValue(PO);
6094           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6095         }
6096 
6097         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6098       } else {
6099         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6100         Value *VecPtr = vectorizeTree(E->getOperand(0));
6101         // Use the minimum alignment of the gathered loads.
6102         Align CommonAlignment = LI->getAlign();
6103         for (Value *V : E->Scalars)
6104           CommonAlignment =
6105               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6106         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6107       }
6108       Value *V = propagateMetadata(NewLI, E->Scalars);
6109 
6110       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6111       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6112       V = ShuffleBuilder.finalize(V);
6113       E->VectorizedValue = V;
6114       ++NumVectorInstructions;
6115       return V;
6116     }
6117     case Instruction::Store: {
6118       auto *SI = cast<StoreInst>(VL0);
6119       unsigned AS = SI->getPointerAddressSpace();
6120 
6121       setInsertPointAfterBundle(E);
6122 
6123       Value *VecValue = vectorizeTree(E->getOperand(0));
6124       ShuffleBuilder.addMask(E->ReorderIndices);
6125       VecValue = ShuffleBuilder.finalize(VecValue);
6126 
6127       Value *ScalarPtr = SI->getPointerOperand();
6128       Value *VecPtr = Builder.CreateBitCast(
6129           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6130       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6131                                                  SI->getAlign());
6132 
6133       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6134       // ExternalUses to make sure that an extract will be generated in the
6135       // future.
6136       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6137         // Find which lane we need to extract.
6138         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6139         ExternalUses.push_back(
6140             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6141       }
6142 
6143       Value *V = propagateMetadata(ST, E->Scalars);
6144 
6145       E->VectorizedValue = V;
6146       ++NumVectorInstructions;
6147       return V;
6148     }
6149     case Instruction::GetElementPtr: {
6150       setInsertPointAfterBundle(E);
6151 
6152       Value *Op0 = vectorizeTree(E->getOperand(0));
6153 
6154       std::vector<Value *> OpVecs;
6155       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
6156            ++j) {
6157         ValueList &VL = E->getOperand(j);
6158         // Need to cast all elements to the same type before vectorization to
6159         // avoid crash.
6160         Type *VL0Ty = VL0->getOperand(j)->getType();
6161         Type *Ty = llvm::all_of(
6162                        VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
6163                        ? VL0Ty
6164                        : DL->getIndexType(cast<GetElementPtrInst>(VL0)
6165                                               ->getPointerOperandType()
6166                                               ->getScalarType());
6167         for (Value *&V : VL) {
6168           auto *CI = cast<ConstantInt>(V);
6169           V = ConstantExpr::getIntegerCast(CI, Ty,
6170                                            CI->getValue().isSignBitSet());
6171         }
6172         Value *OpVec = vectorizeTree(VL);
6173         OpVecs.push_back(OpVec);
6174       }
6175 
6176       Value *V = Builder.CreateGEP(
6177           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
6178       if (Instruction *I = dyn_cast<Instruction>(V))
6179         V = propagateMetadata(I, E->Scalars);
6180 
6181       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6182       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6183       V = ShuffleBuilder.finalize(V);
6184 
6185       E->VectorizedValue = V;
6186       ++NumVectorInstructions;
6187 
6188       return V;
6189     }
6190     case Instruction::Call: {
6191       CallInst *CI = cast<CallInst>(VL0);
6192       setInsertPointAfterBundle(E);
6193 
6194       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6195       if (Function *FI = CI->getCalledFunction())
6196         IID = FI->getIntrinsicID();
6197 
6198       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6199 
6200       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6201       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6202                           VecCallCosts.first <= VecCallCosts.second;
6203 
6204       Value *ScalarArg = nullptr;
6205       std::vector<Value *> OpVecs;
6206       SmallVector<Type *, 2> TysForDecl =
6207           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6208       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6209         ValueList OpVL;
6210         // Some intrinsics have scalar arguments. This argument should not be
6211         // vectorized.
6212         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6213           CallInst *CEI = cast<CallInst>(VL0);
6214           ScalarArg = CEI->getArgOperand(j);
6215           OpVecs.push_back(CEI->getArgOperand(j));
6216           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6217             TysForDecl.push_back(ScalarArg->getType());
6218           continue;
6219         }
6220 
6221         Value *OpVec = vectorizeTree(E->getOperand(j));
6222         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6223         OpVecs.push_back(OpVec);
6224       }
6225 
6226       Function *CF;
6227       if (!UseIntrinsic) {
6228         VFShape Shape =
6229             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6230                                   VecTy->getNumElements())),
6231                          false /*HasGlobalPred*/);
6232         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6233       } else {
6234         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6235       }
6236 
6237       SmallVector<OperandBundleDef, 1> OpBundles;
6238       CI->getOperandBundlesAsDefs(OpBundles);
6239       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6240 
6241       // The scalar argument uses an in-tree scalar so we add the new vectorized
6242       // call to ExternalUses list to make sure that an extract will be
6243       // generated in the future.
6244       if (ScalarArg) {
6245         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6246           // Find which lane we need to extract.
6247           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6248           ExternalUses.push_back(
6249               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6250         }
6251       }
6252 
6253       propagateIRFlags(V, E->Scalars, VL0);
6254       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6255       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6256       V = ShuffleBuilder.finalize(V);
6257 
6258       E->VectorizedValue = V;
6259       ++NumVectorInstructions;
6260       return V;
6261     }
6262     case Instruction::ShuffleVector: {
6263       assert(E->isAltShuffle() &&
6264              ((Instruction::isBinaryOp(E->getOpcode()) &&
6265                Instruction::isBinaryOp(E->getAltOpcode())) ||
6266               (Instruction::isCast(E->getOpcode()) &&
6267                Instruction::isCast(E->getAltOpcode()))) &&
6268              "Invalid Shuffle Vector Operand");
6269 
6270       Value *LHS = nullptr, *RHS = nullptr;
6271       if (Instruction::isBinaryOp(E->getOpcode())) {
6272         setInsertPointAfterBundle(E);
6273         LHS = vectorizeTree(E->getOperand(0));
6274         RHS = vectorizeTree(E->getOperand(1));
6275       } else {
6276         setInsertPointAfterBundle(E);
6277         LHS = vectorizeTree(E->getOperand(0));
6278       }
6279 
6280       if (E->VectorizedValue) {
6281         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6282         return E->VectorizedValue;
6283       }
6284 
6285       Value *V0, *V1;
6286       if (Instruction::isBinaryOp(E->getOpcode())) {
6287         V0 = Builder.CreateBinOp(
6288             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6289         V1 = Builder.CreateBinOp(
6290             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6291       } else {
6292         V0 = Builder.CreateCast(
6293             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6294         V1 = Builder.CreateCast(
6295             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6296       }
6297 
6298       // Create shuffle to take alternate operations from the vector.
6299       // Also, gather up main and alt scalar ops to propagate IR flags to
6300       // each vector operation.
6301       ValueList OpScalars, AltScalars;
6302       SmallVector<int> Mask;
6303       buildSuffleEntryMask(
6304           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6305           [E](Instruction *I) {
6306             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6307             return I->getOpcode() == E->getAltOpcode();
6308           },
6309           Mask, &OpScalars, &AltScalars);
6310 
6311       propagateIRFlags(V0, OpScalars);
6312       propagateIRFlags(V1, AltScalars);
6313 
6314       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
6315       if (Instruction *I = dyn_cast<Instruction>(V))
6316         V = propagateMetadata(I, E->Scalars);
6317       V = ShuffleBuilder.finalize(V);
6318 
6319       E->VectorizedValue = V;
6320       ++NumVectorInstructions;
6321 
6322       return V;
6323     }
6324     default:
6325     llvm_unreachable("unknown inst");
6326   }
6327   return nullptr;
6328 }
6329 
6330 Value *BoUpSLP::vectorizeTree() {
6331   ExtraValueToDebugLocsMap ExternallyUsedValues;
6332   return vectorizeTree(ExternallyUsedValues);
6333 }
6334 
6335 Value *
6336 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
6337   // All blocks must be scheduled before any instructions are inserted.
6338   for (auto &BSIter : BlocksSchedules) {
6339     scheduleBlock(BSIter.second.get());
6340   }
6341 
6342   Builder.SetInsertPoint(&F->getEntryBlock().front());
6343   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
6344 
6345   // If the vectorized tree can be rewritten in a smaller type, we truncate the
6346   // vectorized root. InstCombine will then rewrite the entire expression. We
6347   // sign extend the extracted values below.
6348   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6349   if (MinBWs.count(ScalarRoot)) {
6350     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
6351       // If current instr is a phi and not the last phi, insert it after the
6352       // last phi node.
6353       if (isa<PHINode>(I))
6354         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
6355       else
6356         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
6357     }
6358     auto BundleWidth = VectorizableTree[0]->Scalars.size();
6359     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6360     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
6361     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
6362     VectorizableTree[0]->VectorizedValue = Trunc;
6363   }
6364 
6365   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
6366                     << " values .\n");
6367 
6368   // Extract all of the elements with the external uses.
6369   for (const auto &ExternalUse : ExternalUses) {
6370     Value *Scalar = ExternalUse.Scalar;
6371     llvm::User *User = ExternalUse.User;
6372 
6373     // Skip users that we already RAUW. This happens when one instruction
6374     // has multiple uses of the same value.
6375     if (User && !is_contained(Scalar->users(), User))
6376       continue;
6377     TreeEntry *E = getTreeEntry(Scalar);
6378     assert(E && "Invalid scalar");
6379     assert(E->State != TreeEntry::NeedToGather &&
6380            "Extracting from a gather list");
6381 
6382     Value *Vec = E->VectorizedValue;
6383     assert(Vec && "Can't find vectorizable value");
6384 
6385     Value *Lane = Builder.getInt32(ExternalUse.Lane);
6386     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
6387       if (Scalar->getType() != Vec->getType()) {
6388         Value *Ex;
6389         // "Reuse" the existing extract to improve final codegen.
6390         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
6391           Ex = Builder.CreateExtractElement(ES->getOperand(0),
6392                                             ES->getOperand(1));
6393         } else {
6394           Ex = Builder.CreateExtractElement(Vec, Lane);
6395         }
6396         // If necessary, sign-extend or zero-extend ScalarRoot
6397         // to the larger type.
6398         if (!MinBWs.count(ScalarRoot))
6399           return Ex;
6400         if (MinBWs[ScalarRoot].second)
6401           return Builder.CreateSExt(Ex, Scalar->getType());
6402         return Builder.CreateZExt(Ex, Scalar->getType());
6403       }
6404       assert(isa<FixedVectorType>(Scalar->getType()) &&
6405              isa<InsertElementInst>(Scalar) &&
6406              "In-tree scalar of vector type is not insertelement?");
6407       return Vec;
6408     };
6409     // If User == nullptr, the Scalar is used as extra arg. Generate
6410     // ExtractElement instruction and update the record for this scalar in
6411     // ExternallyUsedValues.
6412     if (!User) {
6413       assert(ExternallyUsedValues.count(Scalar) &&
6414              "Scalar with nullptr as an external user must be registered in "
6415              "ExternallyUsedValues map");
6416       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6417         Builder.SetInsertPoint(VecI->getParent(),
6418                                std::next(VecI->getIterator()));
6419       } else {
6420         Builder.SetInsertPoint(&F->getEntryBlock().front());
6421       }
6422       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6423       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
6424       auto &NewInstLocs = ExternallyUsedValues[NewInst];
6425       auto It = ExternallyUsedValues.find(Scalar);
6426       assert(It != ExternallyUsedValues.end() &&
6427              "Externally used scalar is not found in ExternallyUsedValues");
6428       NewInstLocs.append(It->second);
6429       ExternallyUsedValues.erase(Scalar);
6430       // Required to update internally referenced instructions.
6431       Scalar->replaceAllUsesWith(NewInst);
6432       continue;
6433     }
6434 
6435     // Generate extracts for out-of-tree users.
6436     // Find the insertion point for the extractelement lane.
6437     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6438       if (PHINode *PH = dyn_cast<PHINode>(User)) {
6439         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
6440           if (PH->getIncomingValue(i) == Scalar) {
6441             Instruction *IncomingTerminator =
6442                 PH->getIncomingBlock(i)->getTerminator();
6443             if (isa<CatchSwitchInst>(IncomingTerminator)) {
6444               Builder.SetInsertPoint(VecI->getParent(),
6445                                      std::next(VecI->getIterator()));
6446             } else {
6447               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
6448             }
6449             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6450             CSEBlocks.insert(PH->getIncomingBlock(i));
6451             PH->setOperand(i, NewInst);
6452           }
6453         }
6454       } else {
6455         Builder.SetInsertPoint(cast<Instruction>(User));
6456         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6457         CSEBlocks.insert(cast<Instruction>(User)->getParent());
6458         User->replaceUsesOfWith(Scalar, NewInst);
6459       }
6460     } else {
6461       Builder.SetInsertPoint(&F->getEntryBlock().front());
6462       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6463       CSEBlocks.insert(&F->getEntryBlock());
6464       User->replaceUsesOfWith(Scalar, NewInst);
6465     }
6466 
6467     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
6468   }
6469 
6470   // For each vectorized value:
6471   for (auto &TEPtr : VectorizableTree) {
6472     TreeEntry *Entry = TEPtr.get();
6473 
6474     // No need to handle users of gathered values.
6475     if (Entry->State == TreeEntry::NeedToGather)
6476       continue;
6477 
6478     assert(Entry->VectorizedValue && "Can't find vectorizable value");
6479 
6480     // For each lane:
6481     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
6482       Value *Scalar = Entry->Scalars[Lane];
6483 
6484 #ifndef NDEBUG
6485       Type *Ty = Scalar->getType();
6486       if (!Ty->isVoidTy()) {
6487         for (User *U : Scalar->users()) {
6488           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
6489 
6490           // It is legal to delete users in the ignorelist.
6491           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
6492                   (isa_and_nonnull<Instruction>(U) &&
6493                    isDeleted(cast<Instruction>(U)))) &&
6494                  "Deleting out-of-tree value");
6495         }
6496       }
6497 #endif
6498       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
6499       eraseInstruction(cast<Instruction>(Scalar));
6500     }
6501   }
6502 
6503   Builder.ClearInsertionPoint();
6504   InstrElementSize.clear();
6505 
6506   return VectorizableTree[0]->VectorizedValue;
6507 }
6508 
6509 void BoUpSLP::optimizeGatherSequence() {
6510   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
6511                     << " gather sequences instructions.\n");
6512   // LICM InsertElementInst sequences.
6513   for (Instruction *I : GatherSeq) {
6514     if (isDeleted(I))
6515       continue;
6516 
6517     // Check if this block is inside a loop.
6518     Loop *L = LI->getLoopFor(I->getParent());
6519     if (!L)
6520       continue;
6521 
6522     // Check if it has a preheader.
6523     BasicBlock *PreHeader = L->getLoopPreheader();
6524     if (!PreHeader)
6525       continue;
6526 
6527     // If the vector or the element that we insert into it are
6528     // instructions that are defined in this basic block then we can't
6529     // hoist this instruction.
6530     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
6531     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
6532     if (Op0 && L->contains(Op0))
6533       continue;
6534     if (Op1 && L->contains(Op1))
6535       continue;
6536 
6537     // We can hoist this instruction. Move it to the pre-header.
6538     I->moveBefore(PreHeader->getTerminator());
6539   }
6540 
6541   // Make a list of all reachable blocks in our CSE queue.
6542   SmallVector<const DomTreeNode *, 8> CSEWorkList;
6543   CSEWorkList.reserve(CSEBlocks.size());
6544   for (BasicBlock *BB : CSEBlocks)
6545     if (DomTreeNode *N = DT->getNode(BB)) {
6546       assert(DT->isReachableFromEntry(N));
6547       CSEWorkList.push_back(N);
6548     }
6549 
6550   // Sort blocks by domination. This ensures we visit a block after all blocks
6551   // dominating it are visited.
6552   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
6553     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
6554            "Different nodes should have different DFS numbers");
6555     return A->getDFSNumIn() < B->getDFSNumIn();
6556   });
6557 
6558   // Perform O(N^2) search over the gather sequences and merge identical
6559   // instructions. TODO: We can further optimize this scan if we split the
6560   // instructions into different buckets based on the insert lane.
6561   SmallVector<Instruction *, 16> Visited;
6562   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
6563     assert(*I &&
6564            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
6565            "Worklist not sorted properly!");
6566     BasicBlock *BB = (*I)->getBlock();
6567     // For all instructions in blocks containing gather sequences:
6568     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
6569       Instruction *In = &*it++;
6570       if (isDeleted(In))
6571         continue;
6572       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In) &&
6573           !isa<ShuffleVectorInst>(In))
6574         continue;
6575 
6576       // Check if we can replace this instruction with any of the
6577       // visited instructions.
6578       for (Instruction *v : Visited) {
6579         if (In->isIdenticalTo(v) &&
6580             DT->dominates(v->getParent(), In->getParent())) {
6581           In->replaceAllUsesWith(v);
6582           eraseInstruction(In);
6583           In = nullptr;
6584           break;
6585         }
6586       }
6587       if (In) {
6588         assert(!is_contained(Visited, In));
6589         Visited.push_back(In);
6590       }
6591     }
6592   }
6593   CSEBlocks.clear();
6594   GatherSeq.clear();
6595 }
6596 
6597 // Groups the instructions to a bundle (which is then a single scheduling entity)
6598 // and schedules instructions until the bundle gets ready.
6599 Optional<BoUpSLP::ScheduleData *>
6600 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
6601                                             const InstructionsState &S) {
6602   // No need to schedule PHIs, insertelement, extractelement and extractvalue
6603   // instructions.
6604   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
6605     return nullptr;
6606 
6607   // Initialize the instruction bundle.
6608   Instruction *OldScheduleEnd = ScheduleEnd;
6609   ScheduleData *PrevInBundle = nullptr;
6610   ScheduleData *Bundle = nullptr;
6611   bool ReSchedule = false;
6612   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
6613 
6614   auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule,
6615                                                          ScheduleData *Bundle) {
6616     // The scheduling region got new instructions at the lower end (or it is a
6617     // new region for the first bundle). This makes it necessary to
6618     // recalculate all dependencies.
6619     // It is seldom that this needs to be done a second time after adding the
6620     // initial bundle to the region.
6621     if (ScheduleEnd != OldScheduleEnd) {
6622       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
6623         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
6624       ReSchedule = true;
6625     }
6626     if (ReSchedule) {
6627       resetSchedule();
6628       initialFillReadyList(ReadyInsts);
6629     }
6630     if (Bundle) {
6631       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
6632                         << " in block " << BB->getName() << "\n");
6633       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
6634     }
6635 
6636     // Now try to schedule the new bundle or (if no bundle) just calculate
6637     // dependencies. As soon as the bundle is "ready" it means that there are no
6638     // cyclic dependencies and we can schedule it. Note that's important that we
6639     // don't "schedule" the bundle yet (see cancelScheduling).
6640     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
6641            !ReadyInsts.empty()) {
6642       ScheduleData *Picked = ReadyInsts.pop_back_val();
6643       if (Picked->isSchedulingEntity() && Picked->isReady())
6644         schedule(Picked, ReadyInsts);
6645     }
6646   };
6647 
6648   // Make sure that the scheduling region contains all
6649   // instructions of the bundle.
6650   for (Value *V : VL) {
6651     if (!extendSchedulingRegion(V, S)) {
6652       // If the scheduling region got new instructions at the lower end (or it
6653       // is a new region for the first bundle). This makes it necessary to
6654       // recalculate all dependencies.
6655       // Otherwise the compiler may crash trying to incorrectly calculate
6656       // dependencies and emit instruction in the wrong order at the actual
6657       // scheduling.
6658       TryScheduleBundle(/*ReSchedule=*/false, nullptr);
6659       return None;
6660     }
6661   }
6662 
6663   for (Value *V : VL) {
6664     ScheduleData *BundleMember = getScheduleData(V);
6665     assert(BundleMember &&
6666            "no ScheduleData for bundle member (maybe not in same basic block)");
6667     if (BundleMember->IsScheduled) {
6668       // A bundle member was scheduled as single instruction before and now
6669       // needs to be scheduled as part of the bundle. We just get rid of the
6670       // existing schedule.
6671       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
6672                         << " was already scheduled\n");
6673       ReSchedule = true;
6674     }
6675     assert(BundleMember->isSchedulingEntity() &&
6676            "bundle member already part of other bundle");
6677     if (PrevInBundle) {
6678       PrevInBundle->NextInBundle = BundleMember;
6679     } else {
6680       Bundle = BundleMember;
6681     }
6682     BundleMember->UnscheduledDepsInBundle = 0;
6683     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
6684 
6685     // Group the instructions to a bundle.
6686     BundleMember->FirstInBundle = Bundle;
6687     PrevInBundle = BundleMember;
6688   }
6689   assert(Bundle && "Failed to find schedule bundle");
6690   TryScheduleBundle(ReSchedule, Bundle);
6691   if (!Bundle->isReady()) {
6692     cancelScheduling(VL, S.OpValue);
6693     return None;
6694   }
6695   return Bundle;
6696 }
6697 
6698 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
6699                                                 Value *OpValue) {
6700   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
6701     return;
6702 
6703   ScheduleData *Bundle = getScheduleData(OpValue);
6704   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
6705   assert(!Bundle->IsScheduled &&
6706          "Can't cancel bundle which is already scheduled");
6707   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
6708          "tried to unbundle something which is not a bundle");
6709 
6710   // Un-bundle: make single instructions out of the bundle.
6711   ScheduleData *BundleMember = Bundle;
6712   while (BundleMember) {
6713     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
6714     BundleMember->FirstInBundle = BundleMember;
6715     ScheduleData *Next = BundleMember->NextInBundle;
6716     BundleMember->NextInBundle = nullptr;
6717     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
6718     if (BundleMember->UnscheduledDepsInBundle == 0) {
6719       ReadyInsts.insert(BundleMember);
6720     }
6721     BundleMember = Next;
6722   }
6723 }
6724 
6725 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
6726   // Allocate a new ScheduleData for the instruction.
6727   if (ChunkPos >= ChunkSize) {
6728     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
6729     ChunkPos = 0;
6730   }
6731   return &(ScheduleDataChunks.back()[ChunkPos++]);
6732 }
6733 
6734 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
6735                                                       const InstructionsState &S) {
6736   if (getScheduleData(V, isOneOf(S, V)))
6737     return true;
6738   Instruction *I = dyn_cast<Instruction>(V);
6739   assert(I && "bundle member must be an instruction");
6740   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
6741          "phi nodes/insertelements/extractelements/extractvalues don't need to "
6742          "be scheduled");
6743   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
6744     ScheduleData *ISD = getScheduleData(I);
6745     if (!ISD)
6746       return false;
6747     assert(isInSchedulingRegion(ISD) &&
6748            "ScheduleData not in scheduling region");
6749     ScheduleData *SD = allocateScheduleDataChunks();
6750     SD->Inst = I;
6751     SD->init(SchedulingRegionID, S.OpValue);
6752     ExtraScheduleDataMap[I][S.OpValue] = SD;
6753     return true;
6754   };
6755   if (CheckSheduleForI(I))
6756     return true;
6757   if (!ScheduleStart) {
6758     // It's the first instruction in the new region.
6759     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
6760     ScheduleStart = I;
6761     ScheduleEnd = I->getNextNode();
6762     if (isOneOf(S, I) != I)
6763       CheckSheduleForI(I);
6764     assert(ScheduleEnd && "tried to vectorize a terminator?");
6765     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
6766     return true;
6767   }
6768   // Search up and down at the same time, because we don't know if the new
6769   // instruction is above or below the existing scheduling region.
6770   BasicBlock::reverse_iterator UpIter =
6771       ++ScheduleStart->getIterator().getReverse();
6772   BasicBlock::reverse_iterator UpperEnd = BB->rend();
6773   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
6774   BasicBlock::iterator LowerEnd = BB->end();
6775   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
6776          &*DownIter != I) {
6777     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
6778       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
6779       return false;
6780     }
6781 
6782     ++UpIter;
6783     ++DownIter;
6784   }
6785   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
6786     assert(I->getParent() == ScheduleStart->getParent() &&
6787            "Instruction is in wrong basic block.");
6788     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
6789     ScheduleStart = I;
6790     if (isOneOf(S, I) != I)
6791       CheckSheduleForI(I);
6792     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
6793                       << "\n");
6794     return true;
6795   }
6796   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
6797          "Expected to reach top of the basic block or instruction down the "
6798          "lower end.");
6799   assert(I->getParent() == ScheduleEnd->getParent() &&
6800          "Instruction is in wrong basic block.");
6801   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
6802                    nullptr);
6803   ScheduleEnd = I->getNextNode();
6804   if (isOneOf(S, I) != I)
6805     CheckSheduleForI(I);
6806   assert(ScheduleEnd && "tried to vectorize a terminator?");
6807   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
6808   return true;
6809 }
6810 
6811 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
6812                                                 Instruction *ToI,
6813                                                 ScheduleData *PrevLoadStore,
6814                                                 ScheduleData *NextLoadStore) {
6815   ScheduleData *CurrentLoadStore = PrevLoadStore;
6816   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
6817     ScheduleData *SD = ScheduleDataMap[I];
6818     if (!SD) {
6819       SD = allocateScheduleDataChunks();
6820       ScheduleDataMap[I] = SD;
6821       SD->Inst = I;
6822     }
6823     assert(!isInSchedulingRegion(SD) &&
6824            "new ScheduleData already in scheduling region");
6825     SD->init(SchedulingRegionID, I);
6826 
6827     if (I->mayReadOrWriteMemory() &&
6828         (!isa<IntrinsicInst>(I) ||
6829          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
6830           cast<IntrinsicInst>(I)->getIntrinsicID() !=
6831               Intrinsic::pseudoprobe))) {
6832       // Update the linked list of memory accessing instructions.
6833       if (CurrentLoadStore) {
6834         CurrentLoadStore->NextLoadStore = SD;
6835       } else {
6836         FirstLoadStoreInRegion = SD;
6837       }
6838       CurrentLoadStore = SD;
6839     }
6840   }
6841   if (NextLoadStore) {
6842     if (CurrentLoadStore)
6843       CurrentLoadStore->NextLoadStore = NextLoadStore;
6844   } else {
6845     LastLoadStoreInRegion = CurrentLoadStore;
6846   }
6847 }
6848 
6849 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
6850                                                      bool InsertInReadyList,
6851                                                      BoUpSLP *SLP) {
6852   assert(SD->isSchedulingEntity());
6853 
6854   SmallVector<ScheduleData *, 10> WorkList;
6855   WorkList.push_back(SD);
6856 
6857   while (!WorkList.empty()) {
6858     ScheduleData *SD = WorkList.pop_back_val();
6859 
6860     ScheduleData *BundleMember = SD;
6861     while (BundleMember) {
6862       assert(isInSchedulingRegion(BundleMember));
6863       if (!BundleMember->hasValidDependencies()) {
6864 
6865         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
6866                           << "\n");
6867         BundleMember->Dependencies = 0;
6868         BundleMember->resetUnscheduledDeps();
6869 
6870         // Handle def-use chain dependencies.
6871         if (BundleMember->OpValue != BundleMember->Inst) {
6872           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
6873           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
6874             BundleMember->Dependencies++;
6875             ScheduleData *DestBundle = UseSD->FirstInBundle;
6876             if (!DestBundle->IsScheduled)
6877               BundleMember->incrementUnscheduledDeps(1);
6878             if (!DestBundle->hasValidDependencies())
6879               WorkList.push_back(DestBundle);
6880           }
6881         } else {
6882           for (User *U : BundleMember->Inst->users()) {
6883             if (isa<Instruction>(U)) {
6884               ScheduleData *UseSD = getScheduleData(U);
6885               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
6886                 BundleMember->Dependencies++;
6887                 ScheduleData *DestBundle = UseSD->FirstInBundle;
6888                 if (!DestBundle->IsScheduled)
6889                   BundleMember->incrementUnscheduledDeps(1);
6890                 if (!DestBundle->hasValidDependencies())
6891                   WorkList.push_back(DestBundle);
6892               }
6893             } else {
6894               // I'm not sure if this can ever happen. But we need to be safe.
6895               // This lets the instruction/bundle never be scheduled and
6896               // eventually disable vectorization.
6897               BundleMember->Dependencies++;
6898               BundleMember->incrementUnscheduledDeps(1);
6899             }
6900           }
6901         }
6902 
6903         // Handle the memory dependencies.
6904         ScheduleData *DepDest = BundleMember->NextLoadStore;
6905         if (DepDest) {
6906           Instruction *SrcInst = BundleMember->Inst;
6907           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
6908           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
6909           unsigned numAliased = 0;
6910           unsigned DistToSrc = 1;
6911 
6912           while (DepDest) {
6913             assert(isInSchedulingRegion(DepDest));
6914 
6915             // We have two limits to reduce the complexity:
6916             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
6917             //    SLP->isAliased (which is the expensive part in this loop).
6918             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
6919             //    the whole loop (even if the loop is fast, it's quadratic).
6920             //    It's important for the loop break condition (see below) to
6921             //    check this limit even between two read-only instructions.
6922             if (DistToSrc >= MaxMemDepDistance ||
6923                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
6924                      (numAliased >= AliasedCheckLimit ||
6925                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
6926 
6927               // We increment the counter only if the locations are aliased
6928               // (instead of counting all alias checks). This gives a better
6929               // balance between reduced runtime and accurate dependencies.
6930               numAliased++;
6931 
6932               DepDest->MemoryDependencies.push_back(BundleMember);
6933               BundleMember->Dependencies++;
6934               ScheduleData *DestBundle = DepDest->FirstInBundle;
6935               if (!DestBundle->IsScheduled) {
6936                 BundleMember->incrementUnscheduledDeps(1);
6937               }
6938               if (!DestBundle->hasValidDependencies()) {
6939                 WorkList.push_back(DestBundle);
6940               }
6941             }
6942             DepDest = DepDest->NextLoadStore;
6943 
6944             // Example, explaining the loop break condition: Let's assume our
6945             // starting instruction is i0 and MaxMemDepDistance = 3.
6946             //
6947             //                      +--------v--v--v
6948             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
6949             //             +--------^--^--^
6950             //
6951             // MaxMemDepDistance let us stop alias-checking at i3 and we add
6952             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
6953             // Previously we already added dependencies from i3 to i6,i7,i8
6954             // (because of MaxMemDepDistance). As we added a dependency from
6955             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
6956             // and we can abort this loop at i6.
6957             if (DistToSrc >= 2 * MaxMemDepDistance)
6958               break;
6959             DistToSrc++;
6960           }
6961         }
6962       }
6963       BundleMember = BundleMember->NextInBundle;
6964     }
6965     if (InsertInReadyList && SD->isReady()) {
6966       ReadyInsts.push_back(SD);
6967       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
6968                         << "\n");
6969     }
6970   }
6971 }
6972 
6973 void BoUpSLP::BlockScheduling::resetSchedule() {
6974   assert(ScheduleStart &&
6975          "tried to reset schedule on block which has not been scheduled");
6976   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
6977     doForAllOpcodes(I, [&](ScheduleData *SD) {
6978       assert(isInSchedulingRegion(SD) &&
6979              "ScheduleData not in scheduling region");
6980       SD->IsScheduled = false;
6981       SD->resetUnscheduledDeps();
6982     });
6983   }
6984   ReadyInsts.clear();
6985 }
6986 
6987 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
6988   if (!BS->ScheduleStart)
6989     return;
6990 
6991   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
6992 
6993   BS->resetSchedule();
6994 
6995   // For the real scheduling we use a more sophisticated ready-list: it is
6996   // sorted by the original instruction location. This lets the final schedule
6997   // be as  close as possible to the original instruction order.
6998   struct ScheduleDataCompare {
6999     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7000       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7001     }
7002   };
7003   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7004 
7005   // Ensure that all dependency data is updated and fill the ready-list with
7006   // initial instructions.
7007   int Idx = 0;
7008   int NumToSchedule = 0;
7009   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7010        I = I->getNextNode()) {
7011     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7012       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7013               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7014              "scheduler and vectorizer bundle mismatch");
7015       SD->FirstInBundle->SchedulingPriority = Idx++;
7016       if (SD->isSchedulingEntity()) {
7017         BS->calculateDependencies(SD, false, this);
7018         NumToSchedule++;
7019       }
7020     });
7021   }
7022   BS->initialFillReadyList(ReadyInsts);
7023 
7024   Instruction *LastScheduledInst = BS->ScheduleEnd;
7025 
7026   // Do the "real" scheduling.
7027   while (!ReadyInsts.empty()) {
7028     ScheduleData *picked = *ReadyInsts.begin();
7029     ReadyInsts.erase(ReadyInsts.begin());
7030 
7031     // Move the scheduled instruction(s) to their dedicated places, if not
7032     // there yet.
7033     ScheduleData *BundleMember = picked;
7034     while (BundleMember) {
7035       Instruction *pickedInst = BundleMember->Inst;
7036       if (pickedInst->getNextNode() != LastScheduledInst) {
7037         BS->BB->getInstList().remove(pickedInst);
7038         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
7039                                      pickedInst);
7040       }
7041       LastScheduledInst = pickedInst;
7042       BundleMember = BundleMember->NextInBundle;
7043     }
7044 
7045     BS->schedule(picked, ReadyInsts);
7046     NumToSchedule--;
7047   }
7048   assert(NumToSchedule == 0 && "could not schedule all instructions");
7049 
7050   // Avoid duplicate scheduling of the block.
7051   BS->ScheduleStart = nullptr;
7052 }
7053 
7054 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7055   // If V is a store, just return the width of the stored value (or value
7056   // truncated just before storing) without traversing the expression tree.
7057   // This is the common case.
7058   if (auto *Store = dyn_cast<StoreInst>(V)) {
7059     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7060       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7061     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7062   }
7063 
7064   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7065     return getVectorElementSize(IEI->getOperand(1));
7066 
7067   auto E = InstrElementSize.find(V);
7068   if (E != InstrElementSize.end())
7069     return E->second;
7070 
7071   // If V is not a store, we can traverse the expression tree to find loads
7072   // that feed it. The type of the loaded value may indicate a more suitable
7073   // width than V's type. We want to base the vector element size on the width
7074   // of memory operations where possible.
7075   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7076   SmallPtrSet<Instruction *, 16> Visited;
7077   if (auto *I = dyn_cast<Instruction>(V)) {
7078     Worklist.emplace_back(I, I->getParent());
7079     Visited.insert(I);
7080   }
7081 
7082   // Traverse the expression tree in bottom-up order looking for loads. If we
7083   // encounter an instruction we don't yet handle, we give up.
7084   auto Width = 0u;
7085   while (!Worklist.empty()) {
7086     Instruction *I;
7087     BasicBlock *Parent;
7088     std::tie(I, Parent) = Worklist.pop_back_val();
7089 
7090     // We should only be looking at scalar instructions here. If the current
7091     // instruction has a vector type, skip.
7092     auto *Ty = I->getType();
7093     if (isa<VectorType>(Ty))
7094       continue;
7095 
7096     // If the current instruction is a load, update MaxWidth to reflect the
7097     // width of the loaded value.
7098     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7099         isa<ExtractValueInst>(I))
7100       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7101 
7102     // Otherwise, we need to visit the operands of the instruction. We only
7103     // handle the interesting cases from buildTree here. If an operand is an
7104     // instruction we haven't yet visited and from the same basic block as the
7105     // user or the use is a PHI node, we add it to the worklist.
7106     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7107              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7108              isa<UnaryOperator>(I)) {
7109       for (Use &U : I->operands())
7110         if (auto *J = dyn_cast<Instruction>(U.get()))
7111           if (Visited.insert(J).second &&
7112               (isa<PHINode>(I) || J->getParent() == Parent))
7113             Worklist.emplace_back(J, J->getParent());
7114     } else {
7115       break;
7116     }
7117   }
7118 
7119   // If we didn't encounter a memory access in the expression tree, or if we
7120   // gave up for some reason, just return the width of V. Otherwise, return the
7121   // maximum width we found.
7122   if (!Width) {
7123     if (auto *CI = dyn_cast<CmpInst>(V))
7124       V = CI->getOperand(0);
7125     Width = DL->getTypeSizeInBits(V->getType());
7126   }
7127 
7128   for (Instruction *I : Visited)
7129     InstrElementSize[I] = Width;
7130 
7131   return Width;
7132 }
7133 
7134 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7135 // smaller type with a truncation. We collect the values that will be demoted
7136 // in ToDemote and additional roots that require investigating in Roots.
7137 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7138                                   SmallVectorImpl<Value *> &ToDemote,
7139                                   SmallVectorImpl<Value *> &Roots) {
7140   // We can always demote constants.
7141   if (isa<Constant>(V)) {
7142     ToDemote.push_back(V);
7143     return true;
7144   }
7145 
7146   // If the value is not an instruction in the expression with only one use, it
7147   // cannot be demoted.
7148   auto *I = dyn_cast<Instruction>(V);
7149   if (!I || !I->hasOneUse() || !Expr.count(I))
7150     return false;
7151 
7152   switch (I->getOpcode()) {
7153 
7154   // We can always demote truncations and extensions. Since truncations can
7155   // seed additional demotion, we save the truncated value.
7156   case Instruction::Trunc:
7157     Roots.push_back(I->getOperand(0));
7158     break;
7159   case Instruction::ZExt:
7160   case Instruction::SExt:
7161     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7162         isa<InsertElementInst>(I->getOperand(0)))
7163       return false;
7164     break;
7165 
7166   // We can demote certain binary operations if we can demote both of their
7167   // operands.
7168   case Instruction::Add:
7169   case Instruction::Sub:
7170   case Instruction::Mul:
7171   case Instruction::And:
7172   case Instruction::Or:
7173   case Instruction::Xor:
7174     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7175         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7176       return false;
7177     break;
7178 
7179   // We can demote selects if we can demote their true and false values.
7180   case Instruction::Select: {
7181     SelectInst *SI = cast<SelectInst>(I);
7182     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7183         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7184       return false;
7185     break;
7186   }
7187 
7188   // We can demote phis if we can demote all their incoming operands. Note that
7189   // we don't need to worry about cycles since we ensure single use above.
7190   case Instruction::PHI: {
7191     PHINode *PN = cast<PHINode>(I);
7192     for (Value *IncValue : PN->incoming_values())
7193       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7194         return false;
7195     break;
7196   }
7197 
7198   // Otherwise, conservatively give up.
7199   default:
7200     return false;
7201   }
7202 
7203   // Record the value that we can demote.
7204   ToDemote.push_back(V);
7205   return true;
7206 }
7207 
7208 void BoUpSLP::computeMinimumValueSizes() {
7209   // If there are no external uses, the expression tree must be rooted by a
7210   // store. We can't demote in-memory values, so there is nothing to do here.
7211   if (ExternalUses.empty())
7212     return;
7213 
7214   // We only attempt to truncate integer expressions.
7215   auto &TreeRoot = VectorizableTree[0]->Scalars;
7216   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
7217   if (!TreeRootIT)
7218     return;
7219 
7220   // If the expression is not rooted by a store, these roots should have
7221   // external uses. We will rely on InstCombine to rewrite the expression in
7222   // the narrower type. However, InstCombine only rewrites single-use values.
7223   // This means that if a tree entry other than a root is used externally, it
7224   // must have multiple uses and InstCombine will not rewrite it. The code
7225   // below ensures that only the roots are used externally.
7226   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
7227   for (auto &EU : ExternalUses)
7228     if (!Expr.erase(EU.Scalar))
7229       return;
7230   if (!Expr.empty())
7231     return;
7232 
7233   // Collect the scalar values of the vectorizable expression. We will use this
7234   // context to determine which values can be demoted. If we see a truncation,
7235   // we mark it as seeding another demotion.
7236   for (auto &EntryPtr : VectorizableTree)
7237     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
7238 
7239   // Ensure the roots of the vectorizable tree don't form a cycle. They must
7240   // have a single external user that is not in the vectorizable tree.
7241   for (auto *Root : TreeRoot)
7242     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
7243       return;
7244 
7245   // Conservatively determine if we can actually truncate the roots of the
7246   // expression. Collect the values that can be demoted in ToDemote and
7247   // additional roots that require investigating in Roots.
7248   SmallVector<Value *, 32> ToDemote;
7249   SmallVector<Value *, 4> Roots;
7250   for (auto *Root : TreeRoot)
7251     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
7252       return;
7253 
7254   // The maximum bit width required to represent all the values that can be
7255   // demoted without loss of precision. It would be safe to truncate the roots
7256   // of the expression to this width.
7257   auto MaxBitWidth = 8u;
7258 
7259   // We first check if all the bits of the roots are demanded. If they're not,
7260   // we can truncate the roots to this narrower type.
7261   for (auto *Root : TreeRoot) {
7262     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
7263     MaxBitWidth = std::max<unsigned>(
7264         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
7265   }
7266 
7267   // True if the roots can be zero-extended back to their original type, rather
7268   // than sign-extended. We know that if the leading bits are not demanded, we
7269   // can safely zero-extend. So we initialize IsKnownPositive to True.
7270   bool IsKnownPositive = true;
7271 
7272   // If all the bits of the roots are demanded, we can try a little harder to
7273   // compute a narrower type. This can happen, for example, if the roots are
7274   // getelementptr indices. InstCombine promotes these indices to the pointer
7275   // width. Thus, all their bits are technically demanded even though the
7276   // address computation might be vectorized in a smaller type.
7277   //
7278   // We start by looking at each entry that can be demoted. We compute the
7279   // maximum bit width required to store the scalar by using ValueTracking to
7280   // compute the number of high-order bits we can truncate.
7281   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
7282       llvm::all_of(TreeRoot, [](Value *R) {
7283         assert(R->hasOneUse() && "Root should have only one use!");
7284         return isa<GetElementPtrInst>(R->user_back());
7285       })) {
7286     MaxBitWidth = 8u;
7287 
7288     // Determine if the sign bit of all the roots is known to be zero. If not,
7289     // IsKnownPositive is set to False.
7290     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
7291       KnownBits Known = computeKnownBits(R, *DL);
7292       return Known.isNonNegative();
7293     });
7294 
7295     // Determine the maximum number of bits required to store the scalar
7296     // values.
7297     for (auto *Scalar : ToDemote) {
7298       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
7299       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
7300       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
7301     }
7302 
7303     // If we can't prove that the sign bit is zero, we must add one to the
7304     // maximum bit width to account for the unknown sign bit. This preserves
7305     // the existing sign bit so we can safely sign-extend the root back to the
7306     // original type. Otherwise, if we know the sign bit is zero, we will
7307     // zero-extend the root instead.
7308     //
7309     // FIXME: This is somewhat suboptimal, as there will be cases where adding
7310     //        one to the maximum bit width will yield a larger-than-necessary
7311     //        type. In general, we need to add an extra bit only if we can't
7312     //        prove that the upper bit of the original type is equal to the
7313     //        upper bit of the proposed smaller type. If these two bits are the
7314     //        same (either zero or one) we know that sign-extending from the
7315     //        smaller type will result in the same value. Here, since we can't
7316     //        yet prove this, we are just making the proposed smaller type
7317     //        larger to ensure correctness.
7318     if (!IsKnownPositive)
7319       ++MaxBitWidth;
7320   }
7321 
7322   // Round MaxBitWidth up to the next power-of-two.
7323   if (!isPowerOf2_64(MaxBitWidth))
7324     MaxBitWidth = NextPowerOf2(MaxBitWidth);
7325 
7326   // If the maximum bit width we compute is less than the with of the roots'
7327   // type, we can proceed with the narrowing. Otherwise, do nothing.
7328   if (MaxBitWidth >= TreeRootIT->getBitWidth())
7329     return;
7330 
7331   // If we can truncate the root, we must collect additional values that might
7332   // be demoted as a result. That is, those seeded by truncations we will
7333   // modify.
7334   while (!Roots.empty())
7335     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
7336 
7337   // Finally, map the values we can demote to the maximum bit with we computed.
7338   for (auto *Scalar : ToDemote)
7339     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
7340 }
7341 
7342 namespace {
7343 
7344 /// The SLPVectorizer Pass.
7345 struct SLPVectorizer : public FunctionPass {
7346   SLPVectorizerPass Impl;
7347 
7348   /// Pass identification, replacement for typeid
7349   static char ID;
7350 
7351   explicit SLPVectorizer() : FunctionPass(ID) {
7352     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
7353   }
7354 
7355   bool doInitialization(Module &M) override {
7356     return false;
7357   }
7358 
7359   bool runOnFunction(Function &F) override {
7360     if (skipFunction(F))
7361       return false;
7362 
7363     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
7364     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
7365     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7366     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
7367     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
7368     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7369     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7370     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
7371     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
7372     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
7373 
7374     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7375   }
7376 
7377   void getAnalysisUsage(AnalysisUsage &AU) const override {
7378     FunctionPass::getAnalysisUsage(AU);
7379     AU.addRequired<AssumptionCacheTracker>();
7380     AU.addRequired<ScalarEvolutionWrapperPass>();
7381     AU.addRequired<AAResultsWrapperPass>();
7382     AU.addRequired<TargetTransformInfoWrapperPass>();
7383     AU.addRequired<LoopInfoWrapperPass>();
7384     AU.addRequired<DominatorTreeWrapperPass>();
7385     AU.addRequired<DemandedBitsWrapperPass>();
7386     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
7387     AU.addRequired<InjectTLIMappingsLegacy>();
7388     AU.addPreserved<LoopInfoWrapperPass>();
7389     AU.addPreserved<DominatorTreeWrapperPass>();
7390     AU.addPreserved<AAResultsWrapperPass>();
7391     AU.addPreserved<GlobalsAAWrapperPass>();
7392     AU.setPreservesCFG();
7393   }
7394 };
7395 
7396 } // end anonymous namespace
7397 
7398 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
7399   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
7400   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
7401   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
7402   auto *AA = &AM.getResult<AAManager>(F);
7403   auto *LI = &AM.getResult<LoopAnalysis>(F);
7404   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
7405   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
7406   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
7407   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
7408 
7409   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7410   if (!Changed)
7411     return PreservedAnalyses::all();
7412 
7413   PreservedAnalyses PA;
7414   PA.preserveSet<CFGAnalyses>();
7415   return PA;
7416 }
7417 
7418 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
7419                                 TargetTransformInfo *TTI_,
7420                                 TargetLibraryInfo *TLI_, AAResults *AA_,
7421                                 LoopInfo *LI_, DominatorTree *DT_,
7422                                 AssumptionCache *AC_, DemandedBits *DB_,
7423                                 OptimizationRemarkEmitter *ORE_) {
7424   if (!RunSLPVectorization)
7425     return false;
7426   SE = SE_;
7427   TTI = TTI_;
7428   TLI = TLI_;
7429   AA = AA_;
7430   LI = LI_;
7431   DT = DT_;
7432   AC = AC_;
7433   DB = DB_;
7434   DL = &F.getParent()->getDataLayout();
7435 
7436   Stores.clear();
7437   GEPs.clear();
7438   bool Changed = false;
7439 
7440   // If the target claims to have no vector registers don't attempt
7441   // vectorization.
7442   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
7443     return false;
7444 
7445   // Don't vectorize when the attribute NoImplicitFloat is used.
7446   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
7447     return false;
7448 
7449   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
7450 
7451   // Use the bottom up slp vectorizer to construct chains that start with
7452   // store instructions.
7453   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
7454 
7455   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
7456   // delete instructions.
7457 
7458   // Update DFS numbers now so that we can use them for ordering.
7459   DT->updateDFSNumbers();
7460 
7461   // Scan the blocks in the function in post order.
7462   for (auto BB : post_order(&F.getEntryBlock())) {
7463     collectSeedInstructions(BB);
7464 
7465     // Vectorize trees that end at stores.
7466     if (!Stores.empty()) {
7467       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
7468                         << " underlying objects.\n");
7469       Changed |= vectorizeStoreChains(R);
7470     }
7471 
7472     // Vectorize trees that end at reductions.
7473     Changed |= vectorizeChainsInBlock(BB, R);
7474 
7475     // Vectorize the index computations of getelementptr instructions. This
7476     // is primarily intended to catch gather-like idioms ending at
7477     // non-consecutive loads.
7478     if (!GEPs.empty()) {
7479       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
7480                         << " underlying objects.\n");
7481       Changed |= vectorizeGEPIndices(BB, R);
7482     }
7483   }
7484 
7485   if (Changed) {
7486     R.optimizeGatherSequence();
7487     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
7488   }
7489   return Changed;
7490 }
7491 
7492 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
7493                                             unsigned Idx) {
7494   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
7495                     << "\n");
7496   const unsigned Sz = R.getVectorElementSize(Chain[0]);
7497   const unsigned MinVF = R.getMinVecRegSize() / Sz;
7498   unsigned VF = Chain.size();
7499 
7500   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
7501     return false;
7502 
7503   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
7504                     << "\n");
7505 
7506   R.buildTree(Chain);
7507   if (R.isTreeTinyAndNotFullyVectorizable())
7508     return false;
7509   if (R.isLoadCombineCandidate())
7510     return false;
7511   R.reorderTopToBottom();
7512   R.reorderBottomToTop();
7513   R.buildExternalUses();
7514 
7515   R.computeMinimumValueSizes();
7516 
7517   InstructionCost Cost = R.getTreeCost();
7518 
7519   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
7520   if (Cost < -SLPCostThreshold) {
7521     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
7522 
7523     using namespace ore;
7524 
7525     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
7526                                         cast<StoreInst>(Chain[0]))
7527                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
7528                      << " and with tree size "
7529                      << NV("TreeSize", R.getTreeSize()));
7530 
7531     R.vectorizeTree();
7532     return true;
7533   }
7534 
7535   return false;
7536 }
7537 
7538 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
7539                                         BoUpSLP &R) {
7540   // We may run into multiple chains that merge into a single chain. We mark the
7541   // stores that we vectorized so that we don't visit the same store twice.
7542   BoUpSLP::ValueSet VectorizedStores;
7543   bool Changed = false;
7544 
7545   int E = Stores.size();
7546   SmallBitVector Tails(E, false);
7547   int MaxIter = MaxStoreLookup.getValue();
7548   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
7549       E, std::make_pair(E, INT_MAX));
7550   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
7551   int IterCnt;
7552   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
7553                                   &CheckedPairs,
7554                                   &ConsecutiveChain](int K, int Idx) {
7555     if (IterCnt >= MaxIter)
7556       return true;
7557     if (CheckedPairs[Idx].test(K))
7558       return ConsecutiveChain[K].second == 1 &&
7559              ConsecutiveChain[K].first == Idx;
7560     ++IterCnt;
7561     CheckedPairs[Idx].set(K);
7562     CheckedPairs[K].set(Idx);
7563     Optional<int> Diff = getPointersDiff(
7564         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
7565         Stores[Idx]->getValueOperand()->getType(),
7566         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
7567     if (!Diff || *Diff == 0)
7568       return false;
7569     int Val = *Diff;
7570     if (Val < 0) {
7571       if (ConsecutiveChain[Idx].second > -Val) {
7572         Tails.set(K);
7573         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
7574       }
7575       return false;
7576     }
7577     if (ConsecutiveChain[K].second <= Val)
7578       return false;
7579 
7580     Tails.set(Idx);
7581     ConsecutiveChain[K] = std::make_pair(Idx, Val);
7582     return Val == 1;
7583   };
7584   // Do a quadratic search on all of the given stores in reverse order and find
7585   // all of the pairs of stores that follow each other.
7586   for (int Idx = E - 1; Idx >= 0; --Idx) {
7587     // If a store has multiple consecutive store candidates, search according
7588     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
7589     // This is because usually pairing with immediate succeeding or preceding
7590     // candidate create the best chance to find slp vectorization opportunity.
7591     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
7592     IterCnt = 0;
7593     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
7594       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
7595           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
7596         break;
7597   }
7598 
7599   // Tracks if we tried to vectorize stores starting from the given tail
7600   // already.
7601   SmallBitVector TriedTails(E, false);
7602   // For stores that start but don't end a link in the chain:
7603   for (int Cnt = E; Cnt > 0; --Cnt) {
7604     int I = Cnt - 1;
7605     if (ConsecutiveChain[I].first == E || Tails.test(I))
7606       continue;
7607     // We found a store instr that starts a chain. Now follow the chain and try
7608     // to vectorize it.
7609     BoUpSLP::ValueList Operands;
7610     // Collect the chain into a list.
7611     while (I != E && !VectorizedStores.count(Stores[I])) {
7612       Operands.push_back(Stores[I]);
7613       Tails.set(I);
7614       if (ConsecutiveChain[I].second != 1) {
7615         // Mark the new end in the chain and go back, if required. It might be
7616         // required if the original stores come in reversed order, for example.
7617         if (ConsecutiveChain[I].first != E &&
7618             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
7619             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
7620           TriedTails.set(I);
7621           Tails.reset(ConsecutiveChain[I].first);
7622           if (Cnt < ConsecutiveChain[I].first + 2)
7623             Cnt = ConsecutiveChain[I].first + 2;
7624         }
7625         break;
7626       }
7627       // Move to the next value in the chain.
7628       I = ConsecutiveChain[I].first;
7629     }
7630     assert(!Operands.empty() && "Expected non-empty list of stores.");
7631 
7632     unsigned MaxVecRegSize = R.getMaxVecRegSize();
7633     unsigned EltSize = R.getVectorElementSize(Operands[0]);
7634     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
7635 
7636     unsigned MinVF = R.getMinVF(EltSize);
7637     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
7638                               MaxElts);
7639 
7640     // FIXME: Is division-by-2 the correct step? Should we assert that the
7641     // register size is a power-of-2?
7642     unsigned StartIdx = 0;
7643     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
7644       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
7645         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
7646         if (!VectorizedStores.count(Slice.front()) &&
7647             !VectorizedStores.count(Slice.back()) &&
7648             vectorizeStoreChain(Slice, R, Cnt)) {
7649           // Mark the vectorized stores so that we don't vectorize them again.
7650           VectorizedStores.insert(Slice.begin(), Slice.end());
7651           Changed = true;
7652           // If we vectorized initial block, no need to try to vectorize it
7653           // again.
7654           if (Cnt == StartIdx)
7655             StartIdx += Size;
7656           Cnt += Size;
7657           continue;
7658         }
7659         ++Cnt;
7660       }
7661       // Check if the whole array was vectorized already - exit.
7662       if (StartIdx >= Operands.size())
7663         break;
7664     }
7665   }
7666 
7667   return Changed;
7668 }
7669 
7670 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
7671   // Initialize the collections. We will make a single pass over the block.
7672   Stores.clear();
7673   GEPs.clear();
7674 
7675   // Visit the store and getelementptr instructions in BB and organize them in
7676   // Stores and GEPs according to the underlying objects of their pointer
7677   // operands.
7678   for (Instruction &I : *BB) {
7679     // Ignore store instructions that are volatile or have a pointer operand
7680     // that doesn't point to a scalar type.
7681     if (auto *SI = dyn_cast<StoreInst>(&I)) {
7682       if (!SI->isSimple())
7683         continue;
7684       if (!isValidElementType(SI->getValueOperand()->getType()))
7685         continue;
7686       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
7687     }
7688 
7689     // Ignore getelementptr instructions that have more than one index, a
7690     // constant index, or a pointer operand that doesn't point to a scalar
7691     // type.
7692     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
7693       auto Idx = GEP->idx_begin()->get();
7694       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
7695         continue;
7696       if (!isValidElementType(Idx->getType()))
7697         continue;
7698       if (GEP->getType()->isVectorTy())
7699         continue;
7700       GEPs[GEP->getPointerOperand()].push_back(GEP);
7701     }
7702   }
7703 }
7704 
7705 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
7706   if (!A || !B)
7707     return false;
7708   Value *VL[] = {A, B};
7709   return tryToVectorizeList(VL, R);
7710 }
7711 
7712 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
7713                                            bool LimitForRegisterSize) {
7714   if (VL.size() < 2)
7715     return false;
7716 
7717   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
7718                     << VL.size() << ".\n");
7719 
7720   // Check that all of the parts are instructions of the same type,
7721   // we permit an alternate opcode via InstructionsState.
7722   InstructionsState S = getSameOpcode(VL);
7723   if (!S.getOpcode())
7724     return false;
7725 
7726   Instruction *I0 = cast<Instruction>(S.OpValue);
7727   // Make sure invalid types (including vector type) are rejected before
7728   // determining vectorization factor for scalar instructions.
7729   for (Value *V : VL) {
7730     Type *Ty = V->getType();
7731     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
7732       // NOTE: the following will give user internal llvm type name, which may
7733       // not be useful.
7734       R.getORE()->emit([&]() {
7735         std::string type_str;
7736         llvm::raw_string_ostream rso(type_str);
7737         Ty->print(rso);
7738         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
7739                << "Cannot SLP vectorize list: type "
7740                << rso.str() + " is unsupported by vectorizer";
7741       });
7742       return false;
7743     }
7744   }
7745 
7746   unsigned Sz = R.getVectorElementSize(I0);
7747   unsigned MinVF = R.getMinVF(Sz);
7748   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
7749   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
7750   if (MaxVF < 2) {
7751     R.getORE()->emit([&]() {
7752       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
7753              << "Cannot SLP vectorize list: vectorization factor "
7754              << "less than 2 is not supported";
7755     });
7756     return false;
7757   }
7758 
7759   bool Changed = false;
7760   bool CandidateFound = false;
7761   InstructionCost MinCost = SLPCostThreshold.getValue();
7762   Type *ScalarTy = VL[0]->getType();
7763   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
7764     ScalarTy = IE->getOperand(1)->getType();
7765 
7766   unsigned NextInst = 0, MaxInst = VL.size();
7767   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
7768     // No actual vectorization should happen, if number of parts is the same as
7769     // provided vectorization factor (i.e. the scalar type is used for vector
7770     // code during codegen).
7771     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
7772     if (TTI->getNumberOfParts(VecTy) == VF)
7773       continue;
7774     for (unsigned I = NextInst; I < MaxInst; ++I) {
7775       unsigned OpsWidth = 0;
7776 
7777       if (I + VF > MaxInst)
7778         OpsWidth = MaxInst - I;
7779       else
7780         OpsWidth = VF;
7781 
7782       if (!isPowerOf2_32(OpsWidth))
7783         continue;
7784 
7785       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
7786           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
7787         break;
7788 
7789       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
7790       // Check that a previous iteration of this loop did not delete the Value.
7791       if (llvm::any_of(Ops, [&R](Value *V) {
7792             auto *I = dyn_cast<Instruction>(V);
7793             return I && R.isDeleted(I);
7794           }))
7795         continue;
7796 
7797       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
7798                         << "\n");
7799 
7800       R.buildTree(Ops);
7801       if (R.isTreeTinyAndNotFullyVectorizable())
7802         continue;
7803       R.reorderTopToBottom();
7804       R.reorderBottomToTop();
7805       R.buildExternalUses();
7806 
7807       R.computeMinimumValueSizes();
7808       InstructionCost Cost = R.getTreeCost();
7809       CandidateFound = true;
7810       MinCost = std::min(MinCost, Cost);
7811 
7812       if (Cost < -SLPCostThreshold) {
7813         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
7814         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
7815                                                     cast<Instruction>(Ops[0]))
7816                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
7817                                  << " and with tree size "
7818                                  << ore::NV("TreeSize", R.getTreeSize()));
7819 
7820         R.vectorizeTree();
7821         // Move to the next bundle.
7822         I += VF - 1;
7823         NextInst = I + 1;
7824         Changed = true;
7825       }
7826     }
7827   }
7828 
7829   if (!Changed && CandidateFound) {
7830     R.getORE()->emit([&]() {
7831       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
7832              << "List vectorization was possible but not beneficial with cost "
7833              << ore::NV("Cost", MinCost) << " >= "
7834              << ore::NV("Treshold", -SLPCostThreshold);
7835     });
7836   } else if (!Changed) {
7837     R.getORE()->emit([&]() {
7838       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
7839              << "Cannot SLP vectorize list: vectorization was impossible"
7840              << " with available vectorization factors";
7841     });
7842   }
7843   return Changed;
7844 }
7845 
7846 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
7847   if (!I)
7848     return false;
7849 
7850   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
7851     return false;
7852 
7853   Value *P = I->getParent();
7854 
7855   // Vectorize in current basic block only.
7856   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
7857   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
7858   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
7859     return false;
7860 
7861   // Try to vectorize V.
7862   if (tryToVectorizePair(Op0, Op1, R))
7863     return true;
7864 
7865   auto *A = dyn_cast<BinaryOperator>(Op0);
7866   auto *B = dyn_cast<BinaryOperator>(Op1);
7867   // Try to skip B.
7868   if (B && B->hasOneUse()) {
7869     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
7870     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
7871     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
7872       return true;
7873     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
7874       return true;
7875   }
7876 
7877   // Try to skip A.
7878   if (A && A->hasOneUse()) {
7879     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
7880     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
7881     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
7882       return true;
7883     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
7884       return true;
7885   }
7886   return false;
7887 }
7888 
7889 namespace {
7890 
7891 /// Model horizontal reductions.
7892 ///
7893 /// A horizontal reduction is a tree of reduction instructions that has values
7894 /// that can be put into a vector as its leaves. For example:
7895 ///
7896 /// mul mul mul mul
7897 ///  \  /    \  /
7898 ///   +       +
7899 ///    \     /
7900 ///       +
7901 /// This tree has "mul" as its leaf values and "+" as its reduction
7902 /// instructions. A reduction can feed into a store or a binary operation
7903 /// feeding a phi.
7904 ///    ...
7905 ///    \  /
7906 ///     +
7907 ///     |
7908 ///  phi +=
7909 ///
7910 ///  Or:
7911 ///    ...
7912 ///    \  /
7913 ///     +
7914 ///     |
7915 ///   *p =
7916 ///
7917 class HorizontalReduction {
7918   using ReductionOpsType = SmallVector<Value *, 16>;
7919   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
7920   ReductionOpsListType ReductionOps;
7921   SmallVector<Value *, 32> ReducedVals;
7922   // Use map vector to make stable output.
7923   MapVector<Instruction *, Value *> ExtraArgs;
7924   WeakTrackingVH ReductionRoot;
7925   /// The type of reduction operation.
7926   RecurKind RdxKind;
7927 
7928   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
7929 
7930   static bool isCmpSelMinMax(Instruction *I) {
7931     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
7932            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
7933   }
7934 
7935   // And/or are potentially poison-safe logical patterns like:
7936   // select x, y, false
7937   // select x, true, y
7938   static bool isBoolLogicOp(Instruction *I) {
7939     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
7940            match(I, m_LogicalOr(m_Value(), m_Value()));
7941   }
7942 
7943   /// Checks if instruction is associative and can be vectorized.
7944   static bool isVectorizable(RecurKind Kind, Instruction *I) {
7945     if (Kind == RecurKind::None)
7946       return false;
7947 
7948     // Integer ops that map to select instructions or intrinsics are fine.
7949     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
7950         isBoolLogicOp(I))
7951       return true;
7952 
7953     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
7954       // FP min/max are associative except for NaN and -0.0. We do not
7955       // have to rule out -0.0 here because the intrinsic semantics do not
7956       // specify a fixed result for it.
7957       return I->getFastMathFlags().noNaNs();
7958     }
7959 
7960     return I->isAssociative();
7961   }
7962 
7963   static Value *getRdxOperand(Instruction *I, unsigned Index) {
7964     // Poison-safe 'or' takes the form: select X, true, Y
7965     // To make that work with the normal operand processing, we skip the
7966     // true value operand.
7967     // TODO: Change the code and data structures to handle this without a hack.
7968     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
7969       return I->getOperand(2);
7970     return I->getOperand(Index);
7971   }
7972 
7973   /// Checks if the ParentStackElem.first should be marked as a reduction
7974   /// operation with an extra argument or as extra argument itself.
7975   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
7976                     Value *ExtraArg) {
7977     if (ExtraArgs.count(ParentStackElem.first)) {
7978       ExtraArgs[ParentStackElem.first] = nullptr;
7979       // We ran into something like:
7980       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
7981       // The whole ParentStackElem.first should be considered as an extra value
7982       // in this case.
7983       // Do not perform analysis of remaining operands of ParentStackElem.first
7984       // instruction, this whole instruction is an extra argument.
7985       ParentStackElem.second = INVALID_OPERAND_INDEX;
7986     } else {
7987       // We ran into something like:
7988       // ParentStackElem.first += ... + ExtraArg + ...
7989       ExtraArgs[ParentStackElem.first] = ExtraArg;
7990     }
7991   }
7992 
7993   /// Creates reduction operation with the current opcode.
7994   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
7995                          Value *RHS, const Twine &Name, bool UseSelect) {
7996     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
7997     switch (Kind) {
7998     case RecurKind::Add:
7999     case RecurKind::Mul:
8000     case RecurKind::Or:
8001     case RecurKind::And:
8002     case RecurKind::Xor:
8003     case RecurKind::FAdd:
8004     case RecurKind::FMul:
8005       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8006                                  Name);
8007     case RecurKind::FMax:
8008       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8009     case RecurKind::FMin:
8010       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8011     case RecurKind::SMax:
8012       if (UseSelect) {
8013         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8014         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8015       }
8016       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8017     case RecurKind::SMin:
8018       if (UseSelect) {
8019         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8020         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8021       }
8022       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8023     case RecurKind::UMax:
8024       if (UseSelect) {
8025         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8026         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8027       }
8028       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8029     case RecurKind::UMin:
8030       if (UseSelect) {
8031         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8032         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8033       }
8034       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8035     default:
8036       llvm_unreachable("Unknown reduction operation.");
8037     }
8038   }
8039 
8040   /// Creates reduction operation with the current opcode with the IR flags
8041   /// from \p ReductionOps.
8042   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8043                          Value *RHS, const Twine &Name,
8044                          const ReductionOpsListType &ReductionOps) {
8045     bool UseSelect = ReductionOps.size() == 2;
8046     assert((!UseSelect || isa<SelectInst>(ReductionOps[1][0])) &&
8047            "Expected cmp + select pairs for reduction");
8048     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8049     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8050       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8051         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8052         propagateIRFlags(Op, ReductionOps[1]);
8053         return Op;
8054       }
8055     }
8056     propagateIRFlags(Op, ReductionOps[0]);
8057     return Op;
8058   }
8059 
8060   /// Creates reduction operation with the current opcode with the IR flags
8061   /// from \p I.
8062   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8063                          Value *RHS, const Twine &Name, Instruction *I) {
8064     auto *SelI = dyn_cast<SelectInst>(I);
8065     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8066     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8067       if (auto *Sel = dyn_cast<SelectInst>(Op))
8068         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8069     }
8070     propagateIRFlags(Op, I);
8071     return Op;
8072   }
8073 
8074   static RecurKind getRdxKind(Instruction *I) {
8075     assert(I && "Expected instruction for reduction matching");
8076     TargetTransformInfo::ReductionFlags RdxFlags;
8077     if (match(I, m_Add(m_Value(), m_Value())))
8078       return RecurKind::Add;
8079     if (match(I, m_Mul(m_Value(), m_Value())))
8080       return RecurKind::Mul;
8081     if (match(I, m_And(m_Value(), m_Value())) ||
8082         match(I, m_LogicalAnd(m_Value(), m_Value())))
8083       return RecurKind::And;
8084     if (match(I, m_Or(m_Value(), m_Value())) ||
8085         match(I, m_LogicalOr(m_Value(), m_Value())))
8086       return RecurKind::Or;
8087     if (match(I, m_Xor(m_Value(), m_Value())))
8088       return RecurKind::Xor;
8089     if (match(I, m_FAdd(m_Value(), m_Value())))
8090       return RecurKind::FAdd;
8091     if (match(I, m_FMul(m_Value(), m_Value())))
8092       return RecurKind::FMul;
8093 
8094     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8095       return RecurKind::FMax;
8096     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8097       return RecurKind::FMin;
8098 
8099     // This matches either cmp+select or intrinsics. SLP is expected to handle
8100     // either form.
8101     // TODO: If we are canonicalizing to intrinsics, we can remove several
8102     //       special-case paths that deal with selects.
8103     if (match(I, m_SMax(m_Value(), m_Value())))
8104       return RecurKind::SMax;
8105     if (match(I, m_SMin(m_Value(), m_Value())))
8106       return RecurKind::SMin;
8107     if (match(I, m_UMax(m_Value(), m_Value())))
8108       return RecurKind::UMax;
8109     if (match(I, m_UMin(m_Value(), m_Value())))
8110       return RecurKind::UMin;
8111 
8112     if (auto *Select = dyn_cast<SelectInst>(I)) {
8113       // Try harder: look for min/max pattern based on instructions producing
8114       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8115       // During the intermediate stages of SLP, it's very common to have
8116       // pattern like this (since optimizeGatherSequence is run only once
8117       // at the end):
8118       // %1 = extractelement <2 x i32> %a, i32 0
8119       // %2 = extractelement <2 x i32> %a, i32 1
8120       // %cond = icmp sgt i32 %1, %2
8121       // %3 = extractelement <2 x i32> %a, i32 0
8122       // %4 = extractelement <2 x i32> %a, i32 1
8123       // %select = select i1 %cond, i32 %3, i32 %4
8124       CmpInst::Predicate Pred;
8125       Instruction *L1;
8126       Instruction *L2;
8127 
8128       Value *LHS = Select->getTrueValue();
8129       Value *RHS = Select->getFalseValue();
8130       Value *Cond = Select->getCondition();
8131 
8132       // TODO: Support inverse predicates.
8133       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8134         if (!isa<ExtractElementInst>(RHS) ||
8135             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8136           return RecurKind::None;
8137       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8138         if (!isa<ExtractElementInst>(LHS) ||
8139             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8140           return RecurKind::None;
8141       } else {
8142         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8143           return RecurKind::None;
8144         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8145             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8146             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8147           return RecurKind::None;
8148       }
8149 
8150       TargetTransformInfo::ReductionFlags RdxFlags;
8151       switch (Pred) {
8152       default:
8153         return RecurKind::None;
8154       case CmpInst::ICMP_SGT:
8155       case CmpInst::ICMP_SGE:
8156         return RecurKind::SMax;
8157       case CmpInst::ICMP_SLT:
8158       case CmpInst::ICMP_SLE:
8159         return RecurKind::SMin;
8160       case CmpInst::ICMP_UGT:
8161       case CmpInst::ICMP_UGE:
8162         return RecurKind::UMax;
8163       case CmpInst::ICMP_ULT:
8164       case CmpInst::ICMP_ULE:
8165         return RecurKind::UMin;
8166       }
8167     }
8168     return RecurKind::None;
8169   }
8170 
8171   /// Get the index of the first operand.
8172   static unsigned getFirstOperandIndex(Instruction *I) {
8173     return isCmpSelMinMax(I) ? 1 : 0;
8174   }
8175 
8176   /// Total number of operands in the reduction operation.
8177   static unsigned getNumberOfOperands(Instruction *I) {
8178     return isCmpSelMinMax(I) ? 3 : 2;
8179   }
8180 
8181   /// Checks if the instruction is in basic block \p BB.
8182   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8183   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8184     if (isCmpSelMinMax(I)) {
8185       auto *Sel = cast<SelectInst>(I);
8186       auto *Cmp = cast<Instruction>(Sel->getCondition());
8187       return Sel->getParent() == BB && Cmp->getParent() == BB;
8188     }
8189     return I->getParent() == BB;
8190   }
8191 
8192   /// Expected number of uses for reduction operations/reduced values.
8193   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
8194     if (IsCmpSelMinMax) {
8195       // SelectInst must be used twice while the condition op must have single
8196       // use only.
8197       if (auto *Sel = dyn_cast<SelectInst>(I))
8198         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
8199       return I->hasNUses(2);
8200     }
8201 
8202     // Arithmetic reduction operation must be used once only.
8203     return I->hasOneUse();
8204   }
8205 
8206   /// Initializes the list of reduction operations.
8207   void initReductionOps(Instruction *I) {
8208     if (isCmpSelMinMax(I))
8209       ReductionOps.assign(2, ReductionOpsType());
8210     else
8211       ReductionOps.assign(1, ReductionOpsType());
8212   }
8213 
8214   /// Add all reduction operations for the reduction instruction \p I.
8215   void addReductionOps(Instruction *I) {
8216     if (isCmpSelMinMax(I)) {
8217       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
8218       ReductionOps[1].emplace_back(I);
8219     } else {
8220       ReductionOps[0].emplace_back(I);
8221     }
8222   }
8223 
8224   static Value *getLHS(RecurKind Kind, Instruction *I) {
8225     if (Kind == RecurKind::None)
8226       return nullptr;
8227     return I->getOperand(getFirstOperandIndex(I));
8228   }
8229   static Value *getRHS(RecurKind Kind, Instruction *I) {
8230     if (Kind == RecurKind::None)
8231       return nullptr;
8232     return I->getOperand(getFirstOperandIndex(I) + 1);
8233   }
8234 
8235 public:
8236   HorizontalReduction() = default;
8237 
8238   /// Try to find a reduction tree.
8239   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
8240     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
8241            "Phi needs to use the binary operator");
8242     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
8243             isa<IntrinsicInst>(Inst)) &&
8244            "Expected binop, select, or intrinsic for reduction matching");
8245     RdxKind = getRdxKind(Inst);
8246 
8247     // We could have a initial reductions that is not an add.
8248     //  r *= v1 + v2 + v3 + v4
8249     // In such a case start looking for a tree rooted in the first '+'.
8250     if (Phi) {
8251       if (getLHS(RdxKind, Inst) == Phi) {
8252         Phi = nullptr;
8253         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
8254         if (!Inst)
8255           return false;
8256         RdxKind = getRdxKind(Inst);
8257       } else if (getRHS(RdxKind, Inst) == Phi) {
8258         Phi = nullptr;
8259         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
8260         if (!Inst)
8261           return false;
8262         RdxKind = getRdxKind(Inst);
8263       }
8264     }
8265 
8266     if (!isVectorizable(RdxKind, Inst))
8267       return false;
8268 
8269     // Analyze "regular" integer/FP types for reductions - no target-specific
8270     // types or pointers.
8271     Type *Ty = Inst->getType();
8272     if (!isValidElementType(Ty) || Ty->isPointerTy())
8273       return false;
8274 
8275     // Though the ultimate reduction may have multiple uses, its condition must
8276     // have only single use.
8277     if (auto *Sel = dyn_cast<SelectInst>(Inst))
8278       if (!Sel->getCondition()->hasOneUse())
8279         return false;
8280 
8281     ReductionRoot = Inst;
8282 
8283     // The opcode for leaf values that we perform a reduction on.
8284     // For example: load(x) + load(y) + load(z) + fptoui(w)
8285     // The leaf opcode for 'w' does not match, so we don't include it as a
8286     // potential candidate for the reduction.
8287     unsigned LeafOpcode = 0;
8288 
8289     // Post-order traverse the reduction tree starting at Inst. We only handle
8290     // true trees containing binary operators or selects.
8291     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
8292     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
8293     initReductionOps(Inst);
8294     while (!Stack.empty()) {
8295       Instruction *TreeN = Stack.back().first;
8296       unsigned EdgeToVisit = Stack.back().second++;
8297       const RecurKind TreeRdxKind = getRdxKind(TreeN);
8298       bool IsReducedValue = TreeRdxKind != RdxKind;
8299 
8300       // Postorder visit.
8301       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
8302         if (IsReducedValue)
8303           ReducedVals.push_back(TreeN);
8304         else {
8305           auto ExtraArgsIter = ExtraArgs.find(TreeN);
8306           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
8307             // Check if TreeN is an extra argument of its parent operation.
8308             if (Stack.size() <= 1) {
8309               // TreeN can't be an extra argument as it is a root reduction
8310               // operation.
8311               return false;
8312             }
8313             // Yes, TreeN is an extra argument, do not add it to a list of
8314             // reduction operations.
8315             // Stack[Stack.size() - 2] always points to the parent operation.
8316             markExtraArg(Stack[Stack.size() - 2], TreeN);
8317             ExtraArgs.erase(TreeN);
8318           } else
8319             addReductionOps(TreeN);
8320         }
8321         // Retract.
8322         Stack.pop_back();
8323         continue;
8324       }
8325 
8326       // Visit operands.
8327       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
8328       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
8329       if (!EdgeInst) {
8330         // Edge value is not a reduction instruction or a leaf instruction.
8331         // (It may be a constant, function argument, or something else.)
8332         markExtraArg(Stack.back(), EdgeVal);
8333         continue;
8334       }
8335       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
8336       // Continue analysis if the next operand is a reduction operation or
8337       // (possibly) a leaf value. If the leaf value opcode is not set,
8338       // the first met operation != reduction operation is considered as the
8339       // leaf opcode.
8340       // Only handle trees in the current basic block.
8341       // Each tree node needs to have minimal number of users except for the
8342       // ultimate reduction.
8343       const bool IsRdxInst = EdgeRdxKind == RdxKind;
8344       if (EdgeInst != Phi && EdgeInst != Inst &&
8345           hasSameParent(EdgeInst, Inst->getParent()) &&
8346           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
8347           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
8348         if (IsRdxInst) {
8349           // We need to be able to reassociate the reduction operations.
8350           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
8351             // I is an extra argument for TreeN (its parent operation).
8352             markExtraArg(Stack.back(), EdgeInst);
8353             continue;
8354           }
8355         } else if (!LeafOpcode) {
8356           LeafOpcode = EdgeInst->getOpcode();
8357         }
8358         Stack.push_back(
8359             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
8360         continue;
8361       }
8362       // I is an extra argument for TreeN (its parent operation).
8363       markExtraArg(Stack.back(), EdgeInst);
8364     }
8365     return true;
8366   }
8367 
8368   /// Attempt to vectorize the tree found by matchAssociativeReduction.
8369   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
8370     // If there are a sufficient number of reduction values, reduce
8371     // to a nearby power-of-2. We can safely generate oversized
8372     // vectors and rely on the backend to split them to legal sizes.
8373     unsigned NumReducedVals = ReducedVals.size();
8374     if (NumReducedVals < 4)
8375       return nullptr;
8376 
8377     // Intersect the fast-math-flags from all reduction operations.
8378     FastMathFlags RdxFMF;
8379     RdxFMF.set();
8380     for (ReductionOpsType &RdxOp : ReductionOps) {
8381       for (Value *RdxVal : RdxOp) {
8382         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
8383           RdxFMF &= FPMO->getFastMathFlags();
8384       }
8385     }
8386 
8387     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
8388     Builder.setFastMathFlags(RdxFMF);
8389 
8390     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
8391     // The same extra argument may be used several times, so log each attempt
8392     // to use it.
8393     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
8394       assert(Pair.first && "DebugLoc must be set.");
8395       ExternallyUsedValues[Pair.second].push_back(Pair.first);
8396     }
8397 
8398     // The compare instruction of a min/max is the insertion point for new
8399     // instructions and may be replaced with a new compare instruction.
8400     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
8401       assert(isa<SelectInst>(RdxRootInst) &&
8402              "Expected min/max reduction to have select root instruction");
8403       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
8404       assert(isa<Instruction>(ScalarCond) &&
8405              "Expected min/max reduction to have compare condition");
8406       return cast<Instruction>(ScalarCond);
8407     };
8408 
8409     // The reduction root is used as the insertion point for new instructions,
8410     // so set it as externally used to prevent it from being deleted.
8411     ExternallyUsedValues[ReductionRoot];
8412     SmallVector<Value *, 16> IgnoreList;
8413     for (ReductionOpsType &RdxOp : ReductionOps)
8414       IgnoreList.append(RdxOp.begin(), RdxOp.end());
8415 
8416     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
8417     if (NumReducedVals > ReduxWidth) {
8418       // In the loop below, we are building a tree based on a window of
8419       // 'ReduxWidth' values.
8420       // If the operands of those values have common traits (compare predicate,
8421       // constant operand, etc), then we want to group those together to
8422       // minimize the cost of the reduction.
8423 
8424       // TODO: This should be extended to count common operands for
8425       //       compares and binops.
8426 
8427       // Step 1: Count the number of times each compare predicate occurs.
8428       SmallDenseMap<unsigned, unsigned> PredCountMap;
8429       for (Value *RdxVal : ReducedVals) {
8430         CmpInst::Predicate Pred;
8431         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
8432           ++PredCountMap[Pred];
8433       }
8434       // Step 2: Sort the values so the most common predicates come first.
8435       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
8436         CmpInst::Predicate PredA, PredB;
8437         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
8438             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
8439           return PredCountMap[PredA] > PredCountMap[PredB];
8440         }
8441         return false;
8442       });
8443     }
8444 
8445     Value *VectorizedTree = nullptr;
8446     unsigned i = 0;
8447     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
8448       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
8449       V.buildTree(VL, IgnoreList);
8450       if (V.isTreeTinyAndNotFullyVectorizable())
8451         break;
8452       if (V.isLoadCombineReductionCandidate(RdxKind))
8453         break;
8454       V.reorderTopToBottom();
8455       V.reorderBottomToTop();
8456       V.buildExternalUses(ExternallyUsedValues);
8457 
8458       // For a poison-safe boolean logic reduction, do not replace select
8459       // instructions with logic ops. All reduced values will be frozen (see
8460       // below) to prevent leaking poison.
8461       if (isa<SelectInst>(ReductionRoot) &&
8462           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
8463           NumReducedVals != ReduxWidth)
8464         break;
8465 
8466       V.computeMinimumValueSizes();
8467 
8468       // Estimate cost.
8469       InstructionCost TreeCost =
8470           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
8471       InstructionCost ReductionCost =
8472           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
8473       InstructionCost Cost = TreeCost + ReductionCost;
8474       if (!Cost.isValid()) {
8475         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
8476         return nullptr;
8477       }
8478       if (Cost >= -SLPCostThreshold) {
8479         V.getORE()->emit([&]() {
8480           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
8481                                           cast<Instruction>(VL[0]))
8482                  << "Vectorizing horizontal reduction is possible"
8483                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
8484                  << " and threshold "
8485                  << ore::NV("Threshold", -SLPCostThreshold);
8486         });
8487         break;
8488       }
8489 
8490       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
8491                         << Cost << ". (HorRdx)\n");
8492       V.getORE()->emit([&]() {
8493         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
8494                                   cast<Instruction>(VL[0]))
8495                << "Vectorized horizontal reduction with cost "
8496                << ore::NV("Cost", Cost) << " and with tree size "
8497                << ore::NV("TreeSize", V.getTreeSize());
8498       });
8499 
8500       // Vectorize a tree.
8501       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
8502       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
8503 
8504       // Emit a reduction. If the root is a select (min/max idiom), the insert
8505       // point is the compare condition of that select.
8506       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
8507       if (isCmpSelMinMax(RdxRootInst))
8508         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
8509       else
8510         Builder.SetInsertPoint(RdxRootInst);
8511 
8512       // To prevent poison from leaking across what used to be sequential, safe,
8513       // scalar boolean logic operations, the reduction operand must be frozen.
8514       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
8515         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
8516 
8517       Value *ReducedSubTree =
8518           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
8519 
8520       if (!VectorizedTree) {
8521         // Initialize the final value in the reduction.
8522         VectorizedTree = ReducedSubTree;
8523       } else {
8524         // Update the final value in the reduction.
8525         Builder.SetCurrentDebugLocation(Loc);
8526         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8527                                   ReducedSubTree, "op.rdx", ReductionOps);
8528       }
8529       i += ReduxWidth;
8530       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
8531     }
8532 
8533     if (VectorizedTree) {
8534       // Finish the reduction.
8535       for (; i < NumReducedVals; ++i) {
8536         auto *I = cast<Instruction>(ReducedVals[i]);
8537         Builder.SetCurrentDebugLocation(I->getDebugLoc());
8538         VectorizedTree =
8539             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
8540       }
8541       for (auto &Pair : ExternallyUsedValues) {
8542         // Add each externally used value to the final reduction.
8543         for (auto *I : Pair.second) {
8544           Builder.SetCurrentDebugLocation(I->getDebugLoc());
8545           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8546                                     Pair.first, "op.extra", I);
8547         }
8548       }
8549 
8550       ReductionRoot->replaceAllUsesWith(VectorizedTree);
8551 
8552       // Mark all scalar reduction ops for deletion, they are replaced by the
8553       // vector reductions.
8554       V.eraseInstructions(IgnoreList);
8555     }
8556     return VectorizedTree;
8557   }
8558 
8559   unsigned numReductionValues() const { return ReducedVals.size(); }
8560 
8561 private:
8562   /// Calculate the cost of a reduction.
8563   InstructionCost getReductionCost(TargetTransformInfo *TTI,
8564                                    Value *FirstReducedVal, unsigned ReduxWidth,
8565                                    FastMathFlags FMF) {
8566     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
8567     Type *ScalarTy = FirstReducedVal->getType();
8568     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
8569     InstructionCost VectorCost, ScalarCost;
8570     switch (RdxKind) {
8571     case RecurKind::Add:
8572     case RecurKind::Mul:
8573     case RecurKind::Or:
8574     case RecurKind::And:
8575     case RecurKind::Xor:
8576     case RecurKind::FAdd:
8577     case RecurKind::FMul: {
8578       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
8579       VectorCost =
8580           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
8581       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
8582       break;
8583     }
8584     case RecurKind::FMax:
8585     case RecurKind::FMin: {
8586       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
8587       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
8588       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
8589                                                /*unsigned=*/false, CostKind);
8590       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
8591       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
8592                                            SclCondTy, RdxPred, CostKind) +
8593                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
8594                                            SclCondTy, RdxPred, CostKind);
8595       break;
8596     }
8597     case RecurKind::SMax:
8598     case RecurKind::SMin:
8599     case RecurKind::UMax:
8600     case RecurKind::UMin: {
8601       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
8602       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
8603       bool IsUnsigned =
8604           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
8605       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
8606                                                CostKind);
8607       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
8608       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
8609                                            SclCondTy, RdxPred, CostKind) +
8610                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
8611                                            SclCondTy, RdxPred, CostKind);
8612       break;
8613     }
8614     default:
8615       llvm_unreachable("Expected arithmetic or min/max reduction operation");
8616     }
8617 
8618     // Scalar cost is repeated for N-1 elements.
8619     ScalarCost *= (ReduxWidth - 1);
8620     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
8621                       << " for reduction that starts with " << *FirstReducedVal
8622                       << " (It is a splitting reduction)\n");
8623     return VectorCost - ScalarCost;
8624   }
8625 
8626   /// Emit a horizontal reduction of the vectorized value.
8627   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
8628                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
8629     assert(VectorizedValue && "Need to have a vectorized tree node");
8630     assert(isPowerOf2_32(ReduxWidth) &&
8631            "We only handle power-of-two reductions for now");
8632 
8633     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind,
8634                                        ReductionOps.back());
8635   }
8636 };
8637 
8638 } // end anonymous namespace
8639 
8640 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
8641   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
8642     return cast<FixedVectorType>(IE->getType())->getNumElements();
8643 
8644   unsigned AggregateSize = 1;
8645   auto *IV = cast<InsertValueInst>(InsertInst);
8646   Type *CurrentType = IV->getType();
8647   do {
8648     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
8649       for (auto *Elt : ST->elements())
8650         if (Elt != ST->getElementType(0)) // check homogeneity
8651           return None;
8652       AggregateSize *= ST->getNumElements();
8653       CurrentType = ST->getElementType(0);
8654     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
8655       AggregateSize *= AT->getNumElements();
8656       CurrentType = AT->getElementType();
8657     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
8658       AggregateSize *= VT->getNumElements();
8659       return AggregateSize;
8660     } else if (CurrentType->isSingleValueType()) {
8661       return AggregateSize;
8662     } else {
8663       return None;
8664     }
8665   } while (true);
8666 }
8667 
8668 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
8669                                    TargetTransformInfo *TTI,
8670                                    SmallVectorImpl<Value *> &BuildVectorOpds,
8671                                    SmallVectorImpl<Value *> &InsertElts,
8672                                    unsigned OperandOffset) {
8673   do {
8674     Value *InsertedOperand = LastInsertInst->getOperand(1);
8675     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
8676     if (!OperandIndex)
8677       return false;
8678     if (isa<InsertElementInst>(InsertedOperand) ||
8679         isa<InsertValueInst>(InsertedOperand)) {
8680       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
8681                                   BuildVectorOpds, InsertElts, *OperandIndex))
8682         return false;
8683     } else {
8684       BuildVectorOpds[*OperandIndex] = InsertedOperand;
8685       InsertElts[*OperandIndex] = LastInsertInst;
8686     }
8687     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
8688   } while (LastInsertInst != nullptr &&
8689            (isa<InsertValueInst>(LastInsertInst) ||
8690             isa<InsertElementInst>(LastInsertInst)) &&
8691            LastInsertInst->hasOneUse());
8692   return true;
8693 }
8694 
8695 /// Recognize construction of vectors like
8696 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
8697 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
8698 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
8699 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
8700 ///  starting from the last insertelement or insertvalue instruction.
8701 ///
8702 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
8703 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
8704 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
8705 ///
8706 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
8707 ///
8708 /// \return true if it matches.
8709 static bool findBuildAggregate(Instruction *LastInsertInst,
8710                                TargetTransformInfo *TTI,
8711                                SmallVectorImpl<Value *> &BuildVectorOpds,
8712                                SmallVectorImpl<Value *> &InsertElts) {
8713 
8714   assert((isa<InsertElementInst>(LastInsertInst) ||
8715           isa<InsertValueInst>(LastInsertInst)) &&
8716          "Expected insertelement or insertvalue instruction!");
8717 
8718   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
8719          "Expected empty result vectors!");
8720 
8721   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
8722   if (!AggregateSize)
8723     return false;
8724   BuildVectorOpds.resize(*AggregateSize);
8725   InsertElts.resize(*AggregateSize);
8726 
8727   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
8728                              0)) {
8729     llvm::erase_value(BuildVectorOpds, nullptr);
8730     llvm::erase_value(InsertElts, nullptr);
8731     if (BuildVectorOpds.size() >= 2)
8732       return true;
8733   }
8734 
8735   return false;
8736 }
8737 
8738 /// Try and get a reduction value from a phi node.
8739 ///
8740 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
8741 /// if they come from either \p ParentBB or a containing loop latch.
8742 ///
8743 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
8744 /// if not possible.
8745 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
8746                                 BasicBlock *ParentBB, LoopInfo *LI) {
8747   // There are situations where the reduction value is not dominated by the
8748   // reduction phi. Vectorizing such cases has been reported to cause
8749   // miscompiles. See PR25787.
8750   auto DominatedReduxValue = [&](Value *R) {
8751     return isa<Instruction>(R) &&
8752            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
8753   };
8754 
8755   Value *Rdx = nullptr;
8756 
8757   // Return the incoming value if it comes from the same BB as the phi node.
8758   if (P->getIncomingBlock(0) == ParentBB) {
8759     Rdx = P->getIncomingValue(0);
8760   } else if (P->getIncomingBlock(1) == ParentBB) {
8761     Rdx = P->getIncomingValue(1);
8762   }
8763 
8764   if (Rdx && DominatedReduxValue(Rdx))
8765     return Rdx;
8766 
8767   // Otherwise, check whether we have a loop latch to look at.
8768   Loop *BBL = LI->getLoopFor(ParentBB);
8769   if (!BBL)
8770     return nullptr;
8771   BasicBlock *BBLatch = BBL->getLoopLatch();
8772   if (!BBLatch)
8773     return nullptr;
8774 
8775   // There is a loop latch, return the incoming value if it comes from
8776   // that. This reduction pattern occasionally turns up.
8777   if (P->getIncomingBlock(0) == BBLatch) {
8778     Rdx = P->getIncomingValue(0);
8779   } else if (P->getIncomingBlock(1) == BBLatch) {
8780     Rdx = P->getIncomingValue(1);
8781   }
8782 
8783   if (Rdx && DominatedReduxValue(Rdx))
8784     return Rdx;
8785 
8786   return nullptr;
8787 }
8788 
8789 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
8790   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
8791     return true;
8792   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
8793     return true;
8794   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
8795     return true;
8796   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
8797     return true;
8798   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
8799     return true;
8800   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
8801     return true;
8802   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
8803     return true;
8804   return false;
8805 }
8806 
8807 /// Attempt to reduce a horizontal reduction.
8808 /// If it is legal to match a horizontal reduction feeding the phi node \a P
8809 /// with reduction operators \a Root (or one of its operands) in a basic block
8810 /// \a BB, then check if it can be done. If horizontal reduction is not found
8811 /// and root instruction is a binary operation, vectorization of the operands is
8812 /// attempted.
8813 /// \returns true if a horizontal reduction was matched and reduced or operands
8814 /// of one of the binary instruction were vectorized.
8815 /// \returns false if a horizontal reduction was not matched (or not possible)
8816 /// or no vectorization of any binary operation feeding \a Root instruction was
8817 /// performed.
8818 static bool tryToVectorizeHorReductionOrInstOperands(
8819     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
8820     TargetTransformInfo *TTI,
8821     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
8822   if (!ShouldVectorizeHor)
8823     return false;
8824 
8825   if (!Root)
8826     return false;
8827 
8828   if (Root->getParent() != BB || isa<PHINode>(Root))
8829     return false;
8830   // Start analysis starting from Root instruction. If horizontal reduction is
8831   // found, try to vectorize it. If it is not a horizontal reduction or
8832   // vectorization is not possible or not effective, and currently analyzed
8833   // instruction is a binary operation, try to vectorize the operands, using
8834   // pre-order DFS traversal order. If the operands were not vectorized, repeat
8835   // the same procedure considering each operand as a possible root of the
8836   // horizontal reduction.
8837   // Interrupt the process if the Root instruction itself was vectorized or all
8838   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
8839   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
8840   // CmpInsts so we can skip extra attempts in
8841   // tryToVectorizeHorReductionOrInstOperands and save compile time.
8842   std::queue<std::pair<Instruction *, unsigned>> Stack;
8843   Stack.emplace(Root, 0);
8844   SmallPtrSet<Value *, 8> VisitedInstrs;
8845   SmallVector<WeakTrackingVH> PostponedInsts;
8846   bool Res = false;
8847   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
8848                                      Value *&B1) -> Value * {
8849     bool IsBinop = matchRdxBop(Inst, B0, B1);
8850     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
8851     if (IsBinop || IsSelect) {
8852       HorizontalReduction HorRdx;
8853       if (HorRdx.matchAssociativeReduction(P, Inst))
8854         return HorRdx.tryToReduce(R, TTI);
8855     }
8856     return nullptr;
8857   };
8858   while (!Stack.empty()) {
8859     Instruction *Inst;
8860     unsigned Level;
8861     std::tie(Inst, Level) = Stack.front();
8862     Stack.pop();
8863     // Do not try to analyze instruction that has already been vectorized.
8864     // This may happen when we vectorize instruction operands on a previous
8865     // iteration while stack was populated before that happened.
8866     if (R.isDeleted(Inst))
8867       continue;
8868     Value *B0 = nullptr, *B1 = nullptr;
8869     if (Value *V = TryToReduce(Inst, B0, B1)) {
8870       Res = true;
8871       // Set P to nullptr to avoid re-analysis of phi node in
8872       // matchAssociativeReduction function unless this is the root node.
8873       P = nullptr;
8874       if (auto *I = dyn_cast<Instruction>(V)) {
8875         // Try to find another reduction.
8876         Stack.emplace(I, Level);
8877         continue;
8878       }
8879     } else {
8880       bool IsBinop = B0 && B1;
8881       if (P && IsBinop) {
8882         Inst = dyn_cast<Instruction>(B0);
8883         if (Inst == P)
8884           Inst = dyn_cast<Instruction>(B1);
8885         if (!Inst) {
8886           // Set P to nullptr to avoid re-analysis of phi node in
8887           // matchAssociativeReduction function unless this is the root node.
8888           P = nullptr;
8889           continue;
8890         }
8891       }
8892     }
8893     // Set P to nullptr to avoid re-analysis of phi node in
8894     // matchAssociativeReduction function unless this is the root node.
8895     P = nullptr;
8896     // Do not try to vectorize CmpInst operands, this is done separately.
8897     // Final attempt for binop args vectorization should happen after the loop
8898     // to try to find reductions.
8899     if (!isa<CmpInst>(Inst))
8900       PostponedInsts.push_back(Inst);
8901 
8902     // Try to vectorize operands.
8903     // Continue analysis for the instruction from the same basic block only to
8904     // save compile time.
8905     if (++Level < RecursionMaxDepth)
8906       for (auto *Op : Inst->operand_values())
8907         if (VisitedInstrs.insert(Op).second)
8908           if (auto *I = dyn_cast<Instruction>(Op))
8909             // Do not try to vectorize CmpInst operands,  this is done
8910             // separately.
8911             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
8912                 I->getParent() == BB)
8913               Stack.emplace(I, Level);
8914   }
8915   // Try to vectorized binops where reductions were not found.
8916   for (Value *V : PostponedInsts)
8917     if (auto *Inst = dyn_cast<Instruction>(V))
8918       if (!R.isDeleted(Inst))
8919         Res |= Vectorize(Inst, R);
8920   return Res;
8921 }
8922 
8923 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
8924                                                  BasicBlock *BB, BoUpSLP &R,
8925                                                  TargetTransformInfo *TTI) {
8926   auto *I = dyn_cast_or_null<Instruction>(V);
8927   if (!I)
8928     return false;
8929 
8930   if (!isa<BinaryOperator>(I))
8931     P = nullptr;
8932   // Try to match and vectorize a horizontal reduction.
8933   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
8934     return tryToVectorize(I, R);
8935   };
8936   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
8937                                                   ExtraVectorization);
8938 }
8939 
8940 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
8941                                                  BasicBlock *BB, BoUpSLP &R) {
8942   const DataLayout &DL = BB->getModule()->getDataLayout();
8943   if (!R.canMapToVector(IVI->getType(), DL))
8944     return false;
8945 
8946   SmallVector<Value *, 16> BuildVectorOpds;
8947   SmallVector<Value *, 16> BuildVectorInsts;
8948   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
8949     return false;
8950 
8951   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
8952   // Aggregate value is unlikely to be processed in vector register, we need to
8953   // extract scalars into scalar registers, so NeedExtraction is set true.
8954   return tryToVectorizeList(BuildVectorOpds, R);
8955 }
8956 
8957 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
8958                                                    BasicBlock *BB, BoUpSLP &R) {
8959   SmallVector<Value *, 16> BuildVectorInsts;
8960   SmallVector<Value *, 16> BuildVectorOpds;
8961   SmallVector<int> Mask;
8962   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
8963       (llvm::all_of(BuildVectorOpds,
8964                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
8965        isFixedVectorShuffle(BuildVectorOpds, Mask)))
8966     return false;
8967 
8968   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
8969   return tryToVectorizeList(BuildVectorInsts, R);
8970 }
8971 
8972 bool SLPVectorizerPass::vectorizeSimpleInstructions(
8973     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
8974     bool AtTerminator) {
8975   bool OpsChanged = false;
8976   SmallVector<Instruction *, 4> PostponedCmps;
8977   for (auto *I : reverse(Instructions)) {
8978     if (R.isDeleted(I))
8979       continue;
8980     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
8981       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
8982     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
8983       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
8984     else if (isa<CmpInst>(I))
8985       PostponedCmps.push_back(I);
8986   }
8987   if (AtTerminator) {
8988     // Try to find reductions first.
8989     for (Instruction *I : PostponedCmps) {
8990       if (R.isDeleted(I))
8991         continue;
8992       for (Value *Op : I->operands())
8993         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
8994     }
8995     // Try to vectorize operands as vector bundles.
8996     for (Instruction *I : PostponedCmps) {
8997       if (R.isDeleted(I))
8998         continue;
8999       OpsChanged |= tryToVectorize(I, R);
9000     }
9001     Instructions.clear();
9002   } else {
9003     // Insert in reverse order since the PostponedCmps vector was filled in
9004     // reverse order.
9005     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9006   }
9007   return OpsChanged;
9008 }
9009 
9010 template <typename T>
9011 static bool
9012 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9013                        function_ref<unsigned(T *)> Limit,
9014                        function_ref<bool(T *, T *)> Comparator,
9015                        function_ref<bool(T *, T *)> AreCompatible,
9016                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorize,
9017                        bool LimitForRegisterSize) {
9018   bool Changed = false;
9019   // Sort by type, parent, operands.
9020   stable_sort(Incoming, Comparator);
9021 
9022   // Try to vectorize elements base on their type.
9023   SmallVector<T *> Candidates;
9024   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9025     // Look for the next elements with the same type, parent and operand
9026     // kinds.
9027     auto *SameTypeIt = IncIt;
9028     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9029       ++SameTypeIt;
9030 
9031     // Try to vectorize them.
9032     unsigned NumElts = (SameTypeIt - IncIt);
9033     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9034                       << NumElts << ")\n");
9035     // The vectorization is a 3-state attempt:
9036     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9037     // size of maximal register at first.
9038     // 2. Try to vectorize remaining instructions with the same type, if
9039     // possible. This may result in the better vectorization results rather than
9040     // if we try just to vectorize instructions with the same/alternate opcodes.
9041     // 3. Final attempt to try to vectorize all instructions with the
9042     // same/alternate ops only, this may result in some extra final
9043     // vectorization.
9044     if (NumElts > 1 &&
9045         TryToVectorize(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9046       // Success start over because instructions might have been changed.
9047       Changed = true;
9048     } else if (NumElts < Limit(*IncIt) &&
9049                (Candidates.empty() ||
9050                 Candidates.front()->getType() == (*IncIt)->getType())) {
9051       Candidates.append(IncIt, std::next(IncIt, NumElts));
9052     }
9053     // Final attempt to vectorize instructions with the same types.
9054     if (Candidates.size() > 1 &&
9055         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9056       if (TryToVectorize(Candidates, /*LimitForRegisterSize=*/false)) {
9057         // Success start over because instructions might have been changed.
9058         Changed = true;
9059       } else if (LimitForRegisterSize) {
9060         // Try to vectorize using small vectors.
9061         for (auto *It = Candidates.begin(), *End = Candidates.end();
9062              It != End;) {
9063           auto *SameTypeIt = It;
9064           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9065             ++SameTypeIt;
9066           unsigned NumElts = (SameTypeIt - It);
9067           if (NumElts > 1 && TryToVectorize(makeArrayRef(It, NumElts),
9068                                             /*LimitForRegisterSize=*/false))
9069             Changed = true;
9070           It = SameTypeIt;
9071         }
9072       }
9073       Candidates.clear();
9074     }
9075 
9076     // Start over at the next instruction of a different type (or the end).
9077     IncIt = SameTypeIt;
9078   }
9079   return Changed;
9080 }
9081 
9082 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9083   bool Changed = false;
9084   SmallVector<Value *, 4> Incoming;
9085   SmallPtrSet<Value *, 16> VisitedInstrs;
9086   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9087   // node. Allows better to identify the chains that can be vectorized in the
9088   // better way.
9089   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9090   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9091     assert(isValidElementType(V1->getType()) &&
9092            isValidElementType(V2->getType()) &&
9093            "Expected vectorizable types only.");
9094     // It is fine to compare type IDs here, since we expect only vectorizable
9095     // types, like ints, floats and pointers, we don't care about other type.
9096     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9097       return true;
9098     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
9099       return false;
9100     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9101     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9102     if (Opcodes1.size() < Opcodes2.size())
9103       return true;
9104     if (Opcodes1.size() > Opcodes2.size())
9105       return false;
9106     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9107       // Undefs are compatible with any other value.
9108       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9109         continue;
9110       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9111         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9112           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
9113           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
9114           if (!NodeI1)
9115             return NodeI2 != nullptr;
9116           if (!NodeI2)
9117             return false;
9118           assert((NodeI1 == NodeI2) ==
9119                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9120                  "Different nodes should have different DFS numbers");
9121           if (NodeI1 != NodeI2)
9122             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9123           InstructionsState S = getSameOpcode({I1, I2});
9124           if (S.getOpcode())
9125             continue;
9126           return I1->getOpcode() < I2->getOpcode();
9127         }
9128       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9129         continue;
9130       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
9131         return true;
9132       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
9133         return false;
9134     }
9135     return false;
9136   };
9137   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
9138     if (V1 == V2)
9139       return true;
9140     if (V1->getType() != V2->getType())
9141       return false;
9142     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9143     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9144     if (Opcodes1.size() != Opcodes2.size())
9145       return false;
9146     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9147       // Undefs are compatible with any other value.
9148       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9149         continue;
9150       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9151         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9152           if (I1->getParent() != I2->getParent())
9153             return false;
9154           InstructionsState S = getSameOpcode({I1, I2});
9155           if (S.getOpcode())
9156             continue;
9157           return false;
9158         }
9159       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9160         continue;
9161       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
9162         return false;
9163     }
9164     return true;
9165   };
9166   auto Limit = [&R](Value *V) {
9167     unsigned EltSize = R.getVectorElementSize(V);
9168     return std::max(2U, R.getMaxVecRegSize() / EltSize);
9169   };
9170 
9171   bool HaveVectorizedPhiNodes = false;
9172   do {
9173     // Collect the incoming values from the PHIs.
9174     Incoming.clear();
9175     for (Instruction &I : *BB) {
9176       PHINode *P = dyn_cast<PHINode>(&I);
9177       if (!P)
9178         break;
9179 
9180       // No need to analyze deleted, vectorized and non-vectorizable
9181       // instructions.
9182       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
9183           isValidElementType(P->getType()))
9184         Incoming.push_back(P);
9185     }
9186 
9187     // Find the corresponding non-phi nodes for better matching when trying to
9188     // build the tree.
9189     for (Value *V : Incoming) {
9190       SmallVectorImpl<Value *> &Opcodes =
9191           PHIToOpcodes.try_emplace(V).first->getSecond();
9192       if (!Opcodes.empty())
9193         continue;
9194       SmallVector<Value *, 4> Nodes(1, V);
9195       SmallPtrSet<Value *, 4> Visited;
9196       while (!Nodes.empty()) {
9197         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
9198         if (!Visited.insert(PHI).second)
9199           continue;
9200         for (Value *V : PHI->incoming_values()) {
9201           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
9202             Nodes.push_back(PHI1);
9203             continue;
9204           }
9205           Opcodes.emplace_back(V);
9206         }
9207       }
9208     }
9209 
9210     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
9211         Incoming, Limit, PHICompare, AreCompatiblePHIs,
9212         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9213           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9214         },
9215         /*LimitForRegisterSize=*/true);
9216     Changed |= HaveVectorizedPhiNodes;
9217     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
9218   } while (HaveVectorizedPhiNodes);
9219 
9220   VisitedInstrs.clear();
9221 
9222   SmallVector<Instruction *, 8> PostProcessInstructions;
9223   SmallDenseSet<Instruction *, 4> KeyNodes;
9224   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
9225     // Skip instructions with scalable type. The num of elements is unknown at
9226     // compile-time for scalable type.
9227     if (isa<ScalableVectorType>(it->getType()))
9228       continue;
9229 
9230     // Skip instructions marked for the deletion.
9231     if (R.isDeleted(&*it))
9232       continue;
9233     // We may go through BB multiple times so skip the one we have checked.
9234     if (!VisitedInstrs.insert(&*it).second) {
9235       if (it->use_empty() && KeyNodes.contains(&*it) &&
9236           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9237                                       it->isTerminator())) {
9238         // We would like to start over since some instructions are deleted
9239         // and the iterator may become invalid value.
9240         Changed = true;
9241         it = BB->begin();
9242         e = BB->end();
9243       }
9244       continue;
9245     }
9246 
9247     if (isa<DbgInfoIntrinsic>(it))
9248       continue;
9249 
9250     // Try to vectorize reductions that use PHINodes.
9251     if (PHINode *P = dyn_cast<PHINode>(it)) {
9252       // Check that the PHI is a reduction PHI.
9253       if (P->getNumIncomingValues() == 2) {
9254         // Try to match and vectorize a horizontal reduction.
9255         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
9256                                      TTI)) {
9257           Changed = true;
9258           it = BB->begin();
9259           e = BB->end();
9260           continue;
9261         }
9262       }
9263       // Try to vectorize the incoming values of the PHI, to catch reductions
9264       // that feed into PHIs.
9265       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
9266         // Skip if the incoming block is the current BB for now. Also, bypass
9267         // unreachable IR for efficiency and to avoid crashing.
9268         // TODO: Collect the skipped incoming values and try to vectorize them
9269         // after processing BB.
9270         if (BB == P->getIncomingBlock(I) ||
9271             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
9272           continue;
9273 
9274         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
9275                                             P->getIncomingBlock(I), R, TTI);
9276       }
9277       continue;
9278     }
9279 
9280     // Ran into an instruction without users, like terminator, or function call
9281     // with ignored return value, store. Ignore unused instructions (basing on
9282     // instruction type, except for CallInst and InvokeInst).
9283     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
9284                             isa<InvokeInst>(it))) {
9285       KeyNodes.insert(&*it);
9286       bool OpsChanged = false;
9287       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
9288         for (auto *V : it->operand_values()) {
9289           // Try to match and vectorize a horizontal reduction.
9290           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
9291         }
9292       }
9293       // Start vectorization of post-process list of instructions from the
9294       // top-tree instructions to try to vectorize as many instructions as
9295       // possible.
9296       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9297                                                 it->isTerminator());
9298       if (OpsChanged) {
9299         // We would like to start over since some instructions are deleted
9300         // and the iterator may become invalid value.
9301         Changed = true;
9302         it = BB->begin();
9303         e = BB->end();
9304         continue;
9305       }
9306     }
9307 
9308     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
9309         isa<InsertValueInst>(it))
9310       PostProcessInstructions.push_back(&*it);
9311   }
9312 
9313   return Changed;
9314 }
9315 
9316 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
9317   auto Changed = false;
9318   for (auto &Entry : GEPs) {
9319     // If the getelementptr list has fewer than two elements, there's nothing
9320     // to do.
9321     if (Entry.second.size() < 2)
9322       continue;
9323 
9324     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
9325                       << Entry.second.size() << ".\n");
9326 
9327     // Process the GEP list in chunks suitable for the target's supported
9328     // vector size. If a vector register can't hold 1 element, we are done. We
9329     // are trying to vectorize the index computations, so the maximum number of
9330     // elements is based on the size of the index expression, rather than the
9331     // size of the GEP itself (the target's pointer size).
9332     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9333     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
9334     if (MaxVecRegSize < EltSize)
9335       continue;
9336 
9337     unsigned MaxElts = MaxVecRegSize / EltSize;
9338     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
9339       auto Len = std::min<unsigned>(BE - BI, MaxElts);
9340       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
9341 
9342       // Initialize a set a candidate getelementptrs. Note that we use a
9343       // SetVector here to preserve program order. If the index computations
9344       // are vectorizable and begin with loads, we want to minimize the chance
9345       // of having to reorder them later.
9346       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
9347 
9348       // Some of the candidates may have already been vectorized after we
9349       // initially collected them. If so, they are marked as deleted, so remove
9350       // them from the set of candidates.
9351       Candidates.remove_if(
9352           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
9353 
9354       // Remove from the set of candidates all pairs of getelementptrs with
9355       // constant differences. Such getelementptrs are likely not good
9356       // candidates for vectorization in a bottom-up phase since one can be
9357       // computed from the other. We also ensure all candidate getelementptr
9358       // indices are unique.
9359       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
9360         auto *GEPI = GEPList[I];
9361         if (!Candidates.count(GEPI))
9362           continue;
9363         auto *SCEVI = SE->getSCEV(GEPList[I]);
9364         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
9365           auto *GEPJ = GEPList[J];
9366           auto *SCEVJ = SE->getSCEV(GEPList[J]);
9367           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
9368             Candidates.remove(GEPI);
9369             Candidates.remove(GEPJ);
9370           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
9371             Candidates.remove(GEPJ);
9372           }
9373         }
9374       }
9375 
9376       // We break out of the above computation as soon as we know there are
9377       // fewer than two candidates remaining.
9378       if (Candidates.size() < 2)
9379         continue;
9380 
9381       // Add the single, non-constant index of each candidate to the bundle. We
9382       // ensured the indices met these constraints when we originally collected
9383       // the getelementptrs.
9384       SmallVector<Value *, 16> Bundle(Candidates.size());
9385       auto BundleIndex = 0u;
9386       for (auto *V : Candidates) {
9387         auto *GEP = cast<GetElementPtrInst>(V);
9388         auto *GEPIdx = GEP->idx_begin()->get();
9389         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
9390         Bundle[BundleIndex++] = GEPIdx;
9391       }
9392 
9393       // Try and vectorize the indices. We are currently only interested in
9394       // gather-like cases of the form:
9395       //
9396       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
9397       //
9398       // where the loads of "a", the loads of "b", and the subtractions can be
9399       // performed in parallel. It's likely that detecting this pattern in a
9400       // bottom-up phase will be simpler and less costly than building a
9401       // full-blown top-down phase beginning at the consecutive loads.
9402       Changed |= tryToVectorizeList(Bundle, R);
9403     }
9404   }
9405   return Changed;
9406 }
9407 
9408 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
9409   bool Changed = false;
9410   // Sort by type, base pointers and values operand. Value operands must be
9411   // compatible (have the same opcode, same parent), otherwise it is
9412   // definitely not profitable to try to vectorize them.
9413   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
9414     if (V->getPointerOperandType()->getTypeID() <
9415         V2->getPointerOperandType()->getTypeID())
9416       return true;
9417     if (V->getPointerOperandType()->getTypeID() >
9418         V2->getPointerOperandType()->getTypeID())
9419       return false;
9420     // UndefValues are compatible with all other values.
9421     if (isa<UndefValue>(V->getValueOperand()) ||
9422         isa<UndefValue>(V2->getValueOperand()))
9423       return false;
9424     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
9425       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9426         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
9427             DT->getNode(I1->getParent());
9428         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
9429             DT->getNode(I2->getParent());
9430         assert(NodeI1 && "Should only process reachable instructions");
9431         assert(NodeI1 && "Should only process reachable instructions");
9432         assert((NodeI1 == NodeI2) ==
9433                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9434                "Different nodes should have different DFS numbers");
9435         if (NodeI1 != NodeI2)
9436           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9437         InstructionsState S = getSameOpcode({I1, I2});
9438         if (S.getOpcode())
9439           return false;
9440         return I1->getOpcode() < I2->getOpcode();
9441       }
9442     if (isa<Constant>(V->getValueOperand()) &&
9443         isa<Constant>(V2->getValueOperand()))
9444       return false;
9445     return V->getValueOperand()->getValueID() <
9446            V2->getValueOperand()->getValueID();
9447   };
9448 
9449   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
9450     if (V1 == V2)
9451       return true;
9452     if (V1->getPointerOperandType() != V2->getPointerOperandType())
9453       return false;
9454     // Undefs are compatible with any other value.
9455     if (isa<UndefValue>(V1->getValueOperand()) ||
9456         isa<UndefValue>(V2->getValueOperand()))
9457       return true;
9458     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
9459       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9460         if (I1->getParent() != I2->getParent())
9461           return false;
9462         InstructionsState S = getSameOpcode({I1, I2});
9463         return S.getOpcode() > 0;
9464       }
9465     if (isa<Constant>(V1->getValueOperand()) &&
9466         isa<Constant>(V2->getValueOperand()))
9467       return true;
9468     return V1->getValueOperand()->getValueID() ==
9469            V2->getValueOperand()->getValueID();
9470   };
9471   auto Limit = [&R, this](StoreInst *SI) {
9472     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
9473     return R.getMinVF(EltSize);
9474   };
9475 
9476   // Attempt to sort and vectorize each of the store-groups.
9477   for (auto &Pair : Stores) {
9478     if (Pair.second.size() < 2)
9479       continue;
9480 
9481     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
9482                       << Pair.second.size() << ".\n");
9483 
9484     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
9485       continue;
9486 
9487     Changed |= tryToVectorizeSequence<StoreInst>(
9488         Pair.second, Limit, StoreSorter, AreCompatibleStores,
9489         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
9490           return vectorizeStores(Candidates, R);
9491         },
9492         /*LimitForRegisterSize=*/false);
9493   }
9494   return Changed;
9495 }
9496 
9497 char SLPVectorizer::ID = 0;
9498 
9499 static const char lv_name[] = "SLP Vectorizer";
9500 
9501 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
9502 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
9503 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
9504 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9505 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
9506 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
9507 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
9508 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
9509 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
9510 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
9511 
9512 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
9513