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