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