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