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