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