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