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