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