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