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