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