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