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