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