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