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