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