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