1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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/OptimizationDiagnosticInfo.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 static cl::opt<int>
109     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
110                      cl::desc("Only vectorize if you gain more than this "
111                               "number "));
112 
113 static cl::opt<bool>
114 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
115                    cl::desc("Attempt to vectorize horizontal reductions"));
116 
117 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
118     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
119     cl::desc(
120         "Attempt to vectorize horizontal reductions feeding into a store"));
121 
122 static cl::opt<int>
123 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
124     cl::desc("Attempt to vectorize for this register size in bits"));
125 
126 /// Limits the size of scheduling regions in a block.
127 /// It avoid long compile times for _very_ large blocks where vector
128 /// instructions are spread over a wide range.
129 /// This limit is way higher than needed by real-world functions.
130 static cl::opt<int>
131 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
132     cl::desc("Limit the size of the SLP scheduling region per block"));
133 
134 static cl::opt<int> MinVectorRegSizeOption(
135     "slp-min-reg-size", cl::init(128), cl::Hidden,
136     cl::desc("Attempt to vectorize for this register size in bits"));
137 
138 static cl::opt<unsigned> RecursionMaxDepth(
139     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
140     cl::desc("Limit the recursion depth when building a vectorizable tree"));
141 
142 static cl::opt<unsigned> MinTreeSize(
143     "slp-min-tree-size", cl::init(3), cl::Hidden,
144     cl::desc("Only vectorize small trees if they are fully vectorizable"));
145 
146 static cl::opt<bool>
147     ViewSLPTree("view-slp-tree", cl::Hidden,
148                 cl::desc("Display the SLP trees with Graphviz"));
149 
150 // Limit the number of alias checks. The limit is chosen so that
151 // it has no negative effect on the llvm benchmarks.
152 static const unsigned AliasedCheckLimit = 10;
153 
154 // Another limit for the alias checks: The maximum distance between load/store
155 // instructions where alias checks are done.
156 // This limit is useful for very large basic blocks.
157 static const unsigned MaxMemDepDistance = 160;
158 
159 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
160 /// regions to be handled.
161 static const int MinScheduleRegionSize = 16;
162 
163 /// \brief Predicate for the element types that the SLP vectorizer supports.
164 ///
165 /// The most important thing to filter here are types which are invalid in LLVM
166 /// vectors. We also filter target specific types which have absolutely no
167 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
168 /// avoids spending time checking the cost model and realizing that they will
169 /// be inevitably scalarized.
170 static bool isValidElementType(Type *Ty) {
171   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
172          !Ty->isPPC_FP128Ty();
173 }
174 
175 /// \returns true if all of the instructions in \p VL are in the same block or
176 /// false otherwise.
177 static bool allSameBlock(ArrayRef<Value *> VL) {
178   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
179   if (!I0)
180     return false;
181   BasicBlock *BB = I0->getParent();
182   for (int i = 1, e = VL.size(); i < e; i++) {
183     Instruction *I = dyn_cast<Instruction>(VL[i]);
184     if (!I)
185       return false;
186 
187     if (BB != I->getParent())
188       return false;
189   }
190   return true;
191 }
192 
193 /// \returns True if all of the values in \p VL are constants.
194 static bool allConstant(ArrayRef<Value *> VL) {
195   for (Value *i : VL)
196     if (!isa<Constant>(i))
197       return false;
198   return true;
199 }
200 
201 /// \returns True if all of the values in \p VL are identical.
202 static bool isSplat(ArrayRef<Value *> VL) {
203   for (unsigned i = 1, e = VL.size(); i < e; ++i)
204     if (VL[i] != VL[0])
205       return false;
206   return true;
207 }
208 
209 /// Checks if the vector of instructions can be represented as a shuffle, like:
210 /// %x0 = extractelement <4 x i8> %x, i32 0
211 /// %x3 = extractelement <4 x i8> %x, i32 3
212 /// %y1 = extractelement <4 x i8> %y, i32 1
213 /// %y2 = extractelement <4 x i8> %y, i32 2
214 /// %x0x0 = mul i8 %x0, %x0
215 /// %x3x3 = mul i8 %x3, %x3
216 /// %y1y1 = mul i8 %y1, %y1
217 /// %y2y2 = mul i8 %y2, %y2
218 /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
219 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
220 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
221 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
222 /// ret <4 x i8> %ins4
223 /// can be transformed into:
224 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
225 ///                                                         i32 6>
226 /// %2 = mul <4 x i8> %1, %1
227 /// ret <4 x i8> %2
228 /// We convert this initially to something like:
229 /// %x0 = extractelement <4 x i8> %x, i32 0
230 /// %x3 = extractelement <4 x i8> %x, i32 3
231 /// %y1 = extractelement <4 x i8> %y, i32 1
232 /// %y2 = extractelement <4 x i8> %y, i32 2
233 /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
234 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
235 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
236 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
237 /// %5 = mul <4 x i8> %4, %4
238 /// %6 = extractelement <4 x i8> %5, i32 0
239 /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
240 /// %7 = extractelement <4 x i8> %5, i32 1
241 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
242 /// %8 = extractelement <4 x i8> %5, i32 2
243 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
244 /// %9 = extractelement <4 x i8> %5, i32 3
245 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
246 /// ret <4 x i8> %ins4
247 /// InstCombiner transforms this into a shuffle and vector mul
248 static Optional<TargetTransformInfo::ShuffleKind>
249 isShuffle(ArrayRef<Value *> VL) {
250   auto *EI0 = cast<ExtractElementInst>(VL[0]);
251   unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
252   Value *Vec1 = nullptr;
253   Value *Vec2 = nullptr;
254   enum ShuffleMode {Unknown, FirstAlternate, SecondAlternate, Permute};
255   ShuffleMode CommonShuffleMode = Unknown;
256   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
257     auto *EI = cast<ExtractElementInst>(VL[I]);
258     auto *Vec = EI->getVectorOperand();
259     // All vector operands must have the same number of vector elements.
260     if (Vec->getType()->getVectorNumElements() != Size)
261       return None;
262     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
263     if (!Idx)
264       return None;
265     // Undefined behavior if Idx is negative or >= Size.
266     if (Idx->getValue().uge(Size))
267       continue;
268     unsigned IntIdx = Idx->getValue().getZExtValue();
269     // We can extractelement from undef vector.
270     if (isa<UndefValue>(Vec))
271       continue;
272     // For correct shuffling we have to have at most 2 different vector operands
273     // in all extractelement instructions.
274     if (Vec1 && Vec2 && Vec != Vec1 && Vec != Vec2)
275       return None;
276     if (CommonShuffleMode == Permute)
277       continue;
278     // If the extract index is not the same as the operation number, it is a
279     // permutation.
280     if (IntIdx != I) {
281       CommonShuffleMode = Permute;
282       continue;
283     }
284     // Check the shuffle mode for the current operation.
285     if (!Vec1)
286       Vec1 = Vec;
287     else if (Vec != Vec1)
288       Vec2 = Vec;
289     // Example: shufflevector A, B, <0,5,2,7>
290     // I is odd and IntIdx for A == I - FirstAlternate shuffle.
291     // I is even and IntIdx for B == I - FirstAlternate shuffle.
292     // Example: shufflevector A, B, <4,1,6,3>
293     // I is even and IntIdx for A == I - SecondAlternate shuffle.
294     // I is odd and IntIdx for B == I - SecondAlternate shuffle.
295     const bool IIsEven = I & 1;
296     const bool CurrVecIsA = Vec == Vec1;
297     const bool IIsOdd = !IIsEven;
298     const bool CurrVecIsB = !CurrVecIsA;
299     ShuffleMode CurrentShuffleMode =
300         ((IIsOdd && CurrVecIsA) || (IIsEven && CurrVecIsB)) ? FirstAlternate
301                                                             : SecondAlternate;
302     // Common mode is not set or the same as the shuffle mode of the current
303     // operation - alternate.
304     if (CommonShuffleMode == Unknown)
305       CommonShuffleMode = CurrentShuffleMode;
306     // Common shuffle mode is not the same as the shuffle mode of the current
307     // operation - permutation.
308     if (CommonShuffleMode != CurrentShuffleMode)
309       CommonShuffleMode = Permute;
310   }
311   // If we're not crossing lanes in different vectors, consider it as blending.
312   if ((CommonShuffleMode == FirstAlternate ||
313        CommonShuffleMode == SecondAlternate) &&
314       Vec2)
315     return TargetTransformInfo::SK_Alternate;
316   // If Vec2 was never used, we have a permutation of a single vector, otherwise
317   // we have permutation of 2 vectors.
318   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
319               : TargetTransformInfo::SK_PermuteSingleSrc;
320 }
321 
322 ///\returns Opcode that can be clubbed with \p Op to create an alternate
323 /// sequence which can later be merged as a ShuffleVector instruction.
324 static unsigned getAltOpcode(unsigned Op) {
325   switch (Op) {
326   case Instruction::FAdd:
327     return Instruction::FSub;
328   case Instruction::FSub:
329     return Instruction::FAdd;
330   case Instruction::Add:
331     return Instruction::Sub;
332   case Instruction::Sub:
333     return Instruction::Add;
334   default:
335     return 0;
336   }
337 }
338 
339 static bool isOdd(unsigned Value) {
340   return Value & 1;
341 }
342 
343 static bool sameOpcodeOrAlt(unsigned Opcode, unsigned AltOpcode,
344                             unsigned CheckedOpcode) {
345   return Opcode == CheckedOpcode || AltOpcode == CheckedOpcode;
346 }
347 
348 /// Chooses the correct key for scheduling data. If \p Op has the same (or
349 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
350 /// OpValue.
351 static Value *isOneOf(Value *OpValue, Value *Op) {
352   auto *I = dyn_cast<Instruction>(Op);
353   if (!I)
354     return OpValue;
355   auto *OpInst = cast<Instruction>(OpValue);
356   unsigned OpInstOpcode = OpInst->getOpcode();
357   unsigned IOpcode = I->getOpcode();
358   if (sameOpcodeOrAlt(OpInstOpcode, getAltOpcode(OpInstOpcode), IOpcode))
359     return Op;
360   return OpValue;
361 }
362 
363 namespace {
364 /// Contains data for the instructions going to be vectorized.
365 struct RawInstructionsData {
366   /// Main Opcode of the instructions going to be vectorized.
367   unsigned Opcode = 0;
368   /// The list of instructions have some instructions with alternate opcodes.
369   bool HasAltOpcodes = false;
370 };
371 } // namespace
372 
373 /// Checks the list of the vectorized instructions \p VL and returns info about
374 /// this list.
375 static RawInstructionsData getMainOpcode(ArrayRef<Value *> VL) {
376   auto *I0 = dyn_cast<Instruction>(VL[0]);
377   if (!I0)
378     return {};
379   RawInstructionsData Res;
380   unsigned Opcode = I0->getOpcode();
381   // Walk through the list of the vectorized instructions
382   // in order to check its structure described by RawInstructionsData.
383   for (unsigned Cnt = 0, E = VL.size(); Cnt != E; ++Cnt) {
384     auto *I = dyn_cast<Instruction>(VL[Cnt]);
385     if (!I)
386       return {};
387     if (Opcode != I->getOpcode())
388       Res.HasAltOpcodes = true;
389   }
390   Res.Opcode = Opcode;
391   return Res;
392 }
393 
394 namespace {
395 /// Main data required for vectorization of instructions.
396 struct InstructionsState {
397   /// The very first instruction in the list with the main opcode.
398   Value *OpValue = nullptr;
399   /// The main opcode for the list of instructions.
400   unsigned Opcode = 0;
401   /// Some of the instructions in the list have alternate opcodes.
402   bool IsAltShuffle = false;
403   InstructionsState() = default;
404   InstructionsState(Value *OpValue, unsigned Opcode, bool IsAltShuffle)
405       : OpValue(OpValue), Opcode(Opcode), IsAltShuffle(IsAltShuffle) {}
406 };
407 } // namespace
408 
409 /// \returns analysis of the Instructions in \p VL described in
410 /// InstructionsState, the Opcode that we suppose the whole list
411 /// could be vectorized even if its structure is diverse.
412 static InstructionsState getSameOpcode(ArrayRef<Value *> VL) {
413   auto Res = getMainOpcode(VL);
414   unsigned Opcode = Res.Opcode;
415   if (!Res.HasAltOpcodes)
416     return InstructionsState(VL[0], Opcode, false);
417   auto *OpInst = cast<Instruction>(VL[0]);
418   unsigned AltOpcode = getAltOpcode(Opcode);
419   // Examine each element in the list instructions VL to determine
420   // if some operations there could be considered as an alternative
421   // (for example as subtraction relates to addition operation).
422   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
423     auto *I = cast<Instruction>(VL[Cnt]);
424     unsigned InstOpcode = I->getOpcode();
425     if ((Res.HasAltOpcodes &&
426          InstOpcode != (isOdd(Cnt) ? AltOpcode : Opcode)) ||
427         (!Res.HasAltOpcodes && InstOpcode != Opcode)) {
428       return InstructionsState(OpInst, 0, false);
429     }
430   }
431   return InstructionsState(OpInst, Opcode, Res.HasAltOpcodes);
432 }
433 
434 /// \returns true if all of the values in \p VL have the same type or false
435 /// otherwise.
436 static bool allSameType(ArrayRef<Value *> VL) {
437   Type *Ty = VL[0]->getType();
438   for (int i = 1, e = VL.size(); i < e; i++)
439     if (VL[i]->getType() != Ty)
440       return false;
441 
442   return true;
443 }
444 
445 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
446 static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode) {
447   assert(Opcode == Instruction::ExtractElement ||
448          Opcode == Instruction::ExtractValue);
449   if (Opcode == Instruction::ExtractElement) {
450     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
451     return CI && CI->getZExtValue() == Idx;
452   } else {
453     ExtractValueInst *EI = cast<ExtractValueInst>(E);
454     return EI->getNumIndices() == 1 && *EI->idx_begin() == Idx;
455   }
456 }
457 
458 /// \returns True if in-tree use also needs extract. This refers to
459 /// possible scalar operand in vectorized instruction.
460 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
461                                     TargetLibraryInfo *TLI) {
462   unsigned Opcode = UserInst->getOpcode();
463   switch (Opcode) {
464   case Instruction::Load: {
465     LoadInst *LI = cast<LoadInst>(UserInst);
466     return (LI->getPointerOperand() == Scalar);
467   }
468   case Instruction::Store: {
469     StoreInst *SI = cast<StoreInst>(UserInst);
470     return (SI->getPointerOperand() == Scalar);
471   }
472   case Instruction::Call: {
473     CallInst *CI = cast<CallInst>(UserInst);
474     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
475     if (hasVectorInstrinsicScalarOpd(ID, 1)) {
476       return (CI->getArgOperand(1) == Scalar);
477     }
478     LLVM_FALLTHROUGH;
479   }
480   default:
481     return false;
482   }
483 }
484 
485 /// \returns the AA location that is being access by the instruction.
486 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
487   if (StoreInst *SI = dyn_cast<StoreInst>(I))
488     return MemoryLocation::get(SI);
489   if (LoadInst *LI = dyn_cast<LoadInst>(I))
490     return MemoryLocation::get(LI);
491   return MemoryLocation();
492 }
493 
494 /// \returns True if the instruction is not a volatile or atomic load/store.
495 static bool isSimple(Instruction *I) {
496   if (LoadInst *LI = dyn_cast<LoadInst>(I))
497     return LI->isSimple();
498   if (StoreInst *SI = dyn_cast<StoreInst>(I))
499     return SI->isSimple();
500   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
501     return !MI->isVolatile();
502   return true;
503 }
504 
505 namespace llvm {
506 
507 namespace slpvectorizer {
508 
509 /// Bottom Up SLP Vectorizer.
510 class BoUpSLP {
511 public:
512   using ValueList = SmallVector<Value *, 8>;
513   using InstrList = SmallVector<Instruction *, 16>;
514   using ValueSet = SmallPtrSet<Value *, 16>;
515   using StoreList = SmallVector<StoreInst *, 8>;
516   using ExtraValueToDebugLocsMap =
517       MapVector<Value *, SmallVector<Instruction *, 2>>;
518 
519   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
520           TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
521           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
522           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
523       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
524         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
525     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
526     // Use the vector register size specified by the target unless overridden
527     // by a command-line option.
528     // TODO: It would be better to limit the vectorization factor based on
529     //       data type rather than just register size. For example, x86 AVX has
530     //       256-bit registers, but it does not support integer operations
531     //       at that width (that requires AVX2).
532     if (MaxVectorRegSizeOption.getNumOccurrences())
533       MaxVecRegSize = MaxVectorRegSizeOption;
534     else
535       MaxVecRegSize = TTI->getRegisterBitWidth(true);
536 
537     if (MinVectorRegSizeOption.getNumOccurrences())
538       MinVecRegSize = MinVectorRegSizeOption;
539     else
540       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
541   }
542 
543   /// \brief Vectorize the tree that starts with the elements in \p VL.
544   /// Returns the vectorized root.
545   Value *vectorizeTree();
546 
547   /// Vectorize the tree but with the list of externally used values \p
548   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
549   /// generated extractvalue instructions.
550   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
551 
552   /// \returns the cost incurred by unwanted spills and fills, caused by
553   /// holding live values over call sites.
554   int getSpillCost();
555 
556   /// \returns the vectorization cost of the subtree that starts at \p VL.
557   /// A negative number means that this is profitable.
558   int getTreeCost();
559 
560   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
561   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
562   void buildTree(ArrayRef<Value *> Roots,
563                  ArrayRef<Value *> UserIgnoreLst = None);
564 
565   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
566   /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
567   /// into account (anf updating it, if required) list of externally used
568   /// values stored in \p ExternallyUsedValues.
569   void buildTree(ArrayRef<Value *> Roots,
570                  ExtraValueToDebugLocsMap &ExternallyUsedValues,
571                  ArrayRef<Value *> UserIgnoreLst = None);
572 
573   /// Clear the internal data structures that are created by 'buildTree'.
574   void deleteTree() {
575     VectorizableTree.clear();
576     ScalarToTreeEntry.clear();
577     MustGather.clear();
578     ExternalUses.clear();
579     NumLoadsWantToKeepOrder = 0;
580     NumLoadsWantToChangeOrder = 0;
581     for (auto &Iter : BlocksSchedules) {
582       BlockScheduling *BS = Iter.second.get();
583       BS->clear();
584     }
585     MinBWs.clear();
586   }
587 
588   unsigned getTreeSize() const { return VectorizableTree.size(); }
589 
590   /// \brief Perform LICM and CSE on the newly generated gather sequences.
591   void optimizeGatherSequence();
592 
593   /// \returns true if it is beneficial to reverse the vector order.
594   bool shouldReorder() const {
595     return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
596   }
597 
598   /// \return The vector element size in bits to use when vectorizing the
599   /// expression tree ending at \p V. If V is a store, the size is the width of
600   /// the stored value. Otherwise, the size is the width of the largest loaded
601   /// value reaching V. This method is used by the vectorizer to calculate
602   /// vectorization factors.
603   unsigned getVectorElementSize(Value *V);
604 
605   /// Compute the minimum type sizes required to represent the entries in a
606   /// vectorizable tree.
607   void computeMinimumValueSizes();
608 
609   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
610   unsigned getMaxVecRegSize() const {
611     return MaxVecRegSize;
612   }
613 
614   // \returns minimum vector register size as set by cl::opt.
615   unsigned getMinVecRegSize() const {
616     return MinVecRegSize;
617   }
618 
619   /// \brief Check if ArrayType or StructType is isomorphic to some VectorType.
620   ///
621   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
622   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
623 
624   /// \returns True if the VectorizableTree is both tiny and not fully
625   /// vectorizable. We do not vectorize such trees.
626   bool isTreeTinyAndNotFullyVectorizable();
627 
628   OptimizationRemarkEmitter *getORE() { return ORE; }
629 
630 private:
631   struct TreeEntry;
632 
633   /// Checks if all users of \p I are the part of the vectorization tree.
634   bool areAllUsersVectorized(Instruction *I) const;
635 
636   /// \returns the cost of the vectorizable entry.
637   int getEntryCost(TreeEntry *E);
638 
639   /// This is the recursive part of buildTree.
640   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, int);
641 
642   /// \returns True if the ExtractElement/ExtractValue instructions in VL can
643   /// be vectorized to use the original vector (or aggregate "bitcast" to a vector).
644   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue) const;
645 
646   /// Vectorize a single entry in the tree.
647   Value *vectorizeTree(TreeEntry *E);
648 
649   /// Vectorize a single entry in the tree, starting in \p VL.
650   Value *vectorizeTree(ArrayRef<Value *> VL);
651 
652   /// \returns the pointer to the vectorized value if \p VL is already
653   /// vectorized, or NULL. They may happen in cycles.
654   Value *alreadyVectorized(ArrayRef<Value *> VL, Value *OpValue) const;
655 
656   /// \returns the scalarization cost for this type. Scalarization in this
657   /// context means the creation of vectors from a group of scalars.
658   int getGatherCost(Type *Ty);
659 
660   /// \returns the scalarization cost for this list of values. Assuming that
661   /// this subtree gets vectorized, we may need to extract the values from the
662   /// roots. This method calculates the cost of extracting the values.
663   int getGatherCost(ArrayRef<Value *> VL);
664 
665   /// \brief Set the Builder insert point to one after the last instruction in
666   /// the bundle
667   void setInsertPointAfterBundle(ArrayRef<Value *> VL, Value *OpValue);
668 
669   /// \returns a vector from a collection of scalars in \p VL.
670   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
671 
672   /// \returns whether the VectorizableTree is fully vectorizable and will
673   /// be beneficial even the tree height is tiny.
674   bool isFullyVectorizableTinyTree();
675 
676   /// \reorder commutative operands in alt shuffle if they result in
677   ///  vectorized code.
678   void reorderAltShuffleOperands(unsigned Opcode, ArrayRef<Value *> VL,
679                                  SmallVectorImpl<Value *> &Left,
680                                  SmallVectorImpl<Value *> &Right);
681 
682   /// \reorder commutative operands to get better probability of
683   /// generating vectorized code.
684   void reorderInputsAccordingToOpcode(unsigned Opcode, ArrayRef<Value *> VL,
685                                       SmallVectorImpl<Value *> &Left,
686                                       SmallVectorImpl<Value *> &Right);
687   struct TreeEntry {
688     TreeEntry(std::vector<TreeEntry> &Container) : Container(Container) {}
689 
690     /// \returns true if the scalars in VL are equal to this entry.
691     bool isSame(ArrayRef<Value *> VL) const {
692       assert(VL.size() == Scalars.size() && "Invalid size");
693       return std::equal(VL.begin(), VL.end(), Scalars.begin());
694     }
695 
696     /// A vector of scalars.
697     ValueList Scalars;
698 
699     /// The Scalars are vectorized into this value. It is initialized to Null.
700     Value *VectorizedValue = nullptr;
701 
702     /// Do we need to gather this sequence ?
703     bool NeedToGather = false;
704 
705     /// Points back to the VectorizableTree.
706     ///
707     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
708     /// to be a pointer and needs to be able to initialize the child iterator.
709     /// Thus we need a reference back to the container to translate the indices
710     /// to entries.
711     std::vector<TreeEntry> &Container;
712 
713     /// The TreeEntry index containing the user of this entry.  We can actually
714     /// have multiple users so the data structure is not truly a tree.
715     SmallVector<int, 1> UserTreeIndices;
716   };
717 
718   /// Create a new VectorizableTree entry.
719   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized,
720                           int &UserTreeIdx) {
721     VectorizableTree.emplace_back(VectorizableTree);
722     int idx = VectorizableTree.size() - 1;
723     TreeEntry *Last = &VectorizableTree[idx];
724     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
725     Last->NeedToGather = !Vectorized;
726     if (Vectorized) {
727       for (int i = 0, e = VL.size(); i != e; ++i) {
728         assert(!getTreeEntry(VL[i]) && "Scalar already in tree!");
729         ScalarToTreeEntry[VL[i]] = idx;
730       }
731     } else {
732       MustGather.insert(VL.begin(), VL.end());
733     }
734 
735     if (UserTreeIdx >= 0)
736       Last->UserTreeIndices.push_back(UserTreeIdx);
737     UserTreeIdx = idx;
738     return Last;
739   }
740 
741   /// -- Vectorization State --
742   /// Holds all of the tree entries.
743   std::vector<TreeEntry> VectorizableTree;
744 
745   TreeEntry *getTreeEntry(Value *V) {
746     auto I = ScalarToTreeEntry.find(V);
747     if (I != ScalarToTreeEntry.end())
748       return &VectorizableTree[I->second];
749     return nullptr;
750   }
751 
752   const TreeEntry *getTreeEntry(Value *V) const {
753     auto I = ScalarToTreeEntry.find(V);
754     if (I != ScalarToTreeEntry.end())
755       return &VectorizableTree[I->second];
756     return nullptr;
757   }
758 
759   /// Maps a specific scalar to its tree entry.
760   SmallDenseMap<Value*, int> ScalarToTreeEntry;
761 
762   /// A list of scalars that we found that we need to keep as scalars.
763   ValueSet MustGather;
764 
765   /// This POD struct describes one external user in the vectorized tree.
766   struct ExternalUser {
767     ExternalUser(Value *S, llvm::User *U, int L)
768         : Scalar(S), User(U), Lane(L) {}
769 
770     // Which scalar in our function.
771     Value *Scalar;
772 
773     // Which user that uses the scalar.
774     llvm::User *User;
775 
776     // Which lane does the scalar belong to.
777     int Lane;
778   };
779   using UserList = SmallVector<ExternalUser, 16>;
780 
781   /// Checks if two instructions may access the same memory.
782   ///
783   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
784   /// is invariant in the calling loop.
785   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
786                  Instruction *Inst2) {
787     // First check if the result is already in the cache.
788     AliasCacheKey key = std::make_pair(Inst1, Inst2);
789     Optional<bool> &result = AliasCache[key];
790     if (result.hasValue()) {
791       return result.getValue();
792     }
793     MemoryLocation Loc2 = getLocation(Inst2, AA);
794     bool aliased = true;
795     if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
796       // Do the alias check.
797       aliased = AA->alias(Loc1, Loc2);
798     }
799     // Store the result in the cache.
800     result = aliased;
801     return aliased;
802   }
803 
804   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
805 
806   /// Cache for alias results.
807   /// TODO: consider moving this to the AliasAnalysis itself.
808   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
809 
810   /// Removes an instruction from its block and eventually deletes it.
811   /// It's like Instruction::eraseFromParent() except that the actual deletion
812   /// is delayed until BoUpSLP is destructed.
813   /// This is required to ensure that there are no incorrect collisions in the
814   /// AliasCache, which can happen if a new instruction is allocated at the
815   /// same address as a previously deleted instruction.
816   void eraseInstruction(Instruction *I) {
817     I->removeFromParent();
818     I->dropAllReferences();
819     DeletedInstructions.emplace_back(I);
820   }
821 
822   /// Temporary store for deleted instructions. Instructions will be deleted
823   /// eventually when the BoUpSLP is destructed.
824   SmallVector<unique_value, 8> DeletedInstructions;
825 
826   /// A list of values that need to extracted out of the tree.
827   /// This list holds pairs of (Internal Scalar : External User). External User
828   /// can be nullptr, it means that this Internal Scalar will be used later,
829   /// after vectorization.
830   UserList ExternalUses;
831 
832   /// Values used only by @llvm.assume calls.
833   SmallPtrSet<const Value *, 32> EphValues;
834 
835   /// Holds all of the instructions that we gathered.
836   SetVector<Instruction *> GatherSeq;
837 
838   /// A list of blocks that we are going to CSE.
839   SetVector<BasicBlock *> CSEBlocks;
840 
841   /// Contains all scheduling relevant data for an instruction.
842   /// A ScheduleData either represents a single instruction or a member of an
843   /// instruction bundle (= a group of instructions which is combined into a
844   /// vector instruction).
845   struct ScheduleData {
846     // The initial value for the dependency counters. It means that the
847     // dependencies are not calculated yet.
848     enum { InvalidDeps = -1 };
849 
850     ScheduleData() = default;
851 
852     void init(int BlockSchedulingRegionID, Value *OpVal) {
853       FirstInBundle = this;
854       NextInBundle = nullptr;
855       NextLoadStore = nullptr;
856       IsScheduled = false;
857       SchedulingRegionID = BlockSchedulingRegionID;
858       UnscheduledDepsInBundle = UnscheduledDeps;
859       clearDependencies();
860       OpValue = OpVal;
861     }
862 
863     /// Returns true if the dependency information has been calculated.
864     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
865 
866     /// Returns true for single instructions and for bundle representatives
867     /// (= the head of a bundle).
868     bool isSchedulingEntity() const { return FirstInBundle == this; }
869 
870     /// Returns true if it represents an instruction bundle and not only a
871     /// single instruction.
872     bool isPartOfBundle() const {
873       return NextInBundle != nullptr || FirstInBundle != this;
874     }
875 
876     /// Returns true if it is ready for scheduling, i.e. it has no more
877     /// unscheduled depending instructions/bundles.
878     bool isReady() const {
879       assert(isSchedulingEntity() &&
880              "can't consider non-scheduling entity for ready list");
881       return UnscheduledDepsInBundle == 0 && !IsScheduled;
882     }
883 
884     /// Modifies the number of unscheduled dependencies, also updating it for
885     /// the whole bundle.
886     int incrementUnscheduledDeps(int Incr) {
887       UnscheduledDeps += Incr;
888       return FirstInBundle->UnscheduledDepsInBundle += Incr;
889     }
890 
891     /// Sets the number of unscheduled dependencies to the number of
892     /// dependencies.
893     void resetUnscheduledDeps() {
894       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
895     }
896 
897     /// Clears all dependency information.
898     void clearDependencies() {
899       Dependencies = InvalidDeps;
900       resetUnscheduledDeps();
901       MemoryDependencies.clear();
902     }
903 
904     void dump(raw_ostream &os) const {
905       if (!isSchedulingEntity()) {
906         os << "/ " << *Inst;
907       } else if (NextInBundle) {
908         os << '[' << *Inst;
909         ScheduleData *SD = NextInBundle;
910         while (SD) {
911           os << ';' << *SD->Inst;
912           SD = SD->NextInBundle;
913         }
914         os << ']';
915       } else {
916         os << *Inst;
917       }
918     }
919 
920     Instruction *Inst = nullptr;
921 
922     /// Points to the head in an instruction bundle (and always to this for
923     /// single instructions).
924     ScheduleData *FirstInBundle = nullptr;
925 
926     /// Single linked list of all instructions in a bundle. Null if it is a
927     /// single instruction.
928     ScheduleData *NextInBundle = nullptr;
929 
930     /// Single linked list of all memory instructions (e.g. load, store, call)
931     /// in the block - until the end of the scheduling region.
932     ScheduleData *NextLoadStore = nullptr;
933 
934     /// The dependent memory instructions.
935     /// This list is derived on demand in calculateDependencies().
936     SmallVector<ScheduleData *, 4> MemoryDependencies;
937 
938     /// This ScheduleData is in the current scheduling region if this matches
939     /// the current SchedulingRegionID of BlockScheduling.
940     int SchedulingRegionID = 0;
941 
942     /// Used for getting a "good" final ordering of instructions.
943     int SchedulingPriority = 0;
944 
945     /// The number of dependencies. Constitutes of the number of users of the
946     /// instruction plus the number of dependent memory instructions (if any).
947     /// This value is calculated on demand.
948     /// If InvalidDeps, the number of dependencies is not calculated yet.
949     int Dependencies = InvalidDeps;
950 
951     /// The number of dependencies minus the number of dependencies of scheduled
952     /// instructions. As soon as this is zero, the instruction/bundle gets ready
953     /// for scheduling.
954     /// Note that this is negative as long as Dependencies is not calculated.
955     int UnscheduledDeps = InvalidDeps;
956 
957     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
958     /// single instructions.
959     int UnscheduledDepsInBundle = InvalidDeps;
960 
961     /// True if this instruction is scheduled (or considered as scheduled in the
962     /// dry-run).
963     bool IsScheduled = false;
964 
965     /// Opcode of the current instruction in the schedule data.
966     Value *OpValue = nullptr;
967   };
968 
969 #ifndef NDEBUG
970   friend inline raw_ostream &operator<<(raw_ostream &os,
971                                         const BoUpSLP::ScheduleData &SD) {
972     SD.dump(os);
973     return os;
974   }
975 #endif
976   friend struct GraphTraits<BoUpSLP *>;
977   friend struct DOTGraphTraits<BoUpSLP *>;
978 
979   /// Contains all scheduling data for a basic block.
980   struct BlockScheduling {
981     BlockScheduling(BasicBlock *BB)
982         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
983 
984     void clear() {
985       ReadyInsts.clear();
986       ScheduleStart = nullptr;
987       ScheduleEnd = nullptr;
988       FirstLoadStoreInRegion = nullptr;
989       LastLoadStoreInRegion = nullptr;
990 
991       // Reduce the maximum schedule region size by the size of the
992       // previous scheduling run.
993       ScheduleRegionSizeLimit -= ScheduleRegionSize;
994       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
995         ScheduleRegionSizeLimit = MinScheduleRegionSize;
996       ScheduleRegionSize = 0;
997 
998       // Make a new scheduling region, i.e. all existing ScheduleData is not
999       // in the new region yet.
1000       ++SchedulingRegionID;
1001     }
1002 
1003     ScheduleData *getScheduleData(Value *V) {
1004       ScheduleData *SD = ScheduleDataMap[V];
1005       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1006         return SD;
1007       return nullptr;
1008     }
1009 
1010     ScheduleData *getScheduleData(Value *V, Value *Key) {
1011       if (V == Key)
1012         return getScheduleData(V);
1013       auto I = ExtraScheduleDataMap.find(V);
1014       if (I != ExtraScheduleDataMap.end()) {
1015         ScheduleData *SD = I->second[Key];
1016         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1017           return SD;
1018       }
1019       return nullptr;
1020     }
1021 
1022     bool isInSchedulingRegion(ScheduleData *SD) {
1023       return SD->SchedulingRegionID == SchedulingRegionID;
1024     }
1025 
1026     /// Marks an instruction as scheduled and puts all dependent ready
1027     /// instructions into the ready-list.
1028     template <typename ReadyListType>
1029     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
1030       SD->IsScheduled = true;
1031       DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
1032 
1033       ScheduleData *BundleMember = SD;
1034       while (BundleMember) {
1035         if (BundleMember->Inst != BundleMember->OpValue) {
1036           BundleMember = BundleMember->NextInBundle;
1037           continue;
1038         }
1039         // Handle the def-use chain dependencies.
1040         for (Use &U : BundleMember->Inst->operands()) {
1041           auto *I = dyn_cast<Instruction>(U.get());
1042           if (!I)
1043             continue;
1044           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
1045             if (OpDef && OpDef->hasValidDependencies() &&
1046                 OpDef->incrementUnscheduledDeps(-1) == 0) {
1047               // There are no more unscheduled dependencies after
1048               // decrementing, so we can put the dependent instruction
1049               // into the ready list.
1050               ScheduleData *DepBundle = OpDef->FirstInBundle;
1051               assert(!DepBundle->IsScheduled &&
1052                      "already scheduled bundle gets ready");
1053               ReadyList.insert(DepBundle);
1054               DEBUG(dbgs()
1055                     << "SLP:    gets ready (def): " << *DepBundle << "\n");
1056             }
1057           });
1058         }
1059         // Handle the memory dependencies.
1060         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
1061           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
1062             // There are no more unscheduled dependencies after decrementing,
1063             // so we can put the dependent instruction into the ready list.
1064             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
1065             assert(!DepBundle->IsScheduled &&
1066                    "already scheduled bundle gets ready");
1067             ReadyList.insert(DepBundle);
1068             DEBUG(dbgs() << "SLP:    gets ready (mem): " << *DepBundle
1069                          << "\n");
1070           }
1071         }
1072         BundleMember = BundleMember->NextInBundle;
1073       }
1074     }
1075 
1076     void doForAllOpcodes(Value *V,
1077                          function_ref<void(ScheduleData *SD)> Action) {
1078       if (ScheduleData *SD = getScheduleData(V))
1079         Action(SD);
1080       auto I = ExtraScheduleDataMap.find(V);
1081       if (I != ExtraScheduleDataMap.end())
1082         for (auto &P : I->second)
1083           if (P.second->SchedulingRegionID == SchedulingRegionID)
1084             Action(P.second);
1085     }
1086 
1087     /// Put all instructions into the ReadyList which are ready for scheduling.
1088     template <typename ReadyListType>
1089     void initialFillReadyList(ReadyListType &ReadyList) {
1090       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
1091         doForAllOpcodes(I, [&](ScheduleData *SD) {
1092           if (SD->isSchedulingEntity() && SD->isReady()) {
1093             ReadyList.insert(SD);
1094             DEBUG(dbgs() << "SLP:    initially in ready list: " << *I << "\n");
1095           }
1096         });
1097       }
1098     }
1099 
1100     /// Checks if a bundle of instructions can be scheduled, i.e. has no
1101     /// cyclic dependencies. This is only a dry-run, no instructions are
1102     /// actually moved at this stage.
1103     bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, Value *OpValue);
1104 
1105     /// Un-bundles a group of instructions.
1106     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
1107 
1108     /// Allocates schedule data chunk.
1109     ScheduleData *allocateScheduleDataChunks();
1110 
1111     /// Extends the scheduling region so that V is inside the region.
1112     /// \returns true if the region size is within the limit.
1113     bool extendSchedulingRegion(Value *V, Value *OpValue);
1114 
1115     /// Initialize the ScheduleData structures for new instructions in the
1116     /// scheduling region.
1117     void initScheduleData(Instruction *FromI, Instruction *ToI,
1118                           ScheduleData *PrevLoadStore,
1119                           ScheduleData *NextLoadStore);
1120 
1121     /// Updates the dependency information of a bundle and of all instructions/
1122     /// bundles which depend on the original bundle.
1123     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
1124                                BoUpSLP *SLP);
1125 
1126     /// Sets all instruction in the scheduling region to un-scheduled.
1127     void resetSchedule();
1128 
1129     BasicBlock *BB;
1130 
1131     /// Simple memory allocation for ScheduleData.
1132     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
1133 
1134     /// The size of a ScheduleData array in ScheduleDataChunks.
1135     int ChunkSize;
1136 
1137     /// The allocator position in the current chunk, which is the last entry
1138     /// of ScheduleDataChunks.
1139     int ChunkPos;
1140 
1141     /// Attaches ScheduleData to Instruction.
1142     /// Note that the mapping survives during all vectorization iterations, i.e.
1143     /// ScheduleData structures are recycled.
1144     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
1145 
1146     /// Attaches ScheduleData to Instruction with the leading key.
1147     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
1148         ExtraScheduleDataMap;
1149 
1150     struct ReadyList : SmallVector<ScheduleData *, 8> {
1151       void insert(ScheduleData *SD) { push_back(SD); }
1152     };
1153 
1154     /// The ready-list for scheduling (only used for the dry-run).
1155     ReadyList ReadyInsts;
1156 
1157     /// The first instruction of the scheduling region.
1158     Instruction *ScheduleStart = nullptr;
1159 
1160     /// The first instruction _after_ the scheduling region.
1161     Instruction *ScheduleEnd = nullptr;
1162 
1163     /// The first memory accessing instruction in the scheduling region
1164     /// (can be null).
1165     ScheduleData *FirstLoadStoreInRegion = nullptr;
1166 
1167     /// The last memory accessing instruction in the scheduling region
1168     /// (can be null).
1169     ScheduleData *LastLoadStoreInRegion = nullptr;
1170 
1171     /// The current size of the scheduling region.
1172     int ScheduleRegionSize = 0;
1173 
1174     /// The maximum size allowed for the scheduling region.
1175     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
1176 
1177     /// The ID of the scheduling region. For a new vectorization iteration this
1178     /// is incremented which "removes" all ScheduleData from the region.
1179     int SchedulingRegionID = 1;
1180     // Make sure that the initial SchedulingRegionID is greater than the
1181     // initial SchedulingRegionID in ScheduleData (which is 0).
1182   };
1183 
1184   /// Attaches the BlockScheduling structures to basic blocks.
1185   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
1186 
1187   /// Performs the "real" scheduling. Done before vectorization is actually
1188   /// performed in a basic block.
1189   void scheduleBlock(BlockScheduling *BS);
1190 
1191   /// List of users to ignore during scheduling and that don't need extracting.
1192   ArrayRef<Value *> UserIgnoreList;
1193 
1194   // Number of load bundles that contain consecutive loads.
1195   int NumLoadsWantToKeepOrder = 0;
1196 
1197   // Number of load bundles that contain consecutive loads in reversed order.
1198   int NumLoadsWantToChangeOrder = 0;
1199 
1200   // Analysis and block reference.
1201   Function *F;
1202   ScalarEvolution *SE;
1203   TargetTransformInfo *TTI;
1204   TargetLibraryInfo *TLI;
1205   AliasAnalysis *AA;
1206   LoopInfo *LI;
1207   DominatorTree *DT;
1208   AssumptionCache *AC;
1209   DemandedBits *DB;
1210   const DataLayout *DL;
1211   OptimizationRemarkEmitter *ORE;
1212 
1213   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
1214   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
1215   /// Instruction builder to construct the vectorized tree.
1216   IRBuilder<> Builder;
1217 
1218   /// A map of scalar integer values to the smallest bit width with which they
1219   /// can legally be represented. The values map to (width, signed) pairs,
1220   /// where "width" indicates the minimum bit width and "signed" is True if the
1221   /// value must be signed-extended, rather than zero-extended, back to its
1222   /// original width.
1223   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
1224 };
1225 
1226 } // end namespace slpvectorizer
1227 
1228 template <> struct GraphTraits<BoUpSLP *> {
1229   using TreeEntry = BoUpSLP::TreeEntry;
1230 
1231   /// NodeRef has to be a pointer per the GraphWriter.
1232   using NodeRef = TreeEntry *;
1233 
1234   /// \brief Add the VectorizableTree to the index iterator to be able to return
1235   /// TreeEntry pointers.
1236   struct ChildIteratorType
1237       : public iterator_adaptor_base<ChildIteratorType,
1238                                      SmallVector<int, 1>::iterator> {
1239     std::vector<TreeEntry> &VectorizableTree;
1240 
1241     ChildIteratorType(SmallVector<int, 1>::iterator W,
1242                       std::vector<TreeEntry> &VT)
1243         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
1244 
1245     NodeRef operator*() { return &VectorizableTree[*I]; }
1246   };
1247 
1248   static NodeRef getEntryNode(BoUpSLP &R) { return &R.VectorizableTree[0]; }
1249 
1250   static ChildIteratorType child_begin(NodeRef N) {
1251     return {N->UserTreeIndices.begin(), N->Container};
1252   }
1253 
1254   static ChildIteratorType child_end(NodeRef N) {
1255     return {N->UserTreeIndices.end(), N->Container};
1256   }
1257 
1258   /// For the node iterator we just need to turn the TreeEntry iterator into a
1259   /// TreeEntry* iterator so that it dereferences to NodeRef.
1260   using nodes_iterator = pointer_iterator<std::vector<TreeEntry>::iterator>;
1261 
1262   static nodes_iterator nodes_begin(BoUpSLP *R) {
1263     return nodes_iterator(R->VectorizableTree.begin());
1264   }
1265 
1266   static nodes_iterator nodes_end(BoUpSLP *R) {
1267     return nodes_iterator(R->VectorizableTree.end());
1268   }
1269 
1270   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
1271 };
1272 
1273 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
1274   using TreeEntry = BoUpSLP::TreeEntry;
1275 
1276   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
1277 
1278   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
1279     std::string Str;
1280     raw_string_ostream OS(Str);
1281     if (isSplat(Entry->Scalars)) {
1282       OS << "<splat> " << *Entry->Scalars[0];
1283       return Str;
1284     }
1285     for (auto V : Entry->Scalars) {
1286       OS << *V;
1287       if (std::any_of(
1288               R->ExternalUses.begin(), R->ExternalUses.end(),
1289               [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
1290         OS << " <extract>";
1291       OS << "\n";
1292     }
1293     return Str;
1294   }
1295 
1296   static std::string getNodeAttributes(const TreeEntry *Entry,
1297                                        const BoUpSLP *) {
1298     if (Entry->NeedToGather)
1299       return "color=red";
1300     return "";
1301   }
1302 };
1303 
1304 } // end namespace llvm
1305 
1306 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1307                         ArrayRef<Value *> UserIgnoreLst) {
1308   ExtraValueToDebugLocsMap ExternallyUsedValues;
1309   buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
1310 }
1311 
1312 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1313                         ExtraValueToDebugLocsMap &ExternallyUsedValues,
1314                         ArrayRef<Value *> UserIgnoreLst) {
1315   deleteTree();
1316   UserIgnoreList = UserIgnoreLst;
1317   if (!allSameType(Roots))
1318     return;
1319   buildTree_rec(Roots, 0, -1);
1320 
1321   // Collect the values that we need to extract from the tree.
1322   for (TreeEntry &EIdx : VectorizableTree) {
1323     TreeEntry *Entry = &EIdx;
1324 
1325     // No need to handle users of gathered values.
1326     if (Entry->NeedToGather)
1327       continue;
1328 
1329     // For each lane:
1330     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1331       Value *Scalar = Entry->Scalars[Lane];
1332 
1333       // Check if the scalar is externally used as an extra arg.
1334       auto ExtI = ExternallyUsedValues.find(Scalar);
1335       if (ExtI != ExternallyUsedValues.end()) {
1336         DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " <<
1337               Lane << " from " << *Scalar << ".\n");
1338         ExternalUses.emplace_back(Scalar, nullptr, Lane);
1339         continue;
1340       }
1341       for (User *U : Scalar->users()) {
1342         DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
1343 
1344         Instruction *UserInst = dyn_cast<Instruction>(U);
1345         if (!UserInst)
1346           continue;
1347 
1348         // Skip in-tree scalars that become vectors
1349         if (TreeEntry *UseEntry = getTreeEntry(U)) {
1350           Value *UseScalar = UseEntry->Scalars[0];
1351           // Some in-tree scalars will remain as scalar in vectorized
1352           // instructions. If that is the case, the one in Lane 0 will
1353           // be used.
1354           if (UseScalar != U ||
1355               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
1356             DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
1357                          << ".\n");
1358             assert(!UseEntry->NeedToGather && "Bad state");
1359             continue;
1360           }
1361         }
1362 
1363         // Ignore users in the user ignore list.
1364         if (is_contained(UserIgnoreList, UserInst))
1365           continue;
1366 
1367         DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
1368               Lane << " from " << *Scalar << ".\n");
1369         ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
1370       }
1371     }
1372   }
1373 }
1374 
1375 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
1376                             int UserTreeIdx) {
1377   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
1378 
1379   InstructionsState S = getSameOpcode(VL);
1380   if (Depth == RecursionMaxDepth) {
1381     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1382     newTreeEntry(VL, false, UserTreeIdx);
1383     return;
1384   }
1385 
1386   // Don't handle vectors.
1387   if (S.OpValue->getType()->isVectorTy()) {
1388     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1389     newTreeEntry(VL, false, UserTreeIdx);
1390     return;
1391   }
1392 
1393   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
1394     if (SI->getValueOperand()->getType()->isVectorTy()) {
1395       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1396       newTreeEntry(VL, false, UserTreeIdx);
1397       return;
1398     }
1399 
1400   // If all of the operands are identical or constant we have a simple solution.
1401   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.Opcode) {
1402     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1403     newTreeEntry(VL, false, UserTreeIdx);
1404     return;
1405   }
1406 
1407   // We now know that this is a vector of instructions of the same type from
1408   // the same block.
1409 
1410   // Don't vectorize ephemeral values.
1411   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1412     if (EphValues.count(VL[i])) {
1413       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1414             ") is ephemeral.\n");
1415       newTreeEntry(VL, false, UserTreeIdx);
1416       return;
1417     }
1418   }
1419 
1420   // Check if this is a duplicate of another entry.
1421   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
1422     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1423       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1424       if (E->Scalars[i] != VL[i]) {
1425         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1426         newTreeEntry(VL, false, UserTreeIdx);
1427         return;
1428       }
1429     }
1430     // Record the reuse of the tree node.  FIXME, currently this is only used to
1431     // properly draw the graph rather than for the actual vectorization.
1432     E->UserTreeIndices.push_back(UserTreeIdx);
1433     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue << ".\n");
1434     return;
1435   }
1436 
1437   // Check that none of the instructions in the bundle are already in the tree.
1438   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1439       auto *I = dyn_cast<Instruction>(VL[i]);
1440       if (!I)
1441         continue;
1442       if (getTreeEntry(I)) {
1443       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1444             ") is already in tree.\n");
1445       newTreeEntry(VL, false, UserTreeIdx);
1446       return;
1447     }
1448   }
1449 
1450   // If any of the scalars is marked as a value that needs to stay scalar then
1451   // we need to gather the scalars.
1452   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1453     if (MustGather.count(VL[i])) {
1454       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1455       newTreeEntry(VL, false, UserTreeIdx);
1456       return;
1457     }
1458   }
1459 
1460   // Check that all of the users of the scalars that we want to vectorize are
1461   // schedulable.
1462   auto *VL0 = cast<Instruction>(S.OpValue);
1463   BasicBlock *BB = VL0->getParent();
1464 
1465   if (!DT->isReachableFromEntry(BB)) {
1466     // Don't go into unreachable blocks. They may contain instructions with
1467     // dependency cycles which confuse the final scheduling.
1468     DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1469     newTreeEntry(VL, false, UserTreeIdx);
1470     return;
1471   }
1472 
1473   // Check that every instructions appears once in this bundle.
1474   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1475     for (unsigned j = i+1; j < e; ++j)
1476       if (VL[i] == VL[j]) {
1477         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1478         newTreeEntry(VL, false, UserTreeIdx);
1479         return;
1480       }
1481 
1482   auto &BSRef = BlocksSchedules[BB];
1483   if (!BSRef) {
1484     BSRef = llvm::make_unique<BlockScheduling>(BB);
1485   }
1486   BlockScheduling &BS = *BSRef.get();
1487 
1488   if (!BS.tryScheduleBundle(VL, this, S.OpValue)) {
1489     DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1490     assert((!BS.getScheduleData(VL0) ||
1491             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
1492            "tryScheduleBundle should cancelScheduling on failure");
1493     newTreeEntry(VL, false, UserTreeIdx);
1494     return;
1495   }
1496   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1497 
1498   unsigned ShuffleOrOp = S.IsAltShuffle ?
1499                 (unsigned) Instruction::ShuffleVector : S.Opcode;
1500   switch (ShuffleOrOp) {
1501     case Instruction::PHI: {
1502       PHINode *PH = dyn_cast<PHINode>(VL0);
1503 
1504       // Check for terminator values (e.g. invoke).
1505       for (unsigned j = 0; j < VL.size(); ++j)
1506         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1507           TerminatorInst *Term = dyn_cast<TerminatorInst>(
1508               cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1509           if (Term) {
1510             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1511             BS.cancelScheduling(VL, VL0);
1512             newTreeEntry(VL, false, UserTreeIdx);
1513             return;
1514           }
1515         }
1516 
1517       newTreeEntry(VL, true, UserTreeIdx);
1518       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1519 
1520       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1521         ValueList Operands;
1522         // Prepare the operand vector.
1523         for (Value *j : VL)
1524           Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1525               PH->getIncomingBlock(i)));
1526 
1527         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1528       }
1529       return;
1530     }
1531     case Instruction::ExtractValue:
1532     case Instruction::ExtractElement: {
1533       bool Reuse = canReuseExtract(VL, VL0);
1534       if (Reuse) {
1535         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1536       } else {
1537         BS.cancelScheduling(VL, VL0);
1538       }
1539       newTreeEntry(VL, Reuse, UserTreeIdx);
1540       return;
1541     }
1542     case Instruction::Load: {
1543       // Check that a vectorized load would load the same memory as a scalar
1544       // load.
1545       // For example we don't want vectorize loads that are smaller than 8 bit.
1546       // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats
1547       // loading/storing it as an i8 struct. If we vectorize loads/stores from
1548       // such a struct we read/write packed bits disagreeing with the
1549       // unvectorized version.
1550       Type *ScalarTy = VL0->getType();
1551 
1552       if (DL->getTypeSizeInBits(ScalarTy) !=
1553           DL->getTypeAllocSizeInBits(ScalarTy)) {
1554         BS.cancelScheduling(VL, VL0);
1555         newTreeEntry(VL, false, UserTreeIdx);
1556         DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
1557         return;
1558       }
1559 
1560       // Make sure all loads in the bundle are simple - we can't vectorize
1561       // atomic or volatile loads.
1562       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1563         LoadInst *L = cast<LoadInst>(VL[i]);
1564         if (!L->isSimple()) {
1565           BS.cancelScheduling(VL, VL0);
1566           newTreeEntry(VL, false, UserTreeIdx);
1567           DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1568           return;
1569         }
1570       }
1571 
1572       // Check if the loads are consecutive, reversed, or neither.
1573       // TODO: What we really want is to sort the loads, but for now, check
1574       // the two likely directions.
1575       bool Consecutive = true;
1576       bool ReverseConsecutive = true;
1577       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1578         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1579           Consecutive = false;
1580           break;
1581         } else {
1582           ReverseConsecutive = false;
1583         }
1584       }
1585 
1586       if (Consecutive) {
1587         ++NumLoadsWantToKeepOrder;
1588         newTreeEntry(VL, true, UserTreeIdx);
1589         DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1590         return;
1591       }
1592 
1593       // If none of the load pairs were consecutive when checked in order,
1594       // check the reverse order.
1595       if (ReverseConsecutive)
1596         for (unsigned i = VL.size() - 1; i > 0; --i)
1597           if (!isConsecutiveAccess(VL[i], VL[i - 1], *DL, *SE)) {
1598             ReverseConsecutive = false;
1599             break;
1600           }
1601 
1602       BS.cancelScheduling(VL, VL0);
1603       newTreeEntry(VL, false, UserTreeIdx);
1604 
1605       if (ReverseConsecutive) {
1606         ++NumLoadsWantToChangeOrder;
1607         DEBUG(dbgs() << "SLP: Gathering reversed loads.\n");
1608       } else {
1609         DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1610       }
1611       return;
1612     }
1613     case Instruction::ZExt:
1614     case Instruction::SExt:
1615     case Instruction::FPToUI:
1616     case Instruction::FPToSI:
1617     case Instruction::FPExt:
1618     case Instruction::PtrToInt:
1619     case Instruction::IntToPtr:
1620     case Instruction::SIToFP:
1621     case Instruction::UIToFP:
1622     case Instruction::Trunc:
1623     case Instruction::FPTrunc:
1624     case Instruction::BitCast: {
1625       Type *SrcTy = VL0->getOperand(0)->getType();
1626       for (unsigned i = 0; i < VL.size(); ++i) {
1627         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1628         if (Ty != SrcTy || !isValidElementType(Ty)) {
1629           BS.cancelScheduling(VL, VL0);
1630           newTreeEntry(VL, false, UserTreeIdx);
1631           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1632           return;
1633         }
1634       }
1635       newTreeEntry(VL, true, UserTreeIdx);
1636       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1637 
1638       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1639         ValueList Operands;
1640         // Prepare the operand vector.
1641         for (Value *j : VL)
1642           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1643 
1644         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1645       }
1646       return;
1647     }
1648     case Instruction::ICmp:
1649     case Instruction::FCmp: {
1650       // Check that all of the compares have the same predicate.
1651       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
1652       Type *ComparedTy = VL0->getOperand(0)->getType();
1653       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1654         CmpInst *Cmp = cast<CmpInst>(VL[i]);
1655         if (Cmp->getPredicate() != P0 ||
1656             Cmp->getOperand(0)->getType() != ComparedTy) {
1657           BS.cancelScheduling(VL, VL0);
1658           newTreeEntry(VL, false, UserTreeIdx);
1659           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1660           return;
1661         }
1662       }
1663 
1664       newTreeEntry(VL, true, UserTreeIdx);
1665       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1666 
1667       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1668         ValueList Operands;
1669         // Prepare the operand vector.
1670         for (Value *j : VL)
1671           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1672 
1673         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1674       }
1675       return;
1676     }
1677     case Instruction::Select:
1678     case Instruction::Add:
1679     case Instruction::FAdd:
1680     case Instruction::Sub:
1681     case Instruction::FSub:
1682     case Instruction::Mul:
1683     case Instruction::FMul:
1684     case Instruction::UDiv:
1685     case Instruction::SDiv:
1686     case Instruction::FDiv:
1687     case Instruction::URem:
1688     case Instruction::SRem:
1689     case Instruction::FRem:
1690     case Instruction::Shl:
1691     case Instruction::LShr:
1692     case Instruction::AShr:
1693     case Instruction::And:
1694     case Instruction::Or:
1695     case Instruction::Xor:
1696       newTreeEntry(VL, true, UserTreeIdx);
1697       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1698 
1699       // Sort operands of the instructions so that each side is more likely to
1700       // have the same opcode.
1701       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1702         ValueList Left, Right;
1703         reorderInputsAccordingToOpcode(S.Opcode, VL, Left, Right);
1704         buildTree_rec(Left, Depth + 1, UserTreeIdx);
1705         buildTree_rec(Right, Depth + 1, UserTreeIdx);
1706         return;
1707       }
1708 
1709       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1710         ValueList Operands;
1711         // Prepare the operand vector.
1712         for (Value *j : VL)
1713           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1714 
1715         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1716       }
1717       return;
1718 
1719     case Instruction::GetElementPtr: {
1720       // We don't combine GEPs with complicated (nested) indexing.
1721       for (unsigned j = 0; j < VL.size(); ++j) {
1722         if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1723           DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1724           BS.cancelScheduling(VL, VL0);
1725           newTreeEntry(VL, false, UserTreeIdx);
1726           return;
1727         }
1728       }
1729 
1730       // We can't combine several GEPs into one vector if they operate on
1731       // different types.
1732       Type *Ty0 = VL0->getOperand(0)->getType();
1733       for (unsigned j = 0; j < VL.size(); ++j) {
1734         Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1735         if (Ty0 != CurTy) {
1736           DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1737           BS.cancelScheduling(VL, VL0);
1738           newTreeEntry(VL, false, UserTreeIdx);
1739           return;
1740         }
1741       }
1742 
1743       // We don't combine GEPs with non-constant indexes.
1744       for (unsigned j = 0; j < VL.size(); ++j) {
1745         auto Op = cast<Instruction>(VL[j])->getOperand(1);
1746         if (!isa<ConstantInt>(Op)) {
1747           DEBUG(
1748               dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1749           BS.cancelScheduling(VL, VL0);
1750           newTreeEntry(VL, false, UserTreeIdx);
1751           return;
1752         }
1753       }
1754 
1755       newTreeEntry(VL, true, UserTreeIdx);
1756       DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1757       for (unsigned i = 0, e = 2; i < e; ++i) {
1758         ValueList Operands;
1759         // Prepare the operand vector.
1760         for (Value *j : VL)
1761           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1762 
1763         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1764       }
1765       return;
1766     }
1767     case Instruction::Store: {
1768       // Check if the stores are consecutive or of we need to swizzle them.
1769       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1770         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1771           BS.cancelScheduling(VL, VL0);
1772           newTreeEntry(VL, false, UserTreeIdx);
1773           DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1774           return;
1775         }
1776 
1777       newTreeEntry(VL, true, UserTreeIdx);
1778       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1779 
1780       ValueList Operands;
1781       for (Value *j : VL)
1782         Operands.push_back(cast<Instruction>(j)->getOperand(0));
1783 
1784       buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1785       return;
1786     }
1787     case Instruction::Call: {
1788       // Check if the calls are all to the same vectorizable intrinsic.
1789       CallInst *CI = cast<CallInst>(VL0);
1790       // Check if this is an Intrinsic call or something that can be
1791       // represented by an intrinsic call
1792       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1793       if (!isTriviallyVectorizable(ID)) {
1794         BS.cancelScheduling(VL, VL0);
1795         newTreeEntry(VL, false, UserTreeIdx);
1796         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1797         return;
1798       }
1799       Function *Int = CI->getCalledFunction();
1800       Value *A1I = nullptr;
1801       if (hasVectorInstrinsicScalarOpd(ID, 1))
1802         A1I = CI->getArgOperand(1);
1803       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1804         CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1805         if (!CI2 || CI2->getCalledFunction() != Int ||
1806             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
1807             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1808           BS.cancelScheduling(VL, VL0);
1809           newTreeEntry(VL, false, UserTreeIdx);
1810           DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1811                        << "\n");
1812           return;
1813         }
1814         // ctlz,cttz and powi are special intrinsics whose second argument
1815         // should be same in order for them to be vectorized.
1816         if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1817           Value *A1J = CI2->getArgOperand(1);
1818           if (A1I != A1J) {
1819             BS.cancelScheduling(VL, VL0);
1820             newTreeEntry(VL, false, UserTreeIdx);
1821             DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1822                          << " argument "<< A1I<<"!=" << A1J
1823                          << "\n");
1824             return;
1825           }
1826         }
1827         // Verify that the bundle operands are identical between the two calls.
1828         if (CI->hasOperandBundles() &&
1829             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
1830                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
1831                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1832           BS.cancelScheduling(VL, VL0);
1833           newTreeEntry(VL, false, UserTreeIdx);
1834           DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!="
1835                        << *VL[i] << '\n');
1836           return;
1837         }
1838       }
1839 
1840       newTreeEntry(VL, true, UserTreeIdx);
1841       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1842         ValueList Operands;
1843         // Prepare the operand vector.
1844         for (Value *j : VL) {
1845           CallInst *CI2 = dyn_cast<CallInst>(j);
1846           Operands.push_back(CI2->getArgOperand(i));
1847         }
1848         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1849       }
1850       return;
1851     }
1852     case Instruction::ShuffleVector:
1853       // If this is not an alternate sequence of opcode like add-sub
1854       // then do not vectorize this instruction.
1855       if (!S.IsAltShuffle) {
1856         BS.cancelScheduling(VL, VL0);
1857         newTreeEntry(VL, false, UserTreeIdx);
1858         DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1859         return;
1860       }
1861       newTreeEntry(VL, true, UserTreeIdx);
1862       DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1863 
1864       // Reorder operands if reordering would enable vectorization.
1865       if (isa<BinaryOperator>(VL0)) {
1866         ValueList Left, Right;
1867         reorderAltShuffleOperands(S.Opcode, VL, Left, Right);
1868         buildTree_rec(Left, Depth + 1, UserTreeIdx);
1869         buildTree_rec(Right, Depth + 1, UserTreeIdx);
1870         return;
1871       }
1872 
1873       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1874         ValueList Operands;
1875         // Prepare the operand vector.
1876         for (Value *j : VL)
1877           Operands.push_back(cast<Instruction>(j)->getOperand(i));
1878 
1879         buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1880       }
1881       return;
1882 
1883     default:
1884       BS.cancelScheduling(VL, VL0);
1885       newTreeEntry(VL, false, UserTreeIdx);
1886       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1887       return;
1888   }
1889 }
1890 
1891 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
1892   unsigned N;
1893   Type *EltTy;
1894   auto *ST = dyn_cast<StructType>(T);
1895   if (ST) {
1896     N = ST->getNumElements();
1897     EltTy = *ST->element_begin();
1898   } else {
1899     N = cast<ArrayType>(T)->getNumElements();
1900     EltTy = cast<ArrayType>(T)->getElementType();
1901   }
1902   if (!isValidElementType(EltTy))
1903     return 0;
1904   uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
1905   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
1906     return 0;
1907   if (ST) {
1908     // Check that struct is homogeneous.
1909     for (const auto *Ty : ST->elements())
1910       if (Ty != EltTy)
1911         return 0;
1912   }
1913   return N;
1914 }
1915 
1916 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue) const {
1917   Instruction *E0 = cast<Instruction>(OpValue);
1918   assert(E0->getOpcode() == Instruction::ExtractElement ||
1919          E0->getOpcode() == Instruction::ExtractValue);
1920   assert(E0->getOpcode() == getSameOpcode(VL).Opcode && "Invalid opcode");
1921   // Check if all of the extracts come from the same vector and from the
1922   // correct offset.
1923   Value *Vec = E0->getOperand(0);
1924 
1925   // We have to extract from a vector/aggregate with the same number of elements.
1926   unsigned NElts;
1927   if (E0->getOpcode() == Instruction::ExtractValue) {
1928     const DataLayout &DL = E0->getModule()->getDataLayout();
1929     NElts = canMapToVector(Vec->getType(), DL);
1930     if (!NElts)
1931       return false;
1932     // Check if load can be rewritten as load of vector.
1933     LoadInst *LI = dyn_cast<LoadInst>(Vec);
1934     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
1935       return false;
1936   } else {
1937     NElts = Vec->getType()->getVectorNumElements();
1938   }
1939 
1940   if (NElts != VL.size())
1941     return false;
1942 
1943   // Check that all of the indices extract from the correct offset.
1944   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
1945     Instruction *Inst = cast<Instruction>(VL[I]);
1946     if (!matchExtractIndex(Inst, I, Inst->getOpcode()))
1947       return false;
1948     if (Inst->getOperand(0) != Vec)
1949       return false;
1950   }
1951 
1952   return true;
1953 }
1954 
1955 bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
1956   return I->hasOneUse() ||
1957          std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
1958            return ScalarToTreeEntry.count(U) > 0;
1959          });
1960 }
1961 
1962 int BoUpSLP::getEntryCost(TreeEntry *E) {
1963   ArrayRef<Value*> VL = E->Scalars;
1964 
1965   Type *ScalarTy = VL[0]->getType();
1966   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1967     ScalarTy = SI->getValueOperand()->getType();
1968   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
1969     ScalarTy = CI->getOperand(0)->getType();
1970   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1971 
1972   // If we have computed a smaller type for the expression, update VecTy so
1973   // that the costs will be accurate.
1974   if (MinBWs.count(VL[0]))
1975     VecTy = VectorType::get(
1976         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
1977 
1978   if (E->NeedToGather) {
1979     if (allConstant(VL))
1980       return 0;
1981     if (isSplat(VL)) {
1982       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1983     }
1984     if (getSameOpcode(VL).Opcode == Instruction::ExtractElement) {
1985       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL);
1986       if (ShuffleKind.hasValue()) {
1987         int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy);
1988         for (auto *V : VL) {
1989           // If all users of instruction are going to be vectorized and this
1990           // instruction itself is not going to be vectorized, consider this
1991           // instruction as dead and remove its cost from the final cost of the
1992           // vectorized tree.
1993           if (areAllUsersVectorized(cast<Instruction>(V)) &&
1994               !ScalarToTreeEntry.count(V)) {
1995             auto *IO = cast<ConstantInt>(
1996                 cast<ExtractElementInst>(V)->getIndexOperand());
1997             Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1998                                             IO->getZExtValue());
1999           }
2000         }
2001         return Cost;
2002       }
2003     }
2004     return getGatherCost(E->Scalars);
2005   }
2006   InstructionsState S = getSameOpcode(VL);
2007   assert(S.Opcode && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
2008   Instruction *VL0 = cast<Instruction>(S.OpValue);
2009   unsigned ShuffleOrOp = S.IsAltShuffle ?
2010                (unsigned) Instruction::ShuffleVector : S.Opcode;
2011   switch (ShuffleOrOp) {
2012     case Instruction::PHI:
2013       return 0;
2014 
2015     case Instruction::ExtractValue:
2016     case Instruction::ExtractElement:
2017       if (canReuseExtract(VL, S.OpValue)) {
2018         int DeadCost = 0;
2019         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2020           Instruction *E = cast<Instruction>(VL[i]);
2021           // If all users are going to be vectorized, instruction can be
2022           // considered as dead.
2023           // The same, if have only one user, it will be vectorized for sure.
2024           if (areAllUsersVectorized(E))
2025             // Take credit for instruction that will become dead.
2026             DeadCost +=
2027                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
2028         }
2029         return -DeadCost;
2030       }
2031       return getGatherCost(VecTy);
2032 
2033     case Instruction::ZExt:
2034     case Instruction::SExt:
2035     case Instruction::FPToUI:
2036     case Instruction::FPToSI:
2037     case Instruction::FPExt:
2038     case Instruction::PtrToInt:
2039     case Instruction::IntToPtr:
2040     case Instruction::SIToFP:
2041     case Instruction::UIToFP:
2042     case Instruction::Trunc:
2043     case Instruction::FPTrunc:
2044     case Instruction::BitCast: {
2045       Type *SrcTy = VL0->getOperand(0)->getType();
2046 
2047       // Calculate the cost of this instruction.
2048       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
2049                                                          VL0->getType(), SrcTy, VL0);
2050 
2051       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
2052       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy, VL0);
2053       return VecCost - ScalarCost;
2054     }
2055     case Instruction::FCmp:
2056     case Instruction::ICmp:
2057     case Instruction::Select: {
2058       // Calculate the cost of this instruction.
2059       VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
2060       int ScalarCost = VecTy->getNumElements() *
2061           TTI->getCmpSelInstrCost(S.Opcode, ScalarTy, Builder.getInt1Ty(), VL0);
2062       int VecCost = TTI->getCmpSelInstrCost(S.Opcode, VecTy, MaskTy, VL0);
2063       return VecCost - ScalarCost;
2064     }
2065     case Instruction::Add:
2066     case Instruction::FAdd:
2067     case Instruction::Sub:
2068     case Instruction::FSub:
2069     case Instruction::Mul:
2070     case Instruction::FMul:
2071     case Instruction::UDiv:
2072     case Instruction::SDiv:
2073     case Instruction::FDiv:
2074     case Instruction::URem:
2075     case Instruction::SRem:
2076     case Instruction::FRem:
2077     case Instruction::Shl:
2078     case Instruction::LShr:
2079     case Instruction::AShr:
2080     case Instruction::And:
2081     case Instruction::Or:
2082     case Instruction::Xor: {
2083       // Certain instructions can be cheaper to vectorize if they have a
2084       // constant second vector operand.
2085       TargetTransformInfo::OperandValueKind Op1VK =
2086           TargetTransformInfo::OK_AnyValue;
2087       TargetTransformInfo::OperandValueKind Op2VK =
2088           TargetTransformInfo::OK_UniformConstantValue;
2089       TargetTransformInfo::OperandValueProperties Op1VP =
2090           TargetTransformInfo::OP_None;
2091       TargetTransformInfo::OperandValueProperties Op2VP =
2092           TargetTransformInfo::OP_None;
2093 
2094       // If all operands are exactly the same ConstantInt then set the
2095       // operand kind to OK_UniformConstantValue.
2096       // If instead not all operands are constants, then set the operand kind
2097       // to OK_AnyValue. If all operands are constants but not the same,
2098       // then set the operand kind to OK_NonUniformConstantValue.
2099       ConstantInt *CInt = nullptr;
2100       for (unsigned i = 0; i < VL.size(); ++i) {
2101         const Instruction *I = cast<Instruction>(VL[i]);
2102         if (!isa<ConstantInt>(I->getOperand(1))) {
2103           Op2VK = TargetTransformInfo::OK_AnyValue;
2104           break;
2105         }
2106         if (i == 0) {
2107           CInt = cast<ConstantInt>(I->getOperand(1));
2108           continue;
2109         }
2110         if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
2111             CInt != cast<ConstantInt>(I->getOperand(1)))
2112           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
2113       }
2114       // FIXME: Currently cost of model modification for division by power of
2115       // 2 is handled for X86 and AArch64. Add support for other targets.
2116       if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
2117           CInt->getValue().isPowerOf2())
2118         Op2VP = TargetTransformInfo::OP_PowerOf2;
2119 
2120       SmallVector<const Value *, 4> Operands(VL0->operand_values());
2121       int ScalarCost =
2122           VecTy->getNumElements() *
2123           TTI->getArithmeticInstrCost(S.Opcode, ScalarTy, Op1VK, Op2VK, Op1VP,
2124                                       Op2VP, Operands);
2125       int VecCost = TTI->getArithmeticInstrCost(S.Opcode, VecTy, Op1VK, Op2VK,
2126                                                 Op1VP, Op2VP, Operands);
2127       return VecCost - ScalarCost;
2128     }
2129     case Instruction::GetElementPtr: {
2130       TargetTransformInfo::OperandValueKind Op1VK =
2131           TargetTransformInfo::OK_AnyValue;
2132       TargetTransformInfo::OperandValueKind Op2VK =
2133           TargetTransformInfo::OK_UniformConstantValue;
2134 
2135       int ScalarCost =
2136           VecTy->getNumElements() *
2137           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
2138       int VecCost =
2139           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
2140 
2141       return VecCost - ScalarCost;
2142     }
2143     case Instruction::Load: {
2144       // Cost of wide load - cost of scalar loads.
2145       unsigned alignment = dyn_cast<LoadInst>(VL0)->getAlignment();
2146       int ScalarLdCost = VecTy->getNumElements() *
2147           TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
2148       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
2149                                            VecTy, alignment, 0, VL0);
2150       return VecLdCost - ScalarLdCost;
2151     }
2152     case Instruction::Store: {
2153       // We know that we can merge the stores. Calculate the cost.
2154       unsigned alignment = dyn_cast<StoreInst>(VL0)->getAlignment();
2155       int ScalarStCost = VecTy->getNumElements() *
2156           TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
2157       int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
2158                                            VecTy, alignment, 0, VL0);
2159       return VecStCost - ScalarStCost;
2160     }
2161     case Instruction::Call: {
2162       CallInst *CI = cast<CallInst>(VL0);
2163       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2164 
2165       // Calculate the cost of the scalar and vector calls.
2166       SmallVector<Type*, 4> ScalarTys;
2167       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op)
2168         ScalarTys.push_back(CI->getArgOperand(op)->getType());
2169 
2170       FastMathFlags FMF;
2171       if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2172         FMF = FPMO->getFastMathFlags();
2173 
2174       int ScalarCallCost = VecTy->getNumElements() *
2175           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
2176 
2177       SmallVector<Value *, 4> Args(CI->arg_operands());
2178       int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
2179                                                    VecTy->getNumElements());
2180 
2181       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
2182             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
2183             << " for " << *CI << "\n");
2184 
2185       return VecCallCost - ScalarCallCost;
2186     }
2187     case Instruction::ShuffleVector: {
2188       TargetTransformInfo::OperandValueKind Op1VK =
2189           TargetTransformInfo::OK_AnyValue;
2190       TargetTransformInfo::OperandValueKind Op2VK =
2191           TargetTransformInfo::OK_AnyValue;
2192       int ScalarCost = 0;
2193       int VecCost = 0;
2194       for (Value *i : VL) {
2195         Instruction *I = cast<Instruction>(i);
2196         if (!I)
2197           break;
2198         ScalarCost +=
2199             TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
2200       }
2201       // VecCost is equal to sum of the cost of creating 2 vectors
2202       // and the cost of creating shuffle.
2203       Instruction *I0 = cast<Instruction>(VL[0]);
2204       VecCost =
2205           TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
2206       Instruction *I1 = cast<Instruction>(VL[1]);
2207       VecCost +=
2208           TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
2209       VecCost +=
2210           TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
2211       return VecCost - ScalarCost;
2212     }
2213     default:
2214       llvm_unreachable("Unknown instruction");
2215   }
2216 }
2217 
2218 bool BoUpSLP::isFullyVectorizableTinyTree() {
2219   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
2220         VectorizableTree.size() << " is fully vectorizable .\n");
2221 
2222   // We only handle trees of heights 1 and 2.
2223   if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
2224     return true;
2225 
2226   if (VectorizableTree.size() != 2)
2227     return false;
2228 
2229   // Handle splat and all-constants stores.
2230   if (!VectorizableTree[0].NeedToGather &&
2231       (allConstant(VectorizableTree[1].Scalars) ||
2232        isSplat(VectorizableTree[1].Scalars)))
2233     return true;
2234 
2235   // Gathering cost would be too much for tiny trees.
2236   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
2237     return false;
2238 
2239   return true;
2240 }
2241 
2242 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
2243   // We can vectorize the tree if its size is greater than or equal to the
2244   // minimum size specified by the MinTreeSize command line option.
2245   if (VectorizableTree.size() >= MinTreeSize)
2246     return false;
2247 
2248   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
2249   // can vectorize it if we can prove it fully vectorizable.
2250   if (isFullyVectorizableTinyTree())
2251     return false;
2252 
2253   assert(VectorizableTree.empty()
2254              ? ExternalUses.empty()
2255              : true && "We shouldn't have any external users");
2256 
2257   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
2258   // vectorizable.
2259   return true;
2260 }
2261 
2262 int BoUpSLP::getSpillCost() {
2263   // Walk from the bottom of the tree to the top, tracking which values are
2264   // live. When we see a call instruction that is not part of our tree,
2265   // query TTI to see if there is a cost to keeping values live over it
2266   // (for example, if spills and fills are required).
2267   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
2268   int Cost = 0;
2269 
2270   SmallPtrSet<Instruction*, 4> LiveValues;
2271   Instruction *PrevInst = nullptr;
2272 
2273   for (const auto &N : VectorizableTree) {
2274     Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
2275     if (!Inst)
2276       continue;
2277 
2278     if (!PrevInst) {
2279       PrevInst = Inst;
2280       continue;
2281     }
2282 
2283     // Update LiveValues.
2284     LiveValues.erase(PrevInst);
2285     for (auto &J : PrevInst->operands()) {
2286       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
2287         LiveValues.insert(cast<Instruction>(&*J));
2288     }
2289 
2290     DEBUG(
2291       dbgs() << "SLP: #LV: " << LiveValues.size();
2292       for (auto *X : LiveValues)
2293         dbgs() << " " << X->getName();
2294       dbgs() << ", Looking at ";
2295       Inst->dump();
2296       );
2297 
2298     // Now find the sequence of instructions between PrevInst and Inst.
2299     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
2300                                  PrevInstIt =
2301                                      PrevInst->getIterator().getReverse();
2302     while (InstIt != PrevInstIt) {
2303       if (PrevInstIt == PrevInst->getParent()->rend()) {
2304         PrevInstIt = Inst->getParent()->rbegin();
2305         continue;
2306       }
2307 
2308       if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
2309         SmallVector<Type*, 4> V;
2310         for (auto *II : LiveValues)
2311           V.push_back(VectorType::get(II->getType(), BundleWidth));
2312         Cost += TTI->getCostOfKeepingLiveOverCall(V);
2313       }
2314 
2315       ++PrevInstIt;
2316     }
2317 
2318     PrevInst = Inst;
2319   }
2320 
2321   return Cost;
2322 }
2323 
2324 int BoUpSLP::getTreeCost() {
2325   int Cost = 0;
2326   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
2327         VectorizableTree.size() << ".\n");
2328 
2329   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2330 
2331   for (TreeEntry &TE : VectorizableTree) {
2332     int C = getEntryCost(&TE);
2333     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
2334                  << *TE.Scalars[0] << ".\n");
2335     Cost += C;
2336   }
2337 
2338   SmallSet<Value *, 16> ExtractCostCalculated;
2339   int ExtractCost = 0;
2340   for (ExternalUser &EU : ExternalUses) {
2341     // We only add extract cost once for the same scalar.
2342     if (!ExtractCostCalculated.insert(EU.Scalar).second)
2343       continue;
2344 
2345     // Uses by ephemeral values are free (because the ephemeral value will be
2346     // removed prior to code generation, and so the extraction will be
2347     // removed as well).
2348     if (EphValues.count(EU.User))
2349       continue;
2350 
2351     // If we plan to rewrite the tree in a smaller type, we will need to sign
2352     // extend the extracted value back to the original type. Here, we account
2353     // for the extract and the added cost of the sign extend if needed.
2354     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
2355     auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2356     if (MinBWs.count(ScalarRoot)) {
2357       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2358       auto Extend =
2359           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2360       VecTy = VectorType::get(MinTy, BundleWidth);
2361       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2362                                                    VecTy, EU.Lane);
2363     } else {
2364       ExtractCost +=
2365           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
2366     }
2367   }
2368 
2369   int SpillCost = getSpillCost();
2370   Cost += SpillCost + ExtractCost;
2371 
2372   std::string Str;
2373   {
2374     raw_string_ostream OS(Str);
2375     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
2376        << "SLP: Extract Cost = " << ExtractCost << ".\n"
2377        << "SLP: Total Cost = " << Cost << ".\n";
2378   }
2379   DEBUG(dbgs() << Str);
2380 
2381   if (ViewSLPTree)
2382     ViewGraph(this, "SLP" + F->getName(), false, Str);
2383 
2384   return Cost;
2385 }
2386 
2387 int BoUpSLP::getGatherCost(Type *Ty) {
2388   int Cost = 0;
2389   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2390     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
2391   return Cost;
2392 }
2393 
2394 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
2395   // Find the type of the operands in VL.
2396   Type *ScalarTy = VL[0]->getType();
2397   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2398     ScalarTy = SI->getValueOperand()->getType();
2399   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2400   // Find the cost of inserting/extracting values from the vector.
2401   return getGatherCost(VecTy);
2402 }
2403 
2404 // Reorder commutative operations in alternate shuffle if the resulting vectors
2405 // are consecutive loads. This would allow us to vectorize the tree.
2406 // If we have something like-
2407 // load a[0] - load b[0]
2408 // load b[1] + load a[1]
2409 // load a[2] - load b[2]
2410 // load a[3] + load b[3]
2411 // Reordering the second load b[1]  load a[1] would allow us to vectorize this
2412 // code.
2413 void BoUpSLP::reorderAltShuffleOperands(unsigned Opcode, ArrayRef<Value *> VL,
2414                                         SmallVectorImpl<Value *> &Left,
2415                                         SmallVectorImpl<Value *> &Right) {
2416   // Push left and right operands of binary operation into Left and Right
2417   unsigned AltOpcode = getAltOpcode(Opcode);
2418   (void)AltOpcode;
2419   for (Value *V : VL) {
2420     auto *I = cast<Instruction>(V);
2421     assert(sameOpcodeOrAlt(Opcode, AltOpcode, I->getOpcode()) &&
2422            "Incorrect instruction in vector");
2423     Left.push_back(I->getOperand(0));
2424     Right.push_back(I->getOperand(1));
2425   }
2426 
2427   // Reorder if we have a commutative operation and consecutive access
2428   // are on either side of the alternate instructions.
2429   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2430     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2431       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2432         Instruction *VL1 = cast<Instruction>(VL[j]);
2433         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2434         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2435           std::swap(Left[j], Right[j]);
2436           continue;
2437         } else if (VL2->isCommutative() &&
2438                    isConsecutiveAccess(L, L1, *DL, *SE)) {
2439           std::swap(Left[j + 1], Right[j + 1]);
2440           continue;
2441         }
2442         // else unchanged
2443       }
2444     }
2445     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2446       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2447         Instruction *VL1 = cast<Instruction>(VL[j]);
2448         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2449         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2450           std::swap(Left[j], Right[j]);
2451           continue;
2452         } else if (VL2->isCommutative() &&
2453                    isConsecutiveAccess(L, L1, *DL, *SE)) {
2454           std::swap(Left[j + 1], Right[j + 1]);
2455           continue;
2456         }
2457         // else unchanged
2458       }
2459     }
2460   }
2461 }
2462 
2463 // Return true if I should be commuted before adding it's left and right
2464 // operands to the arrays Left and Right.
2465 //
2466 // The vectorizer is trying to either have all elements one side being
2467 // instruction with the same opcode to enable further vectorization, or having
2468 // a splat to lower the vectorizing cost.
2469 static bool shouldReorderOperands(
2470     int i, unsigned Opcode, Instruction &I, ArrayRef<Value *> Left,
2471     ArrayRef<Value *> Right, bool AllSameOpcodeLeft, bool AllSameOpcodeRight,
2472     bool SplatLeft, bool SplatRight, Value *&VLeft, Value *&VRight) {
2473   VLeft = I.getOperand(0);
2474   VRight = I.getOperand(1);
2475   // If we have "SplatRight", try to see if commuting is needed to preserve it.
2476   if (SplatRight) {
2477     if (VRight == Right[i - 1])
2478       // Preserve SplatRight
2479       return false;
2480     if (VLeft == Right[i - 1]) {
2481       // Commuting would preserve SplatRight, but we don't want to break
2482       // SplatLeft either, i.e. preserve the original order if possible.
2483       // (FIXME: why do we care?)
2484       if (SplatLeft && VLeft == Left[i - 1])
2485         return false;
2486       return true;
2487     }
2488   }
2489   // Symmetrically handle Right side.
2490   if (SplatLeft) {
2491     if (VLeft == Left[i - 1])
2492       // Preserve SplatLeft
2493       return false;
2494     if (VRight == Left[i - 1])
2495       return true;
2496   }
2497 
2498   Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2499   Instruction *IRight = dyn_cast<Instruction>(VRight);
2500 
2501   // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2502   // it and not the right, in this case we want to commute.
2503   if (AllSameOpcodeRight) {
2504     unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2505     if (IRight && RightPrevOpcode == IRight->getOpcode())
2506       // Do not commute, a match on the right preserves AllSameOpcodeRight
2507       return false;
2508     if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2509       // We have a match and may want to commute, but first check if there is
2510       // not also a match on the existing operands on the Left to preserve
2511       // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2512       // (FIXME: why do we care?)
2513       if (AllSameOpcodeLeft && ILeft &&
2514           cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2515         return false;
2516       return true;
2517     }
2518   }
2519   // Symmetrically handle Left side.
2520   if (AllSameOpcodeLeft) {
2521     unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2522     if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2523       return false;
2524     if (IRight && LeftPrevOpcode == IRight->getOpcode())
2525       return true;
2526   }
2527   return false;
2528 }
2529 
2530 void BoUpSLP::reorderInputsAccordingToOpcode(unsigned Opcode,
2531                                              ArrayRef<Value *> VL,
2532                                              SmallVectorImpl<Value *> &Left,
2533                                              SmallVectorImpl<Value *> &Right) {
2534   if (!VL.empty()) {
2535     // Peel the first iteration out of the loop since there's nothing
2536     // interesting to do anyway and it simplifies the checks in the loop.
2537     auto *I = cast<Instruction>(VL[0]);
2538     Value *VLeft = I->getOperand(0);
2539     Value *VRight = I->getOperand(1);
2540     if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2541       // Favor having instruction to the right. FIXME: why?
2542       std::swap(VLeft, VRight);
2543     Left.push_back(VLeft);
2544     Right.push_back(VRight);
2545   }
2546 
2547   // Keep track if we have instructions with all the same opcode on one side.
2548   bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2549   bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2550   // Keep track if we have one side with all the same value (broadcast).
2551   bool SplatLeft = true;
2552   bool SplatRight = true;
2553 
2554   for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2555     Instruction *I = cast<Instruction>(VL[i]);
2556     assert(((I->getOpcode() == Opcode && I->isCommutative()) ||
2557             (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) &&
2558            "Can only process commutative instruction");
2559     // Commute to favor either a splat or maximizing having the same opcodes on
2560     // one side.
2561     Value *VLeft;
2562     Value *VRight;
2563     if (shouldReorderOperands(i, Opcode, *I, Left, Right, AllSameOpcodeLeft,
2564                               AllSameOpcodeRight, SplatLeft, SplatRight, VLeft,
2565                               VRight)) {
2566       Left.push_back(VRight);
2567       Right.push_back(VLeft);
2568     } else {
2569       Left.push_back(VLeft);
2570       Right.push_back(VRight);
2571     }
2572     // Update Splat* and AllSameOpcode* after the insertion.
2573     SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2574     SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2575     AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2576                         (cast<Instruction>(Left[i - 1])->getOpcode() ==
2577                          cast<Instruction>(Left[i])->getOpcode());
2578     AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2579                          (cast<Instruction>(Right[i - 1])->getOpcode() ==
2580                           cast<Instruction>(Right[i])->getOpcode());
2581   }
2582 
2583   // If one operand end up being broadcast, return this operand order.
2584   if (SplatRight || SplatLeft)
2585     return;
2586 
2587   // Finally check if we can get longer vectorizable chain by reordering
2588   // without breaking the good operand order detected above.
2589   // E.g. If we have something like-
2590   // load a[0]  load b[0]
2591   // load b[1]  load a[1]
2592   // load a[2]  load b[2]
2593   // load a[3]  load b[3]
2594   // Reordering the second load b[1]  load a[1] would allow us to vectorize
2595   // this code and we still retain AllSameOpcode property.
2596   // FIXME: This load reordering might break AllSameOpcode in some rare cases
2597   // such as-
2598   // add a[0],c[0]  load b[0]
2599   // add a[1],c[2]  load b[1]
2600   // b[2]           load b[2]
2601   // add a[3],c[3]  load b[3]
2602   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2603     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2604       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2605         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2606           std::swap(Left[j + 1], Right[j + 1]);
2607           continue;
2608         }
2609       }
2610     }
2611     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2612       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2613         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2614           std::swap(Left[j + 1], Right[j + 1]);
2615           continue;
2616         }
2617       }
2618     }
2619     // else unchanged
2620   }
2621 }
2622 
2623 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL, Value *OpValue) {
2624   // Get the basic block this bundle is in. All instructions in the bundle
2625   // should be in this block.
2626   auto *Front = cast<Instruction>(OpValue);
2627   auto *BB = Front->getParent();
2628   const unsigned Opcode = cast<Instruction>(OpValue)->getOpcode();
2629   const unsigned AltOpcode = getAltOpcode(Opcode);
2630   assert(llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool {
2631     return !sameOpcodeOrAlt(Opcode, AltOpcode,
2632                             cast<Instruction>(V)->getOpcode()) ||
2633            cast<Instruction>(V)->getParent() == BB;
2634   }));
2635 
2636   // The last instruction in the bundle in program order.
2637   Instruction *LastInst = nullptr;
2638 
2639   // Find the last instruction. The common case should be that BB has been
2640   // scheduled, and the last instruction is VL.back(). So we start with
2641   // VL.back() and iterate over schedule data until we reach the end of the
2642   // bundle. The end of the bundle is marked by null ScheduleData.
2643   if (BlocksSchedules.count(BB)) {
2644     auto *Bundle =
2645         BlocksSchedules[BB]->getScheduleData(isOneOf(OpValue, VL.back()));
2646     if (Bundle && Bundle->isPartOfBundle())
2647       for (; Bundle; Bundle = Bundle->NextInBundle)
2648         if (Bundle->OpValue == Bundle->Inst)
2649           LastInst = Bundle->Inst;
2650   }
2651 
2652   // LastInst can still be null at this point if there's either not an entry
2653   // for BB in BlocksSchedules or there's no ScheduleData available for
2654   // VL.back(). This can be the case if buildTree_rec aborts for various
2655   // reasons (e.g., the maximum recursion depth is reached, the maximum region
2656   // size is reached, etc.). ScheduleData is initialized in the scheduling
2657   // "dry-run".
2658   //
2659   // If this happens, we can still find the last instruction by brute force. We
2660   // iterate forwards from Front (inclusive) until we either see all
2661   // instructions in the bundle or reach the end of the block. If Front is the
2662   // last instruction in program order, LastInst will be set to Front, and we
2663   // will visit all the remaining instructions in the block.
2664   //
2665   // One of the reasons we exit early from buildTree_rec is to place an upper
2666   // bound on compile-time. Thus, taking an additional compile-time hit here is
2667   // not ideal. However, this should be exceedingly rare since it requires that
2668   // we both exit early from buildTree_rec and that the bundle be out-of-order
2669   // (causing us to iterate all the way to the end of the block).
2670   if (!LastInst) {
2671     SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2672     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2673       if (Bundle.erase(&I) && sameOpcodeOrAlt(Opcode, AltOpcode, I.getOpcode()))
2674         LastInst = &I;
2675       if (Bundle.empty())
2676         break;
2677     }
2678   }
2679 
2680   // Set the insertion point after the last instruction in the bundle. Set the
2681   // debug location to Front.
2682   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2683   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2684 }
2685 
2686 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2687   Value *Vec = UndefValue::get(Ty);
2688   // Generate the 'InsertElement' instruction.
2689   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2690     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2691     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2692       GatherSeq.insert(Insrt);
2693       CSEBlocks.insert(Insrt->getParent());
2694 
2695       // Add to our 'need-to-extract' list.
2696       if (TreeEntry *E = getTreeEntry(VL[i])) {
2697         // Find which lane we need to extract.
2698         int FoundLane = -1;
2699         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2700           // Is this the lane of the scalar that we are looking for ?
2701           if (E->Scalars[Lane] == VL[i]) {
2702             FoundLane = Lane;
2703             break;
2704           }
2705         }
2706         assert(FoundLane >= 0 && "Could not find the correct lane");
2707         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2708       }
2709     }
2710   }
2711 
2712   return Vec;
2713 }
2714 
2715 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL, Value *OpValue) const {
2716   if (const TreeEntry *En = getTreeEntry(OpValue)) {
2717     if (En->isSame(VL) && En->VectorizedValue)
2718       return En->VectorizedValue;
2719   }
2720   return nullptr;
2721 }
2722 
2723 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2724   InstructionsState S = getSameOpcode(VL);
2725   if (S.Opcode) {
2726     if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2727       if (E->isSame(VL))
2728         return vectorizeTree(E);
2729     }
2730   }
2731 
2732   Type *ScalarTy = S.OpValue->getType();
2733   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2734     ScalarTy = SI->getValueOperand()->getType();
2735   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2736 
2737   return Gather(VL, VecTy);
2738 }
2739 
2740 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2741   IRBuilder<>::InsertPointGuard Guard(Builder);
2742 
2743   if (E->VectorizedValue) {
2744     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2745     return E->VectorizedValue;
2746   }
2747 
2748   InstructionsState S = getSameOpcode(E->Scalars);
2749   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2750   Type *ScalarTy = VL0->getType();
2751   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2752     ScalarTy = SI->getValueOperand()->getType();
2753   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2754 
2755   if (E->NeedToGather) {
2756     setInsertPointAfterBundle(E->Scalars, VL0);
2757     auto *V = Gather(E->Scalars, VecTy);
2758     E->VectorizedValue = V;
2759     return V;
2760   }
2761 
2762   unsigned ShuffleOrOp = S.IsAltShuffle ?
2763            (unsigned) Instruction::ShuffleVector : S.Opcode;
2764   switch (ShuffleOrOp) {
2765     case Instruction::PHI: {
2766       PHINode *PH = dyn_cast<PHINode>(VL0);
2767       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2768       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2769       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2770       E->VectorizedValue = NewPhi;
2771 
2772       // PHINodes may have multiple entries from the same block. We want to
2773       // visit every block once.
2774       SmallSet<BasicBlock*, 4> VisitedBBs;
2775 
2776       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2777         ValueList Operands;
2778         BasicBlock *IBB = PH->getIncomingBlock(i);
2779 
2780         if (!VisitedBBs.insert(IBB).second) {
2781           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2782           continue;
2783         }
2784 
2785         // Prepare the operand vector.
2786         for (Value *V : E->Scalars)
2787           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2788 
2789         Builder.SetInsertPoint(IBB->getTerminator());
2790         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2791         Value *Vec = vectorizeTree(Operands);
2792         NewPhi->addIncoming(Vec, IBB);
2793       }
2794 
2795       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2796              "Invalid number of incoming values");
2797       return NewPhi;
2798     }
2799 
2800     case Instruction::ExtractElement: {
2801       if (canReuseExtract(E->Scalars, VL0)) {
2802         Value *V = VL0->getOperand(0);
2803         E->VectorizedValue = V;
2804         return V;
2805       }
2806       setInsertPointAfterBundle(E->Scalars, VL0);
2807       auto *V = Gather(E->Scalars, VecTy);
2808       E->VectorizedValue = V;
2809       return V;
2810     }
2811     case Instruction::ExtractValue: {
2812       if (canReuseExtract(E->Scalars, VL0)) {
2813         LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
2814         Builder.SetInsertPoint(LI);
2815         PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
2816         Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
2817         LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
2818         E->VectorizedValue = V;
2819         return propagateMetadata(V, E->Scalars);
2820       }
2821       setInsertPointAfterBundle(E->Scalars, VL0);
2822       auto *V = Gather(E->Scalars, VecTy);
2823       E->VectorizedValue = V;
2824       return V;
2825     }
2826     case Instruction::ZExt:
2827     case Instruction::SExt:
2828     case Instruction::FPToUI:
2829     case Instruction::FPToSI:
2830     case Instruction::FPExt:
2831     case Instruction::PtrToInt:
2832     case Instruction::IntToPtr:
2833     case Instruction::SIToFP:
2834     case Instruction::UIToFP:
2835     case Instruction::Trunc:
2836     case Instruction::FPTrunc:
2837     case Instruction::BitCast: {
2838       ValueList INVL;
2839       for (Value *V : E->Scalars)
2840         INVL.push_back(cast<Instruction>(V)->getOperand(0));
2841 
2842       setInsertPointAfterBundle(E->Scalars, VL0);
2843 
2844       Value *InVec = vectorizeTree(INVL);
2845 
2846       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2847         return V;
2848 
2849       CastInst *CI = dyn_cast<CastInst>(VL0);
2850       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2851       E->VectorizedValue = V;
2852       ++NumVectorInstructions;
2853       return V;
2854     }
2855     case Instruction::FCmp:
2856     case Instruction::ICmp: {
2857       ValueList LHSV, RHSV;
2858       for (Value *V : E->Scalars) {
2859         LHSV.push_back(cast<Instruction>(V)->getOperand(0));
2860         RHSV.push_back(cast<Instruction>(V)->getOperand(1));
2861       }
2862 
2863       setInsertPointAfterBundle(E->Scalars, VL0);
2864 
2865       Value *L = vectorizeTree(LHSV);
2866       Value *R = vectorizeTree(RHSV);
2867 
2868       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2869         return V;
2870 
2871       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2872       Value *V;
2873       if (S.Opcode == Instruction::FCmp)
2874         V = Builder.CreateFCmp(P0, L, R);
2875       else
2876         V = Builder.CreateICmp(P0, L, R);
2877 
2878       E->VectorizedValue = V;
2879       propagateIRFlags(E->VectorizedValue, E->Scalars, VL0);
2880       ++NumVectorInstructions;
2881       return V;
2882     }
2883     case Instruction::Select: {
2884       ValueList TrueVec, FalseVec, CondVec;
2885       for (Value *V : E->Scalars) {
2886         CondVec.push_back(cast<Instruction>(V)->getOperand(0));
2887         TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
2888         FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
2889       }
2890 
2891       setInsertPointAfterBundle(E->Scalars, VL0);
2892 
2893       Value *Cond = vectorizeTree(CondVec);
2894       Value *True = vectorizeTree(TrueVec);
2895       Value *False = vectorizeTree(FalseVec);
2896 
2897       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2898         return V;
2899 
2900       Value *V = Builder.CreateSelect(Cond, True, False);
2901       E->VectorizedValue = V;
2902       ++NumVectorInstructions;
2903       return V;
2904     }
2905     case Instruction::Add:
2906     case Instruction::FAdd:
2907     case Instruction::Sub:
2908     case Instruction::FSub:
2909     case Instruction::Mul:
2910     case Instruction::FMul:
2911     case Instruction::UDiv:
2912     case Instruction::SDiv:
2913     case Instruction::FDiv:
2914     case Instruction::URem:
2915     case Instruction::SRem:
2916     case Instruction::FRem:
2917     case Instruction::Shl:
2918     case Instruction::LShr:
2919     case Instruction::AShr:
2920     case Instruction::And:
2921     case Instruction::Or:
2922     case Instruction::Xor: {
2923       ValueList LHSVL, RHSVL;
2924       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2925         reorderInputsAccordingToOpcode(S.Opcode, E->Scalars, LHSVL,
2926                                        RHSVL);
2927       else
2928         for (Value *V : E->Scalars) {
2929           auto *I = cast<Instruction>(V);
2930           LHSVL.push_back(I->getOperand(0));
2931           RHSVL.push_back(I->getOperand(1));
2932         }
2933 
2934       setInsertPointAfterBundle(E->Scalars, VL0);
2935 
2936       Value *LHS = vectorizeTree(LHSVL);
2937       Value *RHS = vectorizeTree(RHSVL);
2938 
2939       if (Value *V = alreadyVectorized(E->Scalars, VL0))
2940         return V;
2941 
2942       Value *V = Builder.CreateBinOp(
2943           static_cast<Instruction::BinaryOps>(S.Opcode), LHS, RHS);
2944       E->VectorizedValue = V;
2945       propagateIRFlags(E->VectorizedValue, E->Scalars, VL0);
2946       ++NumVectorInstructions;
2947 
2948       if (Instruction *I = dyn_cast<Instruction>(V))
2949         return propagateMetadata(I, E->Scalars);
2950 
2951       return V;
2952     }
2953     case Instruction::Load: {
2954       // Loads are inserted at the head of the tree because we don't want to
2955       // sink them all the way down past store instructions.
2956       setInsertPointAfterBundle(E->Scalars, VL0);
2957 
2958       LoadInst *LI = cast<LoadInst>(VL0);
2959       Type *ScalarLoadTy = LI->getType();
2960       unsigned AS = LI->getPointerAddressSpace();
2961 
2962       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2963                                             VecTy->getPointerTo(AS));
2964 
2965       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2966       // ExternalUses list to make sure that an extract will be generated in the
2967       // future.
2968       Value *PO = LI->getPointerOperand();
2969       if (getTreeEntry(PO))
2970         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
2971 
2972       unsigned Alignment = LI->getAlignment();
2973       LI = Builder.CreateLoad(VecPtr);
2974       if (!Alignment) {
2975         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2976       }
2977       LI->setAlignment(Alignment);
2978       E->VectorizedValue = LI;
2979       ++NumVectorInstructions;
2980       return propagateMetadata(LI, E->Scalars);
2981     }
2982     case Instruction::Store: {
2983       StoreInst *SI = cast<StoreInst>(VL0);
2984       unsigned Alignment = SI->getAlignment();
2985       unsigned AS = SI->getPointerAddressSpace();
2986 
2987       ValueList ValueOp;
2988       for (Value *V : E->Scalars)
2989         ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
2990 
2991       setInsertPointAfterBundle(E->Scalars, VL0);
2992 
2993       Value *VecValue = vectorizeTree(ValueOp);
2994       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2995                                             VecTy->getPointerTo(AS));
2996       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2997 
2998       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2999       // ExternalUses list to make sure that an extract will be generated in the
3000       // future.
3001       Value *PO = SI->getPointerOperand();
3002       if (getTreeEntry(PO))
3003         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
3004 
3005       if (!Alignment) {
3006         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
3007       }
3008       S->setAlignment(Alignment);
3009       E->VectorizedValue = S;
3010       ++NumVectorInstructions;
3011       return propagateMetadata(S, E->Scalars);
3012     }
3013     case Instruction::GetElementPtr: {
3014       setInsertPointAfterBundle(E->Scalars, VL0);
3015 
3016       ValueList Op0VL;
3017       for (Value *V : E->Scalars)
3018         Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
3019 
3020       Value *Op0 = vectorizeTree(Op0VL);
3021 
3022       std::vector<Value *> OpVecs;
3023       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
3024            ++j) {
3025         ValueList OpVL;
3026         for (Value *V : E->Scalars)
3027           OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
3028 
3029         Value *OpVec = vectorizeTree(OpVL);
3030         OpVecs.push_back(OpVec);
3031       }
3032 
3033       Value *V = Builder.CreateGEP(
3034           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
3035       E->VectorizedValue = V;
3036       ++NumVectorInstructions;
3037 
3038       if (Instruction *I = dyn_cast<Instruction>(V))
3039         return propagateMetadata(I, E->Scalars);
3040 
3041       return V;
3042     }
3043     case Instruction::Call: {
3044       CallInst *CI = cast<CallInst>(VL0);
3045       setInsertPointAfterBundle(E->Scalars, VL0);
3046       Function *FI;
3047       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
3048       Value *ScalarArg = nullptr;
3049       if (CI && (FI = CI->getCalledFunction())) {
3050         IID = FI->getIntrinsicID();
3051       }
3052       std::vector<Value *> OpVecs;
3053       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
3054         ValueList OpVL;
3055         // ctlz,cttz and powi are special intrinsics whose second argument is
3056         // a scalar. This argument should not be vectorized.
3057         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
3058           CallInst *CEI = cast<CallInst>(VL0);
3059           ScalarArg = CEI->getArgOperand(j);
3060           OpVecs.push_back(CEI->getArgOperand(j));
3061           continue;
3062         }
3063         for (Value *V : E->Scalars) {
3064           CallInst *CEI = cast<CallInst>(V);
3065           OpVL.push_back(CEI->getArgOperand(j));
3066         }
3067 
3068         Value *OpVec = vectorizeTree(OpVL);
3069         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
3070         OpVecs.push_back(OpVec);
3071       }
3072 
3073       Module *M = F->getParent();
3074       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3075       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
3076       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
3077       SmallVector<OperandBundleDef, 1> OpBundles;
3078       CI->getOperandBundlesAsDefs(OpBundles);
3079       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
3080 
3081       // The scalar argument uses an in-tree scalar so we add the new vectorized
3082       // call to ExternalUses list to make sure that an extract will be
3083       // generated in the future.
3084       if (ScalarArg && getTreeEntry(ScalarArg))
3085         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
3086 
3087       E->VectorizedValue = V;
3088       propagateIRFlags(E->VectorizedValue, E->Scalars, VL0);
3089       ++NumVectorInstructions;
3090       return V;
3091     }
3092     case Instruction::ShuffleVector: {
3093       ValueList LHSVL, RHSVL;
3094       assert(Instruction::isBinaryOp(S.Opcode) &&
3095              "Invalid Shuffle Vector Operand");
3096       reorderAltShuffleOperands(S.Opcode, E->Scalars, LHSVL, RHSVL);
3097       setInsertPointAfterBundle(E->Scalars, VL0);
3098 
3099       Value *LHS = vectorizeTree(LHSVL);
3100       Value *RHS = vectorizeTree(RHSVL);
3101 
3102       if (Value *V = alreadyVectorized(E->Scalars, VL0))
3103         return V;
3104 
3105       // Create a vector of LHS op1 RHS
3106       Value *V0 = Builder.CreateBinOp(
3107           static_cast<Instruction::BinaryOps>(S.Opcode), LHS, RHS);
3108 
3109       unsigned AltOpcode = getAltOpcode(S.Opcode);
3110       // Create a vector of LHS op2 RHS
3111       Value *V1 = Builder.CreateBinOp(
3112           static_cast<Instruction::BinaryOps>(AltOpcode), LHS, RHS);
3113 
3114       // Create shuffle to take alternate operations from the vector.
3115       // Also, gather up odd and even scalar ops to propagate IR flags to
3116       // each vector operation.
3117       ValueList OddScalars, EvenScalars;
3118       unsigned e = E->Scalars.size();
3119       SmallVector<Constant *, 8> Mask(e);
3120       for (unsigned i = 0; i < e; ++i) {
3121         if (isOdd(i)) {
3122           Mask[i] = Builder.getInt32(e + i);
3123           OddScalars.push_back(E->Scalars[i]);
3124         } else {
3125           Mask[i] = Builder.getInt32(i);
3126           EvenScalars.push_back(E->Scalars[i]);
3127         }
3128       }
3129 
3130       Value *ShuffleMask = ConstantVector::get(Mask);
3131       propagateIRFlags(V0, EvenScalars);
3132       propagateIRFlags(V1, OddScalars);
3133 
3134       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
3135       E->VectorizedValue = V;
3136       ++NumVectorInstructions;
3137       if (Instruction *I = dyn_cast<Instruction>(V))
3138         return propagateMetadata(I, E->Scalars);
3139 
3140       return V;
3141     }
3142     default:
3143     llvm_unreachable("unknown inst");
3144   }
3145   return nullptr;
3146 }
3147 
3148 Value *BoUpSLP::vectorizeTree() {
3149   ExtraValueToDebugLocsMap ExternallyUsedValues;
3150   return vectorizeTree(ExternallyUsedValues);
3151 }
3152 
3153 Value *
3154 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3155   // All blocks must be scheduled before any instructions are inserted.
3156   for (auto &BSIter : BlocksSchedules) {
3157     scheduleBlock(BSIter.second.get());
3158   }
3159 
3160   Builder.SetInsertPoint(&F->getEntryBlock().front());
3161   auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
3162 
3163   // If the vectorized tree can be rewritten in a smaller type, we truncate the
3164   // vectorized root. InstCombine will then rewrite the entire expression. We
3165   // sign extend the extracted values below.
3166   auto *ScalarRoot = VectorizableTree[0].Scalars[0];
3167   if (MinBWs.count(ScalarRoot)) {
3168     if (auto *I = dyn_cast<Instruction>(VectorRoot))
3169       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
3170     auto BundleWidth = VectorizableTree[0].Scalars.size();
3171     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3172     auto *VecTy = VectorType::get(MinTy, BundleWidth);
3173     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
3174     VectorizableTree[0].VectorizedValue = Trunc;
3175   }
3176 
3177   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
3178 
3179   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
3180   // specified by ScalarType.
3181   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
3182     if (!MinBWs.count(ScalarRoot))
3183       return Ex;
3184     if (MinBWs[ScalarRoot].second)
3185       return Builder.CreateSExt(Ex, ScalarType);
3186     return Builder.CreateZExt(Ex, ScalarType);
3187   };
3188 
3189   // Extract all of the elements with the external uses.
3190   for (const auto &ExternalUse : ExternalUses) {
3191     Value *Scalar = ExternalUse.Scalar;
3192     llvm::User *User = ExternalUse.User;
3193 
3194     // Skip users that we already RAUW. This happens when one instruction
3195     // has multiple uses of the same value.
3196     if (User && !is_contained(Scalar->users(), User))
3197       continue;
3198     TreeEntry *E = getTreeEntry(Scalar);
3199     assert(E && "Invalid scalar");
3200     assert(!E->NeedToGather && "Extracting from a gather list");
3201 
3202     Value *Vec = E->VectorizedValue;
3203     assert(Vec && "Can't find vectorizable value");
3204 
3205     Value *Lane = Builder.getInt32(ExternalUse.Lane);
3206     // If User == nullptr, the Scalar is used as extra arg. Generate
3207     // ExtractElement instruction and update the record for this scalar in
3208     // ExternallyUsedValues.
3209     if (!User) {
3210       assert(ExternallyUsedValues.count(Scalar) &&
3211              "Scalar with nullptr as an external user must be registered in "
3212              "ExternallyUsedValues map");
3213       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3214         Builder.SetInsertPoint(VecI->getParent(),
3215                                std::next(VecI->getIterator()));
3216       } else {
3217         Builder.SetInsertPoint(&F->getEntryBlock().front());
3218       }
3219       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3220       Ex = extend(ScalarRoot, Ex, Scalar->getType());
3221       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
3222       auto &Locs = ExternallyUsedValues[Scalar];
3223       ExternallyUsedValues.insert({Ex, Locs});
3224       ExternallyUsedValues.erase(Scalar);
3225       continue;
3226     }
3227 
3228     // Generate extracts for out-of-tree users.
3229     // Find the insertion point for the extractelement lane.
3230     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3231       if (PHINode *PH = dyn_cast<PHINode>(User)) {
3232         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
3233           if (PH->getIncomingValue(i) == Scalar) {
3234             TerminatorInst *IncomingTerminator =
3235                 PH->getIncomingBlock(i)->getTerminator();
3236             if (isa<CatchSwitchInst>(IncomingTerminator)) {
3237               Builder.SetInsertPoint(VecI->getParent(),
3238                                      std::next(VecI->getIterator()));
3239             } else {
3240               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
3241             }
3242             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3243             Ex = extend(ScalarRoot, Ex, Scalar->getType());
3244             CSEBlocks.insert(PH->getIncomingBlock(i));
3245             PH->setOperand(i, Ex);
3246           }
3247         }
3248       } else {
3249         Builder.SetInsertPoint(cast<Instruction>(User));
3250         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3251         Ex = extend(ScalarRoot, Ex, Scalar->getType());
3252         CSEBlocks.insert(cast<Instruction>(User)->getParent());
3253         User->replaceUsesOfWith(Scalar, Ex);
3254      }
3255     } else {
3256       Builder.SetInsertPoint(&F->getEntryBlock().front());
3257       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3258       Ex = extend(ScalarRoot, Ex, Scalar->getType());
3259       CSEBlocks.insert(&F->getEntryBlock());
3260       User->replaceUsesOfWith(Scalar, Ex);
3261     }
3262 
3263     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
3264   }
3265 
3266   // For each vectorized value:
3267   for (TreeEntry &EIdx : VectorizableTree) {
3268     TreeEntry *Entry = &EIdx;
3269 
3270     // No need to handle users of gathered values.
3271     if (Entry->NeedToGather)
3272       continue;
3273 
3274     assert(Entry->VectorizedValue && "Can't find vectorizable value");
3275 
3276     // For each lane:
3277     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3278       Value *Scalar = Entry->Scalars[Lane];
3279 
3280       Type *Ty = Scalar->getType();
3281       if (!Ty->isVoidTy()) {
3282 #ifndef NDEBUG
3283         for (User *U : Scalar->users()) {
3284           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
3285 
3286           // It is legal to replace users in the ignorelist by undef.
3287           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
3288                  "Replacing out-of-tree value with undef");
3289         }
3290 #endif
3291         Value *Undef = UndefValue::get(Ty);
3292         Scalar->replaceAllUsesWith(Undef);
3293       }
3294       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
3295       eraseInstruction(cast<Instruction>(Scalar));
3296     }
3297   }
3298 
3299   Builder.ClearInsertionPoint();
3300 
3301   return VectorizableTree[0].VectorizedValue;
3302 }
3303 
3304 void BoUpSLP::optimizeGatherSequence() {
3305   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
3306         << " gather sequences instructions.\n");
3307   // LICM InsertElementInst sequences.
3308   for (Instruction *it : GatherSeq) {
3309     InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
3310 
3311     if (!Insert)
3312       continue;
3313 
3314     // Check if this block is inside a loop.
3315     Loop *L = LI->getLoopFor(Insert->getParent());
3316     if (!L)
3317       continue;
3318 
3319     // Check if it has a preheader.
3320     BasicBlock *PreHeader = L->getLoopPreheader();
3321     if (!PreHeader)
3322       continue;
3323 
3324     // If the vector or the element that we insert into it are
3325     // instructions that are defined in this basic block then we can't
3326     // hoist this instruction.
3327     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
3328     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
3329     if (CurrVec && L->contains(CurrVec))
3330       continue;
3331     if (NewElem && L->contains(NewElem))
3332       continue;
3333 
3334     // We can hoist this instruction. Move it to the pre-header.
3335     Insert->moveBefore(PreHeader->getTerminator());
3336   }
3337 
3338   // Make a list of all reachable blocks in our CSE queue.
3339   SmallVector<const DomTreeNode *, 8> CSEWorkList;
3340   CSEWorkList.reserve(CSEBlocks.size());
3341   for (BasicBlock *BB : CSEBlocks)
3342     if (DomTreeNode *N = DT->getNode(BB)) {
3343       assert(DT->isReachableFromEntry(N));
3344       CSEWorkList.push_back(N);
3345     }
3346 
3347   // Sort blocks by domination. This ensures we visit a block after all blocks
3348   // dominating it are visited.
3349   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
3350                    [this](const DomTreeNode *A, const DomTreeNode *B) {
3351     return DT->properlyDominates(A, B);
3352   });
3353 
3354   // Perform O(N^2) search over the gather sequences and merge identical
3355   // instructions. TODO: We can further optimize this scan if we split the
3356   // instructions into different buckets based on the insert lane.
3357   SmallVector<Instruction *, 16> Visited;
3358   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
3359     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
3360            "Worklist not sorted properly!");
3361     BasicBlock *BB = (*I)->getBlock();
3362     // For all instructions in blocks containing gather sequences:
3363     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
3364       Instruction *In = &*it++;
3365       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3366         continue;
3367 
3368       // Check if we can replace this instruction with any of the
3369       // visited instructions.
3370       for (Instruction *v : Visited) {
3371         if (In->isIdenticalTo(v) &&
3372             DT->dominates(v->getParent(), In->getParent())) {
3373           In->replaceAllUsesWith(v);
3374           eraseInstruction(In);
3375           In = nullptr;
3376           break;
3377         }
3378       }
3379       if (In) {
3380         assert(!is_contained(Visited, In));
3381         Visited.push_back(In);
3382       }
3383     }
3384   }
3385   CSEBlocks.clear();
3386   GatherSeq.clear();
3387 }
3388 
3389 // Groups the instructions to a bundle (which is then a single scheduling entity)
3390 // and schedules instructions until the bundle gets ready.
3391 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
3392                                                  BoUpSLP *SLP, Value *OpValue) {
3393   if (isa<PHINode>(OpValue))
3394     return true;
3395 
3396   // Initialize the instruction bundle.
3397   Instruction *OldScheduleEnd = ScheduleEnd;
3398   ScheduleData *PrevInBundle = nullptr;
3399   ScheduleData *Bundle = nullptr;
3400   bool ReSchedule = false;
3401   DEBUG(dbgs() << "SLP:  bundle: " << *OpValue << "\n");
3402 
3403   // Make sure that the scheduling region contains all
3404   // instructions of the bundle.
3405   for (Value *V : VL) {
3406     if (!extendSchedulingRegion(V, OpValue))
3407       return false;
3408   }
3409 
3410   for (Value *V : VL) {
3411     ScheduleData *BundleMember = getScheduleData(V);
3412     assert(BundleMember &&
3413            "no ScheduleData for bundle member (maybe not in same basic block)");
3414     if (BundleMember->IsScheduled) {
3415       // A bundle member was scheduled as single instruction before and now
3416       // needs to be scheduled as part of the bundle. We just get rid of the
3417       // existing schedule.
3418       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
3419                    << " was already scheduled\n");
3420       ReSchedule = true;
3421     }
3422     assert(BundleMember->isSchedulingEntity() &&
3423            "bundle member already part of other bundle");
3424     if (PrevInBundle) {
3425       PrevInBundle->NextInBundle = BundleMember;
3426     } else {
3427       Bundle = BundleMember;
3428     }
3429     BundleMember->UnscheduledDepsInBundle = 0;
3430     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3431 
3432     // Group the instructions to a bundle.
3433     BundleMember->FirstInBundle = Bundle;
3434     PrevInBundle = BundleMember;
3435   }
3436   if (ScheduleEnd != OldScheduleEnd) {
3437     // The scheduling region got new instructions at the lower end (or it is a
3438     // new region for the first bundle). This makes it necessary to
3439     // recalculate all dependencies.
3440     // It is seldom that this needs to be done a second time after adding the
3441     // initial bundle to the region.
3442     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3443       doForAllOpcodes(I, [](ScheduleData *SD) {
3444         SD->clearDependencies();
3445       });
3446     }
3447     ReSchedule = true;
3448   }
3449   if (ReSchedule) {
3450     resetSchedule();
3451     initialFillReadyList(ReadyInsts);
3452   }
3453 
3454   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
3455                << BB->getName() << "\n");
3456 
3457   calculateDependencies(Bundle, true, SLP);
3458 
3459   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
3460   // means that there are no cyclic dependencies and we can schedule it.
3461   // Note that's important that we don't "schedule" the bundle yet (see
3462   // cancelScheduling).
3463   while (!Bundle->isReady() && !ReadyInsts.empty()) {
3464 
3465     ScheduleData *pickedSD = ReadyInsts.back();
3466     ReadyInsts.pop_back();
3467 
3468     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3469       schedule(pickedSD, ReadyInsts);
3470     }
3471   }
3472   if (!Bundle->isReady()) {
3473     cancelScheduling(VL, OpValue);
3474     return false;
3475   }
3476   return true;
3477 }
3478 
3479 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
3480                                                 Value *OpValue) {
3481   if (isa<PHINode>(OpValue))
3482     return;
3483 
3484   ScheduleData *Bundle = getScheduleData(OpValue);
3485   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
3486   assert(!Bundle->IsScheduled &&
3487          "Can't cancel bundle which is already scheduled");
3488   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3489          "tried to unbundle something which is not a bundle");
3490 
3491   // Un-bundle: make single instructions out of the bundle.
3492   ScheduleData *BundleMember = Bundle;
3493   while (BundleMember) {
3494     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3495     BundleMember->FirstInBundle = BundleMember;
3496     ScheduleData *Next = BundleMember->NextInBundle;
3497     BundleMember->NextInBundle = nullptr;
3498     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3499     if (BundleMember->UnscheduledDepsInBundle == 0) {
3500       ReadyInsts.insert(BundleMember);
3501     }
3502     BundleMember = Next;
3503   }
3504 }
3505 
3506 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
3507   // Allocate a new ScheduleData for the instruction.
3508   if (ChunkPos >= ChunkSize) {
3509     ScheduleDataChunks.push_back(llvm::make_unique<ScheduleData[]>(ChunkSize));
3510     ChunkPos = 0;
3511   }
3512   return &(ScheduleDataChunks.back()[ChunkPos++]);
3513 }
3514 
3515 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
3516                                                       Value *OpValue) {
3517   if (getScheduleData(V, isOneOf(OpValue, V)))
3518     return true;
3519   Instruction *I = dyn_cast<Instruction>(V);
3520   assert(I && "bundle member must be an instruction");
3521   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3522   auto &&CheckSheduleForI = [this, OpValue](Instruction *I) -> bool {
3523     ScheduleData *ISD = getScheduleData(I);
3524     if (!ISD)
3525       return false;
3526     assert(isInSchedulingRegion(ISD) &&
3527            "ScheduleData not in scheduling region");
3528     ScheduleData *SD = allocateScheduleDataChunks();
3529     SD->Inst = I;
3530     SD->init(SchedulingRegionID, OpValue);
3531     ExtraScheduleDataMap[I][OpValue] = SD;
3532     return true;
3533   };
3534   if (CheckSheduleForI(I))
3535     return true;
3536   if (!ScheduleStart) {
3537     // It's the first instruction in the new region.
3538     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3539     ScheduleStart = I;
3540     ScheduleEnd = I->getNextNode();
3541     if (isOneOf(OpValue, I) != I)
3542       CheckSheduleForI(I);
3543     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3544     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
3545     return true;
3546   }
3547   // Search up and down at the same time, because we don't know if the new
3548   // instruction is above or below the existing scheduling region.
3549   BasicBlock::reverse_iterator UpIter =
3550       ++ScheduleStart->getIterator().getReverse();
3551   BasicBlock::reverse_iterator UpperEnd = BB->rend();
3552   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3553   BasicBlock::iterator LowerEnd = BB->end();
3554   while (true) {
3555     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3556       DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
3557       return false;
3558     }
3559 
3560     if (UpIter != UpperEnd) {
3561       if (&*UpIter == I) {
3562         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3563         ScheduleStart = I;
3564         if (isOneOf(OpValue, I) != I)
3565           CheckSheduleForI(I);
3566         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
3567         return true;
3568       }
3569       UpIter++;
3570     }
3571     if (DownIter != LowerEnd) {
3572       if (&*DownIter == I) {
3573         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3574                          nullptr);
3575         ScheduleEnd = I->getNextNode();
3576         if (isOneOf(OpValue, I) != I)
3577           CheckSheduleForI(I);
3578         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3579         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
3580         return true;
3581       }
3582       DownIter++;
3583     }
3584     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3585            "instruction not found in block");
3586   }
3587   return true;
3588 }
3589 
3590 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3591                                                 Instruction *ToI,
3592                                                 ScheduleData *PrevLoadStore,
3593                                                 ScheduleData *NextLoadStore) {
3594   ScheduleData *CurrentLoadStore = PrevLoadStore;
3595   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3596     ScheduleData *SD = ScheduleDataMap[I];
3597     if (!SD) {
3598       SD = allocateScheduleDataChunks();
3599       ScheduleDataMap[I] = SD;
3600       SD->Inst = I;
3601     }
3602     assert(!isInSchedulingRegion(SD) &&
3603            "new ScheduleData already in scheduling region");
3604     SD->init(SchedulingRegionID, I);
3605 
3606     if (I->mayReadOrWriteMemory()) {
3607       // Update the linked list of memory accessing instructions.
3608       if (CurrentLoadStore) {
3609         CurrentLoadStore->NextLoadStore = SD;
3610       } else {
3611         FirstLoadStoreInRegion = SD;
3612       }
3613       CurrentLoadStore = SD;
3614     }
3615   }
3616   if (NextLoadStore) {
3617     if (CurrentLoadStore)
3618       CurrentLoadStore->NextLoadStore = NextLoadStore;
3619   } else {
3620     LastLoadStoreInRegion = CurrentLoadStore;
3621   }
3622 }
3623 
3624 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3625                                                      bool InsertInReadyList,
3626                                                      BoUpSLP *SLP) {
3627   assert(SD->isSchedulingEntity());
3628 
3629   SmallVector<ScheduleData *, 10> WorkList;
3630   WorkList.push_back(SD);
3631 
3632   while (!WorkList.empty()) {
3633     ScheduleData *SD = WorkList.back();
3634     WorkList.pop_back();
3635 
3636     ScheduleData *BundleMember = SD;
3637     while (BundleMember) {
3638       assert(isInSchedulingRegion(BundleMember));
3639       if (!BundleMember->hasValidDependencies()) {
3640 
3641         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
3642         BundleMember->Dependencies = 0;
3643         BundleMember->resetUnscheduledDeps();
3644 
3645         // Handle def-use chain dependencies.
3646         if (BundleMember->OpValue != BundleMember->Inst) {
3647           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
3648           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3649             BundleMember->Dependencies++;
3650             ScheduleData *DestBundle = UseSD->FirstInBundle;
3651             if (!DestBundle->IsScheduled)
3652               BundleMember->incrementUnscheduledDeps(1);
3653             if (!DestBundle->hasValidDependencies())
3654               WorkList.push_back(DestBundle);
3655           }
3656         } else {
3657           for (User *U : BundleMember->Inst->users()) {
3658             if (isa<Instruction>(U)) {
3659               ScheduleData *UseSD = getScheduleData(U);
3660               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3661                 BundleMember->Dependencies++;
3662                 ScheduleData *DestBundle = UseSD->FirstInBundle;
3663                 if (!DestBundle->IsScheduled)
3664                   BundleMember->incrementUnscheduledDeps(1);
3665                 if (!DestBundle->hasValidDependencies())
3666                   WorkList.push_back(DestBundle);
3667               }
3668             } else {
3669               // I'm not sure if this can ever happen. But we need to be safe.
3670               // This lets the instruction/bundle never be scheduled and
3671               // eventually disable vectorization.
3672               BundleMember->Dependencies++;
3673               BundleMember->incrementUnscheduledDeps(1);
3674             }
3675           }
3676         }
3677 
3678         // Handle the memory dependencies.
3679         ScheduleData *DepDest = BundleMember->NextLoadStore;
3680         if (DepDest) {
3681           Instruction *SrcInst = BundleMember->Inst;
3682           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3683           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3684           unsigned numAliased = 0;
3685           unsigned DistToSrc = 1;
3686 
3687           while (DepDest) {
3688             assert(isInSchedulingRegion(DepDest));
3689 
3690             // We have two limits to reduce the complexity:
3691             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3692             //    SLP->isAliased (which is the expensive part in this loop).
3693             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3694             //    the whole loop (even if the loop is fast, it's quadratic).
3695             //    It's important for the loop break condition (see below) to
3696             //    check this limit even between two read-only instructions.
3697             if (DistToSrc >= MaxMemDepDistance ||
3698                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3699                      (numAliased >= AliasedCheckLimit ||
3700                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3701 
3702               // We increment the counter only if the locations are aliased
3703               // (instead of counting all alias checks). This gives a better
3704               // balance between reduced runtime and accurate dependencies.
3705               numAliased++;
3706 
3707               DepDest->MemoryDependencies.push_back(BundleMember);
3708               BundleMember->Dependencies++;
3709               ScheduleData *DestBundle = DepDest->FirstInBundle;
3710               if (!DestBundle->IsScheduled) {
3711                 BundleMember->incrementUnscheduledDeps(1);
3712               }
3713               if (!DestBundle->hasValidDependencies()) {
3714                 WorkList.push_back(DestBundle);
3715               }
3716             }
3717             DepDest = DepDest->NextLoadStore;
3718 
3719             // Example, explaining the loop break condition: Let's assume our
3720             // starting instruction is i0 and MaxMemDepDistance = 3.
3721             //
3722             //                      +--------v--v--v
3723             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
3724             //             +--------^--^--^
3725             //
3726             // MaxMemDepDistance let us stop alias-checking at i3 and we add
3727             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3728             // Previously we already added dependencies from i3 to i6,i7,i8
3729             // (because of MaxMemDepDistance). As we added a dependency from
3730             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3731             // and we can abort this loop at i6.
3732             if (DistToSrc >= 2 * MaxMemDepDistance)
3733                 break;
3734             DistToSrc++;
3735           }
3736         }
3737       }
3738       BundleMember = BundleMember->NextInBundle;
3739     }
3740     if (InsertInReadyList && SD->isReady()) {
3741       ReadyInsts.push_back(SD);
3742       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
3743     }
3744   }
3745 }
3746 
3747 void BoUpSLP::BlockScheduling::resetSchedule() {
3748   assert(ScheduleStart &&
3749          "tried to reset schedule on block which has not been scheduled");
3750   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3751     doForAllOpcodes(I, [&](ScheduleData *SD) {
3752       assert(isInSchedulingRegion(SD) &&
3753              "ScheduleData not in scheduling region");
3754       SD->IsScheduled = false;
3755       SD->resetUnscheduledDeps();
3756     });
3757   }
3758   ReadyInsts.clear();
3759 }
3760 
3761 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3762   if (!BS->ScheduleStart)
3763     return;
3764 
3765   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3766 
3767   BS->resetSchedule();
3768 
3769   // For the real scheduling we use a more sophisticated ready-list: it is
3770   // sorted by the original instruction location. This lets the final schedule
3771   // be as  close as possible to the original instruction order.
3772   struct ScheduleDataCompare {
3773     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
3774       return SD2->SchedulingPriority < SD1->SchedulingPriority;
3775     }
3776   };
3777   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3778 
3779   // Ensure that all dependency data is updated and fill the ready-list with
3780   // initial instructions.
3781   int Idx = 0;
3782   int NumToSchedule = 0;
3783   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3784        I = I->getNextNode()) {
3785     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
3786       assert(SD->isPartOfBundle() ==
3787                  (getTreeEntry(SD->Inst) != nullptr) &&
3788              "scheduler and vectorizer bundle mismatch");
3789       SD->FirstInBundle->SchedulingPriority = Idx++;
3790       if (SD->isSchedulingEntity()) {
3791         BS->calculateDependencies(SD, false, this);
3792         NumToSchedule++;
3793       }
3794     });
3795   }
3796   BS->initialFillReadyList(ReadyInsts);
3797 
3798   Instruction *LastScheduledInst = BS->ScheduleEnd;
3799 
3800   // Do the "real" scheduling.
3801   while (!ReadyInsts.empty()) {
3802     ScheduleData *picked = *ReadyInsts.begin();
3803     ReadyInsts.erase(ReadyInsts.begin());
3804 
3805     // Move the scheduled instruction(s) to their dedicated places, if not
3806     // there yet.
3807     ScheduleData *BundleMember = picked;
3808     while (BundleMember) {
3809       Instruction *pickedInst = BundleMember->Inst;
3810       if (LastScheduledInst->getNextNode() != pickedInst) {
3811         BS->BB->getInstList().remove(pickedInst);
3812         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3813                                      pickedInst);
3814       }
3815       LastScheduledInst = pickedInst;
3816       BundleMember = BundleMember->NextInBundle;
3817     }
3818 
3819     BS->schedule(picked, ReadyInsts);
3820     NumToSchedule--;
3821   }
3822   assert(NumToSchedule == 0 && "could not schedule all instructions");
3823 
3824   // Avoid duplicate scheduling of the block.
3825   BS->ScheduleStart = nullptr;
3826 }
3827 
3828 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3829   // If V is a store, just return the width of the stored value without
3830   // traversing the expression tree. This is the common case.
3831   if (auto *Store = dyn_cast<StoreInst>(V))
3832     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3833 
3834   // If V is not a store, we can traverse the expression tree to find loads
3835   // that feed it. The type of the loaded value may indicate a more suitable
3836   // width than V's type. We want to base the vector element size on the width
3837   // of memory operations where possible.
3838   SmallVector<Instruction *, 16> Worklist;
3839   SmallPtrSet<Instruction *, 16> Visited;
3840   if (auto *I = dyn_cast<Instruction>(V))
3841     Worklist.push_back(I);
3842 
3843   // Traverse the expression tree in bottom-up order looking for loads. If we
3844   // encounter an instruciton we don't yet handle, we give up.
3845   auto MaxWidth = 0u;
3846   auto FoundUnknownInst = false;
3847   while (!Worklist.empty() && !FoundUnknownInst) {
3848     auto *I = Worklist.pop_back_val();
3849     Visited.insert(I);
3850 
3851     // We should only be looking at scalar instructions here. If the current
3852     // instruction has a vector type, give up.
3853     auto *Ty = I->getType();
3854     if (isa<VectorType>(Ty))
3855       FoundUnknownInst = true;
3856 
3857     // If the current instruction is a load, update MaxWidth to reflect the
3858     // width of the loaded value.
3859     else if (isa<LoadInst>(I))
3860       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3861 
3862     // Otherwise, we need to visit the operands of the instruction. We only
3863     // handle the interesting cases from buildTree here. If an operand is an
3864     // instruction we haven't yet visited, we add it to the worklist.
3865     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3866              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3867       for (Use &U : I->operands())
3868         if (auto *J = dyn_cast<Instruction>(U.get()))
3869           if (!Visited.count(J))
3870             Worklist.push_back(J);
3871     }
3872 
3873     // If we don't yet handle the instruction, give up.
3874     else
3875       FoundUnknownInst = true;
3876   }
3877 
3878   // If we didn't encounter a memory access in the expression tree, or if we
3879   // gave up for some reason, just return the width of V.
3880   if (!MaxWidth || FoundUnknownInst)
3881     return DL->getTypeSizeInBits(V->getType());
3882 
3883   // Otherwise, return the maximum width we found.
3884   return MaxWidth;
3885 }
3886 
3887 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3888 // smaller type with a truncation. We collect the values that will be demoted
3889 // in ToDemote and additional roots that require investigating in Roots.
3890 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3891                                   SmallVectorImpl<Value *> &ToDemote,
3892                                   SmallVectorImpl<Value *> &Roots) {
3893   // We can always demote constants.
3894   if (isa<Constant>(V)) {
3895     ToDemote.push_back(V);
3896     return true;
3897   }
3898 
3899   // If the value is not an instruction in the expression with only one use, it
3900   // cannot be demoted.
3901   auto *I = dyn_cast<Instruction>(V);
3902   if (!I || !I->hasOneUse() || !Expr.count(I))
3903     return false;
3904 
3905   switch (I->getOpcode()) {
3906 
3907   // We can always demote truncations and extensions. Since truncations can
3908   // seed additional demotion, we save the truncated value.
3909   case Instruction::Trunc:
3910     Roots.push_back(I->getOperand(0));
3911   case Instruction::ZExt:
3912   case Instruction::SExt:
3913     break;
3914 
3915   // We can demote certain binary operations if we can demote both of their
3916   // operands.
3917   case Instruction::Add:
3918   case Instruction::Sub:
3919   case Instruction::Mul:
3920   case Instruction::And:
3921   case Instruction::Or:
3922   case Instruction::Xor:
3923     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3924         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3925       return false;
3926     break;
3927 
3928   // We can demote selects if we can demote their true and false values.
3929   case Instruction::Select: {
3930     SelectInst *SI = cast<SelectInst>(I);
3931     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3932         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3933       return false;
3934     break;
3935   }
3936 
3937   // We can demote phis if we can demote all their incoming operands. Note that
3938   // we don't need to worry about cycles since we ensure single use above.
3939   case Instruction::PHI: {
3940     PHINode *PN = cast<PHINode>(I);
3941     for (Value *IncValue : PN->incoming_values())
3942       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3943         return false;
3944     break;
3945   }
3946 
3947   // Otherwise, conservatively give up.
3948   default:
3949     return false;
3950   }
3951 
3952   // Record the value that we can demote.
3953   ToDemote.push_back(V);
3954   return true;
3955 }
3956 
3957 void BoUpSLP::computeMinimumValueSizes() {
3958   // If there are no external uses, the expression tree must be rooted by a
3959   // store. We can't demote in-memory values, so there is nothing to do here.
3960   if (ExternalUses.empty())
3961     return;
3962 
3963   // We only attempt to truncate integer expressions.
3964   auto &TreeRoot = VectorizableTree[0].Scalars;
3965   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3966   if (!TreeRootIT)
3967     return;
3968 
3969   // If the expression is not rooted by a store, these roots should have
3970   // external uses. We will rely on InstCombine to rewrite the expression in
3971   // the narrower type. However, InstCombine only rewrites single-use values.
3972   // This means that if a tree entry other than a root is used externally, it
3973   // must have multiple uses and InstCombine will not rewrite it. The code
3974   // below ensures that only the roots are used externally.
3975   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3976   for (auto &EU : ExternalUses)
3977     if (!Expr.erase(EU.Scalar))
3978       return;
3979   if (!Expr.empty())
3980     return;
3981 
3982   // Collect the scalar values of the vectorizable expression. We will use this
3983   // context to determine which values can be demoted. If we see a truncation,
3984   // we mark it as seeding another demotion.
3985   for (auto &Entry : VectorizableTree)
3986     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3987 
3988   // Ensure the roots of the vectorizable tree don't form a cycle. They must
3989   // have a single external user that is not in the vectorizable tree.
3990   for (auto *Root : TreeRoot)
3991     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3992       return;
3993 
3994   // Conservatively determine if we can actually truncate the roots of the
3995   // expression. Collect the values that can be demoted in ToDemote and
3996   // additional roots that require investigating in Roots.
3997   SmallVector<Value *, 32> ToDemote;
3998   SmallVector<Value *, 4> Roots;
3999   for (auto *Root : TreeRoot)
4000     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
4001       return;
4002 
4003   // The maximum bit width required to represent all the values that can be
4004   // demoted without loss of precision. It would be safe to truncate the roots
4005   // of the expression to this width.
4006   auto MaxBitWidth = 8u;
4007 
4008   // We first check if all the bits of the roots are demanded. If they're not,
4009   // we can truncate the roots to this narrower type.
4010   for (auto *Root : TreeRoot) {
4011     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
4012     MaxBitWidth = std::max<unsigned>(
4013         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
4014   }
4015 
4016   // True if the roots can be zero-extended back to their original type, rather
4017   // than sign-extended. We know that if the leading bits are not demanded, we
4018   // can safely zero-extend. So we initialize IsKnownPositive to True.
4019   bool IsKnownPositive = true;
4020 
4021   // If all the bits of the roots are demanded, we can try a little harder to
4022   // compute a narrower type. This can happen, for example, if the roots are
4023   // getelementptr indices. InstCombine promotes these indices to the pointer
4024   // width. Thus, all their bits are technically demanded even though the
4025   // address computation might be vectorized in a smaller type.
4026   //
4027   // We start by looking at each entry that can be demoted. We compute the
4028   // maximum bit width required to store the scalar by using ValueTracking to
4029   // compute the number of high-order bits we can truncate.
4030   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
4031     MaxBitWidth = 8u;
4032 
4033     // Determine if the sign bit of all the roots is known to be zero. If not,
4034     // IsKnownPositive is set to False.
4035     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
4036       KnownBits Known = computeKnownBits(R, *DL);
4037       return Known.isNonNegative();
4038     });
4039 
4040     // Determine the maximum number of bits required to store the scalar
4041     // values.
4042     for (auto *Scalar : ToDemote) {
4043       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
4044       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
4045       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
4046     }
4047 
4048     // If we can't prove that the sign bit is zero, we must add one to the
4049     // maximum bit width to account for the unknown sign bit. This preserves
4050     // the existing sign bit so we can safely sign-extend the root back to the
4051     // original type. Otherwise, if we know the sign bit is zero, we will
4052     // zero-extend the root instead.
4053     //
4054     // FIXME: This is somewhat suboptimal, as there will be cases where adding
4055     //        one to the maximum bit width will yield a larger-than-necessary
4056     //        type. In general, we need to add an extra bit only if we can't
4057     //        prove that the upper bit of the original type is equal to the
4058     //        upper bit of the proposed smaller type. If these two bits are the
4059     //        same (either zero or one) we know that sign-extending from the
4060     //        smaller type will result in the same value. Here, since we can't
4061     //        yet prove this, we are just making the proposed smaller type
4062     //        larger to ensure correctness.
4063     if (!IsKnownPositive)
4064       ++MaxBitWidth;
4065   }
4066 
4067   // Round MaxBitWidth up to the next power-of-two.
4068   if (!isPowerOf2_64(MaxBitWidth))
4069     MaxBitWidth = NextPowerOf2(MaxBitWidth);
4070 
4071   // If the maximum bit width we compute is less than the with of the roots'
4072   // type, we can proceed with the narrowing. Otherwise, do nothing.
4073   if (MaxBitWidth >= TreeRootIT->getBitWidth())
4074     return;
4075 
4076   // If we can truncate the root, we must collect additional values that might
4077   // be demoted as a result. That is, those seeded by truncations we will
4078   // modify.
4079   while (!Roots.empty())
4080     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
4081 
4082   // Finally, map the values we can demote to the maximum bit with we computed.
4083   for (auto *Scalar : ToDemote)
4084     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
4085 }
4086 
4087 namespace {
4088 
4089 /// The SLPVectorizer Pass.
4090 struct SLPVectorizer : public FunctionPass {
4091   SLPVectorizerPass Impl;
4092 
4093   /// Pass identification, replacement for typeid
4094   static char ID;
4095 
4096   explicit SLPVectorizer() : FunctionPass(ID) {
4097     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
4098   }
4099 
4100   bool doInitialization(Module &M) override {
4101     return false;
4102   }
4103 
4104   bool runOnFunction(Function &F) override {
4105     if (skipFunction(F))
4106       return false;
4107 
4108     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4109     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4110     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
4111     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
4112     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4113     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4114     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4115     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4116     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
4117     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4118 
4119     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4120   }
4121 
4122   void getAnalysisUsage(AnalysisUsage &AU) const override {
4123     FunctionPass::getAnalysisUsage(AU);
4124     AU.addRequired<AssumptionCacheTracker>();
4125     AU.addRequired<ScalarEvolutionWrapperPass>();
4126     AU.addRequired<AAResultsWrapperPass>();
4127     AU.addRequired<TargetTransformInfoWrapperPass>();
4128     AU.addRequired<LoopInfoWrapperPass>();
4129     AU.addRequired<DominatorTreeWrapperPass>();
4130     AU.addRequired<DemandedBitsWrapperPass>();
4131     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4132     AU.addPreserved<LoopInfoWrapperPass>();
4133     AU.addPreserved<DominatorTreeWrapperPass>();
4134     AU.addPreserved<AAResultsWrapperPass>();
4135     AU.addPreserved<GlobalsAAWrapperPass>();
4136     AU.setPreservesCFG();
4137   }
4138 };
4139 
4140 } // end anonymous namespace
4141 
4142 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
4143   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
4144   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
4145   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
4146   auto *AA = &AM.getResult<AAManager>(F);
4147   auto *LI = &AM.getResult<LoopAnalysis>(F);
4148   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
4149   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
4150   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
4151   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4152 
4153   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4154   if (!Changed)
4155     return PreservedAnalyses::all();
4156 
4157   PreservedAnalyses PA;
4158   PA.preserveSet<CFGAnalyses>();
4159   PA.preserve<AAManager>();
4160   PA.preserve<GlobalsAA>();
4161   return PA;
4162 }
4163 
4164 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
4165                                 TargetTransformInfo *TTI_,
4166                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
4167                                 LoopInfo *LI_, DominatorTree *DT_,
4168                                 AssumptionCache *AC_, DemandedBits *DB_,
4169                                 OptimizationRemarkEmitter *ORE_) {
4170   SE = SE_;
4171   TTI = TTI_;
4172   TLI = TLI_;
4173   AA = AA_;
4174   LI = LI_;
4175   DT = DT_;
4176   AC = AC_;
4177   DB = DB_;
4178   DL = &F.getParent()->getDataLayout();
4179 
4180   Stores.clear();
4181   GEPs.clear();
4182   bool Changed = false;
4183 
4184   // If the target claims to have no vector registers don't attempt
4185   // vectorization.
4186   if (!TTI->getNumberOfRegisters(true))
4187     return false;
4188 
4189   // Don't vectorize when the attribute NoImplicitFloat is used.
4190   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
4191     return false;
4192 
4193   DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
4194 
4195   // Use the bottom up slp vectorizer to construct chains that start with
4196   // store instructions.
4197   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
4198 
4199   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
4200   // delete instructions.
4201 
4202   // Scan the blocks in the function in post order.
4203   for (auto BB : post_order(&F.getEntryBlock())) {
4204     collectSeedInstructions(BB);
4205 
4206     // Vectorize trees that end at stores.
4207     if (!Stores.empty()) {
4208       DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
4209                    << " underlying objects.\n");
4210       Changed |= vectorizeStoreChains(R);
4211     }
4212 
4213     // Vectorize trees that end at reductions.
4214     Changed |= vectorizeChainsInBlock(BB, R);
4215 
4216     // Vectorize the index computations of getelementptr instructions. This
4217     // is primarily intended to catch gather-like idioms ending at
4218     // non-consecutive loads.
4219     if (!GEPs.empty()) {
4220       DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
4221                    << " underlying objects.\n");
4222       Changed |= vectorizeGEPIndices(BB, R);
4223     }
4224   }
4225 
4226   if (Changed) {
4227     R.optimizeGatherSequence();
4228     DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
4229     DEBUG(verifyFunction(F));
4230   }
4231   return Changed;
4232 }
4233 
4234 /// \brief Check that the Values in the slice in VL array are still existent in
4235 /// the WeakTrackingVH array.
4236 /// Vectorization of part of the VL array may cause later values in the VL array
4237 /// to become invalid. We track when this has happened in the WeakTrackingVH
4238 /// array.
4239 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
4240                                ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
4241                                unsigned SliceSize) {
4242   VL = VL.slice(SliceBegin, SliceSize);
4243   VH = VH.slice(SliceBegin, SliceSize);
4244   return !std::equal(VL.begin(), VL.end(), VH.begin());
4245 }
4246 
4247 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
4248                                             unsigned VecRegSize) {
4249   unsigned ChainLen = Chain.size();
4250   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
4251         << "\n");
4252   unsigned Sz = R.getVectorElementSize(Chain[0]);
4253   unsigned VF = VecRegSize / Sz;
4254 
4255   if (!isPowerOf2_32(Sz) || VF < 2)
4256     return false;
4257 
4258   // Keep track of values that were deleted by vectorizing in the loop below.
4259   SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
4260 
4261   bool Changed = false;
4262   // Look for profitable vectorizable trees at all offsets, starting at zero.
4263   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
4264     if (i + VF > e)
4265       break;
4266 
4267     // Check that a previous iteration of this loop did not delete the Value.
4268     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
4269       continue;
4270 
4271     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
4272           << "\n");
4273     ArrayRef<Value *> Operands = Chain.slice(i, VF);
4274 
4275     R.buildTree(Operands);
4276     if (R.isTreeTinyAndNotFullyVectorizable())
4277       continue;
4278 
4279     R.computeMinimumValueSizes();
4280 
4281     int Cost = R.getTreeCost();
4282 
4283     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
4284     if (Cost < -SLPCostThreshold) {
4285       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
4286 
4287       using namespace ore;
4288 
4289       R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
4290                                           cast<StoreInst>(Chain[i]))
4291                        << "Stores SLP vectorized with cost " << NV("Cost", Cost)
4292                        << " and with tree size "
4293                        << NV("TreeSize", R.getTreeSize()));
4294 
4295       R.vectorizeTree();
4296 
4297       // Move to the next bundle.
4298       i += VF - 1;
4299       Changed = true;
4300     }
4301   }
4302 
4303   return Changed;
4304 }
4305 
4306 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
4307                                         BoUpSLP &R) {
4308   SetVector<StoreInst *> Heads, Tails;
4309   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
4310 
4311   // We may run into multiple chains that merge into a single chain. We mark the
4312   // stores that we vectorized so that we don't visit the same store twice.
4313   BoUpSLP::ValueSet VectorizedStores;
4314   bool Changed = false;
4315 
4316   // Do a quadratic search on all of the given stores and find
4317   // all of the pairs of stores that follow each other.
4318   SmallVector<unsigned, 16> IndexQueue;
4319   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
4320     IndexQueue.clear();
4321     // If a store has multiple consecutive store candidates, search Stores
4322     // array according to the sequence: from i+1 to e, then from i-1 to 0.
4323     // This is because usually pairing with immediate succeeding or preceding
4324     // candidate create the best chance to find slp vectorization opportunity.
4325     unsigned j = 0;
4326     for (j = i + 1; j < e; ++j)
4327       IndexQueue.push_back(j);
4328     for (j = i; j > 0; --j)
4329       IndexQueue.push_back(j - 1);
4330 
4331     for (auto &k : IndexQueue) {
4332       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
4333         Tails.insert(Stores[k]);
4334         Heads.insert(Stores[i]);
4335         ConsecutiveChain[Stores[i]] = Stores[k];
4336         break;
4337       }
4338     }
4339   }
4340 
4341   // For stores that start but don't end a link in the chain:
4342   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
4343        it != e; ++it) {
4344     if (Tails.count(*it))
4345       continue;
4346 
4347     // We found a store instr that starts a chain. Now follow the chain and try
4348     // to vectorize it.
4349     BoUpSLP::ValueList Operands;
4350     StoreInst *I = *it;
4351     // Collect the chain into a list.
4352     while (Tails.count(I) || Heads.count(I)) {
4353       if (VectorizedStores.count(I))
4354         break;
4355       Operands.push_back(I);
4356       // Move to the next value in the chain.
4357       I = ConsecutiveChain[I];
4358     }
4359 
4360     // FIXME: Is division-by-2 the correct step? Should we assert that the
4361     // register size is a power-of-2?
4362     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4363          Size /= 2) {
4364       if (vectorizeStoreChain(Operands, R, Size)) {
4365         // Mark the vectorized stores so that we don't vectorize them again.
4366         VectorizedStores.insert(Operands.begin(), Operands.end());
4367         Changed = true;
4368         break;
4369       }
4370     }
4371   }
4372 
4373   return Changed;
4374 }
4375 
4376 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4377   // Initialize the collections. We will make a single pass over the block.
4378   Stores.clear();
4379   GEPs.clear();
4380 
4381   // Visit the store and getelementptr instructions in BB and organize them in
4382   // Stores and GEPs according to the underlying objects of their pointer
4383   // operands.
4384   for (Instruction &I : *BB) {
4385     // Ignore store instructions that are volatile or have a pointer operand
4386     // that doesn't point to a scalar type.
4387     if (auto *SI = dyn_cast<StoreInst>(&I)) {
4388       if (!SI->isSimple())
4389         continue;
4390       if (!isValidElementType(SI->getValueOperand()->getType()))
4391         continue;
4392       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4393     }
4394 
4395     // Ignore getelementptr instructions that have more than one index, a
4396     // constant index, or a pointer operand that doesn't point to a scalar
4397     // type.
4398     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4399       auto Idx = GEP->idx_begin()->get();
4400       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4401         continue;
4402       if (!isValidElementType(Idx->getType()))
4403         continue;
4404       if (GEP->getType()->isVectorTy())
4405         continue;
4406       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
4407     }
4408   }
4409 }
4410 
4411 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4412   if (!A || !B)
4413     return false;
4414   Value *VL[] = { A, B };
4415   return tryToVectorizeList(VL, R, None, true);
4416 }
4417 
4418 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4419                                            ArrayRef<Value *> BuildVector,
4420                                            bool AllowReorder) {
4421   if (VL.size() < 2)
4422     return false;
4423 
4424   DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()
4425                << ".\n");
4426 
4427   // Check that all of the parts are scalar instructions of the same type.
4428   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
4429   if (!I0)
4430     return false;
4431 
4432   unsigned Opcode0 = I0->getOpcode();
4433 
4434   unsigned Sz = R.getVectorElementSize(I0);
4435   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4436   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4437   if (MaxVF < 2)
4438     return false;
4439 
4440   for (Value *V : VL) {
4441     Type *Ty = V->getType();
4442     if (!isValidElementType(Ty))
4443       return false;
4444     Instruction *Inst = dyn_cast<Instruction>(V);
4445     if (!Inst || Inst->getOpcode() != Opcode0)
4446       return false;
4447   }
4448 
4449   bool Changed = false;
4450 
4451   // Keep track of values that were deleted by vectorizing in the loop below.
4452   SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4453 
4454   unsigned NextInst = 0, MaxInst = VL.size();
4455   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4456        VF /= 2) {
4457     // No actual vectorization should happen, if number of parts is the same as
4458     // provided vectorization factor (i.e. the scalar type is used for vector
4459     // code during codegen).
4460     auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4461     if (TTI->getNumberOfParts(VecTy) == VF)
4462       continue;
4463     for (unsigned I = NextInst; I < MaxInst; ++I) {
4464       unsigned OpsWidth = 0;
4465 
4466       if (I + VF > MaxInst)
4467         OpsWidth = MaxInst - I;
4468       else
4469         OpsWidth = VF;
4470 
4471       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4472         break;
4473 
4474       // Check that a previous iteration of this loop did not delete the Value.
4475       if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4476         continue;
4477 
4478       DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4479                    << "\n");
4480       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4481 
4482       ArrayRef<Value *> BuildVectorSlice;
4483       if (!BuildVector.empty())
4484         BuildVectorSlice = BuildVector.slice(I, OpsWidth);
4485 
4486       R.buildTree(Ops, BuildVectorSlice);
4487       // TODO: check if we can allow reordering for more cases.
4488       if (AllowReorder && R.shouldReorder()) {
4489         // Conceptually, there is nothing actually preventing us from trying to
4490         // reorder a larger list. In fact, we do exactly this when vectorizing
4491         // reductions. However, at this point, we only expect to get here when
4492         // there are exactly two operations.
4493         assert(Ops.size() == 2);
4494         assert(BuildVectorSlice.empty());
4495         Value *ReorderedOps[] = {Ops[1], Ops[0]};
4496         R.buildTree(ReorderedOps, None);
4497       }
4498       if (R.isTreeTinyAndNotFullyVectorizable())
4499         continue;
4500 
4501       R.computeMinimumValueSizes();
4502       int Cost = R.getTreeCost();
4503 
4504       if (Cost < -SLPCostThreshold) {
4505         DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
4506         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
4507                                             cast<Instruction>(Ops[0]))
4508                          << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4509                          << " and with tree size "
4510                          << ore::NV("TreeSize", R.getTreeSize()));
4511 
4512         Value *VectorizedRoot = R.vectorizeTree();
4513 
4514         // Reconstruct the build vector by extracting the vectorized root. This
4515         // way we handle the case where some elements of the vector are
4516         // undefined.
4517         //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
4518         if (!BuildVectorSlice.empty()) {
4519           // The insert point is the last build vector instruction. The
4520           // vectorized root will precede it. This guarantees that we get an
4521           // instruction. The vectorized tree could have been constant folded.
4522           Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
4523           unsigned VecIdx = 0;
4524           for (auto &V : BuildVectorSlice) {
4525             IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
4526                                         ++BasicBlock::iterator(InsertAfter));
4527             Instruction *I = cast<Instruction>(V);
4528             assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
4529             Instruction *Extract =
4530                 cast<Instruction>(Builder.CreateExtractElement(
4531                     VectorizedRoot, Builder.getInt32(VecIdx++)));
4532             I->setOperand(1, Extract);
4533             I->moveAfter(Extract);
4534             InsertAfter = I;
4535           }
4536         }
4537         // Move to the next bundle.
4538         I += VF - 1;
4539         NextInst = I + 1;
4540         Changed = true;
4541       }
4542     }
4543   }
4544 
4545   return Changed;
4546 }
4547 
4548 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
4549   if (!I)
4550     return false;
4551 
4552   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
4553     return false;
4554 
4555   Value *P = I->getParent();
4556 
4557   // Vectorize in current basic block only.
4558   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4559   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4560   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4561     return false;
4562 
4563   // Try to vectorize V.
4564   if (tryToVectorizePair(Op0, Op1, R))
4565     return true;
4566 
4567   auto *A = dyn_cast<BinaryOperator>(Op0);
4568   auto *B = dyn_cast<BinaryOperator>(Op1);
4569   // Try to skip B.
4570   if (B && B->hasOneUse()) {
4571     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4572     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4573     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4574       return true;
4575     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4576       return true;
4577   }
4578 
4579   // Try to skip A.
4580   if (A && A->hasOneUse()) {
4581     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4582     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4583     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4584       return true;
4585     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4586       return true;
4587   }
4588   return false;
4589 }
4590 
4591 /// \brief Generate a shuffle mask to be used in a reduction tree.
4592 ///
4593 /// \param VecLen The length of the vector to be reduced.
4594 /// \param NumEltsToRdx The number of elements that should be reduced in the
4595 ///        vector.
4596 /// \param IsPairwise Whether the reduction is a pairwise or splitting
4597 ///        reduction. A pairwise reduction will generate a mask of
4598 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
4599 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4600 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
4601 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4602                                    bool IsPairwise, bool IsLeft,
4603                                    IRBuilder<> &Builder) {
4604   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
4605 
4606   SmallVector<Constant *, 32> ShuffleMask(
4607       VecLen, UndefValue::get(Builder.getInt32Ty()));
4608 
4609   if (IsPairwise)
4610     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4611     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4612       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4613   else
4614     // Move the upper half of the vector to the lower half.
4615     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4616       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4617 
4618   return ConstantVector::get(ShuffleMask);
4619 }
4620 
4621 namespace {
4622 
4623 /// Model horizontal reductions.
4624 ///
4625 /// A horizontal reduction is a tree of reduction operations (currently add and
4626 /// fadd) that has operations that can be put into a vector as its leaf.
4627 /// For example, this tree:
4628 ///
4629 /// mul mul mul mul
4630 ///  \  /    \  /
4631 ///   +       +
4632 ///    \     /
4633 ///       +
4634 /// This tree has "mul" as its reduced values and "+" as its reduction
4635 /// operations. A reduction might be feeding into a store or a binary operation
4636 /// feeding a phi.
4637 ///    ...
4638 ///    \  /
4639 ///     +
4640 ///     |
4641 ///  phi +=
4642 ///
4643 ///  Or:
4644 ///    ...
4645 ///    \  /
4646 ///     +
4647 ///     |
4648 ///   *p =
4649 ///
4650 class HorizontalReduction {
4651   SmallVector<Value *, 16> ReductionOps;
4652   SmallVector<Value *, 32> ReducedVals;
4653   // Use map vector to make stable output.
4654   MapVector<Instruction *, Value *> ExtraArgs;
4655 
4656   /// Kind of the reduction data.
4657   enum ReductionKind {
4658     RK_None,       /// Not a reduction.
4659     RK_Arithmetic, /// Binary reduction data.
4660     RK_Min,        /// Minimum reduction data.
4661     RK_UMin,       /// Unsigned minimum reduction data.
4662     RK_Max,        /// Maximum reduction data.
4663     RK_UMax,       /// Unsigned maximum reduction data.
4664   };
4665   /// Contains info about operation, like its opcode, left and right operands.
4666   class OperationData {
4667     /// Opcode of the instruction.
4668     unsigned Opcode = 0;
4669 
4670     /// Left operand of the reduction operation.
4671     Value *LHS = nullptr;
4672 
4673     /// Right operand of the reduction operation.
4674     Value *RHS = nullptr;
4675     /// Kind of the reduction operation.
4676     ReductionKind Kind = RK_None;
4677     /// True if float point min/max reduction has no NaNs.
4678     bool NoNaN = false;
4679 
4680     /// Checks if the reduction operation can be vectorized.
4681     bool isVectorizable() const {
4682       return LHS && RHS &&
4683              // We currently only support adds && min/max reductions.
4684              ((Kind == RK_Arithmetic &&
4685                (Opcode == Instruction::Add || Opcode == Instruction::FAdd)) ||
4686               ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
4687                (Kind == RK_Min || Kind == RK_Max)) ||
4688               (Opcode == Instruction::ICmp &&
4689                (Kind == RK_UMin || Kind == RK_UMax)));
4690     }
4691 
4692   public:
4693     explicit OperationData() = default;
4694 
4695     /// Construction for reduced values. They are identified by opcode only and
4696     /// don't have associated LHS/RHS values.
4697     explicit OperationData(Value *V) : Kind(RK_None) {
4698       if (auto *I = dyn_cast<Instruction>(V))
4699         Opcode = I->getOpcode();
4700     }
4701 
4702     /// Constructor for reduction operations with opcode and its left and
4703     /// right operands.
4704     OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
4705                   bool NoNaN = false)
4706         : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
4707       assert(Kind != RK_None && "One of the reduction operations is expected.");
4708     }
4709     explicit operator bool() const { return Opcode; }
4710 
4711     /// Get the index of the first operand.
4712     unsigned getFirstOperandIndex() const {
4713       assert(!!*this && "The opcode is not set.");
4714       switch (Kind) {
4715       case RK_Min:
4716       case RK_UMin:
4717       case RK_Max:
4718       case RK_UMax:
4719         return 1;
4720       case RK_Arithmetic:
4721       case RK_None:
4722         break;
4723       }
4724       return 0;
4725     }
4726 
4727     /// Total number of operands in the reduction operation.
4728     unsigned getNumberOfOperands() const {
4729       assert(Kind != RK_None && !!*this && LHS && RHS &&
4730              "Expected reduction operation.");
4731       switch (Kind) {
4732       case RK_Arithmetic:
4733         return 2;
4734       case RK_Min:
4735       case RK_UMin:
4736       case RK_Max:
4737       case RK_UMax:
4738         return 3;
4739       case RK_None:
4740         break;
4741       }
4742       llvm_unreachable("Reduction kind is not set");
4743     }
4744 
4745     /// Expected number of uses for reduction operations/reduced values.
4746     unsigned getRequiredNumberOfUses() const {
4747       assert(Kind != RK_None && !!*this && LHS && RHS &&
4748              "Expected reduction operation.");
4749       switch (Kind) {
4750       case RK_Arithmetic:
4751         return 1;
4752       case RK_Min:
4753       case RK_UMin:
4754       case RK_Max:
4755       case RK_UMax:
4756         return 2;
4757       case RK_None:
4758         break;
4759       }
4760       llvm_unreachable("Reduction kind is not set");
4761     }
4762 
4763     /// Checks if instruction is associative and can be vectorized.
4764     bool isAssociative(Instruction *I) const {
4765       assert(Kind != RK_None && *this && LHS && RHS &&
4766              "Expected reduction operation.");
4767       switch (Kind) {
4768       case RK_Arithmetic:
4769         return I->isAssociative();
4770       case RK_Min:
4771       case RK_Max:
4772         return Opcode == Instruction::ICmp ||
4773                cast<Instruction>(I->getOperand(0))->hasUnsafeAlgebra();
4774       case RK_UMin:
4775       case RK_UMax:
4776         assert(Opcode == Instruction::ICmp &&
4777                "Only integer compare operation is expected.");
4778         return true;
4779       case RK_None:
4780         break;
4781       }
4782       llvm_unreachable("Reduction kind is not set");
4783     }
4784 
4785     /// Checks if the reduction operation can be vectorized.
4786     bool isVectorizable(Instruction *I) const {
4787       return isVectorizable() && isAssociative(I);
4788     }
4789 
4790     /// Checks if two operation data are both a reduction op or both a reduced
4791     /// value.
4792     bool operator==(const OperationData &OD) {
4793       assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
4794              "One of the comparing operations is incorrect.");
4795       return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
4796     }
4797     bool operator!=(const OperationData &OD) { return !(*this == OD); }
4798     void clear() {
4799       Opcode = 0;
4800       LHS = nullptr;
4801       RHS = nullptr;
4802       Kind = RK_None;
4803       NoNaN = false;
4804     }
4805 
4806     /// Get the opcode of the reduction operation.
4807     unsigned getOpcode() const {
4808       assert(isVectorizable() && "Expected vectorizable operation.");
4809       return Opcode;
4810     }
4811 
4812     /// Get kind of reduction data.
4813     ReductionKind getKind() const { return Kind; }
4814     Value *getLHS() const { return LHS; }
4815     Value *getRHS() const { return RHS; }
4816     Type *getConditionType() const {
4817       switch (Kind) {
4818       case RK_Arithmetic:
4819         return nullptr;
4820       case RK_Min:
4821       case RK_Max:
4822       case RK_UMin:
4823       case RK_UMax:
4824         return CmpInst::makeCmpResultType(LHS->getType());
4825       case RK_None:
4826         break;
4827       }
4828       llvm_unreachable("Reduction kind is not set");
4829     }
4830 
4831     /// Creates reduction operation with the current opcode.
4832     Value *createOp(IRBuilder<> &Builder, const Twine &Name = "") const {
4833       assert(isVectorizable() &&
4834              "Expected add|fadd or min/max reduction operation.");
4835       Value *Cmp;
4836       switch (Kind) {
4837       case RK_Arithmetic:
4838         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
4839                                    Name);
4840       case RK_Min:
4841         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
4842                                           : Builder.CreateFCmpOLT(LHS, RHS);
4843         break;
4844       case RK_Max:
4845         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
4846                                           : Builder.CreateFCmpOGT(LHS, RHS);
4847         break;
4848       case RK_UMin:
4849         assert(Opcode == Instruction::ICmp && "Expected integer types.");
4850         Cmp = Builder.CreateICmpULT(LHS, RHS);
4851         break;
4852       case RK_UMax:
4853         assert(Opcode == Instruction::ICmp && "Expected integer types.");
4854         Cmp = Builder.CreateICmpUGT(LHS, RHS);
4855         break;
4856       case RK_None:
4857         llvm_unreachable("Unknown reduction operation.");
4858       }
4859       return Builder.CreateSelect(Cmp, LHS, RHS, Name);
4860     }
4861     TargetTransformInfo::ReductionFlags getFlags() const {
4862       TargetTransformInfo::ReductionFlags Flags;
4863       Flags.NoNaN = NoNaN;
4864       switch (Kind) {
4865       case RK_Arithmetic:
4866         break;
4867       case RK_Min:
4868         Flags.IsSigned = Opcode == Instruction::ICmp;
4869         Flags.IsMaxOp = false;
4870         break;
4871       case RK_Max:
4872         Flags.IsSigned = Opcode == Instruction::ICmp;
4873         Flags.IsMaxOp = true;
4874         break;
4875       case RK_UMin:
4876         Flags.IsSigned = false;
4877         Flags.IsMaxOp = false;
4878         break;
4879       case RK_UMax:
4880         Flags.IsSigned = false;
4881         Flags.IsMaxOp = true;
4882         break;
4883       case RK_None:
4884         llvm_unreachable("Reduction kind is not set");
4885       }
4886       return Flags;
4887     }
4888   };
4889 
4890   Instruction *ReductionRoot = nullptr;
4891 
4892   /// The operation data of the reduction operation.
4893   OperationData ReductionData;
4894 
4895   /// The operation data of the values we perform a reduction on.
4896   OperationData ReducedValueData;
4897 
4898   /// Should we model this reduction as a pairwise reduction tree or a tree that
4899   /// splits the vector in halves and adds those halves.
4900   bool IsPairwiseReduction = false;
4901 
4902   /// Checks if the ParentStackElem.first should be marked as a reduction
4903   /// operation with an extra argument or as extra argument itself.
4904   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
4905                     Value *ExtraArg) {
4906     if (ExtraArgs.count(ParentStackElem.first)) {
4907       ExtraArgs[ParentStackElem.first] = nullptr;
4908       // We ran into something like:
4909       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
4910       // The whole ParentStackElem.first should be considered as an extra value
4911       // in this case.
4912       // Do not perform analysis of remaining operands of ParentStackElem.first
4913       // instruction, this whole instruction is an extra argument.
4914       ParentStackElem.second = ParentStackElem.first->getNumOperands();
4915     } else {
4916       // We ran into something like:
4917       // ParentStackElem.first += ... + ExtraArg + ...
4918       ExtraArgs[ParentStackElem.first] = ExtraArg;
4919     }
4920   }
4921 
4922   static OperationData getOperationData(Value *V) {
4923     if (!V)
4924       return OperationData();
4925 
4926     Value *LHS;
4927     Value *RHS;
4928     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
4929       return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
4930                            RK_Arithmetic);
4931     }
4932     if (auto *Select = dyn_cast<SelectInst>(V)) {
4933       // Look for a min/max pattern.
4934       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
4935         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
4936       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
4937         return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
4938       } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
4939                  m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
4940         return OperationData(
4941             Instruction::FCmp, LHS, RHS, RK_Min,
4942             cast<Instruction>(Select->getCondition())->hasNoNaNs());
4943       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
4944         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
4945       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
4946         return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
4947       } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
4948                  m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
4949         return OperationData(
4950             Instruction::FCmp, LHS, RHS, RK_Max,
4951             cast<Instruction>(Select->getCondition())->hasNoNaNs());
4952       }
4953     }
4954     return OperationData(V);
4955   }
4956 
4957 public:
4958   HorizontalReduction() = default;
4959 
4960   /// \brief Try to find a reduction tree.
4961   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
4962     assert((!Phi || is_contained(Phi->operands(), B)) &&
4963            "Thi phi needs to use the binary operator");
4964 
4965     ReductionData = getOperationData(B);
4966 
4967     // We could have a initial reductions that is not an add.
4968     //  r *= v1 + v2 + v3 + v4
4969     // In such a case start looking for a tree rooted in the first '+'.
4970     if (Phi) {
4971       if (ReductionData.getLHS() == Phi) {
4972         Phi = nullptr;
4973         B = dyn_cast<Instruction>(ReductionData.getRHS());
4974         ReductionData = getOperationData(B);
4975       } else if (ReductionData.getRHS() == Phi) {
4976         Phi = nullptr;
4977         B = dyn_cast<Instruction>(ReductionData.getLHS());
4978         ReductionData = getOperationData(B);
4979       }
4980     }
4981 
4982     if (!ReductionData.isVectorizable(B))
4983       return false;
4984 
4985     Type *Ty = B->getType();
4986     if (!isValidElementType(Ty))
4987       return false;
4988 
4989     ReducedValueData.clear();
4990     ReductionRoot = B;
4991 
4992     // Post order traverse the reduction tree starting at B. We only handle true
4993     // trees containing only binary operators.
4994     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
4995     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
4996     const unsigned NUses = ReductionData.getRequiredNumberOfUses();
4997     while (!Stack.empty()) {
4998       Instruction *TreeN = Stack.back().first;
4999       unsigned EdgeToVist = Stack.back().second++;
5000       OperationData OpData = getOperationData(TreeN);
5001       bool IsReducedValue = OpData != ReductionData;
5002 
5003       // Postorder vist.
5004       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
5005         if (IsReducedValue)
5006           ReducedVals.push_back(TreeN);
5007         else {
5008           auto I = ExtraArgs.find(TreeN);
5009           if (I != ExtraArgs.end() && !I->second) {
5010             // Check if TreeN is an extra argument of its parent operation.
5011             if (Stack.size() <= 1) {
5012               // TreeN can't be an extra argument as it is a root reduction
5013               // operation.
5014               return false;
5015             }
5016             // Yes, TreeN is an extra argument, do not add it to a list of
5017             // reduction operations.
5018             // Stack[Stack.size() - 2] always points to the parent operation.
5019             markExtraArg(Stack[Stack.size() - 2], TreeN);
5020             ExtraArgs.erase(TreeN);
5021           } else
5022             ReductionOps.push_back(TreeN);
5023         }
5024         // Retract.
5025         Stack.pop_back();
5026         continue;
5027       }
5028 
5029       // Visit left or right.
5030       Value *NextV = TreeN->getOperand(EdgeToVist);
5031       if (NextV != Phi) {
5032         auto *I = dyn_cast<Instruction>(NextV);
5033         OpData = getOperationData(I);
5034         // Continue analysis if the next operand is a reduction operation or
5035         // (possibly) a reduced value. If the reduced value opcode is not set,
5036         // the first met operation != reduction operation is considered as the
5037         // reduced value class.
5038         if (I && (!ReducedValueData || OpData == ReducedValueData ||
5039                   OpData == ReductionData)) {
5040           // Only handle trees in the current basic block.
5041           if (I->getParent() != B->getParent()) {
5042             // I is an extra argument for TreeN (its parent operation).
5043             markExtraArg(Stack.back(), I);
5044             continue;
5045           }
5046 
5047           // Each tree node needs to have minimal number of users except for the
5048           // ultimate reduction.
5049           if (!I->hasNUses(NUses) && I != B) {
5050             // I is an extra argument for TreeN (its parent operation).
5051             markExtraArg(Stack.back(), I);
5052             continue;
5053           }
5054 
5055           if (OpData == ReductionData) {
5056             // We need to be able to reassociate the reduction operations.
5057             if (!OpData.isAssociative(I)) {
5058               // I is an extra argument for TreeN (its parent operation).
5059               markExtraArg(Stack.back(), I);
5060               continue;
5061             }
5062           } else if (ReducedValueData &&
5063                      ReducedValueData != OpData) {
5064             // Make sure that the opcodes of the operations that we are going to
5065             // reduce match.
5066             // I is an extra argument for TreeN (its parent operation).
5067             markExtraArg(Stack.back(), I);
5068             continue;
5069           } else if (!ReducedValueData)
5070             ReducedValueData = OpData;
5071 
5072           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5073           continue;
5074         }
5075       }
5076       // NextV is an extra argument for TreeN (its parent operation).
5077       markExtraArg(Stack.back(), NextV);
5078     }
5079     return true;
5080   }
5081 
5082   /// \brief Attempt to vectorize the tree found by
5083   /// matchAssociativeReduction.
5084   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
5085     if (ReducedVals.empty())
5086       return false;
5087 
5088     // If there is a sufficient number of reduction values, reduce
5089     // to a nearby power-of-2. Can safely generate oversized
5090     // vectors and rely on the backend to split them to legal sizes.
5091     unsigned NumReducedVals = ReducedVals.size();
5092     if (NumReducedVals < 4)
5093       return false;
5094 
5095     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
5096 
5097     Value *VectorizedTree = nullptr;
5098     IRBuilder<> Builder(ReductionRoot);
5099     FastMathFlags Unsafe;
5100     Unsafe.setUnsafeAlgebra();
5101     Builder.setFastMathFlags(Unsafe);
5102     unsigned i = 0;
5103 
5104     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
5105     // The same extra argument may be used several time, so log each attempt
5106     // to use it.
5107     for (auto &Pair : ExtraArgs)
5108       ExternallyUsedValues[Pair.second].push_back(Pair.first);
5109     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5110       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
5111       V.buildTree(VL, ExternallyUsedValues, ReductionOps);
5112       if (V.shouldReorder()) {
5113         SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
5114         V.buildTree(Reversed, ExternallyUsedValues, ReductionOps);
5115       }
5116       if (V.isTreeTinyAndNotFullyVectorizable())
5117         break;
5118 
5119       V.computeMinimumValueSizes();
5120 
5121       // Estimate cost.
5122       int Cost =
5123           V.getTreeCost() + getReductionCost(TTI, ReducedVals[i], ReduxWidth);
5124       if (Cost >= -SLPCostThreshold)
5125         break;
5126 
5127       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
5128                    << ". (HorRdx)\n");
5129       auto *I0 = cast<Instruction>(VL[0]);
5130       V.getORE()->emit(
5131           OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", I0)
5132           << "Vectorized horizontal reduction with cost "
5133           << ore::NV("Cost", Cost) << " and with tree size "
5134           << ore::NV("TreeSize", V.getTreeSize()));
5135 
5136       // Vectorize a tree.
5137       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
5138       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5139 
5140       // Emit a reduction.
5141       Value *ReducedSubTree =
5142           emitReduction(VectorizedRoot, Builder, ReduxWidth, ReductionOps, TTI);
5143       if (VectorizedTree) {
5144         Builder.SetCurrentDebugLocation(Loc);
5145         OperationData VectReductionData(ReductionData.getOpcode(),
5146                                         VectorizedTree, ReducedSubTree,
5147                                         ReductionData.getKind());
5148         VectorizedTree = VectReductionData.createOp(Builder, "op.rdx");
5149         propagateIRFlags(VectorizedTree, ReductionOps);
5150       } else
5151         VectorizedTree = ReducedSubTree;
5152       i += ReduxWidth;
5153       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
5154     }
5155 
5156     if (VectorizedTree) {
5157       // Finish the reduction.
5158       for (; i < NumReducedVals; ++i) {
5159         auto *I = cast<Instruction>(ReducedVals[i]);
5160         Builder.SetCurrentDebugLocation(I->getDebugLoc());
5161         OperationData VectReductionData(ReductionData.getOpcode(),
5162                                         VectorizedTree, I,
5163                                         ReductionData.getKind());
5164         VectorizedTree = VectReductionData.createOp(Builder);
5165         propagateIRFlags(VectorizedTree, ReductionOps);
5166       }
5167       for (auto &Pair : ExternallyUsedValues) {
5168         assert(!Pair.second.empty() &&
5169                "At least one DebugLoc must be inserted");
5170         // Add each externally used value to the final reduction.
5171         for (auto *I : Pair.second) {
5172           Builder.SetCurrentDebugLocation(I->getDebugLoc());
5173           OperationData VectReductionData(ReductionData.getOpcode(),
5174                                           VectorizedTree, Pair.first,
5175                                           ReductionData.getKind());
5176           VectorizedTree = VectReductionData.createOp(Builder, "op.extra");
5177           propagateIRFlags(VectorizedTree, I);
5178         }
5179       }
5180       // Update users.
5181       ReductionRoot->replaceAllUsesWith(VectorizedTree);
5182     }
5183     return VectorizedTree != nullptr;
5184   }
5185 
5186   unsigned numReductionValues() const {
5187     return ReducedVals.size();
5188   }
5189 
5190 private:
5191   /// \brief Calculate the cost of a reduction.
5192   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
5193                        unsigned ReduxWidth) {
5194     Type *ScalarTy = FirstReducedVal->getType();
5195     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
5196 
5197     int PairwiseRdxCost;
5198     int SplittingRdxCost;
5199     switch (ReductionData.getKind()) {
5200     case RK_Arithmetic:
5201       PairwiseRdxCost =
5202           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5203                                           /*IsPairwiseForm=*/true);
5204       SplittingRdxCost =
5205           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5206                                           /*IsPairwiseForm=*/false);
5207       break;
5208     case RK_Min:
5209     case RK_Max:
5210     case RK_UMin:
5211     case RK_UMax: {
5212       Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
5213       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
5214                         ReductionData.getKind() == RK_UMax;
5215       PairwiseRdxCost =
5216           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5217                                       /*IsPairwiseForm=*/true, IsUnsigned);
5218       SplittingRdxCost =
5219           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5220                                       /*IsPairwiseForm=*/false, IsUnsigned);
5221       break;
5222     }
5223     case RK_None:
5224       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5225     }
5226 
5227     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5228     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5229 
5230     int ScalarReduxCost;
5231     switch (ReductionData.getKind()) {
5232     case RK_Arithmetic:
5233       ScalarReduxCost =
5234           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
5235       break;
5236     case RK_Min:
5237     case RK_Max:
5238     case RK_UMin:
5239     case RK_UMax:
5240       ScalarReduxCost =
5241           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
5242           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
5243                                   CmpInst::makeCmpResultType(ScalarTy));
5244       break;
5245     case RK_None:
5246       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5247     }
5248     ScalarReduxCost *= (ReduxWidth - 1);
5249 
5250     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
5251                  << " for reduction that starts with " << *FirstReducedVal
5252                  << " (It is a "
5253                  << (IsPairwiseReduction ? "pairwise" : "splitting")
5254                  << " reduction)\n");
5255 
5256     return VecReduxCost - ScalarReduxCost;
5257   }
5258 
5259   /// \brief Emit a horizontal reduction of the vectorized value.
5260   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
5261                        unsigned ReduxWidth, ArrayRef<Value *> RedOps,
5262                        const TargetTransformInfo *TTI) {
5263     assert(VectorizedValue && "Need to have a vectorized tree node");
5264     assert(isPowerOf2_32(ReduxWidth) &&
5265            "We only handle power-of-two reductions for now");
5266 
5267     if (!IsPairwiseReduction)
5268       return createSimpleTargetReduction(
5269           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
5270           ReductionData.getFlags(), RedOps);
5271 
5272     Value *TmpVec = VectorizedValue;
5273     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5274       Value *LeftMask =
5275           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
5276       Value *RightMask =
5277           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
5278 
5279       Value *LeftShuf = Builder.CreateShuffleVector(
5280           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
5281       Value *RightShuf = Builder.CreateShuffleVector(
5282           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
5283           "rdx.shuf.r");
5284       OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
5285                                       RightShuf, ReductionData.getKind());
5286       TmpVec = VectReductionData.createOp(Builder, "op.rdx");
5287       propagateIRFlags(TmpVec, RedOps);
5288     }
5289 
5290     // The result is in the first element of the vector.
5291     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
5292   }
5293 };
5294 
5295 } // end anonymous namespace
5296 
5297 /// \brief Recognize construction of vectors like
5298 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
5299 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
5300 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
5301 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
5302 ///  starting from the last insertelement instruction.
5303 ///
5304 /// Returns true if it matches
5305 ///
5306 static bool findBuildVector(InsertElementInst *LastInsertElem,
5307                             SmallVectorImpl<Value *> &BuildVector,
5308                             SmallVectorImpl<Value *> &BuildVectorOpds) {
5309   Value *V = nullptr;
5310   do {
5311     BuildVector.push_back(LastInsertElem);
5312     BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
5313     V = LastInsertElem->getOperand(0);
5314     if (isa<UndefValue>(V))
5315       break;
5316     LastInsertElem = dyn_cast<InsertElementInst>(V);
5317     if (!LastInsertElem || !LastInsertElem->hasOneUse())
5318       return false;
5319   } while (true);
5320   std::reverse(BuildVector.begin(), BuildVector.end());
5321   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5322   return true;
5323 }
5324 
5325 /// \brief Like findBuildVector, but looks for construction of aggregate.
5326 ///
5327 /// \return true if it matches.
5328 static bool findBuildAggregate(InsertValueInst *IV,
5329                                SmallVectorImpl<Value *> &BuildVector,
5330                                SmallVectorImpl<Value *> &BuildVectorOpds) {
5331   Value *V;
5332   do {
5333     BuildVector.push_back(IV);
5334     BuildVectorOpds.push_back(IV->getInsertedValueOperand());
5335     V = IV->getAggregateOperand();
5336     if (isa<UndefValue>(V))
5337       break;
5338     IV = dyn_cast<InsertValueInst>(V);
5339     if (!IV || !IV->hasOneUse())
5340       return false;
5341   } while (true);
5342   std::reverse(BuildVector.begin(), BuildVector.end());
5343   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5344   return true;
5345 }
5346 
5347 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
5348   return V->getType() < V2->getType();
5349 }
5350 
5351 /// \brief Try and get a reduction value from a phi node.
5352 ///
5353 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
5354 /// if they come from either \p ParentBB or a containing loop latch.
5355 ///
5356 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
5357 /// if not possible.
5358 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
5359                                 BasicBlock *ParentBB, LoopInfo *LI) {
5360   // There are situations where the reduction value is not dominated by the
5361   // reduction phi. Vectorizing such cases has been reported to cause
5362   // miscompiles. See PR25787.
5363   auto DominatedReduxValue = [&](Value *R) {
5364     return (
5365         dyn_cast<Instruction>(R) &&
5366         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
5367   };
5368 
5369   Value *Rdx = nullptr;
5370 
5371   // Return the incoming value if it comes from the same BB as the phi node.
5372   if (P->getIncomingBlock(0) == ParentBB) {
5373     Rdx = P->getIncomingValue(0);
5374   } else if (P->getIncomingBlock(1) == ParentBB) {
5375     Rdx = P->getIncomingValue(1);
5376   }
5377 
5378   if (Rdx && DominatedReduxValue(Rdx))
5379     return Rdx;
5380 
5381   // Otherwise, check whether we have a loop latch to look at.
5382   Loop *BBL = LI->getLoopFor(ParentBB);
5383   if (!BBL)
5384     return nullptr;
5385   BasicBlock *BBLatch = BBL->getLoopLatch();
5386   if (!BBLatch)
5387     return nullptr;
5388 
5389   // There is a loop latch, return the incoming value if it comes from
5390   // that. This reduction pattern occasionally turns up.
5391   if (P->getIncomingBlock(0) == BBLatch) {
5392     Rdx = P->getIncomingValue(0);
5393   } else if (P->getIncomingBlock(1) == BBLatch) {
5394     Rdx = P->getIncomingValue(1);
5395   }
5396 
5397   if (Rdx && DominatedReduxValue(Rdx))
5398     return Rdx;
5399 
5400   return nullptr;
5401 }
5402 
5403 /// Attempt to reduce a horizontal reduction.
5404 /// If it is legal to match a horizontal reduction feeding the phi node \a P
5405 /// with reduction operators \a Root (or one of its operands) in a basic block
5406 /// \a BB, then check if it can be done. If horizontal reduction is not found
5407 /// and root instruction is a binary operation, vectorization of the operands is
5408 /// attempted.
5409 /// \returns true if a horizontal reduction was matched and reduced or operands
5410 /// of one of the binary instruction were vectorized.
5411 /// \returns false if a horizontal reduction was not matched (or not possible)
5412 /// or no vectorization of any binary operation feeding \a Root instruction was
5413 /// performed.
5414 static bool tryToVectorizeHorReductionOrInstOperands(
5415     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
5416     TargetTransformInfo *TTI,
5417     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
5418   if (!ShouldVectorizeHor)
5419     return false;
5420 
5421   if (!Root)
5422     return false;
5423 
5424   if (Root->getParent() != BB || isa<PHINode>(Root))
5425     return false;
5426   // Start analysis starting from Root instruction. If horizontal reduction is
5427   // found, try to vectorize it. If it is not a horizontal reduction or
5428   // vectorization is not possible or not effective, and currently analyzed
5429   // instruction is a binary operation, try to vectorize the operands, using
5430   // pre-order DFS traversal order. If the operands were not vectorized, repeat
5431   // the same procedure considering each operand as a possible root of the
5432   // horizontal reduction.
5433   // Interrupt the process if the Root instruction itself was vectorized or all
5434   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
5435   SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
5436   SmallSet<Value *, 8> VisitedInstrs;
5437   bool Res = false;
5438   while (!Stack.empty()) {
5439     Value *V;
5440     unsigned Level;
5441     std::tie(V, Level) = Stack.pop_back_val();
5442     if (!V)
5443       continue;
5444     auto *Inst = dyn_cast<Instruction>(V);
5445     if (!Inst)
5446       continue;
5447     auto *BI = dyn_cast<BinaryOperator>(Inst);
5448     auto *SI = dyn_cast<SelectInst>(Inst);
5449     if (BI || SI) {
5450       HorizontalReduction HorRdx;
5451       if (HorRdx.matchAssociativeReduction(P, Inst)) {
5452         if (HorRdx.tryToReduce(R, TTI)) {
5453           Res = true;
5454           // Set P to nullptr to avoid re-analysis of phi node in
5455           // matchAssociativeReduction function unless this is the root node.
5456           P = nullptr;
5457           continue;
5458         }
5459       }
5460       if (P && BI) {
5461         Inst = dyn_cast<Instruction>(BI->getOperand(0));
5462         if (Inst == P)
5463           Inst = dyn_cast<Instruction>(BI->getOperand(1));
5464         if (!Inst) {
5465           // Set P to nullptr to avoid re-analysis of phi node in
5466           // matchAssociativeReduction function unless this is the root node.
5467           P = nullptr;
5468           continue;
5469         }
5470       }
5471     }
5472     // Set P to nullptr to avoid re-analysis of phi node in
5473     // matchAssociativeReduction function unless this is the root node.
5474     P = nullptr;
5475     if (Vectorize(Inst, R)) {
5476       Res = true;
5477       continue;
5478     }
5479 
5480     // Try to vectorize operands.
5481     // Continue analysis for the instruction from the same basic block only to
5482     // save compile time.
5483     if (++Level < RecursionMaxDepth)
5484       for (auto *Op : Inst->operand_values())
5485         if (VisitedInstrs.insert(Op).second)
5486           if (auto *I = dyn_cast<Instruction>(Op))
5487             if (!isa<PHINode>(I) && I->getParent() == BB)
5488               Stack.emplace_back(Op, Level);
5489   }
5490   return Res;
5491 }
5492 
5493 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
5494                                                  BasicBlock *BB, BoUpSLP &R,
5495                                                  TargetTransformInfo *TTI) {
5496   if (!V)
5497     return false;
5498   auto *I = dyn_cast<Instruction>(V);
5499   if (!I)
5500     return false;
5501 
5502   if (!isa<BinaryOperator>(I))
5503     P = nullptr;
5504   // Try to match and vectorize a horizontal reduction.
5505   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
5506     return tryToVectorize(I, R);
5507   };
5508   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
5509                                                   ExtraVectorization);
5510 }
5511 
5512 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
5513                                                  BasicBlock *BB, BoUpSLP &R) {
5514   const DataLayout &DL = BB->getModule()->getDataLayout();
5515   if (!R.canMapToVector(IVI->getType(), DL))
5516     return false;
5517 
5518   SmallVector<Value *, 16> BuildVector;
5519   SmallVector<Value *, 16> BuildVectorOpds;
5520   if (!findBuildAggregate(IVI, BuildVector, BuildVectorOpds))
5521     return false;
5522 
5523   DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
5524   return tryToVectorizeList(BuildVectorOpds, R, BuildVector, false);
5525 }
5526 
5527 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
5528                                                    BasicBlock *BB, BoUpSLP &R) {
5529   SmallVector<Value *, 16> BuildVector;
5530   SmallVector<Value *, 16> BuildVectorOpds;
5531   if (!findBuildVector(IEI, BuildVector, BuildVectorOpds))
5532     return false;
5533 
5534   // Vectorize starting with the build vector operands ignoring the BuildVector
5535   // instructions for the purpose of scheduling and user extraction.
5536   return tryToVectorizeList(BuildVectorOpds, R, BuildVector);
5537 }
5538 
5539 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
5540                                          BoUpSLP &R) {
5541   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
5542     return true;
5543 
5544   bool OpsChanged = false;
5545   for (int Idx = 0; Idx < 2; ++Idx) {
5546     OpsChanged |=
5547         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
5548   }
5549   return OpsChanged;
5550 }
5551 
5552 bool SLPVectorizerPass::vectorizeSimpleInstructions(
5553     SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
5554   bool OpsChanged = false;
5555   for (auto &VH : reverse(Instructions)) {
5556     auto *I = dyn_cast_or_null<Instruction>(VH);
5557     if (!I)
5558       continue;
5559     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
5560       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
5561     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
5562       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
5563     else if (auto *CI = dyn_cast<CmpInst>(I))
5564       OpsChanged |= vectorizeCmpInst(CI, BB, R);
5565   }
5566   Instructions.clear();
5567   return OpsChanged;
5568 }
5569 
5570 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
5571   bool Changed = false;
5572   SmallVector<Value *, 4> Incoming;
5573   SmallSet<Value *, 16> VisitedInstrs;
5574 
5575   bool HaveVectorizedPhiNodes = true;
5576   while (HaveVectorizedPhiNodes) {
5577     HaveVectorizedPhiNodes = false;
5578 
5579     // Collect the incoming values from the PHIs.
5580     Incoming.clear();
5581     for (Instruction &I : *BB) {
5582       PHINode *P = dyn_cast<PHINode>(&I);
5583       if (!P)
5584         break;
5585 
5586       if (!VisitedInstrs.count(P))
5587         Incoming.push_back(P);
5588     }
5589 
5590     // Sort by type.
5591     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
5592 
5593     // Try to vectorize elements base on their type.
5594     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
5595                                            E = Incoming.end();
5596          IncIt != E;) {
5597 
5598       // Look for the next elements with the same type.
5599       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
5600       while (SameTypeIt != E &&
5601              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
5602         VisitedInstrs.insert(*SameTypeIt);
5603         ++SameTypeIt;
5604       }
5605 
5606       // Try to vectorize them.
5607       unsigned NumElts = (SameTypeIt - IncIt);
5608       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
5609       // The order in which the phi nodes appear in the program does not matter.
5610       // So allow tryToVectorizeList to reorder them if it is beneficial. This
5611       // is done when there are exactly two elements since tryToVectorizeList
5612       // asserts that there are only two values when AllowReorder is true.
5613       bool AllowReorder = NumElts == 2;
5614       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
5615                                             None, AllowReorder)) {
5616         // Success start over because instructions might have been changed.
5617         HaveVectorizedPhiNodes = true;
5618         Changed = true;
5619         break;
5620       }
5621 
5622       // Start over at the next instruction of a different type (or the end).
5623       IncIt = SameTypeIt;
5624     }
5625   }
5626 
5627   VisitedInstrs.clear();
5628 
5629   SmallVector<WeakVH, 8> PostProcessInstructions;
5630   SmallDenseSet<Instruction *, 4> KeyNodes;
5631   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
5632     // We may go through BB multiple times so skip the one we have checked.
5633     if (!VisitedInstrs.insert(&*it).second) {
5634       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
5635           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
5636         // We would like to start over since some instructions are deleted
5637         // and the iterator may become invalid value.
5638         Changed = true;
5639         it = BB->begin();
5640         e = BB->end();
5641       }
5642       continue;
5643     }
5644 
5645     if (isa<DbgInfoIntrinsic>(it))
5646       continue;
5647 
5648     // Try to vectorize reductions that use PHINodes.
5649     if (PHINode *P = dyn_cast<PHINode>(it)) {
5650       // Check that the PHI is a reduction PHI.
5651       if (P->getNumIncomingValues() != 2)
5652         return Changed;
5653 
5654       // Try to match and vectorize a horizontal reduction.
5655       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
5656                                    TTI)) {
5657         Changed = true;
5658         it = BB->begin();
5659         e = BB->end();
5660         continue;
5661       }
5662       continue;
5663     }
5664 
5665     // Ran into an instruction without users, like terminator, or function call
5666     // with ignored return value, store. Ignore unused instructions (basing on
5667     // instruction type, except for CallInst and InvokeInst).
5668     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
5669                             isa<InvokeInst>(it))) {
5670       KeyNodes.insert(&*it);
5671       bool OpsChanged = false;
5672       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
5673         for (auto *V : it->operand_values()) {
5674           // Try to match and vectorize a horizontal reduction.
5675           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
5676         }
5677       }
5678       // Start vectorization of post-process list of instructions from the
5679       // top-tree instructions to try to vectorize as many instructions as
5680       // possible.
5681       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
5682       if (OpsChanged) {
5683         // We would like to start over since some instructions are deleted
5684         // and the iterator may become invalid value.
5685         Changed = true;
5686         it = BB->begin();
5687         e = BB->end();
5688         continue;
5689       }
5690     }
5691 
5692     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
5693         isa<InsertValueInst>(it))
5694       PostProcessInstructions.push_back(&*it);
5695 
5696   }
5697 
5698   return Changed;
5699 }
5700 
5701 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
5702   auto Changed = false;
5703   for (auto &Entry : GEPs) {
5704     // If the getelementptr list has fewer than two elements, there's nothing
5705     // to do.
5706     if (Entry.second.size() < 2)
5707       continue;
5708 
5709     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
5710                  << Entry.second.size() << ".\n");
5711 
5712     // We process the getelementptr list in chunks of 16 (like we do for
5713     // stores) to minimize compile-time.
5714     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
5715       auto Len = std::min<unsigned>(BE - BI, 16);
5716       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
5717 
5718       // Initialize a set a candidate getelementptrs. Note that we use a
5719       // SetVector here to preserve program order. If the index computations
5720       // are vectorizable and begin with loads, we want to minimize the chance
5721       // of having to reorder them later.
5722       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
5723 
5724       // Some of the candidates may have already been vectorized after we
5725       // initially collected them. If so, the WeakTrackingVHs will have
5726       // nullified the
5727       // values, so remove them from the set of candidates.
5728       Candidates.remove(nullptr);
5729 
5730       // Remove from the set of candidates all pairs of getelementptrs with
5731       // constant differences. Such getelementptrs are likely not good
5732       // candidates for vectorization in a bottom-up phase since one can be
5733       // computed from the other. We also ensure all candidate getelementptr
5734       // indices are unique.
5735       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
5736         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
5737         if (!Candidates.count(GEPI))
5738           continue;
5739         auto *SCEVI = SE->getSCEV(GEPList[I]);
5740         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
5741           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
5742           auto *SCEVJ = SE->getSCEV(GEPList[J]);
5743           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
5744             Candidates.remove(GEPList[I]);
5745             Candidates.remove(GEPList[J]);
5746           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
5747             Candidates.remove(GEPList[J]);
5748           }
5749         }
5750       }
5751 
5752       // We break out of the above computation as soon as we know there are
5753       // fewer than two candidates remaining.
5754       if (Candidates.size() < 2)
5755         continue;
5756 
5757       // Add the single, non-constant index of each candidate to the bundle. We
5758       // ensured the indices met these constraints when we originally collected
5759       // the getelementptrs.
5760       SmallVector<Value *, 16> Bundle(Candidates.size());
5761       auto BundleIndex = 0u;
5762       for (auto *V : Candidates) {
5763         auto *GEP = cast<GetElementPtrInst>(V);
5764         auto *GEPIdx = GEP->idx_begin()->get();
5765         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
5766         Bundle[BundleIndex++] = GEPIdx;
5767       }
5768 
5769       // Try and vectorize the indices. We are currently only interested in
5770       // gather-like cases of the form:
5771       //
5772       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
5773       //
5774       // where the loads of "a", the loads of "b", and the subtractions can be
5775       // performed in parallel. It's likely that detecting this pattern in a
5776       // bottom-up phase will be simpler and less costly than building a
5777       // full-blown top-down phase beginning at the consecutive loads.
5778       Changed |= tryToVectorizeList(Bundle, R);
5779     }
5780   }
5781   return Changed;
5782 }
5783 
5784 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
5785   bool Changed = false;
5786   // Attempt to sort and vectorize each of the store-groups.
5787   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
5788        ++it) {
5789     if (it->second.size() < 2)
5790       continue;
5791 
5792     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
5793           << it->second.size() << ".\n");
5794 
5795     // Process the stores in chunks of 16.
5796     // TODO: The limit of 16 inhibits greater vectorization factors.
5797     //       For example, AVX2 supports v32i8. Increasing this limit, however,
5798     //       may cause a significant compile-time increase.
5799     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
5800       unsigned Len = std::min<unsigned>(CE - CI, 16);
5801       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
5802     }
5803   }
5804   return Changed;
5805 }
5806 
5807 char SLPVectorizer::ID = 0;
5808 
5809 static const char lv_name[] = "SLP Vectorizer";
5810 
5811 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
5812 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5813 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5814 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5815 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5816 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5817 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
5818 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
5819 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
5820 
5821 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
5822