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