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