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() << "Empty";
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       int DeadCost = 0;
3484       if (NeedToShuffleReuses) {
3485         unsigned Idx = 0;
3486         for (unsigned I : E->ReuseShuffleIndices) {
3487           if (ShuffleOrOp == Instruction::ExtractElement) {
3488             auto *IO = cast<ConstantInt>(
3489                 cast<ExtractElementInst>(VL[I])->getIndexOperand());
3490             Idx = IO->getZExtValue();
3491             ReuseShuffleCost -= TTI->getVectorInstrCost(
3492                 Instruction::ExtractElement, VecTy, Idx);
3493           } else {
3494             ReuseShuffleCost -= TTI->getVectorInstrCost(
3495                 Instruction::ExtractElement, VecTy, Idx);
3496             ++Idx;
3497           }
3498         }
3499         Idx = ReuseShuffleNumbers;
3500         for (Value *V : VL) {
3501           if (ShuffleOrOp == Instruction::ExtractElement) {
3502             auto *IO = cast<ConstantInt>(
3503                 cast<ExtractElementInst>(V)->getIndexOperand());
3504             Idx = IO->getZExtValue();
3505           } else {
3506             --Idx;
3507           }
3508           ReuseShuffleCost +=
3509               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
3510         }
3511         DeadCost = ReuseShuffleCost;
3512       } else if (!E->ReorderIndices.empty()) {
3513         DeadCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
3514                                        VecTy);
3515       }
3516       for (unsigned I = 0, E = VL.size(); I < E; ++I) {
3517         Instruction *EI = cast<Instruction>(VL[I]);
3518         // If all users are going to be vectorized, instruction can be
3519         // considered as dead.
3520         // The same, if have only one user, it will be vectorized for sure.
3521         if (areAllUsersVectorized(EI)) {
3522           // Take credit for instruction that will become dead.
3523           if (EI->hasOneUse()) {
3524             Instruction *Ext = EI->user_back();
3525             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3526                 all_of(Ext->users(),
3527                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
3528               // Use getExtractWithExtendCost() to calculate the cost of
3529               // extractelement/ext pair.
3530               DeadCost -= TTI->getExtractWithExtendCost(
3531                   Ext->getOpcode(), Ext->getType(), VecTy, I);
3532               // Add back the cost of s|zext which is subtracted separately.
3533               DeadCost += TTI->getCastInstrCost(
3534                   Ext->getOpcode(), Ext->getType(), EI->getType(),
3535                   TTI::getCastContextHint(Ext), CostKind, Ext);
3536               continue;
3537             }
3538           }
3539           DeadCost -=
3540               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
3541         }
3542       }
3543       return DeadCost;
3544     }
3545     case Instruction::ZExt:
3546     case Instruction::SExt:
3547     case Instruction::FPToUI:
3548     case Instruction::FPToSI:
3549     case Instruction::FPExt:
3550     case Instruction::PtrToInt:
3551     case Instruction::IntToPtr:
3552     case Instruction::SIToFP:
3553     case Instruction::UIToFP:
3554     case Instruction::Trunc:
3555     case Instruction::FPTrunc:
3556     case Instruction::BitCast: {
3557       Type *SrcTy = VL0->getOperand(0)->getType();
3558       int ScalarEltCost =
3559           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
3560                                 TTI::getCastContextHint(VL0), CostKind, VL0);
3561       if (NeedToShuffleReuses) {
3562         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3563       }
3564 
3565       // Calculate the cost of this instruction.
3566       int ScalarCost = VL.size() * ScalarEltCost;
3567 
3568       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
3569       int VecCost = 0;
3570       // Check if the values are candidates to demote.
3571       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
3572         VecCost =
3573             ReuseShuffleCost +
3574             TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy,
3575                                   TTI::getCastContextHint(VL0), CostKind, VL0);
3576       }
3577       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3578       return VecCost - ScalarCost;
3579     }
3580     case Instruction::FCmp:
3581     case Instruction::ICmp:
3582     case Instruction::Select: {
3583       // Calculate the cost of this instruction.
3584       int ScalarEltCost =
3585           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
3586                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
3587       if (NeedToShuffleReuses) {
3588         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3589       }
3590       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
3591       int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3592 
3593       // Check if all entries in VL are either compares or selects with compares
3594       // as condition that have the same predicates.
3595       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
3596       bool First = true;
3597       for (auto *V : VL) {
3598         CmpInst::Predicate CurrentPred;
3599         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
3600         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
3601              !match(V, MatchCmp)) ||
3602             (!First && VecPred != CurrentPred)) {
3603           VecPred = CmpInst::BAD_ICMP_PREDICATE;
3604           break;
3605         }
3606         First = false;
3607         VecPred = CurrentPred;
3608       }
3609 
3610       int VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), VecTy, MaskTy,
3611                                             VecPred, CostKind, VL0);
3612       // Check if it is possible and profitable to use min/max for selects in
3613       // VL.
3614       //
3615       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
3616       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
3617         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
3618                                           {VecTy, VecTy});
3619         int IntrinsicCost = TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
3620         // If the selects are the only uses of the compares, they will be dead
3621         // and we can adjust the cost by removing their cost.
3622         if (IntrinsicAndUse.second)
3623           IntrinsicCost -=
3624               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
3625                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
3626         VecCost = std::min(VecCost, IntrinsicCost);
3627       }
3628       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3629       return ReuseShuffleCost + VecCost - ScalarCost;
3630     }
3631     case Instruction::FNeg:
3632     case Instruction::Add:
3633     case Instruction::FAdd:
3634     case Instruction::Sub:
3635     case Instruction::FSub:
3636     case Instruction::Mul:
3637     case Instruction::FMul:
3638     case Instruction::UDiv:
3639     case Instruction::SDiv:
3640     case Instruction::FDiv:
3641     case Instruction::URem:
3642     case Instruction::SRem:
3643     case Instruction::FRem:
3644     case Instruction::Shl:
3645     case Instruction::LShr:
3646     case Instruction::AShr:
3647     case Instruction::And:
3648     case Instruction::Or:
3649     case Instruction::Xor: {
3650       // Certain instructions can be cheaper to vectorize if they have a
3651       // constant second vector operand.
3652       TargetTransformInfo::OperandValueKind Op1VK =
3653           TargetTransformInfo::OK_AnyValue;
3654       TargetTransformInfo::OperandValueKind Op2VK =
3655           TargetTransformInfo::OK_UniformConstantValue;
3656       TargetTransformInfo::OperandValueProperties Op1VP =
3657           TargetTransformInfo::OP_None;
3658       TargetTransformInfo::OperandValueProperties Op2VP =
3659           TargetTransformInfo::OP_PowerOf2;
3660 
3661       // If all operands are exactly the same ConstantInt then set the
3662       // operand kind to OK_UniformConstantValue.
3663       // If instead not all operands are constants, then set the operand kind
3664       // to OK_AnyValue. If all operands are constants but not the same,
3665       // then set the operand kind to OK_NonUniformConstantValue.
3666       ConstantInt *CInt0 = nullptr;
3667       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3668         const Instruction *I = cast<Instruction>(VL[i]);
3669         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
3670         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
3671         if (!CInt) {
3672           Op2VK = TargetTransformInfo::OK_AnyValue;
3673           Op2VP = TargetTransformInfo::OP_None;
3674           break;
3675         }
3676         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
3677             !CInt->getValue().isPowerOf2())
3678           Op2VP = TargetTransformInfo::OP_None;
3679         if (i == 0) {
3680           CInt0 = CInt;
3681           continue;
3682         }
3683         if (CInt0 != CInt)
3684           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
3685       }
3686 
3687       SmallVector<const Value *, 4> Operands(VL0->operand_values());
3688       int ScalarEltCost = TTI->getArithmeticInstrCost(
3689           E->getOpcode(), ScalarTy, CostKind, Op1VK, Op2VK, Op1VP, Op2VP,
3690           Operands, VL0);
3691       if (NeedToShuffleReuses) {
3692         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3693       }
3694       int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3695       int VecCost = TTI->getArithmeticInstrCost(
3696           E->getOpcode(), VecTy, CostKind, Op1VK, Op2VK, Op1VP, Op2VP,
3697           Operands, VL0);
3698       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3699       return ReuseShuffleCost + VecCost - ScalarCost;
3700     }
3701     case Instruction::GetElementPtr: {
3702       TargetTransformInfo::OperandValueKind Op1VK =
3703           TargetTransformInfo::OK_AnyValue;
3704       TargetTransformInfo::OperandValueKind Op2VK =
3705           TargetTransformInfo::OK_UniformConstantValue;
3706 
3707       int ScalarEltCost =
3708           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, CostKind,
3709                                       Op1VK, Op2VK);
3710       if (NeedToShuffleReuses) {
3711         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3712       }
3713       int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3714       int VecCost =
3715           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, CostKind,
3716                                       Op1VK, Op2VK);
3717       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3718       return ReuseShuffleCost + VecCost - ScalarCost;
3719     }
3720     case Instruction::Load: {
3721       // Cost of wide load - cost of scalar loads.
3722       Align alignment = cast<LoadInst>(VL0)->getAlign();
3723       int ScalarEltCost =
3724           TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0,
3725                                CostKind, VL0);
3726       if (NeedToShuffleReuses) {
3727         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3728       }
3729       int ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
3730       int VecLdCost;
3731       if (E->State == TreeEntry::Vectorize) {
3732         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0,
3733                                          CostKind, VL0);
3734       } else {
3735         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
3736         VecLdCost = TTI->getGatherScatterOpCost(
3737             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
3738             /*VariableMask=*/false, alignment, CostKind, VL0);
3739       }
3740       if (!NeedToShuffleReuses && !E->ReorderIndices.empty())
3741         VecLdCost += TTI->getShuffleCost(
3742             TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
3743       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecLdCost, ScalarLdCost));
3744       return ReuseShuffleCost + VecLdCost - ScalarLdCost;
3745     }
3746     case Instruction::Store: {
3747       // We know that we can merge the stores. Calculate the cost.
3748       bool IsReorder = !E->ReorderIndices.empty();
3749       auto *SI =
3750           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
3751       Align Alignment = SI->getAlign();
3752       int ScalarEltCost =
3753           TTI->getMemoryOpCost(Instruction::Store, ScalarTy, Alignment, 0,
3754                                CostKind, VL0);
3755       int ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
3756       int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
3757                                            VecTy, Alignment, 0, CostKind, VL0);
3758       if (IsReorder)
3759         VecStCost += TTI->getShuffleCost(
3760             TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
3761       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecStCost, ScalarStCost));
3762       return VecStCost - ScalarStCost;
3763     }
3764     case Instruction::Call: {
3765       CallInst *CI = cast<CallInst>(VL0);
3766       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3767 
3768       // Calculate the cost of the scalar and vector calls.
3769       IntrinsicCostAttributes CostAttrs(ID, *CI, ElementCount::getFixed(1), 1);
3770       int ScalarEltCost = TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
3771       if (NeedToShuffleReuses) {
3772         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3773       }
3774       int ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
3775 
3776       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
3777       int VecCallCost = std::min(VecCallCosts.first, VecCallCosts.second);
3778 
3779       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
3780                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
3781                         << " for " << *CI << "\n");
3782 
3783       return ReuseShuffleCost + VecCallCost - ScalarCallCost;
3784     }
3785     case Instruction::ShuffleVector: {
3786       assert(E->isAltShuffle() &&
3787              ((Instruction::isBinaryOp(E->getOpcode()) &&
3788                Instruction::isBinaryOp(E->getAltOpcode())) ||
3789               (Instruction::isCast(E->getOpcode()) &&
3790                Instruction::isCast(E->getAltOpcode()))) &&
3791              "Invalid Shuffle Vector Operand");
3792       int ScalarCost = 0;
3793       if (NeedToShuffleReuses) {
3794         for (unsigned Idx : E->ReuseShuffleIndices) {
3795           Instruction *I = cast<Instruction>(VL[Idx]);
3796           ReuseShuffleCost -= TTI->getInstructionCost(I, CostKind);
3797         }
3798         for (Value *V : VL) {
3799           Instruction *I = cast<Instruction>(V);
3800           ReuseShuffleCost += TTI->getInstructionCost(I, CostKind);
3801         }
3802       }
3803       for (Value *V : VL) {
3804         Instruction *I = cast<Instruction>(V);
3805         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
3806         ScalarCost += TTI->getInstructionCost(I, CostKind);
3807       }
3808       // VecCost is equal to sum of the cost of creating 2 vectors
3809       // and the cost of creating shuffle.
3810       int VecCost = 0;
3811       if (Instruction::isBinaryOp(E->getOpcode())) {
3812         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
3813         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
3814                                                CostKind);
3815       } else {
3816         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
3817         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
3818         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
3819         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
3820         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
3821                                         TTI::CastContextHint::None, CostKind);
3822         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
3823                                          TTI::CastContextHint::None, CostKind);
3824       }
3825       VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
3826       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3827       return ReuseShuffleCost + VecCost - ScalarCost;
3828     }
3829     default:
3830       llvm_unreachable("Unknown instruction");
3831   }
3832 }
3833 
3834 bool BoUpSLP::isFullyVectorizableTinyTree() const {
3835   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
3836                     << VectorizableTree.size() << " is fully vectorizable .\n");
3837 
3838   // We only handle trees of heights 1 and 2.
3839   if (VectorizableTree.size() == 1 &&
3840       VectorizableTree[0]->State == TreeEntry::Vectorize)
3841     return true;
3842 
3843   if (VectorizableTree.size() != 2)
3844     return false;
3845 
3846   // Handle splat and all-constants stores.
3847   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
3848       (allConstant(VectorizableTree[1]->Scalars) ||
3849        isSplat(VectorizableTree[1]->Scalars)))
3850     return true;
3851 
3852   // Gathering cost would be too much for tiny trees.
3853   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
3854       VectorizableTree[1]->State == TreeEntry::NeedToGather)
3855     return false;
3856 
3857   return true;
3858 }
3859 
3860 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
3861                                        TargetTransformInfo *TTI) {
3862   // Look past the root to find a source value. Arbitrarily follow the
3863   // path through operand 0 of any 'or'. Also, peek through optional
3864   // shift-left-by-multiple-of-8-bits.
3865   Value *ZextLoad = Root;
3866   const APInt *ShAmtC;
3867   while (!isa<ConstantExpr>(ZextLoad) &&
3868          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
3869           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
3870            ShAmtC->urem(8) == 0)))
3871     ZextLoad = cast<BinaryOperator>(ZextLoad)->getOperand(0);
3872 
3873   // Check if the input is an extended load of the required or/shift expression.
3874   Value *LoadPtr;
3875   if (ZextLoad == Root || !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
3876     return false;
3877 
3878   // Require that the total load bit width is a legal integer type.
3879   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
3880   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
3881   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
3882   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
3883   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
3884     return false;
3885 
3886   // Everything matched - assume that we can fold the whole sequence using
3887   // load combining.
3888   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
3889              << *(cast<Instruction>(Root)) << "\n");
3890 
3891   return true;
3892 }
3893 
3894 bool BoUpSLP::isLoadCombineReductionCandidate(unsigned RdxOpcode) const {
3895   if (RdxOpcode != Instruction::Or)
3896     return false;
3897 
3898   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3899   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
3900   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI);
3901 }
3902 
3903 bool BoUpSLP::isLoadCombineCandidate() const {
3904   // Peek through a final sequence of stores and check if all operations are
3905   // likely to be load-combined.
3906   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3907   for (Value *Scalar : VectorizableTree[0]->Scalars) {
3908     Value *X;
3909     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
3910         !isLoadCombineCandidateImpl(X, NumElts, TTI))
3911       return false;
3912   }
3913   return true;
3914 }
3915 
3916 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
3917   // We can vectorize the tree if its size is greater than or equal to the
3918   // minimum size specified by the MinTreeSize command line option.
3919   if (VectorizableTree.size() >= MinTreeSize)
3920     return false;
3921 
3922   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
3923   // can vectorize it if we can prove it fully vectorizable.
3924   if (isFullyVectorizableTinyTree())
3925     return false;
3926 
3927   assert(VectorizableTree.empty()
3928              ? ExternalUses.empty()
3929              : true && "We shouldn't have any external users");
3930 
3931   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
3932   // vectorizable.
3933   return true;
3934 }
3935 
3936 int BoUpSLP::getSpillCost() const {
3937   // Walk from the bottom of the tree to the top, tracking which values are
3938   // live. When we see a call instruction that is not part of our tree,
3939   // query TTI to see if there is a cost to keeping values live over it
3940   // (for example, if spills and fills are required).
3941   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
3942   int Cost = 0;
3943 
3944   SmallPtrSet<Instruction*, 4> LiveValues;
3945   Instruction *PrevInst = nullptr;
3946 
3947   // The entries in VectorizableTree are not necessarily ordered by their
3948   // position in basic blocks. Collect them and order them by dominance so later
3949   // instructions are guaranteed to be visited first. For instructions in
3950   // different basic blocks, we only scan to the beginning of the block, so
3951   // their order does not matter, as long as all instructions in a basic block
3952   // are grouped together. Using dominance ensures a deterministic order.
3953   SmallVector<Instruction *, 16> OrderedScalars;
3954   for (const auto &TEPtr : VectorizableTree) {
3955     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
3956     if (!Inst)
3957       continue;
3958     OrderedScalars.push_back(Inst);
3959   }
3960   llvm::stable_sort(OrderedScalars, [this](Instruction *A, Instruction *B) {
3961     return DT->dominates(B, A);
3962   });
3963 
3964   for (Instruction *Inst : OrderedScalars) {
3965     if (!PrevInst) {
3966       PrevInst = Inst;
3967       continue;
3968     }
3969 
3970     // Update LiveValues.
3971     LiveValues.erase(PrevInst);
3972     for (auto &J : PrevInst->operands()) {
3973       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
3974         LiveValues.insert(cast<Instruction>(&*J));
3975     }
3976 
3977     LLVM_DEBUG({
3978       dbgs() << "SLP: #LV: " << LiveValues.size();
3979       for (auto *X : LiveValues)
3980         dbgs() << " " << X->getName();
3981       dbgs() << ", Looking at ";
3982       Inst->dump();
3983     });
3984 
3985     // Now find the sequence of instructions between PrevInst and Inst.
3986     unsigned NumCalls = 0;
3987     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
3988                                  PrevInstIt =
3989                                      PrevInst->getIterator().getReverse();
3990     while (InstIt != PrevInstIt) {
3991       if (PrevInstIt == PrevInst->getParent()->rend()) {
3992         PrevInstIt = Inst->getParent()->rbegin();
3993         continue;
3994       }
3995 
3996       // Debug information does not impact spill cost.
3997       if ((isa<CallInst>(&*PrevInstIt) &&
3998            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
3999           &*PrevInstIt != PrevInst)
4000         NumCalls++;
4001 
4002       ++PrevInstIt;
4003     }
4004 
4005     if (NumCalls) {
4006       SmallVector<Type*, 4> V;
4007       for (auto *II : LiveValues)
4008         V.push_back(FixedVectorType::get(II->getType(), BundleWidth));
4009       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
4010     }
4011 
4012     PrevInst = Inst;
4013   }
4014 
4015   return Cost;
4016 }
4017 
4018 int BoUpSLP::getTreeCost() {
4019   int Cost = 0;
4020   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
4021                     << VectorizableTree.size() << ".\n");
4022 
4023   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
4024 
4025   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
4026     TreeEntry &TE = *VectorizableTree[I].get();
4027 
4028     // We create duplicate tree entries for gather sequences that have multiple
4029     // uses. However, we should not compute the cost of duplicate sequences.
4030     // For example, if we have a build vector (i.e., insertelement sequence)
4031     // that is used by more than one vector instruction, we only need to
4032     // compute the cost of the insertelement instructions once. The redundant
4033     // instructions will be eliminated by CSE.
4034     //
4035     // We should consider not creating duplicate tree entries for gather
4036     // sequences, and instead add additional edges to the tree representing
4037     // their uses. Since such an approach results in fewer total entries,
4038     // existing heuristics based on tree size may yield different results.
4039     //
4040     if (TE.State == TreeEntry::NeedToGather &&
4041         std::any_of(std::next(VectorizableTree.begin(), I + 1),
4042                     VectorizableTree.end(),
4043                     [TE](const std::unique_ptr<TreeEntry> &EntryPtr) {
4044                       return EntryPtr->State == TreeEntry::NeedToGather &&
4045                              EntryPtr->isSame(TE.Scalars);
4046                     }))
4047       continue;
4048 
4049     int C = getEntryCost(&TE);
4050     Cost += C;
4051     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
4052                       << " for bundle that starts with " << *TE.Scalars[0]
4053                       << ".\n"
4054                       << "SLP: Current total cost = " << Cost << "\n");
4055   }
4056 
4057   SmallPtrSet<Value *, 16> ExtractCostCalculated;
4058   int ExtractCost = 0;
4059   for (ExternalUser &EU : ExternalUses) {
4060     // We only add extract cost once for the same scalar.
4061     if (!ExtractCostCalculated.insert(EU.Scalar).second)
4062       continue;
4063 
4064     // Uses by ephemeral values are free (because the ephemeral value will be
4065     // removed prior to code generation, and so the extraction will be
4066     // removed as well).
4067     if (EphValues.count(EU.User))
4068       continue;
4069 
4070     // If we plan to rewrite the tree in a smaller type, we will need to sign
4071     // extend the extracted value back to the original type. Here, we account
4072     // for the extract and the added cost of the sign extend if needed.
4073     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
4074     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4075     if (MinBWs.count(ScalarRoot)) {
4076       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4077       auto Extend =
4078           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
4079       VecTy = FixedVectorType::get(MinTy, BundleWidth);
4080       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
4081                                                    VecTy, EU.Lane);
4082     } else {
4083       ExtractCost +=
4084           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
4085     }
4086   }
4087 
4088   int SpillCost = getSpillCost();
4089   Cost += SpillCost + ExtractCost;
4090 
4091 #ifndef NDEBUG
4092   SmallString<256> Str;
4093   {
4094     raw_svector_ostream OS(Str);
4095     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
4096        << "SLP: Extract Cost = " << ExtractCost << ".\n"
4097        << "SLP: Total Cost = " << Cost << ".\n";
4098   }
4099   LLVM_DEBUG(dbgs() << Str);
4100   if (ViewSLPTree)
4101     ViewGraph(this, "SLP" + F->getName(), false, Str);
4102 #endif
4103 
4104   return Cost;
4105 }
4106 
4107 int BoUpSLP::getGatherCost(FixedVectorType *Ty,
4108                            const DenseSet<unsigned> &ShuffledIndices) const {
4109   unsigned NumElts = Ty->getNumElements();
4110   APInt DemandedElts = APInt::getNullValue(NumElts);
4111   for (unsigned I = 0; I < NumElts; ++I)
4112     if (!ShuffledIndices.count(I))
4113       DemandedElts.setBit(I);
4114   int Cost = TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
4115                                            /*Extract*/ false);
4116   if (!ShuffledIndices.empty())
4117     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
4118   return Cost;
4119 }
4120 
4121 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
4122   // Find the type of the operands in VL.
4123   Type *ScalarTy = VL[0]->getType();
4124   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4125     ScalarTy = SI->getValueOperand()->getType();
4126   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4127   // Find the cost of inserting/extracting values from the vector.
4128   // Check if the same elements are inserted several times and count them as
4129   // shuffle candidates.
4130   DenseSet<unsigned> ShuffledElements;
4131   DenseSet<Value *> UniqueElements;
4132   // Iterate in reverse order to consider insert elements with the high cost.
4133   for (unsigned I = VL.size(); I > 0; --I) {
4134     unsigned Idx = I - 1;
4135     if (!UniqueElements.insert(VL[Idx]).second)
4136       ShuffledElements.insert(Idx);
4137   }
4138   return getGatherCost(VecTy, ShuffledElements);
4139 }
4140 
4141 // Perform operand reordering on the instructions in VL and return the reordered
4142 // operands in Left and Right.
4143 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
4144                                              SmallVectorImpl<Value *> &Left,
4145                                              SmallVectorImpl<Value *> &Right,
4146                                              const DataLayout &DL,
4147                                              ScalarEvolution &SE,
4148                                              const BoUpSLP &R) {
4149   if (VL.empty())
4150     return;
4151   VLOperands Ops(VL, DL, SE, R);
4152   // Reorder the operands in place.
4153   Ops.reorder();
4154   Left = Ops.getVL(0);
4155   Right = Ops.getVL(1);
4156 }
4157 
4158 void BoUpSLP::setInsertPointAfterBundle(TreeEntry *E) {
4159   // Get the basic block this bundle is in. All instructions in the bundle
4160   // should be in this block.
4161   auto *Front = E->getMainOp();
4162   auto *BB = Front->getParent();
4163   assert(llvm::all_of(make_range(E->Scalars.begin(), E->Scalars.end()),
4164                       [=](Value *V) -> bool {
4165                         auto *I = cast<Instruction>(V);
4166                         return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
4167                       }));
4168 
4169   // The last instruction in the bundle in program order.
4170   Instruction *LastInst = nullptr;
4171 
4172   // Find the last instruction. The common case should be that BB has been
4173   // scheduled, and the last instruction is VL.back(). So we start with
4174   // VL.back() and iterate over schedule data until we reach the end of the
4175   // bundle. The end of the bundle is marked by null ScheduleData.
4176   if (BlocksSchedules.count(BB)) {
4177     auto *Bundle =
4178         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
4179     if (Bundle && Bundle->isPartOfBundle())
4180       for (; Bundle; Bundle = Bundle->NextInBundle)
4181         if (Bundle->OpValue == Bundle->Inst)
4182           LastInst = Bundle->Inst;
4183   }
4184 
4185   // LastInst can still be null at this point if there's either not an entry
4186   // for BB in BlocksSchedules or there's no ScheduleData available for
4187   // VL.back(). This can be the case if buildTree_rec aborts for various
4188   // reasons (e.g., the maximum recursion depth is reached, the maximum region
4189   // size is reached, etc.). ScheduleData is initialized in the scheduling
4190   // "dry-run".
4191   //
4192   // If this happens, we can still find the last instruction by brute force. We
4193   // iterate forwards from Front (inclusive) until we either see all
4194   // instructions in the bundle or reach the end of the block. If Front is the
4195   // last instruction in program order, LastInst will be set to Front, and we
4196   // will visit all the remaining instructions in the block.
4197   //
4198   // One of the reasons we exit early from buildTree_rec is to place an upper
4199   // bound on compile-time. Thus, taking an additional compile-time hit here is
4200   // not ideal. However, this should be exceedingly rare since it requires that
4201   // we both exit early from buildTree_rec and that the bundle be out-of-order
4202   // (causing us to iterate all the way to the end of the block).
4203   if (!LastInst) {
4204     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
4205     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
4206       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
4207         LastInst = &I;
4208       if (Bundle.empty())
4209         break;
4210     }
4211   }
4212   assert(LastInst && "Failed to find last instruction in bundle");
4213 
4214   // Set the insertion point after the last instruction in the bundle. Set the
4215   // debug location to Front.
4216   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
4217   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
4218 }
4219 
4220 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
4221   Value *Val0 =
4222       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
4223   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
4224   Value *Vec = UndefValue::get(VecTy);
4225   unsigned InsIndex = 0;
4226   for (Value *Val : VL) {
4227     Vec = Builder.CreateInsertElement(Vec, Val, Builder.getInt32(InsIndex++));
4228     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
4229     if (!InsElt)
4230       continue;
4231     GatherSeq.insert(InsElt);
4232     CSEBlocks.insert(InsElt->getParent());
4233     // Add to our 'need-to-extract' list.
4234     if (TreeEntry *Entry = getTreeEntry(Val)) {
4235       // Find which lane we need to extract.
4236       unsigned FoundLane = std::distance(Entry->Scalars.begin(),
4237                                          find(Entry->Scalars, Val));
4238       assert(FoundLane < Entry->Scalars.size() && "Couldn't find extract lane");
4239       if (!Entry->ReuseShuffleIndices.empty()) {
4240         FoundLane = std::distance(Entry->ReuseShuffleIndices.begin(),
4241                                   find(Entry->ReuseShuffleIndices, FoundLane));
4242       }
4243       ExternalUses.push_back(ExternalUser(Val, InsElt, FoundLane));
4244     }
4245   }
4246 
4247   return Vec;
4248 }
4249 
4250 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
4251   InstructionsState S = getSameOpcode(VL);
4252   if (S.getOpcode()) {
4253     if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4254       if (E->isSame(VL)) {
4255         Value *V = vectorizeTree(E);
4256         if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
4257           // We need to get the vectorized value but without shuffle.
4258           if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
4259             V = SV->getOperand(0);
4260           } else {
4261             // Reshuffle to get only unique values.
4262             SmallVector<int, 4> UniqueIdxs;
4263             SmallSet<int, 4> UsedIdxs;
4264             for (int Idx : E->ReuseShuffleIndices)
4265               if (UsedIdxs.insert(Idx).second)
4266                 UniqueIdxs.emplace_back(Idx);
4267             V = Builder.CreateShuffleVector(V, UniqueIdxs);
4268           }
4269         }
4270         return V;
4271       }
4272     }
4273   }
4274 
4275   // Check that every instruction appears once in this bundle.
4276   SmallVector<int, 4> ReuseShuffleIndicies;
4277   SmallVector<Value *, 4> UniqueValues;
4278   if (VL.size() > 2) {
4279     DenseMap<Value *, unsigned> UniquePositions;
4280     for (Value *V : VL) {
4281       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4282       ReuseShuffleIndicies.emplace_back(Res.first->second);
4283       if (Res.second || isa<Constant>(V))
4284         UniqueValues.emplace_back(V);
4285     }
4286     // Do not shuffle single element or if number of unique values is not power
4287     // of 2.
4288     if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
4289         !llvm::isPowerOf2_32(UniqueValues.size()))
4290       ReuseShuffleIndicies.clear();
4291     else
4292       VL = UniqueValues;
4293   }
4294 
4295   Value *Vec = gather(VL);
4296   if (!ReuseShuffleIndicies.empty()) {
4297     Vec = Builder.CreateShuffleVector(Vec, ReuseShuffleIndicies, "shuffle");
4298     if (auto *I = dyn_cast<Instruction>(Vec)) {
4299       GatherSeq.insert(I);
4300       CSEBlocks.insert(I->getParent());
4301     }
4302   }
4303   return Vec;
4304 }
4305 
4306 namespace {
4307 /// Merges shuffle masks and emits final shuffle instruction, if required.
4308 class ShuffleInstructionBuilder {
4309   IRBuilderBase &Builder;
4310   bool IsFinalized = false;
4311   SmallVector<int, 4> Mask;
4312 
4313 public:
4314   ShuffleInstructionBuilder(IRBuilderBase &Builder) : Builder(Builder) {}
4315 
4316   /// Adds a mask, inverting it before applying.
4317   void addInversedMask(ArrayRef<unsigned> SubMask) {
4318     if (SubMask.empty())
4319       return;
4320     SmallVector<int, 4> NewMask;
4321     inversePermutation(SubMask, NewMask);
4322     addMask(NewMask);
4323   }
4324 
4325   /// Functions adds masks, merging them into  single one.
4326   void addMask(ArrayRef<unsigned> SubMask) {
4327     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
4328     addMask(NewMask);
4329   }
4330 
4331   void addMask(ArrayRef<int> SubMask) {
4332     if (SubMask.empty())
4333       return;
4334     if (Mask.empty()) {
4335       Mask.append(SubMask.begin(), SubMask.end());
4336       return;
4337     }
4338     SmallVector<int, 4> NewMask(SubMask.size(), SubMask.size());
4339     int TermValue = std::min(Mask.size(), SubMask.size());
4340     for (int I = 0, E = SubMask.size(); I < E; ++I) {
4341       if (SubMask[I] >= TermValue || Mask[SubMask[I]] >= TermValue) {
4342         NewMask[I] = E;
4343         continue;
4344       }
4345       NewMask[I] = Mask[SubMask[I]];
4346     }
4347     Mask.swap(NewMask);
4348   }
4349 
4350   Value *finalize(Value *V) {
4351     IsFinalized = true;
4352     if (Mask.empty())
4353       return V;
4354     return Builder.CreateShuffleVector(V, Mask, "shuffle");
4355   }
4356 
4357   ~ShuffleInstructionBuilder() {
4358     assert((IsFinalized || Mask.empty()) &&
4359            "Must be finalized construction of the shuffles.");
4360   }
4361 };
4362 } // namespace
4363 
4364 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
4365   IRBuilder<>::InsertPointGuard Guard(Builder);
4366 
4367   if (E->VectorizedValue) {
4368     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
4369     return E->VectorizedValue;
4370   }
4371 
4372   ShuffleInstructionBuilder ShuffleBuilder(Builder);
4373   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4374   if (E->State == TreeEntry::NeedToGather) {
4375     setInsertPointAfterBundle(E);
4376     Value *Vec = gather(E->Scalars);
4377     if (NeedToShuffleReuses) {
4378       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4379       Vec = ShuffleBuilder.finalize(Vec);
4380       if (auto *I = dyn_cast<Instruction>(Vec)) {
4381         GatherSeq.insert(I);
4382         CSEBlocks.insert(I->getParent());
4383       }
4384     }
4385     E->VectorizedValue = Vec;
4386     return Vec;
4387   }
4388 
4389   assert((E->State == TreeEntry::Vectorize ||
4390           E->State == TreeEntry::ScatterVectorize) &&
4391          "Unhandled state");
4392   unsigned ShuffleOrOp =
4393       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4394   Instruction *VL0 = E->getMainOp();
4395   Type *ScalarTy = VL0->getType();
4396   if (auto *Store = dyn_cast<StoreInst>(VL0))
4397     ScalarTy = Store->getValueOperand()->getType();
4398   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
4399   switch (ShuffleOrOp) {
4400     case Instruction::PHI: {
4401       auto *PH = cast<PHINode>(VL0);
4402       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
4403       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4404       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
4405       Value *V = NewPhi;
4406       if (NeedToShuffleReuses)
4407         V = Builder.CreateShuffleVector(V, E->ReuseShuffleIndices, "shuffle");
4408 
4409       E->VectorizedValue = V;
4410 
4411       // PHINodes may have multiple entries from the same block. We want to
4412       // visit every block once.
4413       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
4414 
4415       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
4416         ValueList Operands;
4417         BasicBlock *IBB = PH->getIncomingBlock(i);
4418 
4419         if (!VisitedBBs.insert(IBB).second) {
4420           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
4421           continue;
4422         }
4423 
4424         Builder.SetInsertPoint(IBB->getTerminator());
4425         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4426         Value *Vec = vectorizeTree(E->getOperand(i));
4427         NewPhi->addIncoming(Vec, IBB);
4428       }
4429 
4430       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
4431              "Invalid number of incoming values");
4432       return V;
4433     }
4434 
4435     case Instruction::ExtractElement: {
4436       Value *V = E->getSingleOperand(0);
4437       Builder.SetInsertPoint(VL0);
4438       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4439       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4440       V = ShuffleBuilder.finalize(V);
4441       E->VectorizedValue = V;
4442       return V;
4443     }
4444     case Instruction::ExtractValue: {
4445       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
4446       Builder.SetInsertPoint(LI);
4447       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
4448       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
4449       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
4450       Value *NewV = propagateMetadata(V, E->Scalars);
4451       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4452       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4453       NewV = ShuffleBuilder.finalize(NewV);
4454       E->VectorizedValue = NewV;
4455       return NewV;
4456     }
4457     case Instruction::ZExt:
4458     case Instruction::SExt:
4459     case Instruction::FPToUI:
4460     case Instruction::FPToSI:
4461     case Instruction::FPExt:
4462     case Instruction::PtrToInt:
4463     case Instruction::IntToPtr:
4464     case Instruction::SIToFP:
4465     case Instruction::UIToFP:
4466     case Instruction::Trunc:
4467     case Instruction::FPTrunc:
4468     case Instruction::BitCast: {
4469       setInsertPointAfterBundle(E);
4470 
4471       Value *InVec = vectorizeTree(E->getOperand(0));
4472 
4473       if (E->VectorizedValue) {
4474         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4475         return E->VectorizedValue;
4476       }
4477 
4478       auto *CI = cast<CastInst>(VL0);
4479       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
4480       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4481       V = ShuffleBuilder.finalize(V);
4482 
4483       E->VectorizedValue = V;
4484       ++NumVectorInstructions;
4485       return V;
4486     }
4487     case Instruction::FCmp:
4488     case Instruction::ICmp: {
4489       setInsertPointAfterBundle(E);
4490 
4491       Value *L = vectorizeTree(E->getOperand(0));
4492       Value *R = vectorizeTree(E->getOperand(1));
4493 
4494       if (E->VectorizedValue) {
4495         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4496         return E->VectorizedValue;
4497       }
4498 
4499       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4500       Value *V = Builder.CreateCmp(P0, L, R);
4501       propagateIRFlags(V, E->Scalars, VL0);
4502       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4503       V = ShuffleBuilder.finalize(V);
4504 
4505       E->VectorizedValue = V;
4506       ++NumVectorInstructions;
4507       return V;
4508     }
4509     case Instruction::Select: {
4510       setInsertPointAfterBundle(E);
4511 
4512       Value *Cond = vectorizeTree(E->getOperand(0));
4513       Value *True = vectorizeTree(E->getOperand(1));
4514       Value *False = vectorizeTree(E->getOperand(2));
4515 
4516       if (E->VectorizedValue) {
4517         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4518         return E->VectorizedValue;
4519       }
4520 
4521       Value *V = Builder.CreateSelect(Cond, True, False);
4522       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4523       V = ShuffleBuilder.finalize(V);
4524 
4525       E->VectorizedValue = V;
4526       ++NumVectorInstructions;
4527       return V;
4528     }
4529     case Instruction::FNeg: {
4530       setInsertPointAfterBundle(E);
4531 
4532       Value *Op = vectorizeTree(E->getOperand(0));
4533 
4534       if (E->VectorizedValue) {
4535         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4536         return E->VectorizedValue;
4537       }
4538 
4539       Value *V = Builder.CreateUnOp(
4540           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
4541       propagateIRFlags(V, E->Scalars, VL0);
4542       if (auto *I = dyn_cast<Instruction>(V))
4543         V = propagateMetadata(I, E->Scalars);
4544 
4545       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4546       V = ShuffleBuilder.finalize(V);
4547 
4548       E->VectorizedValue = V;
4549       ++NumVectorInstructions;
4550 
4551       return V;
4552     }
4553     case Instruction::Add:
4554     case Instruction::FAdd:
4555     case Instruction::Sub:
4556     case Instruction::FSub:
4557     case Instruction::Mul:
4558     case Instruction::FMul:
4559     case Instruction::UDiv:
4560     case Instruction::SDiv:
4561     case Instruction::FDiv:
4562     case Instruction::URem:
4563     case Instruction::SRem:
4564     case Instruction::FRem:
4565     case Instruction::Shl:
4566     case Instruction::LShr:
4567     case Instruction::AShr:
4568     case Instruction::And:
4569     case Instruction::Or:
4570     case Instruction::Xor: {
4571       setInsertPointAfterBundle(E);
4572 
4573       Value *LHS = vectorizeTree(E->getOperand(0));
4574       Value *RHS = vectorizeTree(E->getOperand(1));
4575 
4576       if (E->VectorizedValue) {
4577         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4578         return E->VectorizedValue;
4579       }
4580 
4581       Value *V = Builder.CreateBinOp(
4582           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
4583           RHS);
4584       propagateIRFlags(V, E->Scalars, VL0);
4585       if (auto *I = dyn_cast<Instruction>(V))
4586         V = propagateMetadata(I, E->Scalars);
4587 
4588       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4589       V = ShuffleBuilder.finalize(V);
4590 
4591       E->VectorizedValue = V;
4592       ++NumVectorInstructions;
4593 
4594       return V;
4595     }
4596     case Instruction::Load: {
4597       // Loads are inserted at the head of the tree because we don't want to
4598       // sink them all the way down past store instructions.
4599       bool IsReorder = E->updateStateIfReorder();
4600       if (IsReorder)
4601         VL0 = E->getMainOp();
4602       setInsertPointAfterBundle(E);
4603 
4604       LoadInst *LI = cast<LoadInst>(VL0);
4605       Instruction *NewLI;
4606       unsigned AS = LI->getPointerAddressSpace();
4607       Value *PO = LI->getPointerOperand();
4608       if (E->State == TreeEntry::Vectorize) {
4609 
4610         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
4611 
4612         // The pointer operand uses an in-tree scalar so we add the new BitCast
4613         // to ExternalUses list to make sure that an extract will be generated
4614         // in the future.
4615         if (getTreeEntry(PO))
4616           ExternalUses.emplace_back(PO, cast<User>(VecPtr), 0);
4617 
4618         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
4619       } else {
4620         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
4621         Value *VecPtr = vectorizeTree(E->getOperand(0));
4622         // Use the minimum alignment of the gathered loads.
4623         Align CommonAlignment = LI->getAlign();
4624         for (Value *V : E->Scalars)
4625           CommonAlignment =
4626               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4627         NewLI = Builder.CreateMaskedGather(VecPtr, CommonAlignment);
4628       }
4629       Value *V = propagateMetadata(NewLI, E->Scalars);
4630 
4631       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4632       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4633       V = ShuffleBuilder.finalize(V);
4634       E->VectorizedValue = V;
4635       ++NumVectorInstructions;
4636       return V;
4637     }
4638     case Instruction::Store: {
4639       bool IsReorder = !E->ReorderIndices.empty();
4640       auto *SI = cast<StoreInst>(
4641           IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0);
4642       unsigned AS = SI->getPointerAddressSpace();
4643 
4644       setInsertPointAfterBundle(E);
4645 
4646       Value *VecValue = vectorizeTree(E->getOperand(0));
4647       ShuffleBuilder.addMask(E->ReorderIndices);
4648       VecValue = ShuffleBuilder.finalize(VecValue);
4649 
4650       Value *ScalarPtr = SI->getPointerOperand();
4651       Value *VecPtr = Builder.CreateBitCast(
4652           ScalarPtr, VecValue->getType()->getPointerTo(AS));
4653       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
4654                                                  SI->getAlign());
4655 
4656       // The pointer operand uses an in-tree scalar, so add the new BitCast to
4657       // ExternalUses to make sure that an extract will be generated in the
4658       // future.
4659       if (getTreeEntry(ScalarPtr))
4660         ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
4661 
4662       Value *V = propagateMetadata(ST, E->Scalars);
4663 
4664       E->VectorizedValue = V;
4665       ++NumVectorInstructions;
4666       return V;
4667     }
4668     case Instruction::GetElementPtr: {
4669       setInsertPointAfterBundle(E);
4670 
4671       Value *Op0 = vectorizeTree(E->getOperand(0));
4672 
4673       std::vector<Value *> OpVecs;
4674       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
4675            ++j) {
4676         ValueList &VL = E->getOperand(j);
4677         // Need to cast all elements to the same type before vectorization to
4678         // avoid crash.
4679         Type *VL0Ty = VL0->getOperand(j)->getType();
4680         Type *Ty = llvm::all_of(
4681                        VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
4682                        ? VL0Ty
4683                        : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4684                                               ->getPointerOperandType()
4685                                               ->getScalarType());
4686         for (Value *&V : VL) {
4687           auto *CI = cast<ConstantInt>(V);
4688           V = ConstantExpr::getIntegerCast(CI, Ty,
4689                                            CI->getValue().isSignBitSet());
4690         }
4691         Value *OpVec = vectorizeTree(VL);
4692         OpVecs.push_back(OpVec);
4693       }
4694 
4695       Value *V = Builder.CreateGEP(
4696           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
4697       if (Instruction *I = dyn_cast<Instruction>(V))
4698         V = propagateMetadata(I, E->Scalars);
4699 
4700       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4701       V = ShuffleBuilder.finalize(V);
4702 
4703       E->VectorizedValue = V;
4704       ++NumVectorInstructions;
4705 
4706       return V;
4707     }
4708     case Instruction::Call: {
4709       CallInst *CI = cast<CallInst>(VL0);
4710       setInsertPointAfterBundle(E);
4711 
4712       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
4713       if (Function *FI = CI->getCalledFunction())
4714         IID = FI->getIntrinsicID();
4715 
4716       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4717 
4718       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4719       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
4720                           VecCallCosts.first <= VecCallCosts.second;
4721 
4722       Value *ScalarArg = nullptr;
4723       std::vector<Value *> OpVecs;
4724       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
4725         ValueList OpVL;
4726         // Some intrinsics have scalar arguments. This argument should not be
4727         // vectorized.
4728         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
4729           CallInst *CEI = cast<CallInst>(VL0);
4730           ScalarArg = CEI->getArgOperand(j);
4731           OpVecs.push_back(CEI->getArgOperand(j));
4732           continue;
4733         }
4734 
4735         Value *OpVec = vectorizeTree(E->getOperand(j));
4736         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
4737         OpVecs.push_back(OpVec);
4738       }
4739 
4740       Function *CF;
4741       if (!UseIntrinsic) {
4742         VFShape Shape =
4743             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4744                                   VecTy->getNumElements())),
4745                          false /*HasGlobalPred*/);
4746         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
4747       } else {
4748         Type *Tys[] = {FixedVectorType::get(CI->getType(), E->Scalars.size())};
4749         CF = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
4750       }
4751 
4752       SmallVector<OperandBundleDef, 1> OpBundles;
4753       CI->getOperandBundlesAsDefs(OpBundles);
4754       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
4755 
4756       // The scalar argument uses an in-tree scalar so we add the new vectorized
4757       // call to ExternalUses list to make sure that an extract will be
4758       // generated in the future.
4759       if (ScalarArg && getTreeEntry(ScalarArg))
4760         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
4761 
4762       propagateIRFlags(V, E->Scalars, VL0);
4763       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4764       V = ShuffleBuilder.finalize(V);
4765 
4766       E->VectorizedValue = V;
4767       ++NumVectorInstructions;
4768       return V;
4769     }
4770     case Instruction::ShuffleVector: {
4771       assert(E->isAltShuffle() &&
4772              ((Instruction::isBinaryOp(E->getOpcode()) &&
4773                Instruction::isBinaryOp(E->getAltOpcode())) ||
4774               (Instruction::isCast(E->getOpcode()) &&
4775                Instruction::isCast(E->getAltOpcode()))) &&
4776              "Invalid Shuffle Vector Operand");
4777 
4778       Value *LHS = nullptr, *RHS = nullptr;
4779       if (Instruction::isBinaryOp(E->getOpcode())) {
4780         setInsertPointAfterBundle(E);
4781         LHS = vectorizeTree(E->getOperand(0));
4782         RHS = vectorizeTree(E->getOperand(1));
4783       } else {
4784         setInsertPointAfterBundle(E);
4785         LHS = vectorizeTree(E->getOperand(0));
4786       }
4787 
4788       if (E->VectorizedValue) {
4789         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4790         return E->VectorizedValue;
4791       }
4792 
4793       Value *V0, *V1;
4794       if (Instruction::isBinaryOp(E->getOpcode())) {
4795         V0 = Builder.CreateBinOp(
4796             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
4797         V1 = Builder.CreateBinOp(
4798             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
4799       } else {
4800         V0 = Builder.CreateCast(
4801             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
4802         V1 = Builder.CreateCast(
4803             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
4804       }
4805 
4806       // Create shuffle to take alternate operations from the vector.
4807       // Also, gather up main and alt scalar ops to propagate IR flags to
4808       // each vector operation.
4809       ValueList OpScalars, AltScalars;
4810       unsigned e = E->Scalars.size();
4811       SmallVector<int, 8> Mask(e);
4812       for (unsigned i = 0; i < e; ++i) {
4813         auto *OpInst = cast<Instruction>(E->Scalars[i]);
4814         assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
4815         if (OpInst->getOpcode() == E->getAltOpcode()) {
4816           Mask[i] = e + i;
4817           AltScalars.push_back(E->Scalars[i]);
4818         } else {
4819           Mask[i] = i;
4820           OpScalars.push_back(E->Scalars[i]);
4821         }
4822       }
4823 
4824       propagateIRFlags(V0, OpScalars);
4825       propagateIRFlags(V1, AltScalars);
4826 
4827       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
4828       if (Instruction *I = dyn_cast<Instruction>(V))
4829         V = propagateMetadata(I, E->Scalars);
4830       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4831       V = ShuffleBuilder.finalize(V);
4832 
4833       E->VectorizedValue = V;
4834       ++NumVectorInstructions;
4835 
4836       return V;
4837     }
4838     default:
4839     llvm_unreachable("unknown inst");
4840   }
4841   return nullptr;
4842 }
4843 
4844 Value *BoUpSLP::vectorizeTree() {
4845   ExtraValueToDebugLocsMap ExternallyUsedValues;
4846   return vectorizeTree(ExternallyUsedValues);
4847 }
4848 
4849 Value *
4850 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4851   // All blocks must be scheduled before any instructions are inserted.
4852   for (auto &BSIter : BlocksSchedules) {
4853     scheduleBlock(BSIter.second.get());
4854   }
4855 
4856   Builder.SetInsertPoint(&F->getEntryBlock().front());
4857   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
4858 
4859   // If the vectorized tree can be rewritten in a smaller type, we truncate the
4860   // vectorized root. InstCombine will then rewrite the entire expression. We
4861   // sign extend the extracted values below.
4862   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4863   if (MinBWs.count(ScalarRoot)) {
4864     if (auto *I = dyn_cast<Instruction>(VectorRoot))
4865       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
4866     auto BundleWidth = VectorizableTree[0]->Scalars.size();
4867     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4868     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
4869     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
4870     VectorizableTree[0]->VectorizedValue = Trunc;
4871   }
4872 
4873   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
4874                     << " values .\n");
4875 
4876   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4877   // specified by ScalarType.
4878   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
4879     if (!MinBWs.count(ScalarRoot))
4880       return Ex;
4881     if (MinBWs[ScalarRoot].second)
4882       return Builder.CreateSExt(Ex, ScalarType);
4883     return Builder.CreateZExt(Ex, ScalarType);
4884   };
4885 
4886   // Extract all of the elements with the external uses.
4887   for (const auto &ExternalUse : ExternalUses) {
4888     Value *Scalar = ExternalUse.Scalar;
4889     llvm::User *User = ExternalUse.User;
4890 
4891     // Skip users that we already RAUW. This happens when one instruction
4892     // has multiple uses of the same value.
4893     if (User && !is_contained(Scalar->users(), User))
4894       continue;
4895     TreeEntry *E = getTreeEntry(Scalar);
4896     assert(E && "Invalid scalar");
4897     assert(E->State != TreeEntry::NeedToGather &&
4898            "Extracting from a gather list");
4899 
4900     Value *Vec = E->VectorizedValue;
4901     assert(Vec && "Can't find vectorizable value");
4902 
4903     Value *Lane = Builder.getInt32(ExternalUse.Lane);
4904     // If User == nullptr, the Scalar is used as extra arg. Generate
4905     // ExtractElement instruction and update the record for this scalar in
4906     // ExternallyUsedValues.
4907     if (!User) {
4908       assert(ExternallyUsedValues.count(Scalar) &&
4909              "Scalar with nullptr as an external user must be registered in "
4910              "ExternallyUsedValues map");
4911       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4912         Builder.SetInsertPoint(VecI->getParent(),
4913                                std::next(VecI->getIterator()));
4914       } else {
4915         Builder.SetInsertPoint(&F->getEntryBlock().front());
4916       }
4917       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4918       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4919       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
4920       auto &Locs = ExternallyUsedValues[Scalar];
4921       ExternallyUsedValues.insert({Ex, Locs});
4922       ExternallyUsedValues.erase(Scalar);
4923       // Required to update internally referenced instructions.
4924       Scalar->replaceAllUsesWith(Ex);
4925       continue;
4926     }
4927 
4928     // Generate extracts for out-of-tree users.
4929     // Find the insertion point for the extractelement lane.
4930     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4931       if (PHINode *PH = dyn_cast<PHINode>(User)) {
4932         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
4933           if (PH->getIncomingValue(i) == Scalar) {
4934             Instruction *IncomingTerminator =
4935                 PH->getIncomingBlock(i)->getTerminator();
4936             if (isa<CatchSwitchInst>(IncomingTerminator)) {
4937               Builder.SetInsertPoint(VecI->getParent(),
4938                                      std::next(VecI->getIterator()));
4939             } else {
4940               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
4941             }
4942             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4943             Ex = extend(ScalarRoot, Ex, Scalar->getType());
4944             CSEBlocks.insert(PH->getIncomingBlock(i));
4945             PH->setOperand(i, Ex);
4946           }
4947         }
4948       } else {
4949         Builder.SetInsertPoint(cast<Instruction>(User));
4950         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4951         Ex = extend(ScalarRoot, Ex, Scalar->getType());
4952         CSEBlocks.insert(cast<Instruction>(User)->getParent());
4953         User->replaceUsesOfWith(Scalar, Ex);
4954       }
4955     } else {
4956       Builder.SetInsertPoint(&F->getEntryBlock().front());
4957       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4958       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4959       CSEBlocks.insert(&F->getEntryBlock());
4960       User->replaceUsesOfWith(Scalar, Ex);
4961     }
4962 
4963     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
4964   }
4965 
4966   // For each vectorized value:
4967   for (auto &TEPtr : VectorizableTree) {
4968     TreeEntry *Entry = TEPtr.get();
4969 
4970     // No need to handle users of gathered values.
4971     if (Entry->State == TreeEntry::NeedToGather)
4972       continue;
4973 
4974     assert(Entry->VectorizedValue && "Can't find vectorizable value");
4975 
4976     // For each lane:
4977     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4978       Value *Scalar = Entry->Scalars[Lane];
4979 
4980 #ifndef NDEBUG
4981       Type *Ty = Scalar->getType();
4982       if (!Ty->isVoidTy()) {
4983         for (User *U : Scalar->users()) {
4984           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
4985 
4986           // It is legal to delete users in the ignorelist.
4987           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
4988                  "Deleting out-of-tree value");
4989         }
4990       }
4991 #endif
4992       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
4993       eraseInstruction(cast<Instruction>(Scalar));
4994     }
4995   }
4996 
4997   Builder.ClearInsertionPoint();
4998   InstrElementSize.clear();
4999 
5000   return VectorizableTree[0]->VectorizedValue;
5001 }
5002 
5003 void BoUpSLP::optimizeGatherSequence() {
5004   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
5005                     << " gather sequences instructions.\n");
5006   // LICM InsertElementInst sequences.
5007   for (Instruction *I : GatherSeq) {
5008     if (isDeleted(I))
5009       continue;
5010 
5011     // Check if this block is inside a loop.
5012     Loop *L = LI->getLoopFor(I->getParent());
5013     if (!L)
5014       continue;
5015 
5016     // Check if it has a preheader.
5017     BasicBlock *PreHeader = L->getLoopPreheader();
5018     if (!PreHeader)
5019       continue;
5020 
5021     // If the vector or the element that we insert into it are
5022     // instructions that are defined in this basic block then we can't
5023     // hoist this instruction.
5024     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
5025     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
5026     if (Op0 && L->contains(Op0))
5027       continue;
5028     if (Op1 && L->contains(Op1))
5029       continue;
5030 
5031     // We can hoist this instruction. Move it to the pre-header.
5032     I->moveBefore(PreHeader->getTerminator());
5033   }
5034 
5035   // Make a list of all reachable blocks in our CSE queue.
5036   SmallVector<const DomTreeNode *, 8> CSEWorkList;
5037   CSEWorkList.reserve(CSEBlocks.size());
5038   for (BasicBlock *BB : CSEBlocks)
5039     if (DomTreeNode *N = DT->getNode(BB)) {
5040       assert(DT->isReachableFromEntry(N));
5041       CSEWorkList.push_back(N);
5042     }
5043 
5044   // Sort blocks by domination. This ensures we visit a block after all blocks
5045   // dominating it are visited.
5046   llvm::stable_sort(CSEWorkList,
5047                     [this](const DomTreeNode *A, const DomTreeNode *B) {
5048                       return DT->properlyDominates(A, B);
5049                     });
5050 
5051   // Perform O(N^2) search over the gather sequences and merge identical
5052   // instructions. TODO: We can further optimize this scan if we split the
5053   // instructions into different buckets based on the insert lane.
5054   SmallVector<Instruction *, 16> Visited;
5055   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
5056     assert(*I &&
5057            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
5058            "Worklist not sorted properly!");
5059     BasicBlock *BB = (*I)->getBlock();
5060     // For all instructions in blocks containing gather sequences:
5061     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
5062       Instruction *In = &*it++;
5063       if (isDeleted(In))
5064         continue;
5065       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
5066         continue;
5067 
5068       // Check if we can replace this instruction with any of the
5069       // visited instructions.
5070       for (Instruction *v : Visited) {
5071         if (In->isIdenticalTo(v) &&
5072             DT->dominates(v->getParent(), In->getParent())) {
5073           In->replaceAllUsesWith(v);
5074           eraseInstruction(In);
5075           In = nullptr;
5076           break;
5077         }
5078       }
5079       if (In) {
5080         assert(!is_contained(Visited, In));
5081         Visited.push_back(In);
5082       }
5083     }
5084   }
5085   CSEBlocks.clear();
5086   GatherSeq.clear();
5087 }
5088 
5089 // Groups the instructions to a bundle (which is then a single scheduling entity)
5090 // and schedules instructions until the bundle gets ready.
5091 Optional<BoUpSLP::ScheduleData *>
5092 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
5093                                             const InstructionsState &S) {
5094   if (isa<PHINode>(S.OpValue))
5095     return nullptr;
5096 
5097   // Initialize the instruction bundle.
5098   Instruction *OldScheduleEnd = ScheduleEnd;
5099   ScheduleData *PrevInBundle = nullptr;
5100   ScheduleData *Bundle = nullptr;
5101   bool ReSchedule = false;
5102   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
5103 
5104   // Make sure that the scheduling region contains all
5105   // instructions of the bundle.
5106   for (Value *V : VL) {
5107     if (!extendSchedulingRegion(V, S))
5108       return None;
5109   }
5110 
5111   for (Value *V : VL) {
5112     ScheduleData *BundleMember = getScheduleData(V);
5113     assert(BundleMember &&
5114            "no ScheduleData for bundle member (maybe not in same basic block)");
5115     if (BundleMember->IsScheduled) {
5116       // A bundle member was scheduled as single instruction before and now
5117       // needs to be scheduled as part of the bundle. We just get rid of the
5118       // existing schedule.
5119       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
5120                         << " was already scheduled\n");
5121       ReSchedule = true;
5122     }
5123     assert(BundleMember->isSchedulingEntity() &&
5124            "bundle member already part of other bundle");
5125     if (PrevInBundle) {
5126       PrevInBundle->NextInBundle = BundleMember;
5127     } else {
5128       Bundle = BundleMember;
5129     }
5130     BundleMember->UnscheduledDepsInBundle = 0;
5131     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
5132 
5133     // Group the instructions to a bundle.
5134     BundleMember->FirstInBundle = Bundle;
5135     PrevInBundle = BundleMember;
5136   }
5137   if (ScheduleEnd != OldScheduleEnd) {
5138     // The scheduling region got new instructions at the lower end (or it is a
5139     // new region for the first bundle). This makes it necessary to
5140     // recalculate all dependencies.
5141     // It is seldom that this needs to be done a second time after adding the
5142     // initial bundle to the region.
5143     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5144       doForAllOpcodes(I, [](ScheduleData *SD) {
5145         SD->clearDependencies();
5146       });
5147     }
5148     ReSchedule = true;
5149   }
5150   if (ReSchedule) {
5151     resetSchedule();
5152     initialFillReadyList(ReadyInsts);
5153   }
5154   assert(Bundle && "Failed to find schedule bundle");
5155 
5156   LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
5157                     << BB->getName() << "\n");
5158 
5159   calculateDependencies(Bundle, true, SLP);
5160 
5161   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
5162   // means that there are no cyclic dependencies and we can schedule it.
5163   // Note that's important that we don't "schedule" the bundle yet (see
5164   // cancelScheduling).
5165   while (!Bundle->isReady() && !ReadyInsts.empty()) {
5166 
5167     ScheduleData *pickedSD = ReadyInsts.back();
5168     ReadyInsts.pop_back();
5169 
5170     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
5171       schedule(pickedSD, ReadyInsts);
5172     }
5173   }
5174   if (!Bundle->isReady()) {
5175     cancelScheduling(VL, S.OpValue);
5176     return None;
5177   }
5178   return Bundle;
5179 }
5180 
5181 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
5182                                                 Value *OpValue) {
5183   if (isa<PHINode>(OpValue))
5184     return;
5185 
5186   ScheduleData *Bundle = getScheduleData(OpValue);
5187   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
5188   assert(!Bundle->IsScheduled &&
5189          "Can't cancel bundle which is already scheduled");
5190   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
5191          "tried to unbundle something which is not a bundle");
5192 
5193   // Un-bundle: make single instructions out of the bundle.
5194   ScheduleData *BundleMember = Bundle;
5195   while (BundleMember) {
5196     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
5197     BundleMember->FirstInBundle = BundleMember;
5198     ScheduleData *Next = BundleMember->NextInBundle;
5199     BundleMember->NextInBundle = nullptr;
5200     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
5201     if (BundleMember->UnscheduledDepsInBundle == 0) {
5202       ReadyInsts.insert(BundleMember);
5203     }
5204     BundleMember = Next;
5205   }
5206 }
5207 
5208 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
5209   // Allocate a new ScheduleData for the instruction.
5210   if (ChunkPos >= ChunkSize) {
5211     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
5212     ChunkPos = 0;
5213   }
5214   return &(ScheduleDataChunks.back()[ChunkPos++]);
5215 }
5216 
5217 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
5218                                                       const InstructionsState &S) {
5219   if (getScheduleData(V, isOneOf(S, V)))
5220     return true;
5221   Instruction *I = dyn_cast<Instruction>(V);
5222   assert(I && "bundle member must be an instruction");
5223   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
5224   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
5225     ScheduleData *ISD = getScheduleData(I);
5226     if (!ISD)
5227       return false;
5228     assert(isInSchedulingRegion(ISD) &&
5229            "ScheduleData not in scheduling region");
5230     ScheduleData *SD = allocateScheduleDataChunks();
5231     SD->Inst = I;
5232     SD->init(SchedulingRegionID, S.OpValue);
5233     ExtraScheduleDataMap[I][S.OpValue] = SD;
5234     return true;
5235   };
5236   if (CheckSheduleForI(I))
5237     return true;
5238   if (!ScheduleStart) {
5239     // It's the first instruction in the new region.
5240     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
5241     ScheduleStart = I;
5242     ScheduleEnd = I->getNextNode();
5243     if (isOneOf(S, I) != I)
5244       CheckSheduleForI(I);
5245     assert(ScheduleEnd && "tried to vectorize a terminator?");
5246     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
5247     return true;
5248   }
5249   // Search up and down at the same time, because we don't know if the new
5250   // instruction is above or below the existing scheduling region.
5251   BasicBlock::reverse_iterator UpIter =
5252       ++ScheduleStart->getIterator().getReverse();
5253   BasicBlock::reverse_iterator UpperEnd = BB->rend();
5254   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
5255   BasicBlock::iterator LowerEnd = BB->end();
5256   while (true) {
5257     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
5258       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
5259       return false;
5260     }
5261 
5262     if (UpIter != UpperEnd) {
5263       if (&*UpIter == I) {
5264         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
5265         ScheduleStart = I;
5266         if (isOneOf(S, I) != I)
5267           CheckSheduleForI(I);
5268         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
5269                           << "\n");
5270         return true;
5271       }
5272       ++UpIter;
5273     }
5274     if (DownIter != LowerEnd) {
5275       if (&*DownIter == I) {
5276         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
5277                          nullptr);
5278         ScheduleEnd = I->getNextNode();
5279         if (isOneOf(S, I) != I)
5280           CheckSheduleForI(I);
5281         assert(ScheduleEnd && "tried to vectorize a terminator?");
5282         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I
5283                           << "\n");
5284         return true;
5285       }
5286       ++DownIter;
5287     }
5288     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
5289            "instruction not found in block");
5290   }
5291   return true;
5292 }
5293 
5294 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
5295                                                 Instruction *ToI,
5296                                                 ScheduleData *PrevLoadStore,
5297                                                 ScheduleData *NextLoadStore) {
5298   ScheduleData *CurrentLoadStore = PrevLoadStore;
5299   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
5300     ScheduleData *SD = ScheduleDataMap[I];
5301     if (!SD) {
5302       SD = allocateScheduleDataChunks();
5303       ScheduleDataMap[I] = SD;
5304       SD->Inst = I;
5305     }
5306     assert(!isInSchedulingRegion(SD) &&
5307            "new ScheduleData already in scheduling region");
5308     SD->init(SchedulingRegionID, I);
5309 
5310     if (I->mayReadOrWriteMemory() &&
5311         (!isa<IntrinsicInst>(I) ||
5312          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
5313           cast<IntrinsicInst>(I)->getIntrinsicID() !=
5314               Intrinsic::pseudoprobe))) {
5315       // Update the linked list of memory accessing instructions.
5316       if (CurrentLoadStore) {
5317         CurrentLoadStore->NextLoadStore = SD;
5318       } else {
5319         FirstLoadStoreInRegion = SD;
5320       }
5321       CurrentLoadStore = SD;
5322     }
5323   }
5324   if (NextLoadStore) {
5325     if (CurrentLoadStore)
5326       CurrentLoadStore->NextLoadStore = NextLoadStore;
5327   } else {
5328     LastLoadStoreInRegion = CurrentLoadStore;
5329   }
5330 }
5331 
5332 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
5333                                                      bool InsertInReadyList,
5334                                                      BoUpSLP *SLP) {
5335   assert(SD->isSchedulingEntity());
5336 
5337   SmallVector<ScheduleData *, 10> WorkList;
5338   WorkList.push_back(SD);
5339 
5340   while (!WorkList.empty()) {
5341     ScheduleData *SD = WorkList.back();
5342     WorkList.pop_back();
5343 
5344     ScheduleData *BundleMember = SD;
5345     while (BundleMember) {
5346       assert(isInSchedulingRegion(BundleMember));
5347       if (!BundleMember->hasValidDependencies()) {
5348 
5349         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
5350                           << "\n");
5351         BundleMember->Dependencies = 0;
5352         BundleMember->resetUnscheduledDeps();
5353 
5354         // Handle def-use chain dependencies.
5355         if (BundleMember->OpValue != BundleMember->Inst) {
5356           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
5357           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5358             BundleMember->Dependencies++;
5359             ScheduleData *DestBundle = UseSD->FirstInBundle;
5360             if (!DestBundle->IsScheduled)
5361               BundleMember->incrementUnscheduledDeps(1);
5362             if (!DestBundle->hasValidDependencies())
5363               WorkList.push_back(DestBundle);
5364           }
5365         } else {
5366           for (User *U : BundleMember->Inst->users()) {
5367             if (isa<Instruction>(U)) {
5368               ScheduleData *UseSD = getScheduleData(U);
5369               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5370                 BundleMember->Dependencies++;
5371                 ScheduleData *DestBundle = UseSD->FirstInBundle;
5372                 if (!DestBundle->IsScheduled)
5373                   BundleMember->incrementUnscheduledDeps(1);
5374                 if (!DestBundle->hasValidDependencies())
5375                   WorkList.push_back(DestBundle);
5376               }
5377             } else {
5378               // I'm not sure if this can ever happen. But we need to be safe.
5379               // This lets the instruction/bundle never be scheduled and
5380               // eventually disable vectorization.
5381               BundleMember->Dependencies++;
5382               BundleMember->incrementUnscheduledDeps(1);
5383             }
5384           }
5385         }
5386 
5387         // Handle the memory dependencies.
5388         ScheduleData *DepDest = BundleMember->NextLoadStore;
5389         if (DepDest) {
5390           Instruction *SrcInst = BundleMember->Inst;
5391           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
5392           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
5393           unsigned numAliased = 0;
5394           unsigned DistToSrc = 1;
5395 
5396           while (DepDest) {
5397             assert(isInSchedulingRegion(DepDest));
5398 
5399             // We have two limits to reduce the complexity:
5400             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
5401             //    SLP->isAliased (which is the expensive part in this loop).
5402             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
5403             //    the whole loop (even if the loop is fast, it's quadratic).
5404             //    It's important for the loop break condition (see below) to
5405             //    check this limit even between two read-only instructions.
5406             if (DistToSrc >= MaxMemDepDistance ||
5407                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
5408                      (numAliased >= AliasedCheckLimit ||
5409                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
5410 
5411               // We increment the counter only if the locations are aliased
5412               // (instead of counting all alias checks). This gives a better
5413               // balance between reduced runtime and accurate dependencies.
5414               numAliased++;
5415 
5416               DepDest->MemoryDependencies.push_back(BundleMember);
5417               BundleMember->Dependencies++;
5418               ScheduleData *DestBundle = DepDest->FirstInBundle;
5419               if (!DestBundle->IsScheduled) {
5420                 BundleMember->incrementUnscheduledDeps(1);
5421               }
5422               if (!DestBundle->hasValidDependencies()) {
5423                 WorkList.push_back(DestBundle);
5424               }
5425             }
5426             DepDest = DepDest->NextLoadStore;
5427 
5428             // Example, explaining the loop break condition: Let's assume our
5429             // starting instruction is i0 and MaxMemDepDistance = 3.
5430             //
5431             //                      +--------v--v--v
5432             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
5433             //             +--------^--^--^
5434             //
5435             // MaxMemDepDistance let us stop alias-checking at i3 and we add
5436             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
5437             // Previously we already added dependencies from i3 to i6,i7,i8
5438             // (because of MaxMemDepDistance). As we added a dependency from
5439             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
5440             // and we can abort this loop at i6.
5441             if (DistToSrc >= 2 * MaxMemDepDistance)
5442               break;
5443             DistToSrc++;
5444           }
5445         }
5446       }
5447       BundleMember = BundleMember->NextInBundle;
5448     }
5449     if (InsertInReadyList && SD->isReady()) {
5450       ReadyInsts.push_back(SD);
5451       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
5452                         << "\n");
5453     }
5454   }
5455 }
5456 
5457 void BoUpSLP::BlockScheduling::resetSchedule() {
5458   assert(ScheduleStart &&
5459          "tried to reset schedule on block which has not been scheduled");
5460   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5461     doForAllOpcodes(I, [&](ScheduleData *SD) {
5462       assert(isInSchedulingRegion(SD) &&
5463              "ScheduleData not in scheduling region");
5464       SD->IsScheduled = false;
5465       SD->resetUnscheduledDeps();
5466     });
5467   }
5468   ReadyInsts.clear();
5469 }
5470 
5471 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
5472   if (!BS->ScheduleStart)
5473     return;
5474 
5475   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
5476 
5477   BS->resetSchedule();
5478 
5479   // For the real scheduling we use a more sophisticated ready-list: it is
5480   // sorted by the original instruction location. This lets the final schedule
5481   // be as  close as possible to the original instruction order.
5482   struct ScheduleDataCompare {
5483     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
5484       return SD2->SchedulingPriority < SD1->SchedulingPriority;
5485     }
5486   };
5487   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
5488 
5489   // Ensure that all dependency data is updated and fill the ready-list with
5490   // initial instructions.
5491   int Idx = 0;
5492   int NumToSchedule = 0;
5493   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
5494        I = I->getNextNode()) {
5495     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
5496       assert(SD->isPartOfBundle() ==
5497                  (getTreeEntry(SD->Inst) != nullptr) &&
5498              "scheduler and vectorizer bundle mismatch");
5499       SD->FirstInBundle->SchedulingPriority = Idx++;
5500       if (SD->isSchedulingEntity()) {
5501         BS->calculateDependencies(SD, false, this);
5502         NumToSchedule++;
5503       }
5504     });
5505   }
5506   BS->initialFillReadyList(ReadyInsts);
5507 
5508   Instruction *LastScheduledInst = BS->ScheduleEnd;
5509 
5510   // Do the "real" scheduling.
5511   while (!ReadyInsts.empty()) {
5512     ScheduleData *picked = *ReadyInsts.begin();
5513     ReadyInsts.erase(ReadyInsts.begin());
5514 
5515     // Move the scheduled instruction(s) to their dedicated places, if not
5516     // there yet.
5517     ScheduleData *BundleMember = picked;
5518     while (BundleMember) {
5519       Instruction *pickedInst = BundleMember->Inst;
5520       if (LastScheduledInst->getNextNode() != pickedInst) {
5521         BS->BB->getInstList().remove(pickedInst);
5522         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
5523                                      pickedInst);
5524       }
5525       LastScheduledInst = pickedInst;
5526       BundleMember = BundleMember->NextInBundle;
5527     }
5528 
5529     BS->schedule(picked, ReadyInsts);
5530     NumToSchedule--;
5531   }
5532   assert(NumToSchedule == 0 && "could not schedule all instructions");
5533 
5534   // Avoid duplicate scheduling of the block.
5535   BS->ScheduleStart = nullptr;
5536 }
5537 
5538 unsigned BoUpSLP::getVectorElementSize(Value *V) {
5539   // If V is a store, just return the width of the stored value (or value
5540   // truncated just before storing) without traversing the expression tree.
5541   // This is the common case.
5542   if (auto *Store = dyn_cast<StoreInst>(V)) {
5543     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
5544       return DL->getTypeSizeInBits(Trunc->getSrcTy());
5545     else
5546       return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
5547   }
5548 
5549   auto E = InstrElementSize.find(V);
5550   if (E != InstrElementSize.end())
5551     return E->second;
5552 
5553   // If V is not a store, we can traverse the expression tree to find loads
5554   // that feed it. The type of the loaded value may indicate a more suitable
5555   // width than V's type. We want to base the vector element size on the width
5556   // of memory operations where possible.
5557   SmallVector<Instruction *, 16> Worklist;
5558   SmallPtrSet<Instruction *, 16> Visited;
5559   if (auto *I = dyn_cast<Instruction>(V)) {
5560     Worklist.push_back(I);
5561     Visited.insert(I);
5562   }
5563 
5564   // Traverse the expression tree in bottom-up order looking for loads. If we
5565   // encounter an instruction we don't yet handle, we give up.
5566   auto MaxWidth = 0u;
5567   auto FoundUnknownInst = false;
5568   while (!Worklist.empty() && !FoundUnknownInst) {
5569     auto *I = Worklist.pop_back_val();
5570 
5571     // We should only be looking at scalar instructions here. If the current
5572     // instruction has a vector type, give up.
5573     auto *Ty = I->getType();
5574     if (isa<VectorType>(Ty))
5575       FoundUnknownInst = true;
5576 
5577     // If the current instruction is a load, update MaxWidth to reflect the
5578     // width of the loaded value.
5579     else if (isa<LoadInst>(I))
5580       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
5581 
5582     // Otherwise, we need to visit the operands of the instruction. We only
5583     // handle the interesting cases from buildTree here. If an operand is an
5584     // instruction we haven't yet visited, we add it to the worklist.
5585     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5586              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
5587       for (Use &U : I->operands())
5588         if (auto *J = dyn_cast<Instruction>(U.get()))
5589           if (Visited.insert(J).second)
5590             Worklist.push_back(J);
5591     }
5592 
5593     // If we don't yet handle the instruction, give up.
5594     else
5595       FoundUnknownInst = true;
5596   }
5597 
5598   int Width = MaxWidth;
5599   // If we didn't encounter a memory access in the expression tree, or if we
5600   // gave up for some reason, just return the width of V. Otherwise, return the
5601   // maximum width we found.
5602   if (!MaxWidth || FoundUnknownInst)
5603     Width = DL->getTypeSizeInBits(V->getType());
5604 
5605   for (Instruction *I : Visited)
5606     InstrElementSize[I] = Width;
5607 
5608   return Width;
5609 }
5610 
5611 // Determine if a value V in a vectorizable expression Expr can be demoted to a
5612 // smaller type with a truncation. We collect the values that will be demoted
5613 // in ToDemote and additional roots that require investigating in Roots.
5614 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
5615                                   SmallVectorImpl<Value *> &ToDemote,
5616                                   SmallVectorImpl<Value *> &Roots) {
5617   // We can always demote constants.
5618   if (isa<Constant>(V)) {
5619     ToDemote.push_back(V);
5620     return true;
5621   }
5622 
5623   // If the value is not an instruction in the expression with only one use, it
5624   // cannot be demoted.
5625   auto *I = dyn_cast<Instruction>(V);
5626   if (!I || !I->hasOneUse() || !Expr.count(I))
5627     return false;
5628 
5629   switch (I->getOpcode()) {
5630 
5631   // We can always demote truncations and extensions. Since truncations can
5632   // seed additional demotion, we save the truncated value.
5633   case Instruction::Trunc:
5634     Roots.push_back(I->getOperand(0));
5635     break;
5636   case Instruction::ZExt:
5637   case Instruction::SExt:
5638     break;
5639 
5640   // We can demote certain binary operations if we can demote both of their
5641   // operands.
5642   case Instruction::Add:
5643   case Instruction::Sub:
5644   case Instruction::Mul:
5645   case Instruction::And:
5646   case Instruction::Or:
5647   case Instruction::Xor:
5648     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
5649         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
5650       return false;
5651     break;
5652 
5653   // We can demote selects if we can demote their true and false values.
5654   case Instruction::Select: {
5655     SelectInst *SI = cast<SelectInst>(I);
5656     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
5657         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
5658       return false;
5659     break;
5660   }
5661 
5662   // We can demote phis if we can demote all their incoming operands. Note that
5663   // we don't need to worry about cycles since we ensure single use above.
5664   case Instruction::PHI: {
5665     PHINode *PN = cast<PHINode>(I);
5666     for (Value *IncValue : PN->incoming_values())
5667       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
5668         return false;
5669     break;
5670   }
5671 
5672   // Otherwise, conservatively give up.
5673   default:
5674     return false;
5675   }
5676 
5677   // Record the value that we can demote.
5678   ToDemote.push_back(V);
5679   return true;
5680 }
5681 
5682 void BoUpSLP::computeMinimumValueSizes() {
5683   // If there are no external uses, the expression tree must be rooted by a
5684   // store. We can't demote in-memory values, so there is nothing to do here.
5685   if (ExternalUses.empty())
5686     return;
5687 
5688   // We only attempt to truncate integer expressions.
5689   auto &TreeRoot = VectorizableTree[0]->Scalars;
5690   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
5691   if (!TreeRootIT)
5692     return;
5693 
5694   // If the expression is not rooted by a store, these roots should have
5695   // external uses. We will rely on InstCombine to rewrite the expression in
5696   // the narrower type. However, InstCombine only rewrites single-use values.
5697   // This means that if a tree entry other than a root is used externally, it
5698   // must have multiple uses and InstCombine will not rewrite it. The code
5699   // below ensures that only the roots are used externally.
5700   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
5701   for (auto &EU : ExternalUses)
5702     if (!Expr.erase(EU.Scalar))
5703       return;
5704   if (!Expr.empty())
5705     return;
5706 
5707   // Collect the scalar values of the vectorizable expression. We will use this
5708   // context to determine which values can be demoted. If we see a truncation,
5709   // we mark it as seeding another demotion.
5710   for (auto &EntryPtr : VectorizableTree)
5711     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
5712 
5713   // Ensure the roots of the vectorizable tree don't form a cycle. They must
5714   // have a single external user that is not in the vectorizable tree.
5715   for (auto *Root : TreeRoot)
5716     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
5717       return;
5718 
5719   // Conservatively determine if we can actually truncate the roots of the
5720   // expression. Collect the values that can be demoted in ToDemote and
5721   // additional roots that require investigating in Roots.
5722   SmallVector<Value *, 32> ToDemote;
5723   SmallVector<Value *, 4> Roots;
5724   for (auto *Root : TreeRoot)
5725     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
5726       return;
5727 
5728   // The maximum bit width required to represent all the values that can be
5729   // demoted without loss of precision. It would be safe to truncate the roots
5730   // of the expression to this width.
5731   auto MaxBitWidth = 8u;
5732 
5733   // We first check if all the bits of the roots are demanded. If they're not,
5734   // we can truncate the roots to this narrower type.
5735   for (auto *Root : TreeRoot) {
5736     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
5737     MaxBitWidth = std::max<unsigned>(
5738         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
5739   }
5740 
5741   // True if the roots can be zero-extended back to their original type, rather
5742   // than sign-extended. We know that if the leading bits are not demanded, we
5743   // can safely zero-extend. So we initialize IsKnownPositive to True.
5744   bool IsKnownPositive = true;
5745 
5746   // If all the bits of the roots are demanded, we can try a little harder to
5747   // compute a narrower type. This can happen, for example, if the roots are
5748   // getelementptr indices. InstCombine promotes these indices to the pointer
5749   // width. Thus, all their bits are technically demanded even though the
5750   // address computation might be vectorized in a smaller type.
5751   //
5752   // We start by looking at each entry that can be demoted. We compute the
5753   // maximum bit width required to store the scalar by using ValueTracking to
5754   // compute the number of high-order bits we can truncate.
5755   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
5756       llvm::all_of(TreeRoot, [](Value *R) {
5757         assert(R->hasOneUse() && "Root should have only one use!");
5758         return isa<GetElementPtrInst>(R->user_back());
5759       })) {
5760     MaxBitWidth = 8u;
5761 
5762     // Determine if the sign bit of all the roots is known to be zero. If not,
5763     // IsKnownPositive is set to False.
5764     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
5765       KnownBits Known = computeKnownBits(R, *DL);
5766       return Known.isNonNegative();
5767     });
5768 
5769     // Determine the maximum number of bits required to store the scalar
5770     // values.
5771     for (auto *Scalar : ToDemote) {
5772       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
5773       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
5774       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
5775     }
5776 
5777     // If we can't prove that the sign bit is zero, we must add one to the
5778     // maximum bit width to account for the unknown sign bit. This preserves
5779     // the existing sign bit so we can safely sign-extend the root back to the
5780     // original type. Otherwise, if we know the sign bit is zero, we will
5781     // zero-extend the root instead.
5782     //
5783     // FIXME: This is somewhat suboptimal, as there will be cases where adding
5784     //        one to the maximum bit width will yield a larger-than-necessary
5785     //        type. In general, we need to add an extra bit only if we can't
5786     //        prove that the upper bit of the original type is equal to the
5787     //        upper bit of the proposed smaller type. If these two bits are the
5788     //        same (either zero or one) we know that sign-extending from the
5789     //        smaller type will result in the same value. Here, since we can't
5790     //        yet prove this, we are just making the proposed smaller type
5791     //        larger to ensure correctness.
5792     if (!IsKnownPositive)
5793       ++MaxBitWidth;
5794   }
5795 
5796   // Round MaxBitWidth up to the next power-of-two.
5797   if (!isPowerOf2_64(MaxBitWidth))
5798     MaxBitWidth = NextPowerOf2(MaxBitWidth);
5799 
5800   // If the maximum bit width we compute is less than the with of the roots'
5801   // type, we can proceed with the narrowing. Otherwise, do nothing.
5802   if (MaxBitWidth >= TreeRootIT->getBitWidth())
5803     return;
5804 
5805   // If we can truncate the root, we must collect additional values that might
5806   // be demoted as a result. That is, those seeded by truncations we will
5807   // modify.
5808   while (!Roots.empty())
5809     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
5810 
5811   // Finally, map the values we can demote to the maximum bit with we computed.
5812   for (auto *Scalar : ToDemote)
5813     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
5814 }
5815 
5816 namespace {
5817 
5818 /// The SLPVectorizer Pass.
5819 struct SLPVectorizer : public FunctionPass {
5820   SLPVectorizerPass Impl;
5821 
5822   /// Pass identification, replacement for typeid
5823   static char ID;
5824 
5825   explicit SLPVectorizer() : FunctionPass(ID) {
5826     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5827   }
5828 
5829   bool doInitialization(Module &M) override {
5830     return false;
5831   }
5832 
5833   bool runOnFunction(Function &F) override {
5834     if (skipFunction(F))
5835       return false;
5836 
5837     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5838     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5839     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5840     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
5841     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5842     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5843     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5844     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5845     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
5846     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5847 
5848     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5849   }
5850 
5851   void getAnalysisUsage(AnalysisUsage &AU) const override {
5852     FunctionPass::getAnalysisUsage(AU);
5853     AU.addRequired<AssumptionCacheTracker>();
5854     AU.addRequired<ScalarEvolutionWrapperPass>();
5855     AU.addRequired<AAResultsWrapperPass>();
5856     AU.addRequired<TargetTransformInfoWrapperPass>();
5857     AU.addRequired<LoopInfoWrapperPass>();
5858     AU.addRequired<DominatorTreeWrapperPass>();
5859     AU.addRequired<DemandedBitsWrapperPass>();
5860     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5861     AU.addRequired<InjectTLIMappingsLegacy>();
5862     AU.addPreserved<LoopInfoWrapperPass>();
5863     AU.addPreserved<DominatorTreeWrapperPass>();
5864     AU.addPreserved<AAResultsWrapperPass>();
5865     AU.addPreserved<GlobalsAAWrapperPass>();
5866     AU.setPreservesCFG();
5867   }
5868 };
5869 
5870 } // end anonymous namespace
5871 
5872 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
5873   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
5874   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
5875   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
5876   auto *AA = &AM.getResult<AAManager>(F);
5877   auto *LI = &AM.getResult<LoopAnalysis>(F);
5878   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
5879   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
5880   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
5881   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5882 
5883   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5884   if (!Changed)
5885     return PreservedAnalyses::all();
5886 
5887   PreservedAnalyses PA;
5888   PA.preserveSet<CFGAnalyses>();
5889   PA.preserve<AAManager>();
5890   PA.preserve<GlobalsAA>();
5891   return PA;
5892 }
5893 
5894 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
5895                                 TargetTransformInfo *TTI_,
5896                                 TargetLibraryInfo *TLI_, AAResults *AA_,
5897                                 LoopInfo *LI_, DominatorTree *DT_,
5898                                 AssumptionCache *AC_, DemandedBits *DB_,
5899                                 OptimizationRemarkEmitter *ORE_) {
5900   if (!RunSLPVectorization)
5901     return false;
5902   SE = SE_;
5903   TTI = TTI_;
5904   TLI = TLI_;
5905   AA = AA_;
5906   LI = LI_;
5907   DT = DT_;
5908   AC = AC_;
5909   DB = DB_;
5910   DL = &F.getParent()->getDataLayout();
5911 
5912   Stores.clear();
5913   GEPs.clear();
5914   bool Changed = false;
5915 
5916   // If the target claims to have no vector registers don't attempt
5917   // vectorization.
5918   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
5919     return false;
5920 
5921   // Don't vectorize when the attribute NoImplicitFloat is used.
5922   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
5923     return false;
5924 
5925   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
5926 
5927   // Use the bottom up slp vectorizer to construct chains that start with
5928   // store instructions.
5929   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
5930 
5931   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5932   // delete instructions.
5933 
5934   // Scan the blocks in the function in post order.
5935   for (auto BB : post_order(&F.getEntryBlock())) {
5936     collectSeedInstructions(BB);
5937 
5938     // Vectorize trees that end at stores.
5939     if (!Stores.empty()) {
5940       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
5941                         << " underlying objects.\n");
5942       Changed |= vectorizeStoreChains(R);
5943     }
5944 
5945     // Vectorize trees that end at reductions.
5946     Changed |= vectorizeChainsInBlock(BB, R);
5947 
5948     // Vectorize the index computations of getelementptr instructions. This
5949     // is primarily intended to catch gather-like idioms ending at
5950     // non-consecutive loads.
5951     if (!GEPs.empty()) {
5952       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
5953                         << " underlying objects.\n");
5954       Changed |= vectorizeGEPIndices(BB, R);
5955     }
5956   }
5957 
5958   if (Changed) {
5959     R.optimizeGatherSequence();
5960     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
5961   }
5962   return Changed;
5963 }
5964 
5965 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
5966                                             unsigned Idx) {
5967   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
5968                     << "\n");
5969   const unsigned Sz = R.getVectorElementSize(Chain[0]);
5970   const unsigned MinVF = R.getMinVecRegSize() / Sz;
5971   unsigned VF = Chain.size();
5972 
5973   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
5974     return false;
5975 
5976   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
5977                     << "\n");
5978 
5979   R.buildTree(Chain);
5980   Optional<ArrayRef<unsigned>> Order = R.bestOrder();
5981   // TODO: Handle orders of size less than number of elements in the vector.
5982   if (Order && Order->size() == Chain.size()) {
5983     // TODO: reorder tree nodes without tree rebuilding.
5984     SmallVector<Value *, 4> ReorderedOps(Chain.rbegin(), Chain.rend());
5985     llvm::transform(*Order, ReorderedOps.begin(),
5986                     [Chain](const unsigned Idx) { return Chain[Idx]; });
5987     R.buildTree(ReorderedOps);
5988   }
5989   if (R.isTreeTinyAndNotFullyVectorizable())
5990     return false;
5991   if (R.isLoadCombineCandidate())
5992     return false;
5993 
5994   R.computeMinimumValueSizes();
5995 
5996   int Cost = R.getTreeCost();
5997 
5998   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
5999   if (Cost < -SLPCostThreshold) {
6000     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
6001 
6002     using namespace ore;
6003 
6004     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
6005                                         cast<StoreInst>(Chain[0]))
6006                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
6007                      << " and with tree size "
6008                      << NV("TreeSize", R.getTreeSize()));
6009 
6010     R.vectorizeTree();
6011     return true;
6012   }
6013 
6014   return false;
6015 }
6016 
6017 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
6018                                         BoUpSLP &R) {
6019   // We may run into multiple chains that merge into a single chain. We mark the
6020   // stores that we vectorized so that we don't visit the same store twice.
6021   BoUpSLP::ValueSet VectorizedStores;
6022   bool Changed = false;
6023 
6024   int E = Stores.size();
6025   SmallBitVector Tails(E, false);
6026   SmallVector<int, 16> ConsecutiveChain(E, E + 1);
6027   int MaxIter = MaxStoreLookup.getValue();
6028   int IterCnt;
6029   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
6030                                   &ConsecutiveChain](int K, int Idx) {
6031     if (IterCnt >= MaxIter)
6032       return true;
6033     ++IterCnt;
6034     if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE))
6035       return false;
6036 
6037     Tails.set(Idx);
6038     ConsecutiveChain[K] = Idx;
6039     return true;
6040   };
6041   // Do a quadratic search on all of the given stores in reverse order and find
6042   // all of the pairs of stores that follow each other.
6043   for (int Idx = E - 1; Idx >= 0; --Idx) {
6044     // If a store has multiple consecutive store candidates, search according
6045     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
6046     // This is because usually pairing with immediate succeeding or preceding
6047     // candidate create the best chance to find slp vectorization opportunity.
6048     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
6049     IterCnt = 0;
6050     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
6051       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
6052           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
6053         break;
6054   }
6055 
6056   // For stores that start but don't end a link in the chain:
6057   for (int Cnt = E; Cnt > 0; --Cnt) {
6058     int I = Cnt - 1;
6059     if (ConsecutiveChain[I] == E + 1 || Tails.test(I))
6060       continue;
6061     // We found a store instr that starts a chain. Now follow the chain and try
6062     // to vectorize it.
6063     BoUpSLP::ValueList Operands;
6064     // Collect the chain into a list.
6065     while (I != E + 1 && !VectorizedStores.count(Stores[I])) {
6066       Operands.push_back(Stores[I]);
6067       // Move to the next value in the chain.
6068       I = ConsecutiveChain[I];
6069     }
6070 
6071     // If a vector register can't hold 1 element, we are done.
6072     unsigned MaxVecRegSize = R.getMaxVecRegSize();
6073     unsigned EltSize = R.getVectorElementSize(Stores[0]);
6074     if (MaxVecRegSize % EltSize != 0)
6075       continue;
6076 
6077     unsigned MaxElts = MaxVecRegSize / EltSize;
6078     // FIXME: Is division-by-2 the correct step? Should we assert that the
6079     // register size is a power-of-2?
6080     unsigned StartIdx = 0;
6081     for (unsigned Size = llvm::PowerOf2Ceil(MaxElts); Size >= 2; Size /= 2) {
6082       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
6083         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
6084         if (!VectorizedStores.count(Slice.front()) &&
6085             !VectorizedStores.count(Slice.back()) &&
6086             vectorizeStoreChain(Slice, R, Cnt)) {
6087           // Mark the vectorized stores so that we don't vectorize them again.
6088           VectorizedStores.insert(Slice.begin(), Slice.end());
6089           Changed = true;
6090           // If we vectorized initial block, no need to try to vectorize it
6091           // again.
6092           if (Cnt == StartIdx)
6093             StartIdx += Size;
6094           Cnt += Size;
6095           continue;
6096         }
6097         ++Cnt;
6098       }
6099       // Check if the whole array was vectorized already - exit.
6100       if (StartIdx >= Operands.size())
6101         break;
6102     }
6103   }
6104 
6105   return Changed;
6106 }
6107 
6108 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
6109   // Initialize the collections. We will make a single pass over the block.
6110   Stores.clear();
6111   GEPs.clear();
6112 
6113   // Visit the store and getelementptr instructions in BB and organize them in
6114   // Stores and GEPs according to the underlying objects of their pointer
6115   // operands.
6116   for (Instruction &I : *BB) {
6117     // Ignore store instructions that are volatile or have a pointer operand
6118     // that doesn't point to a scalar type.
6119     if (auto *SI = dyn_cast<StoreInst>(&I)) {
6120       if (!SI->isSimple())
6121         continue;
6122       if (!isValidElementType(SI->getValueOperand()->getType()))
6123         continue;
6124       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
6125     }
6126 
6127     // Ignore getelementptr instructions that have more than one index, a
6128     // constant index, or a pointer operand that doesn't point to a scalar
6129     // type.
6130     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
6131       auto Idx = GEP->idx_begin()->get();
6132       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
6133         continue;
6134       if (!isValidElementType(Idx->getType()))
6135         continue;
6136       if (GEP->getType()->isVectorTy())
6137         continue;
6138       GEPs[GEP->getPointerOperand()].push_back(GEP);
6139     }
6140   }
6141 }
6142 
6143 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
6144   if (!A || !B)
6145     return false;
6146   Value *VL[] = {A, B};
6147   return tryToVectorizeList(VL, R, /*AllowReorder=*/true);
6148 }
6149 
6150 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
6151                                            bool AllowReorder,
6152                                            ArrayRef<Value *> InsertUses) {
6153   if (VL.size() < 2)
6154     return false;
6155 
6156   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
6157                     << VL.size() << ".\n");
6158 
6159   // Check that all of the parts are instructions of the same type,
6160   // we permit an alternate opcode via InstructionsState.
6161   InstructionsState S = getSameOpcode(VL);
6162   if (!S.getOpcode())
6163     return false;
6164 
6165   Instruction *I0 = cast<Instruction>(S.OpValue);
6166   // Make sure invalid types (including vector type) are rejected before
6167   // determining vectorization factor for scalar instructions.
6168   for (Value *V : VL) {
6169     Type *Ty = V->getType();
6170     if (!isValidElementType(Ty)) {
6171       // NOTE: the following will give user internal llvm type name, which may
6172       // not be useful.
6173       R.getORE()->emit([&]() {
6174         std::string type_str;
6175         llvm::raw_string_ostream rso(type_str);
6176         Ty->print(rso);
6177         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
6178                << "Cannot SLP vectorize list: type "
6179                << rso.str() + " is unsupported by vectorizer";
6180       });
6181       return false;
6182     }
6183   }
6184 
6185   unsigned Sz = R.getVectorElementSize(I0);
6186   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
6187   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
6188   if (MaxVF < 2) {
6189     R.getORE()->emit([&]() {
6190       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
6191              << "Cannot SLP vectorize list: vectorization factor "
6192              << "less than 2 is not supported";
6193     });
6194     return false;
6195   }
6196 
6197   bool Changed = false;
6198   bool CandidateFound = false;
6199   int MinCost = SLPCostThreshold;
6200 
6201   bool CompensateUseCost =
6202       !InsertUses.empty() && llvm::all_of(InsertUses, [](const Value *V) {
6203         return V && isa<InsertElementInst>(V);
6204       });
6205   assert((!CompensateUseCost || InsertUses.size() == VL.size()) &&
6206          "Each scalar expected to have an associated InsertElement user.");
6207 
6208   unsigned NextInst = 0, MaxInst = VL.size();
6209   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
6210     // No actual vectorization should happen, if number of parts is the same as
6211     // provided vectorization factor (i.e. the scalar type is used for vector
6212     // code during codegen).
6213     auto *VecTy = FixedVectorType::get(VL[0]->getType(), VF);
6214     if (TTI->getNumberOfParts(VecTy) == VF)
6215       continue;
6216     for (unsigned I = NextInst; I < MaxInst; ++I) {
6217       unsigned OpsWidth = 0;
6218 
6219       if (I + VF > MaxInst)
6220         OpsWidth = MaxInst - I;
6221       else
6222         OpsWidth = VF;
6223 
6224       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
6225         break;
6226 
6227       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
6228       // Check that a previous iteration of this loop did not delete the Value.
6229       if (llvm::any_of(Ops, [&R](Value *V) {
6230             auto *I = dyn_cast<Instruction>(V);
6231             return I && R.isDeleted(I);
6232           }))
6233         continue;
6234 
6235       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
6236                         << "\n");
6237 
6238       R.buildTree(Ops);
6239       Optional<ArrayRef<unsigned>> Order = R.bestOrder();
6240       // TODO: check if we can allow reordering for more cases.
6241       if (AllowReorder && Order) {
6242         // TODO: reorder tree nodes without tree rebuilding.
6243         // Conceptually, there is nothing actually preventing us from trying to
6244         // reorder a larger list. In fact, we do exactly this when vectorizing
6245         // reductions. However, at this point, we only expect to get here when
6246         // there are exactly two operations.
6247         assert(Ops.size() == 2);
6248         Value *ReorderedOps[] = {Ops[1], Ops[0]};
6249         R.buildTree(ReorderedOps, None);
6250       }
6251       if (R.isTreeTinyAndNotFullyVectorizable())
6252         continue;
6253 
6254       R.computeMinimumValueSizes();
6255       int Cost = R.getTreeCost();
6256       CandidateFound = true;
6257       if (CompensateUseCost) {
6258         // TODO: Use TTI's getScalarizationOverhead for sequence of inserts
6259         // rather than sum of single inserts as the latter may overestimate
6260         // cost. This work should imply improving cost estimation for extracts
6261         // that added in for external (for vectorization tree) users,i.e. that
6262         // part should also switch to same interface.
6263         // For example, the following case is projected code after SLP:
6264         //  %4 = extractelement <4 x i64> %3, i32 0
6265         //  %v0 = insertelement <4 x i64> undef, i64 %4, i32 0
6266         //  %5 = extractelement <4 x i64> %3, i32 1
6267         //  %v1 = insertelement <4 x i64> %v0, i64 %5, i32 1
6268         //  %6 = extractelement <4 x i64> %3, i32 2
6269         //  %v2 = insertelement <4 x i64> %v1, i64 %6, i32 2
6270         //  %7 = extractelement <4 x i64> %3, i32 3
6271         //  %v3 = insertelement <4 x i64> %v2, i64 %7, i32 3
6272         //
6273         // Extracts here added by SLP in order to feed users (the inserts) of
6274         // original scalars and contribute to "ExtractCost" at cost evaluation.
6275         // The inserts in turn form sequence to build an aggregate that
6276         // detected by findBuildAggregate routine.
6277         // SLP makes an assumption that such sequence will be optimized away
6278         // later (instcombine) so it tries to compensate ExctractCost with
6279         // cost of insert sequence.
6280         // Current per element cost calculation approach is not quite accurate
6281         // and tends to create bias toward favoring vectorization.
6282         // Switching to the TTI interface might help a bit.
6283         // Alternative solution could be pattern-match to detect a no-op or
6284         // shuffle.
6285         unsigned UserCost = 0;
6286         for (unsigned Lane = 0; Lane < OpsWidth; Lane++) {
6287           auto *IE = cast<InsertElementInst>(InsertUses[I + Lane]);
6288           if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2)))
6289             UserCost += TTI->getVectorInstrCost(
6290                 Instruction::InsertElement, IE->getType(), CI->getZExtValue());
6291         }
6292         LLVM_DEBUG(dbgs() << "SLP: Compensate cost of users by: " << UserCost
6293                           << ".\n");
6294         Cost -= UserCost;
6295       }
6296 
6297       MinCost = std::min(MinCost, Cost);
6298 
6299       if (Cost < -SLPCostThreshold) {
6300         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
6301         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
6302                                                     cast<Instruction>(Ops[0]))
6303                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
6304                                  << " and with tree size "
6305                                  << ore::NV("TreeSize", R.getTreeSize()));
6306 
6307         R.vectorizeTree();
6308         // Move to the next bundle.
6309         I += VF - 1;
6310         NextInst = I + 1;
6311         Changed = true;
6312       }
6313     }
6314   }
6315 
6316   if (!Changed && CandidateFound) {
6317     R.getORE()->emit([&]() {
6318       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
6319              << "List vectorization was possible but not beneficial with cost "
6320              << ore::NV("Cost", MinCost) << " >= "
6321              << ore::NV("Treshold", -SLPCostThreshold);
6322     });
6323   } else if (!Changed) {
6324     R.getORE()->emit([&]() {
6325       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
6326              << "Cannot SLP vectorize list: vectorization was impossible"
6327              << " with available vectorization factors";
6328     });
6329   }
6330   return Changed;
6331 }
6332 
6333 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
6334   if (!I)
6335     return false;
6336 
6337   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
6338     return false;
6339 
6340   Value *P = I->getParent();
6341 
6342   // Vectorize in current basic block only.
6343   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
6344   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
6345   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
6346     return false;
6347 
6348   // Try to vectorize V.
6349   if (tryToVectorizePair(Op0, Op1, R))
6350     return true;
6351 
6352   auto *A = dyn_cast<BinaryOperator>(Op0);
6353   auto *B = dyn_cast<BinaryOperator>(Op1);
6354   // Try to skip B.
6355   if (B && B->hasOneUse()) {
6356     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
6357     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
6358     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
6359       return true;
6360     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
6361       return true;
6362   }
6363 
6364   // Try to skip A.
6365   if (A && A->hasOneUse()) {
6366     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
6367     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
6368     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
6369       return true;
6370     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
6371       return true;
6372   }
6373   return false;
6374 }
6375 
6376 /// Generate a shuffle mask to be used in a reduction tree.
6377 ///
6378 /// \param VecLen The length of the vector to be reduced.
6379 /// \param NumEltsToRdx The number of elements that should be reduced in the
6380 ///        vector.
6381 /// \param IsPairwise Whether the reduction is a pairwise or splitting
6382 ///        reduction. A pairwise reduction will generate a mask of
6383 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
6384 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
6385 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
6386 static SmallVector<int, 32> createRdxShuffleMask(unsigned VecLen,
6387                                                  unsigned NumEltsToRdx,
6388                                                  bool IsPairwise, bool IsLeft) {
6389   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
6390 
6391   SmallVector<int, 32> ShuffleMask(VecLen, -1);
6392 
6393   if (IsPairwise)
6394     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
6395     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6396       ShuffleMask[i] = 2 * i + !IsLeft;
6397   else
6398     // Move the upper half of the vector to the lower half.
6399     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6400       ShuffleMask[i] = NumEltsToRdx + i;
6401 
6402   return ShuffleMask;
6403 }
6404 
6405 namespace {
6406 
6407 /// Model horizontal reductions.
6408 ///
6409 /// A horizontal reduction is a tree of reduction operations (currently add and
6410 /// fadd) that has operations that can be put into a vector as its leaf.
6411 /// For example, this tree:
6412 ///
6413 /// mul mul mul mul
6414 ///  \  /    \  /
6415 ///   +       +
6416 ///    \     /
6417 ///       +
6418 /// This tree has "mul" as its reduced values and "+" as its reduction
6419 /// operations. A reduction might be feeding into a store or a binary operation
6420 /// feeding a phi.
6421 ///    ...
6422 ///    \  /
6423 ///     +
6424 ///     |
6425 ///  phi +=
6426 ///
6427 ///  Or:
6428 ///    ...
6429 ///    \  /
6430 ///     +
6431 ///     |
6432 ///   *p =
6433 ///
6434 class HorizontalReduction {
6435   using ReductionOpsType = SmallVector<Value *, 16>;
6436   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
6437   ReductionOpsListType  ReductionOps;
6438   SmallVector<Value *, 32> ReducedVals;
6439   // Use map vector to make stable output.
6440   MapVector<Instruction *, Value *> ExtraArgs;
6441 
6442   /// Kind of the reduction data.
6443   enum ReductionKind {
6444     RK_None,       /// Not a reduction.
6445     RK_Arithmetic, /// Binary reduction data.
6446     RK_SMin,       /// Signed minimum reduction data.
6447     RK_UMin,       /// Unsigned minimum reduction data.
6448     RK_SMax,       /// Signed maximum reduction data.
6449     RK_UMax,       /// Unsigned maximum reduction data.
6450   };
6451 
6452   /// Contains info about operation, like its opcode, left and right operands.
6453   class OperationData {
6454     /// Opcode of the instruction.
6455     unsigned Opcode = 0;
6456 
6457     /// Kind of the reduction operation.
6458     ReductionKind Kind = RK_None;
6459 
6460     /// Checks if the reduction operation can be vectorized.
6461     bool isVectorizable() const {
6462       // We currently only support add/mul/logical && min/max reductions.
6463       return ((Kind == RK_Arithmetic &&
6464                (Opcode == Instruction::Add || Opcode == Instruction::FAdd ||
6465                 Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
6466                 Opcode == Instruction::And || Opcode == Instruction::Or ||
6467                 Opcode == Instruction::Xor)) ||
6468               (Opcode == Instruction::ICmp &&
6469                (Kind == RK_SMin || Kind == RK_SMax ||
6470                 Kind == RK_UMin || Kind == RK_UMax)));
6471     }
6472 
6473     /// Creates reduction operation with the current opcode.
6474     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6475                     const Twine &Name) const {
6476       assert(isVectorizable() &&
6477              "Expected add|fadd or min/max reduction operation.");
6478       Value *Cmp = nullptr;
6479       switch (Kind) {
6480       case RK_Arithmetic:
6481         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
6482                                    Name);
6483       case RK_SMin:
6484         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6485         Cmp = Builder.CreateICmpSLT(LHS, RHS);
6486         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6487       case RK_SMax:
6488         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6489         Cmp = Builder.CreateICmpSGT(LHS, RHS);
6490         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6491       case RK_UMin:
6492         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6493         Cmp = Builder.CreateICmpULT(LHS, RHS);
6494         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6495       case RK_UMax:
6496         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6497         Cmp = Builder.CreateICmpUGT(LHS, RHS);
6498         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6499       case RK_None:
6500         break;
6501       }
6502       llvm_unreachable("Unknown reduction operation.");
6503     }
6504 
6505   public:
6506     explicit OperationData() = default;
6507 
6508     /// Construction for reduced values. They are identified by opcode only and
6509     /// don't have associated LHS/RHS values.
6510     explicit OperationData(Instruction &I) {
6511       Opcode = I.getOpcode();
6512     }
6513 
6514     /// Constructor for reduction operations with opcode and its left and
6515     /// right operands.
6516     OperationData(unsigned Opcode, ReductionKind Kind)
6517         : Opcode(Opcode), Kind(Kind) {
6518       assert(Kind != RK_None && "One of the reduction operations is expected.");
6519     }
6520 
6521     explicit operator bool() const { return Opcode; }
6522 
6523     /// Return true if this operation is any kind of minimum or maximum.
6524     bool isMinMax() const {
6525       switch (Kind) {
6526       case RK_Arithmetic:
6527         return false;
6528       case RK_SMin:
6529       case RK_SMax:
6530       case RK_UMin:
6531       case RK_UMax:
6532         return true;
6533       case RK_None:
6534         break;
6535       }
6536       llvm_unreachable("Reduction kind is not set");
6537     }
6538 
6539     /// Get the index of the first operand.
6540     unsigned getFirstOperandIndex() const {
6541       assert(!!*this && "The opcode is not set.");
6542       // We allow calling this before 'Kind' is set, so handle that specially.
6543       if (Kind == RK_None)
6544         return 0;
6545       return isMinMax() ? 1 : 0;
6546     }
6547 
6548     /// Total number of operands in the reduction operation.
6549     unsigned getNumberOfOperands() const {
6550       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6551       return isMinMax() ? 3 : 2;
6552     }
6553 
6554     /// Checks if the instruction is in basic block \p BB.
6555     /// For a min/max reduction check that both compare and select are in \p BB.
6556     bool hasSameParent(Instruction *I, BasicBlock *BB, bool IsRedOp) const {
6557       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6558       if (IsRedOp && isMinMax()) {
6559         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
6560         return I->getParent() == BB && Cmp && Cmp->getParent() == BB;
6561       }
6562       return I->getParent() == BB;
6563     }
6564 
6565     /// Expected number of uses for reduction operations/reduced values.
6566     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
6567       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6568       // SelectInst must be used twice while the condition op must have single
6569       // use only.
6570       if (isMinMax())
6571         return I->hasNUses(2) &&
6572                (!IsReductionOp ||
6573                 cast<SelectInst>(I)->getCondition()->hasOneUse());
6574 
6575       // Arithmetic reduction operation must be used once only.
6576       return I->hasOneUse();
6577     }
6578 
6579     /// Initializes the list of reduction operations.
6580     void initReductionOps(ReductionOpsListType &ReductionOps) {
6581       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6582       if (isMinMax())
6583         ReductionOps.assign(2, ReductionOpsType());
6584       else
6585         ReductionOps.assign(1, ReductionOpsType());
6586     }
6587 
6588     /// Add all reduction operations for the reduction instruction \p I.
6589     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
6590       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6591       if (isMinMax()) {
6592         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
6593         ReductionOps[1].emplace_back(I);
6594       } else {
6595         ReductionOps[0].emplace_back(I);
6596       }
6597     }
6598 
6599     /// Checks if instruction is associative and can be vectorized.
6600     bool isAssociative(Instruction *I) const {
6601       assert(Kind != RK_None && *this && "Expected reduction operation.");
6602       switch (Kind) {
6603       case RK_Arithmetic:
6604         return I->isAssociative();
6605       case RK_SMin:
6606       case RK_SMax:
6607       case RK_UMin:
6608       case RK_UMax:
6609         assert(Opcode == Instruction::ICmp &&
6610                "Only integer compare operation is expected.");
6611         return true;
6612       case RK_None:
6613         break;
6614       }
6615       llvm_unreachable("Reduction kind is not set");
6616     }
6617 
6618     /// Checks if the reduction operation can be vectorized.
6619     bool isVectorizable(Instruction *I) const {
6620       return isVectorizable() && isAssociative(I);
6621     }
6622 
6623     /// Checks if two operation data are both a reduction op or both a reduced
6624     /// value.
6625     bool operator==(const OperationData &OD) const {
6626       assert(((Kind != OD.Kind) || (Opcode != 0 && OD.Opcode != 0)) &&
6627              "One of the comparing operations is incorrect.");
6628       return Kind == OD.Kind && Opcode == OD.Opcode;
6629     }
6630     bool operator!=(const OperationData &OD) const { return !(*this == OD); }
6631     void clear() {
6632       Opcode = 0;
6633       Kind = RK_None;
6634     }
6635 
6636     /// Get the opcode of the reduction operation.
6637     unsigned getOpcode() const {
6638       assert(isVectorizable() && "Expected vectorizable operation.");
6639       return Opcode;
6640     }
6641 
6642     /// Get kind of reduction data.
6643     ReductionKind getKind() const { return Kind; }
6644     Value *getLHS(Instruction *I) const {
6645       if (Kind == RK_None)
6646         return nullptr;
6647       return I->getOperand(getFirstOperandIndex());
6648     }
6649     Value *getRHS(Instruction *I) const {
6650       if (Kind == RK_None)
6651         return nullptr;
6652       return I->getOperand(getFirstOperandIndex() + 1);
6653     }
6654 
6655     /// Creates reduction operation with the current opcode with the IR flags
6656     /// from \p ReductionOps.
6657     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6658                     const Twine &Name,
6659                     const ReductionOpsListType &ReductionOps) const {
6660       assert(isVectorizable() &&
6661              "Expected add|fadd or min/max reduction operation.");
6662       auto *Op = createOp(Builder, LHS, RHS, Name);
6663       switch (Kind) {
6664       case RK_Arithmetic:
6665         propagateIRFlags(Op, ReductionOps[0]);
6666         return Op;
6667       case RK_SMin:
6668       case RK_SMax:
6669       case RK_UMin:
6670       case RK_UMax:
6671         if (auto *SI = dyn_cast<SelectInst>(Op))
6672           propagateIRFlags(SI->getCondition(), ReductionOps[0]);
6673         propagateIRFlags(Op, ReductionOps[1]);
6674         return Op;
6675       case RK_None:
6676         break;
6677       }
6678       llvm_unreachable("Unknown reduction operation.");
6679     }
6680     /// Creates reduction operation with the current opcode with the IR flags
6681     /// from \p I.
6682     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6683                     const Twine &Name, Instruction *I) const {
6684       assert(isVectorizable() &&
6685              "Expected add|fadd or min/max reduction operation.");
6686       auto *Op = createOp(Builder, LHS, RHS, Name);
6687       switch (Kind) {
6688       case RK_Arithmetic:
6689         propagateIRFlags(Op, I);
6690         return Op;
6691       case RK_SMin:
6692       case RK_SMax:
6693       case RK_UMin:
6694       case RK_UMax:
6695         if (auto *SI = dyn_cast<SelectInst>(Op)) {
6696           propagateIRFlags(SI->getCondition(),
6697                            cast<SelectInst>(I)->getCondition());
6698         }
6699         propagateIRFlags(Op, I);
6700         return Op;
6701       case RK_None:
6702         break;
6703       }
6704       llvm_unreachable("Unknown reduction operation.");
6705     }
6706 
6707     TargetTransformInfo::ReductionFlags getFlags() const {
6708       TargetTransformInfo::ReductionFlags Flags;
6709       switch (Kind) {
6710       case RK_Arithmetic:
6711         break;
6712       case RK_SMin:
6713         Flags.IsSigned = true;
6714         Flags.IsMaxOp = false;
6715         break;
6716       case RK_SMax:
6717         Flags.IsSigned = true;
6718         Flags.IsMaxOp = true;
6719         break;
6720       case RK_UMin:
6721         Flags.IsSigned = false;
6722         Flags.IsMaxOp = false;
6723         break;
6724       case RK_UMax:
6725         Flags.IsSigned = false;
6726         Flags.IsMaxOp = true;
6727         break;
6728       case RK_None:
6729         llvm_unreachable("Reduction kind is not set");
6730       }
6731       return Flags;
6732     }
6733   };
6734 
6735   WeakTrackingVH ReductionRoot;
6736 
6737   /// The operation data of the reduction operation.
6738   OperationData ReductionData;
6739 
6740   /// The operation data of the values we perform a reduction on.
6741   OperationData ReducedValueData;
6742 
6743   /// Should we model this reduction as a pairwise reduction tree or a tree that
6744   /// splits the vector in halves and adds those halves.
6745   bool IsPairwiseReduction = false;
6746 
6747   /// Checks if the ParentStackElem.first should be marked as a reduction
6748   /// operation with an extra argument or as extra argument itself.
6749   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
6750                     Value *ExtraArg) {
6751     if (ExtraArgs.count(ParentStackElem.first)) {
6752       ExtraArgs[ParentStackElem.first] = nullptr;
6753       // We ran into something like:
6754       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6755       // The whole ParentStackElem.first should be considered as an extra value
6756       // in this case.
6757       // Do not perform analysis of remaining operands of ParentStackElem.first
6758       // instruction, this whole instruction is an extra argument.
6759       ParentStackElem.second = ParentStackElem.first->getNumOperands();
6760     } else {
6761       // We ran into something like:
6762       // ParentStackElem.first += ... + ExtraArg + ...
6763       ExtraArgs[ParentStackElem.first] = ExtraArg;
6764     }
6765   }
6766 
6767   static OperationData getOperationData(Instruction *I) {
6768     if (!I)
6769       return OperationData();
6770 
6771     Value *LHS;
6772     Value *RHS;
6773     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(I)) {
6774       return OperationData(cast<BinaryOperator>(I)->getOpcode(), RK_Arithmetic);
6775     }
6776     if (auto *Select = dyn_cast<SelectInst>(I)) {
6777       // Look for a min/max pattern.
6778       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6779         return OperationData(Instruction::ICmp, RK_UMin);
6780       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6781         return OperationData(Instruction::ICmp, RK_SMin);
6782       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6783         return OperationData(Instruction::ICmp, RK_UMax);
6784       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6785         return OperationData(Instruction::ICmp, RK_SMax);
6786       } else {
6787         // Try harder: look for min/max pattern based on instructions producing
6788         // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6789         // During the intermediate stages of SLP, it's very common to have
6790         // pattern like this (since optimizeGatherSequence is run only once
6791         // at the end):
6792         // %1 = extractelement <2 x i32> %a, i32 0
6793         // %2 = extractelement <2 x i32> %a, i32 1
6794         // %cond = icmp sgt i32 %1, %2
6795         // %3 = extractelement <2 x i32> %a, i32 0
6796         // %4 = extractelement <2 x i32> %a, i32 1
6797         // %select = select i1 %cond, i32 %3, i32 %4
6798         CmpInst::Predicate Pred;
6799         Instruction *L1;
6800         Instruction *L2;
6801 
6802         LHS = Select->getTrueValue();
6803         RHS = Select->getFalseValue();
6804         Value *Cond = Select->getCondition();
6805 
6806         // TODO: Support inverse predicates.
6807         if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
6808           if (!isa<ExtractElementInst>(RHS) ||
6809               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6810             return OperationData(*I);
6811         } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
6812           if (!isa<ExtractElementInst>(LHS) ||
6813               !L1->isIdenticalTo(cast<Instruction>(LHS)))
6814             return OperationData(*I);
6815         } else {
6816           if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
6817             return OperationData(*I);
6818           if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
6819               !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
6820               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6821             return OperationData(*I);
6822         }
6823         switch (Pred) {
6824         default:
6825           return OperationData(*I);
6826 
6827         case CmpInst::ICMP_ULT:
6828         case CmpInst::ICMP_ULE:
6829           return OperationData(Instruction::ICmp, RK_UMin);
6830 
6831         case CmpInst::ICMP_SLT:
6832         case CmpInst::ICMP_SLE:
6833           return OperationData(Instruction::ICmp, RK_SMin);
6834 
6835         case CmpInst::ICMP_UGT:
6836         case CmpInst::ICMP_UGE:
6837           return OperationData(Instruction::ICmp, RK_UMax);
6838 
6839         case CmpInst::ICMP_SGT:
6840         case CmpInst::ICMP_SGE:
6841           return OperationData(Instruction::ICmp, RK_SMax);
6842         }
6843       }
6844     }
6845     return OperationData(*I);
6846   }
6847 
6848 public:
6849   HorizontalReduction() = default;
6850 
6851   /// Try to find a reduction tree.
6852   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
6853     assert((!Phi || is_contained(Phi->operands(), B)) &&
6854            "Thi phi needs to use the binary operator");
6855 
6856     ReductionData = getOperationData(B);
6857 
6858     // We could have a initial reductions that is not an add.
6859     //  r *= v1 + v2 + v3 + v4
6860     // In such a case start looking for a tree rooted in the first '+'.
6861     if (Phi) {
6862       if (ReductionData.getLHS(B) == Phi) {
6863         Phi = nullptr;
6864         B = dyn_cast<Instruction>(ReductionData.getRHS(B));
6865         ReductionData = getOperationData(B);
6866       } else if (ReductionData.getRHS(B) == Phi) {
6867         Phi = nullptr;
6868         B = dyn_cast<Instruction>(ReductionData.getLHS(B));
6869         ReductionData = getOperationData(B);
6870       }
6871     }
6872 
6873     if (!ReductionData.isVectorizable(B))
6874       return false;
6875 
6876     Type *Ty = B->getType();
6877     if (!isValidElementType(Ty))
6878       return false;
6879     if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
6880       return false;
6881 
6882     ReducedValueData.clear();
6883     ReductionRoot = B;
6884 
6885     // Post order traverse the reduction tree starting at B. We only handle true
6886     // trees containing only binary operators.
6887     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
6888     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
6889     ReductionData.initReductionOps(ReductionOps);
6890     while (!Stack.empty()) {
6891       Instruction *TreeN = Stack.back().first;
6892       unsigned EdgeToVist = Stack.back().second++;
6893       OperationData OpData = getOperationData(TreeN);
6894       bool IsReducedValue = OpData != ReductionData;
6895 
6896       // Postorder vist.
6897       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
6898         if (IsReducedValue)
6899           ReducedVals.push_back(TreeN);
6900         else {
6901           auto I = ExtraArgs.find(TreeN);
6902           if (I != ExtraArgs.end() && !I->second) {
6903             // Check if TreeN is an extra argument of its parent operation.
6904             if (Stack.size() <= 1) {
6905               // TreeN can't be an extra argument as it is a root reduction
6906               // operation.
6907               return false;
6908             }
6909             // Yes, TreeN is an extra argument, do not add it to a list of
6910             // reduction operations.
6911             // Stack[Stack.size() - 2] always points to the parent operation.
6912             markExtraArg(Stack[Stack.size() - 2], TreeN);
6913             ExtraArgs.erase(TreeN);
6914           } else
6915             ReductionData.addReductionOps(TreeN, ReductionOps);
6916         }
6917         // Retract.
6918         Stack.pop_back();
6919         continue;
6920       }
6921 
6922       // Visit left or right.
6923       Value *NextV = TreeN->getOperand(EdgeToVist);
6924       if (NextV != Phi) {
6925         auto *I = dyn_cast<Instruction>(NextV);
6926         OpData = getOperationData(I);
6927         // Continue analysis if the next operand is a reduction operation or
6928         // (possibly) a reduced value. If the reduced value opcode is not set,
6929         // the first met operation != reduction operation is considered as the
6930         // reduced value class.
6931         if (I && (!ReducedValueData || OpData == ReducedValueData ||
6932                   OpData == ReductionData)) {
6933           const bool IsReductionOperation = OpData == ReductionData;
6934           // Only handle trees in the current basic block.
6935           if (!ReductionData.hasSameParent(I, B->getParent(),
6936                                            IsReductionOperation)) {
6937             // I is an extra argument for TreeN (its parent operation).
6938             markExtraArg(Stack.back(), I);
6939             continue;
6940           }
6941 
6942           // Each tree node needs to have minimal number of users except for the
6943           // ultimate reduction.
6944           if (!ReductionData.hasRequiredNumberOfUses(I,
6945                                                      OpData == ReductionData) &&
6946               I != B) {
6947             // I is an extra argument for TreeN (its parent operation).
6948             markExtraArg(Stack.back(), I);
6949             continue;
6950           }
6951 
6952           if (IsReductionOperation) {
6953             // We need to be able to reassociate the reduction operations.
6954             if (!OpData.isAssociative(I)) {
6955               // I is an extra argument for TreeN (its parent operation).
6956               markExtraArg(Stack.back(), I);
6957               continue;
6958             }
6959           } else if (ReducedValueData &&
6960                      ReducedValueData != OpData) {
6961             // Make sure that the opcodes of the operations that we are going to
6962             // reduce match.
6963             // I is an extra argument for TreeN (its parent operation).
6964             markExtraArg(Stack.back(), I);
6965             continue;
6966           } else if (!ReducedValueData)
6967             ReducedValueData = OpData;
6968 
6969           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
6970           continue;
6971         }
6972       }
6973       // NextV is an extra argument for TreeN (its parent operation).
6974       markExtraArg(Stack.back(), NextV);
6975     }
6976     return true;
6977   }
6978 
6979   /// Attempt to vectorize the tree found by matchAssociativeReduction.
6980   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
6981     // If there are a sufficient number of reduction values, reduce
6982     // to a nearby power-of-2. We can safely generate oversized
6983     // vectors and rely on the backend to split them to legal sizes.
6984     unsigned NumReducedVals = ReducedVals.size();
6985     if (NumReducedVals < 4)
6986       return false;
6987 
6988     // FIXME: Fast-math-flags should be set based on the instructions in the
6989     //        reduction (not all of 'fast' are required).
6990     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
6991     FastMathFlags Unsafe;
6992     Unsafe.setFast();
6993     Builder.setFastMathFlags(Unsafe);
6994 
6995     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
6996     // The same extra argument may be used several times, so log each attempt
6997     // to use it.
6998     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
6999       assert(Pair.first && "DebugLoc must be set.");
7000       ExternallyUsedValues[Pair.second].push_back(Pair.first);
7001     }
7002 
7003     // The compare instruction of a min/max is the insertion point for new
7004     // instructions and may be replaced with a new compare instruction.
7005     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
7006       assert(isa<SelectInst>(RdxRootInst) &&
7007              "Expected min/max reduction to have select root instruction");
7008       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
7009       assert(isa<Instruction>(ScalarCond) &&
7010              "Expected min/max reduction to have compare condition");
7011       return cast<Instruction>(ScalarCond);
7012     };
7013 
7014     // The reduction root is used as the insertion point for new instructions,
7015     // so set it as externally used to prevent it from being deleted.
7016     ExternallyUsedValues[ReductionRoot];
7017     SmallVector<Value *, 16> IgnoreList;
7018     for (ReductionOpsType &RdxOp : ReductionOps)
7019       IgnoreList.append(RdxOp.begin(), RdxOp.end());
7020 
7021     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
7022     if (NumReducedVals > ReduxWidth) {
7023       // In the loop below, we are building a tree based on a window of
7024       // 'ReduxWidth' values.
7025       // If the operands of those values have common traits (compare predicate,
7026       // constant operand, etc), then we want to group those together to
7027       // minimize the cost of the reduction.
7028 
7029       // TODO: This should be extended to count common operands for
7030       //       compares and binops.
7031 
7032       // Step 1: Count the number of times each compare predicate occurs.
7033       SmallDenseMap<unsigned, unsigned> PredCountMap;
7034       for (Value *RdxVal : ReducedVals) {
7035         CmpInst::Predicate Pred;
7036         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
7037           ++PredCountMap[Pred];
7038       }
7039       // Step 2: Sort the values so the most common predicates come first.
7040       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
7041         CmpInst::Predicate PredA, PredB;
7042         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
7043             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
7044           return PredCountMap[PredA] > PredCountMap[PredB];
7045         }
7046         return false;
7047       });
7048     }
7049 
7050     Value *VectorizedTree = nullptr;
7051     unsigned i = 0;
7052     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
7053       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
7054       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
7055       Optional<ArrayRef<unsigned>> Order = V.bestOrder();
7056       if (Order) {
7057         assert(Order->size() == VL.size() &&
7058                "Order size must be the same as number of vectorized "
7059                "instructions.");
7060         // TODO: reorder tree nodes without tree rebuilding.
7061         SmallVector<Value *, 4> ReorderedOps(VL.size());
7062         llvm::transform(*Order, ReorderedOps.begin(),
7063                         [VL](const unsigned Idx) { return VL[Idx]; });
7064         V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
7065       }
7066       if (V.isTreeTinyAndNotFullyVectorizable())
7067         break;
7068       if (V.isLoadCombineReductionCandidate(ReductionData.getOpcode()))
7069         break;
7070 
7071       V.computeMinimumValueSizes();
7072 
7073       // Estimate cost.
7074       int TreeCost = V.getTreeCost();
7075       int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
7076       int Cost = TreeCost + ReductionCost;
7077       if (Cost >= -SLPCostThreshold) {
7078         V.getORE()->emit([&]() {
7079           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
7080                                           cast<Instruction>(VL[0]))
7081                  << "Vectorizing horizontal reduction is possible"
7082                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
7083                  << " and threshold "
7084                  << ore::NV("Threshold", -SLPCostThreshold);
7085         });
7086         break;
7087       }
7088 
7089       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
7090                         << Cost << ". (HorRdx)\n");
7091       V.getORE()->emit([&]() {
7092         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
7093                                   cast<Instruction>(VL[0]))
7094                << "Vectorized horizontal reduction with cost "
7095                << ore::NV("Cost", Cost) << " and with tree size "
7096                << ore::NV("TreeSize", V.getTreeSize());
7097       });
7098 
7099       // Vectorize a tree.
7100       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
7101       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
7102 
7103       // Emit a reduction. For min/max, the root is a select, but the insertion
7104       // point is the compare condition of that select.
7105       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
7106       if (ReductionData.isMinMax())
7107         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
7108       else
7109         Builder.SetInsertPoint(RdxRootInst);
7110 
7111       Value *ReducedSubTree =
7112           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
7113 
7114       if (!VectorizedTree) {
7115         // Initialize the final value in the reduction.
7116         VectorizedTree = ReducedSubTree;
7117       } else {
7118         // Update the final value in the reduction.
7119         Builder.SetCurrentDebugLocation(Loc);
7120         VectorizedTree = ReductionData.createOp(
7121             Builder, VectorizedTree, ReducedSubTree, "op.rdx", ReductionOps);
7122       }
7123       i += ReduxWidth;
7124       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
7125     }
7126 
7127     if (VectorizedTree) {
7128       // Finish the reduction.
7129       for (; i < NumReducedVals; ++i) {
7130         auto *I = cast<Instruction>(ReducedVals[i]);
7131         Builder.SetCurrentDebugLocation(I->getDebugLoc());
7132         VectorizedTree = ReductionData.createOp(Builder, VectorizedTree, I, "",
7133                                                 ReductionOps);
7134       }
7135       for (auto &Pair : ExternallyUsedValues) {
7136         // Add each externally used value to the final reduction.
7137         for (auto *I : Pair.second) {
7138           Builder.SetCurrentDebugLocation(I->getDebugLoc());
7139           VectorizedTree = ReductionData.createOp(Builder, VectorizedTree,
7140                                                   Pair.first, "op.extra", I);
7141         }
7142       }
7143 
7144       // Update users. For a min/max reduction that ends with a compare and
7145       // select, we also have to RAUW for the compare instruction feeding the
7146       // reduction root. That's because the original compare may have extra uses
7147       // besides the final select of the reduction.
7148       if (ReductionData.isMinMax()) {
7149         if (auto *VecSelect = dyn_cast<SelectInst>(VectorizedTree)) {
7150           Instruction *ScalarCmp =
7151               getCmpForMinMaxReduction(cast<Instruction>(ReductionRoot));
7152           ScalarCmp->replaceAllUsesWith(VecSelect->getCondition());
7153         }
7154       }
7155       ReductionRoot->replaceAllUsesWith(VectorizedTree);
7156 
7157       // Mark all scalar reduction ops for deletion, they are replaced by the
7158       // vector reductions.
7159       V.eraseInstructions(IgnoreList);
7160     }
7161     return VectorizedTree != nullptr;
7162   }
7163 
7164   unsigned numReductionValues() const {
7165     return ReducedVals.size();
7166   }
7167 
7168 private:
7169   /// Calculate the cost of a reduction.
7170   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
7171                        unsigned ReduxWidth) {
7172     Type *ScalarTy = FirstReducedVal->getType();
7173     auto *VecTy = FixedVectorType::get(ScalarTy, ReduxWidth);
7174 
7175     int PairwiseRdxCost;
7176     int SplittingRdxCost;
7177     switch (ReductionData.getKind()) {
7178     case RK_Arithmetic:
7179       PairwiseRdxCost =
7180           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
7181                                           /*IsPairwiseForm=*/true);
7182       SplittingRdxCost =
7183           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
7184                                           /*IsPairwiseForm=*/false);
7185       break;
7186     case RK_SMin:
7187     case RK_SMax:
7188     case RK_UMin:
7189     case RK_UMax: {
7190       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VecTy));
7191       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
7192                         ReductionData.getKind() == RK_UMax;
7193       PairwiseRdxCost =
7194           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7195                                       /*IsPairwiseForm=*/true, IsUnsigned);
7196       SplittingRdxCost =
7197           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7198                                       /*IsPairwiseForm=*/false, IsUnsigned);
7199       break;
7200     }
7201     case RK_None:
7202       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7203     }
7204 
7205     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
7206     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
7207 
7208     int ScalarReduxCost = 0;
7209     switch (ReductionData.getKind()) {
7210     case RK_Arithmetic:
7211       ScalarReduxCost =
7212           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
7213       break;
7214     case RK_SMin:
7215     case RK_SMax:
7216     case RK_UMin:
7217     case RK_UMax:
7218       ScalarReduxCost =
7219           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
7220           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
7221                                   CmpInst::makeCmpResultType(ScalarTy));
7222       break;
7223     case RK_None:
7224       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7225     }
7226     ScalarReduxCost *= (ReduxWidth - 1);
7227 
7228     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
7229                       << " for reduction that starts with " << *FirstReducedVal
7230                       << " (It is a "
7231                       << (IsPairwiseReduction ? "pairwise" : "splitting")
7232                       << " reduction)\n");
7233 
7234     return VecReduxCost - ScalarReduxCost;
7235   }
7236 
7237   /// Emit a horizontal reduction of the vectorized value.
7238   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
7239                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
7240     assert(VectorizedValue && "Need to have a vectorized tree node");
7241     assert(isPowerOf2_32(ReduxWidth) &&
7242            "We only handle power-of-two reductions for now");
7243 
7244     if (!IsPairwiseReduction) {
7245       // FIXME: The builder should use an FMF guard. It should not be hard-coded
7246       //        to 'fast'.
7247       assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF");
7248       return createSimpleTargetReduction(
7249           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
7250           ReductionData.getFlags(), ReductionOps.back());
7251     }
7252 
7253     Value *TmpVec = VectorizedValue;
7254     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
7255       auto LeftMask = createRdxShuffleMask(ReduxWidth, i, true, true);
7256       auto RightMask = createRdxShuffleMask(ReduxWidth, i, true, false);
7257 
7258       Value *LeftShuf =
7259           Builder.CreateShuffleVector(TmpVec, LeftMask, "rdx.shuf.l");
7260       Value *RightShuf =
7261           Builder.CreateShuffleVector(TmpVec, RightMask, "rdx.shuf.r");
7262       TmpVec = ReductionData.createOp(Builder, LeftShuf, RightShuf, "op.rdx",
7263                                       ReductionOps);
7264     }
7265 
7266     // The result is in the first element of the vector.
7267     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
7268   }
7269 };
7270 
7271 } // end anonymous namespace
7272 
7273 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
7274   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
7275     return cast<FixedVectorType>(IE->getType())->getNumElements();
7276 
7277   unsigned AggregateSize = 1;
7278   auto *IV = cast<InsertValueInst>(InsertInst);
7279   Type *CurrentType = IV->getType();
7280   do {
7281     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7282       for (auto *Elt : ST->elements())
7283         if (Elt != ST->getElementType(0)) // check homogeneity
7284           return None;
7285       AggregateSize *= ST->getNumElements();
7286       CurrentType = ST->getElementType(0);
7287     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7288       AggregateSize *= AT->getNumElements();
7289       CurrentType = AT->getElementType();
7290     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
7291       AggregateSize *= VT->getNumElements();
7292       return AggregateSize;
7293     } else if (CurrentType->isSingleValueType()) {
7294       return AggregateSize;
7295     } else {
7296       return None;
7297     }
7298   } while (true);
7299 }
7300 
7301 static Optional<unsigned> getOperandIndex(Instruction *InsertInst,
7302                                           unsigned OperandOffset) {
7303   unsigned OperandIndex = OperandOffset;
7304   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
7305     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
7306       auto *VT = cast<FixedVectorType>(IE->getType());
7307       OperandIndex *= VT->getNumElements();
7308       OperandIndex += CI->getZExtValue();
7309       return OperandIndex;
7310     }
7311     return None;
7312   }
7313 
7314   auto *IV = cast<InsertValueInst>(InsertInst);
7315   Type *CurrentType = IV->getType();
7316   for (unsigned int Index : IV->indices()) {
7317     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7318       OperandIndex *= ST->getNumElements();
7319       CurrentType = ST->getElementType(Index);
7320     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7321       OperandIndex *= AT->getNumElements();
7322       CurrentType = AT->getElementType();
7323     } else {
7324       return None;
7325     }
7326     OperandIndex += Index;
7327   }
7328   return OperandIndex;
7329 }
7330 
7331 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
7332                                    TargetTransformInfo *TTI,
7333                                    SmallVectorImpl<Value *> &BuildVectorOpds,
7334                                    SmallVectorImpl<Value *> &InsertElts,
7335                                    unsigned OperandOffset) {
7336   do {
7337     Value *InsertedOperand = LastInsertInst->getOperand(1);
7338     Optional<unsigned> OperandIndex =
7339         getOperandIndex(LastInsertInst, OperandOffset);
7340     if (!OperandIndex)
7341       return false;
7342     if (isa<InsertElementInst>(InsertedOperand) ||
7343         isa<InsertValueInst>(InsertedOperand)) {
7344       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
7345                                   BuildVectorOpds, InsertElts, *OperandIndex))
7346         return false;
7347     } else {
7348       BuildVectorOpds[*OperandIndex] = InsertedOperand;
7349       InsertElts[*OperandIndex] = LastInsertInst;
7350     }
7351     if (isa<UndefValue>(LastInsertInst->getOperand(0)))
7352       return true;
7353     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
7354   } while (LastInsertInst != nullptr &&
7355            (isa<InsertValueInst>(LastInsertInst) ||
7356             isa<InsertElementInst>(LastInsertInst)) &&
7357            LastInsertInst->hasOneUse());
7358   return false;
7359 }
7360 
7361 /// Recognize construction of vectors like
7362 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
7363 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
7364 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
7365 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
7366 ///  starting from the last insertelement or insertvalue instruction.
7367 ///
7368 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
7369 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
7370 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
7371 ///
7372 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
7373 ///
7374 /// \return true if it matches.
7375 static bool findBuildAggregate(Instruction *LastInsertInst,
7376                                TargetTransformInfo *TTI,
7377                                SmallVectorImpl<Value *> &BuildVectorOpds,
7378                                SmallVectorImpl<Value *> &InsertElts) {
7379 
7380   assert((isa<InsertElementInst>(LastInsertInst) ||
7381           isa<InsertValueInst>(LastInsertInst)) &&
7382          "Expected insertelement or insertvalue instruction!");
7383 
7384   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
7385          "Expected empty result vectors!");
7386 
7387   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
7388   if (!AggregateSize)
7389     return false;
7390   BuildVectorOpds.resize(*AggregateSize);
7391   InsertElts.resize(*AggregateSize);
7392 
7393   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
7394                              0)) {
7395     llvm::erase_if(BuildVectorOpds,
7396                    [](const Value *V) { return V == nullptr; });
7397     llvm::erase_if(InsertElts, [](const Value *V) { return V == nullptr; });
7398     if (BuildVectorOpds.size() >= 2)
7399       return true;
7400   }
7401 
7402   return false;
7403 }
7404 
7405 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
7406   return V->getType() < V2->getType();
7407 }
7408 
7409 /// Try and get a reduction value from a phi node.
7410 ///
7411 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
7412 /// if they come from either \p ParentBB or a containing loop latch.
7413 ///
7414 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
7415 /// if not possible.
7416 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
7417                                 BasicBlock *ParentBB, LoopInfo *LI) {
7418   // There are situations where the reduction value is not dominated by the
7419   // reduction phi. Vectorizing such cases has been reported to cause
7420   // miscompiles. See PR25787.
7421   auto DominatedReduxValue = [&](Value *R) {
7422     return isa<Instruction>(R) &&
7423            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
7424   };
7425 
7426   Value *Rdx = nullptr;
7427 
7428   // Return the incoming value if it comes from the same BB as the phi node.
7429   if (P->getIncomingBlock(0) == ParentBB) {
7430     Rdx = P->getIncomingValue(0);
7431   } else if (P->getIncomingBlock(1) == ParentBB) {
7432     Rdx = P->getIncomingValue(1);
7433   }
7434 
7435   if (Rdx && DominatedReduxValue(Rdx))
7436     return Rdx;
7437 
7438   // Otherwise, check whether we have a loop latch to look at.
7439   Loop *BBL = LI->getLoopFor(ParentBB);
7440   if (!BBL)
7441     return nullptr;
7442   BasicBlock *BBLatch = BBL->getLoopLatch();
7443   if (!BBLatch)
7444     return nullptr;
7445 
7446   // There is a loop latch, return the incoming value if it comes from
7447   // that. This reduction pattern occasionally turns up.
7448   if (P->getIncomingBlock(0) == BBLatch) {
7449     Rdx = P->getIncomingValue(0);
7450   } else if (P->getIncomingBlock(1) == BBLatch) {
7451     Rdx = P->getIncomingValue(1);
7452   }
7453 
7454   if (Rdx && DominatedReduxValue(Rdx))
7455     return Rdx;
7456 
7457   return nullptr;
7458 }
7459 
7460 /// Attempt to reduce a horizontal reduction.
7461 /// If it is legal to match a horizontal reduction feeding the phi node \a P
7462 /// with reduction operators \a Root (or one of its operands) in a basic block
7463 /// \a BB, then check if it can be done. If horizontal reduction is not found
7464 /// and root instruction is a binary operation, vectorization of the operands is
7465 /// attempted.
7466 /// \returns true if a horizontal reduction was matched and reduced or operands
7467 /// of one of the binary instruction were vectorized.
7468 /// \returns false if a horizontal reduction was not matched (or not possible)
7469 /// or no vectorization of any binary operation feeding \a Root instruction was
7470 /// performed.
7471 static bool tryToVectorizeHorReductionOrInstOperands(
7472     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
7473     TargetTransformInfo *TTI,
7474     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
7475   if (!ShouldVectorizeHor)
7476     return false;
7477 
7478   if (!Root)
7479     return false;
7480 
7481   if (Root->getParent() != BB || isa<PHINode>(Root))
7482     return false;
7483   // Start analysis starting from Root instruction. If horizontal reduction is
7484   // found, try to vectorize it. If it is not a horizontal reduction or
7485   // vectorization is not possible or not effective, and currently analyzed
7486   // instruction is a binary operation, try to vectorize the operands, using
7487   // pre-order DFS traversal order. If the operands were not vectorized, repeat
7488   // the same procedure considering each operand as a possible root of the
7489   // horizontal reduction.
7490   // Interrupt the process if the Root instruction itself was vectorized or all
7491   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
7492   SmallVector<std::pair<Instruction *, unsigned>, 8> Stack(1, {Root, 0});
7493   SmallPtrSet<Value *, 8> VisitedInstrs;
7494   bool Res = false;
7495   while (!Stack.empty()) {
7496     Instruction *Inst;
7497     unsigned Level;
7498     std::tie(Inst, Level) = Stack.pop_back_val();
7499     Value *B0, *B1;
7500     bool IsBinop = match(Inst, m_BinOp(m_Value(B0), m_Value(B1)));
7501     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
7502     if (IsBinop || IsSelect) {
7503       HorizontalReduction HorRdx;
7504       if (HorRdx.matchAssociativeReduction(P, Inst)) {
7505         if (HorRdx.tryToReduce(R, TTI)) {
7506           Res = true;
7507           // Set P to nullptr to avoid re-analysis of phi node in
7508           // matchAssociativeReduction function unless this is the root node.
7509           P = nullptr;
7510           continue;
7511         }
7512       }
7513       if (P && IsBinop) {
7514         Inst = dyn_cast<Instruction>(B0);
7515         if (Inst == P)
7516           Inst = dyn_cast<Instruction>(B1);
7517         if (!Inst) {
7518           // Set P to nullptr to avoid re-analysis of phi node in
7519           // matchAssociativeReduction function unless this is the root node.
7520           P = nullptr;
7521           continue;
7522         }
7523       }
7524     }
7525     // Set P to nullptr to avoid re-analysis of phi node in
7526     // matchAssociativeReduction function unless this is the root node.
7527     P = nullptr;
7528     if (Vectorize(Inst, R)) {
7529       Res = true;
7530       continue;
7531     }
7532 
7533     // Try to vectorize operands.
7534     // Continue analysis for the instruction from the same basic block only to
7535     // save compile time.
7536     if (++Level < RecursionMaxDepth)
7537       for (auto *Op : Inst->operand_values())
7538         if (VisitedInstrs.insert(Op).second)
7539           if (auto *I = dyn_cast<Instruction>(Op))
7540             if (!isa<PHINode>(I) && !R.isDeleted(I) && I->getParent() == BB)
7541               Stack.emplace_back(I, Level);
7542   }
7543   return Res;
7544 }
7545 
7546 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
7547                                                  BasicBlock *BB, BoUpSLP &R,
7548                                                  TargetTransformInfo *TTI) {
7549   auto *I = dyn_cast_or_null<Instruction>(V);
7550   if (!I)
7551     return false;
7552 
7553   if (!isa<BinaryOperator>(I))
7554     P = nullptr;
7555   // Try to match and vectorize a horizontal reduction.
7556   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
7557     return tryToVectorize(I, R);
7558   };
7559   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
7560                                                   ExtraVectorization);
7561 }
7562 
7563 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
7564                                                  BasicBlock *BB, BoUpSLP &R) {
7565   const DataLayout &DL = BB->getModule()->getDataLayout();
7566   if (!R.canMapToVector(IVI->getType(), DL))
7567     return false;
7568 
7569   SmallVector<Value *, 16> BuildVectorOpds;
7570   SmallVector<Value *, 16> BuildVectorInsts;
7571   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
7572     return false;
7573 
7574   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
7575   // Aggregate value is unlikely to be processed in vector register, we need to
7576   // extract scalars into scalar registers, so NeedExtraction is set true.
7577   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7578                             BuildVectorInsts);
7579 }
7580 
7581 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
7582                                                    BasicBlock *BB, BoUpSLP &R) {
7583   SmallVector<Value *, 16> BuildVectorInsts;
7584   SmallVector<Value *, 16> BuildVectorOpds;
7585   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
7586       (llvm::all_of(BuildVectorOpds,
7587                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
7588        isShuffle(BuildVectorOpds)))
7589     return false;
7590 
7591   // Vectorize starting with the build vector operands ignoring the BuildVector
7592   // instructions for the purpose of scheduling and user extraction.
7593   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7594                             BuildVectorInsts);
7595 }
7596 
7597 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
7598                                          BoUpSLP &R) {
7599   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
7600     return true;
7601 
7602   bool OpsChanged = false;
7603   for (int Idx = 0; Idx < 2; ++Idx) {
7604     OpsChanged |=
7605         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
7606   }
7607   return OpsChanged;
7608 }
7609 
7610 bool SLPVectorizerPass::vectorizeSimpleInstructions(
7611     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R) {
7612   bool OpsChanged = false;
7613   for (auto *I : reverse(Instructions)) {
7614     if (R.isDeleted(I))
7615       continue;
7616     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
7617       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
7618     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
7619       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
7620     else if (auto *CI = dyn_cast<CmpInst>(I))
7621       OpsChanged |= vectorizeCmpInst(CI, BB, R);
7622   }
7623   Instructions.clear();
7624   return OpsChanged;
7625 }
7626 
7627 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
7628   bool Changed = false;
7629   SmallVector<Value *, 4> Incoming;
7630   SmallPtrSet<Value *, 16> VisitedInstrs;
7631   unsigned MaxVecRegSize = R.getMaxVecRegSize();
7632 
7633   bool HaveVectorizedPhiNodes = true;
7634   while (HaveVectorizedPhiNodes) {
7635     HaveVectorizedPhiNodes = false;
7636 
7637     // Collect the incoming values from the PHIs.
7638     Incoming.clear();
7639     for (Instruction &I : *BB) {
7640       PHINode *P = dyn_cast<PHINode>(&I);
7641       if (!P)
7642         break;
7643 
7644       if (!VisitedInstrs.count(P) && !R.isDeleted(P))
7645         Incoming.push_back(P);
7646     }
7647 
7648     // Sort by type.
7649     llvm::stable_sort(Incoming, PhiTypeSorterFunc);
7650 
7651     // Try to vectorize elements base on their type.
7652     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
7653                                            E = Incoming.end();
7654          IncIt != E;) {
7655 
7656       // Look for the next elements with the same type.
7657       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
7658       Type *EltTy = (*IncIt)->getType();
7659 
7660       assert(EltTy->isSized() &&
7661              "Instructions should all be sized at this point");
7662       TypeSize EltTS = DL->getTypeSizeInBits(EltTy);
7663       if (EltTS.isScalable()) {
7664         // For now, just ignore vectorizing scalable types.
7665         ++IncIt;
7666         continue;
7667       }
7668 
7669       unsigned EltSize = EltTS.getFixedSize();
7670       unsigned MaxNumElts = MaxVecRegSize / EltSize;
7671       if (MaxNumElts < 2) {
7672         ++IncIt;
7673         continue;
7674       }
7675 
7676       while (SameTypeIt != E &&
7677              (*SameTypeIt)->getType() == EltTy &&
7678              static_cast<unsigned>(SameTypeIt - IncIt) < MaxNumElts) {
7679         VisitedInstrs.insert(*SameTypeIt);
7680         ++SameTypeIt;
7681       }
7682 
7683       // Try to vectorize them.
7684       unsigned NumElts = (SameTypeIt - IncIt);
7685       LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
7686                         << NumElts << ")\n");
7687       // The order in which the phi nodes appear in the program does not matter.
7688       // So allow tryToVectorizeList to reorder them if it is beneficial. This
7689       // is done when there are exactly two elements since tryToVectorizeList
7690       // asserts that there are only two values when AllowReorder is true.
7691       bool AllowReorder = NumElts == 2;
7692       if (NumElts > 1 &&
7693           tryToVectorizeList(makeArrayRef(IncIt, NumElts), R, AllowReorder)) {
7694         // Success start over because instructions might have been changed.
7695         HaveVectorizedPhiNodes = true;
7696         Changed = true;
7697         break;
7698       }
7699 
7700       // Start over at the next instruction of a different type (or the end).
7701       IncIt = SameTypeIt;
7702     }
7703   }
7704 
7705   VisitedInstrs.clear();
7706 
7707   SmallVector<Instruction *, 8> PostProcessInstructions;
7708   SmallDenseSet<Instruction *, 4> KeyNodes;
7709   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
7710     // Skip instructions with scalable type. The num of elements is unknown at
7711     // compile-time for scalable type.
7712     if (isa<ScalableVectorType>(it->getType()))
7713       continue;
7714 
7715     // Skip instructions marked for the deletion.
7716     if (R.isDeleted(&*it))
7717       continue;
7718     // We may go through BB multiple times so skip the one we have checked.
7719     if (!VisitedInstrs.insert(&*it).second) {
7720       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
7721           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
7722         // We would like to start over since some instructions are deleted
7723         // and the iterator may become invalid value.
7724         Changed = true;
7725         it = BB->begin();
7726         e = BB->end();
7727       }
7728       continue;
7729     }
7730 
7731     if (isa<DbgInfoIntrinsic>(it))
7732       continue;
7733 
7734     // Try to vectorize reductions that use PHINodes.
7735     if (PHINode *P = dyn_cast<PHINode>(it)) {
7736       // Check that the PHI is a reduction PHI.
7737       if (P->getNumIncomingValues() == 2) {
7738         // Try to match and vectorize a horizontal reduction.
7739         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
7740                                      TTI)) {
7741           Changed = true;
7742           it = BB->begin();
7743           e = BB->end();
7744           continue;
7745         }
7746       }
7747       // Try to vectorize the incoming values of the PHI, to catch reductions
7748       // that feed into PHIs.
7749       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
7750         // Skip if the incoming block is the current BB for now. Also, bypass
7751         // unreachable IR for efficiency and to avoid crashing.
7752         // TODO: Collect the skipped incoming values and try to vectorize them
7753         // after processing BB.
7754         if (BB == P->getIncomingBlock(I) ||
7755             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
7756           continue;
7757 
7758         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
7759                                             P->getIncomingBlock(I), R, TTI);
7760       }
7761       continue;
7762     }
7763 
7764     // Ran into an instruction without users, like terminator, or function call
7765     // with ignored return value, store. Ignore unused instructions (basing on
7766     // instruction type, except for CallInst and InvokeInst).
7767     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
7768                             isa<InvokeInst>(it))) {
7769       KeyNodes.insert(&*it);
7770       bool OpsChanged = false;
7771       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
7772         for (auto *V : it->operand_values()) {
7773           // Try to match and vectorize a horizontal reduction.
7774           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
7775         }
7776       }
7777       // Start vectorization of post-process list of instructions from the
7778       // top-tree instructions to try to vectorize as many instructions as
7779       // possible.
7780       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
7781       if (OpsChanged) {
7782         // We would like to start over since some instructions are deleted
7783         // and the iterator may become invalid value.
7784         Changed = true;
7785         it = BB->begin();
7786         e = BB->end();
7787         continue;
7788       }
7789     }
7790 
7791     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
7792         isa<InsertValueInst>(it))
7793       PostProcessInstructions.push_back(&*it);
7794   }
7795 
7796   return Changed;
7797 }
7798 
7799 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
7800   auto Changed = false;
7801   for (auto &Entry : GEPs) {
7802     // If the getelementptr list has fewer than two elements, there's nothing
7803     // to do.
7804     if (Entry.second.size() < 2)
7805       continue;
7806 
7807     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
7808                       << Entry.second.size() << ".\n");
7809 
7810     // Process the GEP list in chunks suitable for the target's supported
7811     // vector size. If a vector register can't hold 1 element, we are done. We
7812     // are trying to vectorize the index computations, so the maximum number of
7813     // elements is based on the size of the index expression, rather than the
7814     // size of the GEP itself (the target's pointer size).
7815     unsigned MaxVecRegSize = R.getMaxVecRegSize();
7816     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
7817     if (MaxVecRegSize < EltSize)
7818       continue;
7819 
7820     unsigned MaxElts = MaxVecRegSize / EltSize;
7821     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
7822       auto Len = std::min<unsigned>(BE - BI, MaxElts);
7823       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
7824 
7825       // Initialize a set a candidate getelementptrs. Note that we use a
7826       // SetVector here to preserve program order. If the index computations
7827       // are vectorizable and begin with loads, we want to minimize the chance
7828       // of having to reorder them later.
7829       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
7830 
7831       // Some of the candidates may have already been vectorized after we
7832       // initially collected them. If so, they are marked as deleted, so remove
7833       // them from the set of candidates.
7834       Candidates.remove_if(
7835           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
7836 
7837       // Remove from the set of candidates all pairs of getelementptrs with
7838       // constant differences. Such getelementptrs are likely not good
7839       // candidates for vectorization in a bottom-up phase since one can be
7840       // computed from the other. We also ensure all candidate getelementptr
7841       // indices are unique.
7842       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
7843         auto *GEPI = GEPList[I];
7844         if (!Candidates.count(GEPI))
7845           continue;
7846         auto *SCEVI = SE->getSCEV(GEPList[I]);
7847         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
7848           auto *GEPJ = GEPList[J];
7849           auto *SCEVJ = SE->getSCEV(GEPList[J]);
7850           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
7851             Candidates.remove(GEPI);
7852             Candidates.remove(GEPJ);
7853           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
7854             Candidates.remove(GEPJ);
7855           }
7856         }
7857       }
7858 
7859       // We break out of the above computation as soon as we know there are
7860       // fewer than two candidates remaining.
7861       if (Candidates.size() < 2)
7862         continue;
7863 
7864       // Add the single, non-constant index of each candidate to the bundle. We
7865       // ensured the indices met these constraints when we originally collected
7866       // the getelementptrs.
7867       SmallVector<Value *, 16> Bundle(Candidates.size());
7868       auto BundleIndex = 0u;
7869       for (auto *V : Candidates) {
7870         auto *GEP = cast<GetElementPtrInst>(V);
7871         auto *GEPIdx = GEP->idx_begin()->get();
7872         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
7873         Bundle[BundleIndex++] = GEPIdx;
7874       }
7875 
7876       // Try and vectorize the indices. We are currently only interested in
7877       // gather-like cases of the form:
7878       //
7879       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7880       //
7881       // where the loads of "a", the loads of "b", and the subtractions can be
7882       // performed in parallel. It's likely that detecting this pattern in a
7883       // bottom-up phase will be simpler and less costly than building a
7884       // full-blown top-down phase beginning at the consecutive loads.
7885       Changed |= tryToVectorizeList(Bundle, R);
7886     }
7887   }
7888   return Changed;
7889 }
7890 
7891 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
7892   bool Changed = false;
7893   // Attempt to sort and vectorize each of the store-groups.
7894   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
7895        ++it) {
7896     if (it->second.size() < 2)
7897       continue;
7898 
7899     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7900                       << it->second.size() << ".\n");
7901 
7902     Changed |= vectorizeStores(it->second, R);
7903   }
7904   return Changed;
7905 }
7906 
7907 char SLPVectorizer::ID = 0;
7908 
7909 static const char lv_name[] = "SLP Vectorizer";
7910 
7911 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
7912 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7913 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7914 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7915 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7916 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
7917 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7918 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7919 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7920 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
7921 
7922 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
7923