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