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