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