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