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