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