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