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