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