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