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/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/CodeMetrics.h"
37 #include "llvm/Analysis/DemandedBits.h"
38 #include "llvm/Analysis/GlobalsModRef.h"
39 #include "llvm/Analysis/LoopAccessAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryLocation.h"
42 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
43 #include "llvm/Analysis/ScalarEvolution.h"
44 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
45 #include "llvm/Analysis/TargetLibraryInfo.h"
46 #include "llvm/Analysis/TargetTransformInfo.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Analysis/VectorUtils.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/Constant.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/IRBuilder.h"
59 #include "llvm/IR/InstrTypes.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/Intrinsics.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/NoFolder.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PassManager.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/Pass.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/DOTGraphTraits.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/GraphWriter.h"
83 #include "llvm/Support/KnownBits.h"
84 #include "llvm/Support/MathExtras.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Transforms/Utils/LoopUtils.h"
87 #include "llvm/Transforms/Vectorize.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstdint>
91 #include <iterator>
92 #include <memory>
93 #include <set>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 #include <vector>
98 
99 using namespace llvm;
100 using namespace llvm::PatternMatch;
101 using namespace slpvectorizer;
102 
103 #define SV_NAME "slp-vectorizer"
104 #define DEBUG_TYPE "SLP"
105 
106 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
107 
108 cl::opt<bool>
109     llvm::RunSLPVectorization("vectorize-slp", cl::init(false), cl::Hidden,
110                               cl::desc("Run the SLP vectorization passes"));
111 
112 static cl::opt<int>
113     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
114                      cl::desc("Only vectorize if you gain more than this "
115                               "number "));
116 
117 static cl::opt<bool>
118 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
119                    cl::desc("Attempt to vectorize horizontal reductions"));
120 
121 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
122     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
123     cl::desc(
124         "Attempt to vectorize horizontal reductions feeding into a store"));
125 
126 static cl::opt<int>
127 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
128     cl::desc("Attempt to vectorize for this register size in bits"));
129 
130 /// Limits the size of scheduling regions in a block.
131 /// It avoid long compile times for _very_ large blocks where vector
132 /// instructions are spread over a wide range.
133 /// This limit is way higher than needed by real-world functions.
134 static cl::opt<int>
135 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
136     cl::desc("Limit the size of the SLP scheduling region per block"));
137 
138 static cl::opt<int> MinVectorRegSizeOption(
139     "slp-min-reg-size", cl::init(128), cl::Hidden,
140     cl::desc("Attempt to vectorize for this register size in bits"));
141 
142 static cl::opt<unsigned> RecursionMaxDepth(
143     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
144     cl::desc("Limit the recursion depth when building a vectorizable tree"));
145 
146 static cl::opt<unsigned> MinTreeSize(
147     "slp-min-tree-size", cl::init(3), cl::Hidden,
148     cl::desc("Only vectorize small trees if they are fully vectorizable"));
149 
150 static cl::opt<bool>
151     ViewSLPTree("view-slp-tree", cl::Hidden,
152                 cl::desc("Display the SLP trees with Graphviz"));
153 
154 // Limit the number of alias checks. The limit is chosen so that
155 // it has no negative effect on the llvm benchmarks.
156 static const unsigned AliasedCheckLimit = 10;
157 
158 // Another limit for the alias checks: The maximum distance between load/store
159 // instructions where alias checks are done.
160 // This limit is useful for very large basic blocks.
161 static const unsigned MaxMemDepDistance = 160;
162 
163 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
164 /// regions to be handled.
165 static const int MinScheduleRegionSize = 16;
166 
167 /// Predicate for the element types that the SLP vectorizer supports.
168 ///
169 /// The most important thing to filter here are types which are invalid in LLVM
170 /// vectors. We also filter target specific types which have absolutely no
171 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
172 /// avoids spending time checking the cost model and realizing that they will
173 /// be inevitably scalarized.
174 static bool isValidElementType(Type *Ty) {
175   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
176          !Ty->isPPC_FP128Ty();
177 }
178 
179 /// \returns true if all of the instructions in \p VL are in the same block or
180 /// false otherwise.
181 static bool allSameBlock(ArrayRef<Value *> VL) {
182   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
183   if (!I0)
184     return false;
185   BasicBlock *BB = I0->getParent();
186   for (int i = 1, e = VL.size(); i < e; i++) {
187     Instruction *I = dyn_cast<Instruction>(VL[i]);
188     if (!I)
189       return false;
190 
191     if (BB != I->getParent())
192       return false;
193   }
194   return true;
195 }
196 
197 /// \returns True if all of the values in \p VL are constants (but not
198 /// globals/constant expressions).
199 static bool allConstant(ArrayRef<Value *> VL) {
200   // Constant expressions and globals can't be vectorized like normal integer/FP
201   // constants.
202   for (Value *i : VL)
203     if (!isa<Constant>(i) || isa<ConstantExpr>(i) || isa<GlobalValue>(i))
204       return false;
205   return true;
206 }
207 
208 /// \returns True if all of the values in \p VL are identical.
209 static bool isSplat(ArrayRef<Value *> VL) {
210   for (unsigned i = 1, e = VL.size(); i < e; ++i)
211     if (VL[i] != VL[0])
212       return false;
213   return true;
214 }
215 
216 /// \returns True if \p I is commutative, handles CmpInst as well as Instruction.
217 static bool isCommutative(Instruction *I) {
218   if (auto *IC = dyn_cast<CmpInst>(I))
219     return IC->isCommutative();
220   return I->isCommutative();
221 }
222 
223 /// Checks if the vector of instructions can be represented as a shuffle, like:
224 /// %x0 = extractelement <4 x i8> %x, i32 0
225 /// %x3 = extractelement <4 x i8> %x, i32 3
226 /// %y1 = extractelement <4 x i8> %y, i32 1
227 /// %y2 = extractelement <4 x i8> %y, i32 2
228 /// %x0x0 = mul i8 %x0, %x0
229 /// %x3x3 = mul i8 %x3, %x3
230 /// %y1y1 = mul i8 %y1, %y1
231 /// %y2y2 = mul i8 %y2, %y2
232 /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
233 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
234 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
235 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
236 /// ret <4 x i8> %ins4
237 /// can be transformed into:
238 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
239 ///                                                         i32 6>
240 /// %2 = mul <4 x i8> %1, %1
241 /// ret <4 x i8> %2
242 /// We convert this initially to something like:
243 /// %x0 = extractelement <4 x i8> %x, i32 0
244 /// %x3 = extractelement <4 x i8> %x, i32 3
245 /// %y1 = extractelement <4 x i8> %y, i32 1
246 /// %y2 = extractelement <4 x i8> %y, i32 2
247 /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
248 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
249 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
250 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
251 /// %5 = mul <4 x i8> %4, %4
252 /// %6 = extractelement <4 x i8> %5, i32 0
253 /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
254 /// %7 = extractelement <4 x i8> %5, i32 1
255 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
256 /// %8 = extractelement <4 x i8> %5, i32 2
257 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
258 /// %9 = extractelement <4 x i8> %5, i32 3
259 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
260 /// ret <4 x i8> %ins4
261 /// InstCombiner transforms this into a shuffle and vector mul
262 /// TODO: Can we split off and reuse the shuffle mask detection from
263 /// TargetTransformInfo::getInstructionThroughput?
264 static Optional<TargetTransformInfo::ShuffleKind>
265 isShuffle(ArrayRef<Value *> VL) {
266   auto *EI0 = cast<ExtractElementInst>(VL[0]);
267   unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
268   Value *Vec1 = nullptr;
269   Value *Vec2 = nullptr;
270   enum ShuffleMode { Unknown, Select, Permute };
271   ShuffleMode CommonShuffleMode = Unknown;
272   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
273     auto *EI = cast<ExtractElementInst>(VL[I]);
274     auto *Vec = EI->getVectorOperand();
275     // All vector operands must have the same number of vector elements.
276     if (Vec->getType()->getVectorNumElements() != Size)
277       return None;
278     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
279     if (!Idx)
280       return None;
281     // Undefined behavior if Idx is negative or >= Size.
282     if (Idx->getValue().uge(Size))
283       continue;
284     unsigned IntIdx = Idx->getValue().getZExtValue();
285     // We can extractelement from undef vector.
286     if (isa<UndefValue>(Vec))
287       continue;
288     // For correct shuffling we have to have at most 2 different vector operands
289     // in all extractelement instructions.
290     if (!Vec1 || Vec1 == Vec)
291       Vec1 = Vec;
292     else if (!Vec2 || Vec2 == Vec)
293       Vec2 = Vec;
294     else
295       return None;
296     if (CommonShuffleMode == Permute)
297       continue;
298     // If the extract index is not the same as the operation number, it is a
299     // permutation.
300     if (IntIdx != I) {
301       CommonShuffleMode = Permute;
302       continue;
303     }
304     CommonShuffleMode = Select;
305   }
306   // If we're not crossing lanes in different vectors, consider it as blending.
307   if (CommonShuffleMode == Select && Vec2)
308     return TargetTransformInfo::SK_Select;
309   // If Vec2 was never used, we have a permutation of a single vector, otherwise
310   // we have permutation of 2 vectors.
311   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
312               : TargetTransformInfo::SK_PermuteSingleSrc;
313 }
314 
315 namespace {
316 
317 /// Main data required for vectorization of instructions.
318 struct InstructionsState {
319   /// The very first instruction in the list with the main opcode.
320   Value *OpValue = nullptr;
321 
322   /// The main/alternate instruction.
323   Instruction *MainOp = nullptr;
324   Instruction *AltOp = nullptr;
325 
326   /// The main/alternate opcodes for the list of instructions.
327   unsigned getOpcode() const {
328     return MainOp ? MainOp->getOpcode() : 0;
329   }
330 
331   unsigned getAltOpcode() const {
332     return AltOp ? AltOp->getOpcode() : 0;
333   }
334 
335   /// Some of the instructions in the list have alternate opcodes.
336   bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
337 
338   bool isOpcodeOrAlt(Instruction *I) const {
339     unsigned CheckedOpcode = I->getOpcode();
340     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
341   }
342 
343   InstructionsState() = delete;
344   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
345       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
346 };
347 
348 } // end anonymous namespace
349 
350 /// Chooses the correct key for scheduling data. If \p Op has the same (or
351 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
352 /// OpValue.
353 static Value *isOneOf(const InstructionsState &S, Value *Op) {
354   auto *I = dyn_cast<Instruction>(Op);
355   if (I && S.isOpcodeOrAlt(I))
356     return Op;
357   return S.OpValue;
358 }
359 
360 /// \returns analysis of the Instructions in \p VL described in
361 /// InstructionsState, the Opcode that we suppose the whole list
362 /// could be vectorized even if its structure is diverse.
363 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
364                                        unsigned BaseIndex = 0) {
365   // Make sure these are all Instructions.
366   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
367     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
368 
369   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
370   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
371   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
372   unsigned AltOpcode = Opcode;
373   unsigned AltIndex = BaseIndex;
374 
375   // Check for one alternate opcode from another BinaryOperator.
376   // TODO - generalize to support all operators (types, calls etc.).
377   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
378     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
379     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
380       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
381         continue;
382       if (Opcode == AltOpcode) {
383         AltOpcode = InstOpcode;
384         AltIndex = Cnt;
385         continue;
386       }
387     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
388       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
389       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
390       if (Ty0 == Ty1) {
391         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
392           continue;
393         if (Opcode == AltOpcode) {
394           AltOpcode = InstOpcode;
395           AltIndex = Cnt;
396           continue;
397         }
398       }
399     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
400       continue;
401     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
402   }
403 
404   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
405                            cast<Instruction>(VL[AltIndex]));
406 }
407 
408 /// \returns true if all of the values in \p VL have the same type or false
409 /// otherwise.
410 static bool allSameType(ArrayRef<Value *> VL) {
411   Type *Ty = VL[0]->getType();
412   for (int i = 1, e = VL.size(); i < e; i++)
413     if (VL[i]->getType() != Ty)
414       return false;
415 
416   return true;
417 }
418 
419 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
420 static Optional<unsigned> getExtractIndex(Instruction *E) {
421   unsigned Opcode = E->getOpcode();
422   assert((Opcode == Instruction::ExtractElement ||
423           Opcode == Instruction::ExtractValue) &&
424          "Expected extractelement or extractvalue instruction.");
425   if (Opcode == Instruction::ExtractElement) {
426     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
427     if (!CI)
428       return None;
429     return CI->getZExtValue();
430   }
431   ExtractValueInst *EI = cast<ExtractValueInst>(E);
432   if (EI->getNumIndices() != 1)
433     return None;
434   return *EI->idx_begin();
435 }
436 
437 /// \returns True if in-tree use also needs extract. This refers to
438 /// possible scalar operand in vectorized instruction.
439 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
440                                     TargetLibraryInfo *TLI) {
441   unsigned Opcode = UserInst->getOpcode();
442   switch (Opcode) {
443   case Instruction::Load: {
444     LoadInst *LI = cast<LoadInst>(UserInst);
445     return (LI->getPointerOperand() == Scalar);
446   }
447   case Instruction::Store: {
448     StoreInst *SI = cast<StoreInst>(UserInst);
449     return (SI->getPointerOperand() == Scalar);
450   }
451   case Instruction::Call: {
452     CallInst *CI = cast<CallInst>(UserInst);
453     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
454     for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
455       if (hasVectorInstrinsicScalarOpd(ID, i))
456         return (CI->getArgOperand(i) == Scalar);
457     }
458     LLVM_FALLTHROUGH;
459   }
460   default:
461     return false;
462   }
463 }
464 
465 /// \returns the AA location that is being access by the instruction.
466 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
467   if (StoreInst *SI = dyn_cast<StoreInst>(I))
468     return MemoryLocation::get(SI);
469   if (LoadInst *LI = dyn_cast<LoadInst>(I))
470     return MemoryLocation::get(LI);
471   return MemoryLocation();
472 }
473 
474 /// \returns True if the instruction is not a volatile or atomic load/store.
475 static bool isSimple(Instruction *I) {
476   if (LoadInst *LI = dyn_cast<LoadInst>(I))
477     return LI->isSimple();
478   if (StoreInst *SI = dyn_cast<StoreInst>(I))
479     return SI->isSimple();
480   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
481     return !MI->isVolatile();
482   return true;
483 }
484 
485 namespace llvm {
486 
487 namespace slpvectorizer {
488 
489 /// Bottom Up SLP Vectorizer.
490 class BoUpSLP {
491   struct TreeEntry;
492   struct ScheduleData;
493 
494 public:
495   using ValueList = SmallVector<Value *, 8>;
496   using InstrList = SmallVector<Instruction *, 16>;
497   using ValueSet = SmallPtrSet<Value *, 16>;
498   using StoreList = SmallVector<StoreInst *, 8>;
499   using ExtraValueToDebugLocsMap =
500       MapVector<Value *, SmallVector<Instruction *, 2>>;
501 
502   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
503           TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
504           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
505           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
506       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
507         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
508     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
509     // Use the vector register size specified by the target unless overridden
510     // by a command-line option.
511     // TODO: It would be better to limit the vectorization factor based on
512     //       data type rather than just register size. For example, x86 AVX has
513     //       256-bit registers, but it does not support integer operations
514     //       at that width (that requires AVX2).
515     if (MaxVectorRegSizeOption.getNumOccurrences())
516       MaxVecRegSize = MaxVectorRegSizeOption;
517     else
518       MaxVecRegSize = TTI->getRegisterBitWidth(true);
519 
520     if (MinVectorRegSizeOption.getNumOccurrences())
521       MinVecRegSize = MinVectorRegSizeOption;
522     else
523       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
524   }
525 
526   /// Vectorize the tree that starts with the elements in \p VL.
527   /// Returns the vectorized root.
528   Value *vectorizeTree();
529 
530   /// Vectorize the tree but with the list of externally used values \p
531   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
532   /// generated extractvalue instructions.
533   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
534 
535   /// \returns the cost incurred by unwanted spills and fills, caused by
536   /// holding live values over call sites.
537   int getSpillCost() const;
538 
539   /// \returns the vectorization cost of the subtree that starts at \p VL.
540   /// A negative number means that this is profitable.
541   int getTreeCost();
542 
543   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
544   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
545   void buildTree(ArrayRef<Value *> Roots,
546                  ArrayRef<Value *> UserIgnoreLst = None);
547 
548   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
549   /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
550   /// into account (anf updating it, if required) list of externally used
551   /// values stored in \p ExternallyUsedValues.
552   void buildTree(ArrayRef<Value *> Roots,
553                  ExtraValueToDebugLocsMap &ExternallyUsedValues,
554                  ArrayRef<Value *> UserIgnoreLst = None);
555 
556   /// Clear the internal data structures that are created by 'buildTree'.
557   void deleteTree() {
558     VectorizableTree.clear();
559     ScalarToTreeEntry.clear();
560     MustGather.clear();
561     ExternalUses.clear();
562     NumOpsWantToKeepOrder.clear();
563     NumOpsWantToKeepOriginalOrder = 0;
564     for (auto &Iter : BlocksSchedules) {
565       BlockScheduling *BS = Iter.second.get();
566       BS->clear();
567     }
568     MinBWs.clear();
569   }
570 
571   unsigned getTreeSize() const { return VectorizableTree.size(); }
572 
573   /// Perform LICM and CSE on the newly generated gather sequences.
574   void optimizeGatherSequence();
575 
576   /// \returns The best order of instructions for vectorization.
577   Optional<ArrayRef<unsigned>> bestOrder() const {
578     auto I = std::max_element(
579         NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
580         [](const decltype(NumOpsWantToKeepOrder)::value_type &D1,
581            const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
582           return D1.second < D2.second;
583         });
584     if (I == NumOpsWantToKeepOrder.end() ||
585         I->getSecond() <= NumOpsWantToKeepOriginalOrder)
586       return None;
587 
588     return makeArrayRef(I->getFirst());
589   }
590 
591   /// \return The vector element size in bits to use when vectorizing the
592   /// expression tree ending at \p V. If V is a store, the size is the width of
593   /// the stored value. Otherwise, the size is the width of the largest loaded
594   /// value reaching V. This method is used by the vectorizer to calculate
595   /// vectorization factors.
596   unsigned getVectorElementSize(Value *V) const;
597 
598   /// Compute the minimum type sizes required to represent the entries in a
599   /// vectorizable tree.
600   void computeMinimumValueSizes();
601 
602   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
603   unsigned getMaxVecRegSize() const {
604     return MaxVecRegSize;
605   }
606 
607   // \returns minimum vector register size as set by cl::opt.
608   unsigned getMinVecRegSize() const {
609     return MinVecRegSize;
610   }
611 
612   /// Check if ArrayType or StructType is isomorphic to some VectorType.
613   ///
614   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
615   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
616 
617   /// \returns True if the VectorizableTree is both tiny and not fully
618   /// vectorizable. We do not vectorize such trees.
619   bool isTreeTinyAndNotFullyVectorizable() const;
620 
621   OptimizationRemarkEmitter *getORE() { return ORE; }
622 
623   /// This structure holds any data we need about the edges being traversed
624   /// during buildTree_rec(). We keep track of:
625   /// (i) the user TreeEntry index, and
626   /// (ii) the index of the edge.
627   struct EdgeInfo {
628     EdgeInfo() = default;
629     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
630         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
631     /// The user TreeEntry.
632     TreeEntry *UserTE = nullptr;
633     /// The operand index of the use.
634     unsigned EdgeIdx = UINT_MAX;
635 #ifndef NDEBUG
636     friend inline raw_ostream &operator<<(raw_ostream &OS,
637                                           const BoUpSLP::EdgeInfo &EI) {
638       EI.dump(OS);
639       return OS;
640     }
641     /// Debug print.
642     void dump(raw_ostream &OS) const {
643       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
644          << " EdgeIdx:" << EdgeIdx << "}";
645     }
646     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
647 #endif
648   };
649 
650   /// A helper data structure to hold the operands of a vector of instructions.
651   /// This supports a fixed vector length for all operand vectors.
652   class VLOperands {
653     /// For each operand we need (i) the value, and (ii) the opcode that it
654     /// would be attached to if the expression was in a left-linearized form.
655     /// This is required to avoid illegal operand reordering.
656     /// For example:
657     /// \verbatim
658     ///                         0 Op1
659     ///                         |/
660     /// Op1 Op2   Linearized    + Op2
661     ///   \ /     ---------->   |/
662     ///    -                    -
663     ///
664     /// Op1 - Op2            (0 + Op1) - Op2
665     /// \endverbatim
666     ///
667     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
668     ///
669     /// Another way to think of this is to track all the operations across the
670     /// path from the operand all the way to the root of the tree and to
671     /// calculate the operation that corresponds to this path. For example, the
672     /// path from Op2 to the root crosses the RHS of the '-', therefore the
673     /// corresponding operation is a '-' (which matches the one in the
674     /// linearized tree, as shown above).
675     ///
676     /// For lack of a better term, we refer to this operation as Accumulated
677     /// Path Operation (APO).
678     struct OperandData {
679       OperandData() = default;
680       OperandData(Value *V, bool APO, bool IsUsed)
681           : V(V), APO(APO), IsUsed(IsUsed) {}
682       /// The operand value.
683       Value *V = nullptr;
684       /// TreeEntries only allow a single opcode, or an alternate sequence of
685       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
686       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
687       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
688       /// (e.g., Add/Mul)
689       bool APO = false;
690       /// Helper data for the reordering function.
691       bool IsUsed = false;
692     };
693 
694     /// During operand reordering, we are trying to select the operand at lane
695     /// that matches best with the operand at the neighboring lane. Our
696     /// selection is based on the type of value we are looking for. For example,
697     /// if the neighboring lane has a load, we need to look for a load that is
698     /// accessing a consecutive address. These strategies are summarized in the
699     /// 'ReorderingMode' enumerator.
700     enum class ReorderingMode {
701       Load,     ///< Matching loads to consecutive memory addresses
702       Opcode,   ///< Matching instructions based on opcode (same or alternate)
703       Constant, ///< Matching constants
704       Splat,    ///< Matching the same instruction multiple times (broadcast)
705       Failed,   ///< We failed to create a vectorizable group
706     };
707 
708     using OperandDataVec = SmallVector<OperandData, 2>;
709 
710     /// A vector of operand vectors.
711     SmallVector<OperandDataVec, 4> OpsVec;
712 
713     const DataLayout &DL;
714     ScalarEvolution &SE;
715 
716     /// \returns the operand data at \p OpIdx and \p Lane.
717     OperandData &getData(unsigned OpIdx, unsigned Lane) {
718       return OpsVec[OpIdx][Lane];
719     }
720 
721     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
722     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
723       return OpsVec[OpIdx][Lane];
724     }
725 
726     /// Clears the used flag for all entries.
727     void clearUsed() {
728       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
729            OpIdx != NumOperands; ++OpIdx)
730         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
731              ++Lane)
732           OpsVec[OpIdx][Lane].IsUsed = false;
733     }
734 
735     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
736     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
737       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
738     }
739 
740     // Search all operands in Ops[*][Lane] for the one that matches best
741     // Ops[OpIdx][LastLane] and return its opreand index.
742     // If no good match can be found, return None.
743     Optional<unsigned>
744     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
745                    ArrayRef<ReorderingMode> ReorderingModes) {
746       unsigned NumOperands = getNumOperands();
747 
748       // The operand of the previous lane at OpIdx.
749       Value *OpLastLane = getData(OpIdx, LastLane).V;
750 
751       // Our strategy mode for OpIdx.
752       ReorderingMode RMode = ReorderingModes[OpIdx];
753 
754       // The linearized opcode of the operand at OpIdx, Lane.
755       bool OpIdxAPO = getData(OpIdx, Lane).APO;
756 
757       const unsigned BestScore = 2;
758       const unsigned GoodScore = 1;
759 
760       // The best operand index and its score.
761       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
762       // are using the score to differentiate between the two.
763       struct BestOpData {
764         Optional<unsigned> Idx = None;
765         unsigned Score = 0;
766       } BestOp;
767 
768       // Iterate through all unused operands and look for the best.
769       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
770         // Get the operand at Idx and Lane.
771         OperandData &OpData = getData(Idx, Lane);
772         Value *Op = OpData.V;
773         bool OpAPO = OpData.APO;
774 
775         // Skip already selected operands.
776         if (OpData.IsUsed)
777           continue;
778 
779         // Skip if we are trying to move the operand to a position with a
780         // different opcode in the linearized tree form. This would break the
781         // semantics.
782         if (OpAPO != OpIdxAPO)
783           continue;
784 
785         // Look for an operand that matches the current mode.
786         switch (RMode) {
787         case ReorderingMode::Load:
788           if (isa<LoadInst>(Op)) {
789             // Figure out which is left and right, so that we can check for
790             // consecutive loads
791             bool LeftToRight = Lane > LastLane;
792             Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
793             Value *OpRight = (LeftToRight) ? Op : OpLastLane;
794             if (isConsecutiveAccess(cast<LoadInst>(OpLeft),
795                                     cast<LoadInst>(OpRight), DL, SE))
796               BestOp.Idx = Idx;
797           }
798           break;
799         case ReorderingMode::Opcode:
800           // We accept both Instructions and Undefs, but with different scores.
801           if ((isa<Instruction>(Op) && isa<Instruction>(OpLastLane) &&
802                cast<Instruction>(Op)->getOpcode() ==
803                    cast<Instruction>(OpLastLane)->getOpcode()) ||
804               (isa<UndefValue>(OpLastLane) && isa<Instruction>(Op)) ||
805               isa<UndefValue>(Op)) {
806             // An instruction has a higher score than an undef.
807             unsigned Score = (isa<UndefValue>(Op)) ? GoodScore : BestScore;
808             if (Score > BestOp.Score) {
809               BestOp.Idx = Idx;
810               BestOp.Score = Score;
811             }
812           }
813           break;
814         case ReorderingMode::Constant:
815           if (isa<Constant>(Op)) {
816             unsigned Score = (isa<UndefValue>(Op)) ? GoodScore : BestScore;
817             if (Score > BestOp.Score) {
818               BestOp.Idx = Idx;
819               BestOp.Score = Score;
820             }
821           }
822           break;
823         case ReorderingMode::Splat:
824           if (Op == OpLastLane)
825             BestOp.Idx = Idx;
826           break;
827         case ReorderingMode::Failed:
828           return None;
829         }
830       }
831 
832       if (BestOp.Idx) {
833         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
834         return BestOp.Idx;
835       }
836       // If we could not find a good match return None.
837       return None;
838     }
839 
840     /// Helper for reorderOperandVecs. \Returns the lane that we should start
841     /// reordering from. This is the one which has the least number of operands
842     /// that can freely move about.
843     unsigned getBestLaneToStartReordering() const {
844       unsigned BestLane = 0;
845       unsigned Min = UINT_MAX;
846       for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
847            ++Lane) {
848         unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane);
849         if (NumFreeOps < Min) {
850           Min = NumFreeOps;
851           BestLane = Lane;
852         }
853       }
854       return BestLane;
855     }
856 
857     /// \Returns the maximum number of operands that are allowed to be reordered
858     /// for \p Lane. This is used as a heuristic for selecting the first lane to
859     /// start operand reordering.
860     unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
861       unsigned CntTrue = 0;
862       unsigned NumOperands = getNumOperands();
863       // Operands with the same APO can be reordered. We therefore need to count
864       // how many of them we have for each APO, like this: Cnt[APO] = x.
865       // Since we only have two APOs, namely true and false, we can avoid using
866       // a map. Instead we can simply count the number of operands that
867       // correspond to one of them (in this case the 'true' APO), and calculate
868       // the other by subtracting it from the total number of operands.
869       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx)
870         if (getData(OpIdx, Lane).APO)
871           ++CntTrue;
872       unsigned CntFalse = NumOperands - CntTrue;
873       return std::max(CntTrue, CntFalse);
874     }
875 
876     /// Go through the instructions in VL and append their operands.
877     void appendOperandsOfVL(ArrayRef<Value *> VL) {
878       assert(!VL.empty() && "Bad VL");
879       assert((empty() || VL.size() == getNumLanes()) &&
880              "Expected same number of lanes");
881       assert(isa<Instruction>(VL[0]) && "Expected instruction");
882       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
883       OpsVec.resize(NumOperands);
884       unsigned NumLanes = VL.size();
885       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
886         OpsVec[OpIdx].resize(NumLanes);
887         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
888           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
889           // Our tree has just 3 nodes: the root and two operands.
890           // It is therefore trivial to get the APO. We only need to check the
891           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
892           // RHS operand. The LHS operand of both add and sub is never attached
893           // to an inversese operation in the linearized form, therefore its APO
894           // is false. The RHS is true only if VL[Lane] is an inverse operation.
895 
896           // Since operand reordering is performed on groups of commutative
897           // operations or alternating sequences (e.g., +, -), we can safely
898           // tell the inverse operations by checking commutativity.
899           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
900           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
901           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
902                                  APO, false};
903         }
904       }
905     }
906 
907     /// \returns the number of operands.
908     unsigned getNumOperands() const { return OpsVec.size(); }
909 
910     /// \returns the number of lanes.
911     unsigned getNumLanes() const { return OpsVec[0].size(); }
912 
913     /// \returns the operand value at \p OpIdx and \p Lane.
914     Value *getValue(unsigned OpIdx, unsigned Lane) const {
915       return getData(OpIdx, Lane).V;
916     }
917 
918     /// \returns true if the data structure is empty.
919     bool empty() const { return OpsVec.empty(); }
920 
921     /// Clears the data.
922     void clear() { OpsVec.clear(); }
923 
924     /// \Returns true if there are enough operands identical to \p Op to fill
925     /// the whole vector.
926     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
927     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
928       bool OpAPO = getData(OpIdx, Lane).APO;
929       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
930         if (Ln == Lane)
931           continue;
932         // This is set to true if we found a candidate for broadcast at Lane.
933         bool FoundCandidate = false;
934         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
935           OperandData &Data = getData(OpI, Ln);
936           if (Data.APO != OpAPO || Data.IsUsed)
937             continue;
938           if (Data.V == Op) {
939             FoundCandidate = true;
940             Data.IsUsed = true;
941             break;
942           }
943         }
944         if (!FoundCandidate)
945           return false;
946       }
947       return true;
948     }
949 
950   public:
951     /// Initialize with all the operands of the instruction vector \p RootVL.
952     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
953                ScalarEvolution &SE)
954         : DL(DL), SE(SE) {
955       // Append all the operands of RootVL.
956       appendOperandsOfVL(RootVL);
957     }
958 
959     /// \Returns a value vector with the operands across all lanes for the
960     /// opearnd at \p OpIdx.
961     ValueList getVL(unsigned OpIdx) const {
962       ValueList OpVL(OpsVec[OpIdx].size());
963       assert(OpsVec[OpIdx].size() == getNumLanes() &&
964              "Expected same num of lanes across all operands");
965       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
966         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
967       return OpVL;
968     }
969 
970     // Performs operand reordering for 2 or more operands.
971     // The original operands are in OrigOps[OpIdx][Lane].
972     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
973     void reorder() {
974       unsigned NumOperands = getNumOperands();
975       unsigned NumLanes = getNumLanes();
976       // Each operand has its own mode. We are using this mode to help us select
977       // the instructions for each lane, so that they match best with the ones
978       // we have selected so far.
979       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
980 
981       // This is a greedy single-pass algorithm. We are going over each lane
982       // once and deciding on the best order right away with no back-tracking.
983       // However, in order to increase its effectiveness, we start with the lane
984       // that has operands that can move the least. For example, given the
985       // following lanes:
986       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
987       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
988       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
989       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
990       // we will start at Lane 1, since the operands of the subtraction cannot
991       // be reordered. Then we will visit the rest of the lanes in a circular
992       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
993 
994       // Find the first lane that we will start our search from.
995       unsigned FirstLane = getBestLaneToStartReordering();
996 
997       // Initialize the modes.
998       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
999         Value *OpLane0 = getValue(OpIdx, FirstLane);
1000         // Keep track if we have instructions with all the same opcode on one
1001         // side.
1002         if (isa<LoadInst>(OpLane0))
1003           ReorderingModes[OpIdx] = ReorderingMode::Load;
1004         else if (isa<Instruction>(OpLane0)) {
1005           // Check if OpLane0 should be broadcast.
1006           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1007             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1008           else
1009             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1010         }
1011         else if (isa<Constant>(OpLane0))
1012           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1013         else if (isa<Argument>(OpLane0))
1014           // Our best hope is a Splat. It may save some cost in some cases.
1015           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1016         else
1017           // NOTE: This should be unreachable.
1018           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1019       }
1020 
1021       // If the initial strategy fails for any of the operand indexes, then we
1022       // perform reordering again in a second pass. This helps avoid assigning
1023       // high priority to the failed strategy, and should improve reordering for
1024       // the non-failed operand indexes.
1025       for (int Pass = 0; Pass != 2; ++Pass) {
1026         // Skip the second pass if the first pass did not fail.
1027         bool StrategyFailed = false;
1028         // Mark all operand data as free to use.
1029         clearUsed();
1030         // We keep the original operand order for the FirstLane, so reorder the
1031         // rest of the lanes. We are visiting the nodes in a circular fashion,
1032         // using FirstLane as the center point and increasing the radius
1033         // distance.
1034         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1035           // Visit the lane on the right and then the lane on the left.
1036           for (int Direction : {+1, -1}) {
1037             int Lane = FirstLane + Direction * Distance;
1038             if (Lane < 0 || Lane >= (int)NumLanes)
1039               continue;
1040             int LastLane = Lane - Direction;
1041             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1042                    "Out of bounds");
1043             // Look for a good match for each operand.
1044             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1045               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1046               Optional<unsigned> BestIdx =
1047                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1048               // By not selecting a value, we allow the operands that follow to
1049               // select a better matching value. We will get a non-null value in
1050               // the next run of getBestOperand().
1051               if (BestIdx) {
1052                 // Swap the current operand with the one returned by
1053                 // getBestOperand().
1054                 swap(OpIdx, BestIdx.getValue(), Lane);
1055               } else {
1056                 // We failed to find a best operand, set mode to 'Failed'.
1057                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1058                 // Enable the second pass.
1059                 StrategyFailed = true;
1060               }
1061             }
1062           }
1063         }
1064         // Skip second pass if the strategy did not fail.
1065         if (!StrategyFailed)
1066           break;
1067       }
1068     }
1069 
1070 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1071     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1072       switch (RMode) {
1073       case ReorderingMode::Load:
1074         return "Load";
1075       case ReorderingMode::Opcode:
1076         return "Opcode";
1077       case ReorderingMode::Constant:
1078         return "Constant";
1079       case ReorderingMode::Splat:
1080         return "Splat";
1081       case ReorderingMode::Failed:
1082         return "Failed";
1083       }
1084       llvm_unreachable("Unimplemented Reordering Type");
1085     }
1086 
1087     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1088                                                    raw_ostream &OS) {
1089       return OS << getModeStr(RMode);
1090     }
1091 
1092     /// Debug print.
1093     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1094       printMode(RMode, dbgs());
1095     }
1096 
1097     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1098       return printMode(RMode, OS);
1099     }
1100 
1101     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1102       const unsigned Indent = 2;
1103       unsigned Cnt = 0;
1104       for (const OperandDataVec &OpDataVec : OpsVec) {
1105         OS << "Operand " << Cnt++ << "\n";
1106         for (const OperandData &OpData : OpDataVec) {
1107           OS.indent(Indent) << "{";
1108           if (Value *V = OpData.V)
1109             OS << *V;
1110           else
1111             OS << "null";
1112           OS << ", APO:" << OpData.APO << "}\n";
1113         }
1114         OS << "\n";
1115       }
1116       return OS;
1117     }
1118 
1119     /// Debug print.
1120     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1121 #endif
1122   };
1123 
1124 private:
1125   /// Checks if all users of \p I are the part of the vectorization tree.
1126   bool areAllUsersVectorized(Instruction *I) const;
1127 
1128   /// \returns the cost of the vectorizable entry.
1129   int getEntryCost(TreeEntry *E);
1130 
1131   /// This is the recursive part of buildTree.
1132   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1133                      const EdgeInfo &EI);
1134 
1135   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1136   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1137   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1138   /// returns false, setting \p CurrentOrder to either an empty vector or a
1139   /// non-identity permutation that allows to reuse extract instructions.
1140   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1141                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1142 
1143   /// Vectorize a single entry in the tree.
1144   Value *vectorizeTree(TreeEntry *E);
1145 
1146   /// Vectorize a single entry in the tree, starting in \p VL.
1147   Value *vectorizeTree(ArrayRef<Value *> VL);
1148 
1149   /// \returns the scalarization cost for this type. Scalarization in this
1150   /// context means the creation of vectors from a group of scalars.
1151   int getGatherCost(Type *Ty, const DenseSet<unsigned> &ShuffledIndices) const;
1152 
1153   /// \returns the scalarization cost for this list of values. Assuming that
1154   /// this subtree gets vectorized, we may need to extract the values from the
1155   /// roots. This method calculates the cost of extracting the values.
1156   int getGatherCost(ArrayRef<Value *> VL) const;
1157 
1158   /// Set the Builder insert point to one after the last instruction in
1159   /// the bundle
1160   void setInsertPointAfterBundle(TreeEntry *E);
1161 
1162   /// \returns a vector from a collection of scalars in \p VL.
1163   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
1164 
1165   /// \returns whether the VectorizableTree is fully vectorizable and will
1166   /// be beneficial even the tree height is tiny.
1167   bool isFullyVectorizableTinyTree() const;
1168 
1169   /// Reorder commutative or alt operands to get better probability of
1170   /// generating vectorized code.
1171   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1172                                              SmallVectorImpl<Value *> &Left,
1173                                              SmallVectorImpl<Value *> &Right,
1174                                              const DataLayout &DL,
1175                                              ScalarEvolution &SE);
1176   struct TreeEntry {
1177     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1178     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1179 
1180     /// \returns true if the scalars in VL are equal to this entry.
1181     bool isSame(ArrayRef<Value *> VL) const {
1182       if (VL.size() == Scalars.size())
1183         return std::equal(VL.begin(), VL.end(), Scalars.begin());
1184       return VL.size() == ReuseShuffleIndices.size() &&
1185              std::equal(
1186                  VL.begin(), VL.end(), ReuseShuffleIndices.begin(),
1187                  [this](Value *V, unsigned Idx) { return V == Scalars[Idx]; });
1188     }
1189 
1190     /// A vector of scalars.
1191     ValueList Scalars;
1192 
1193     /// The Scalars are vectorized into this value. It is initialized to Null.
1194     Value *VectorizedValue = nullptr;
1195 
1196     /// Do we need to gather this sequence ?
1197     bool NeedToGather = false;
1198 
1199     /// Does this sequence require some shuffling?
1200     SmallVector<unsigned, 4> ReuseShuffleIndices;
1201 
1202     /// Does this entry require reordering?
1203     ArrayRef<unsigned> ReorderIndices;
1204 
1205     /// Points back to the VectorizableTree.
1206     ///
1207     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
1208     /// to be a pointer and needs to be able to initialize the child iterator.
1209     /// Thus we need a reference back to the container to translate the indices
1210     /// to entries.
1211     VecTreeTy &Container;
1212 
1213     /// The TreeEntry index containing the user of this entry.  We can actually
1214     /// have multiple users so the data structure is not truly a tree.
1215     SmallVector<EdgeInfo, 1> UserTreeIndices;
1216 
1217     /// The index of this treeEntry in VectorizableTree.
1218     int Idx = -1;
1219 
1220   private:
1221     /// The operands of each instruction in each lane Operands[op_index][lane].
1222     /// Note: This helps avoid the replication of the code that performs the
1223     /// reordering of operands during buildTree_rec() and vectorizeTree().
1224     SmallVector<ValueList, 2> Operands;
1225 
1226     /// The main/alternate instruction.
1227     Instruction *MainOp = nullptr;
1228     Instruction *AltOp = nullptr;
1229 
1230   public:
1231     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1232     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
1233       if (Operands.size() < OpIdx + 1)
1234         Operands.resize(OpIdx + 1);
1235       assert(Operands[OpIdx].size() == 0 && "Already resized?");
1236       Operands[OpIdx].resize(Scalars.size());
1237       for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane)
1238         Operands[OpIdx][Lane] = OpVL[Lane];
1239     }
1240 
1241     /// Set the operands of this bundle in their original order.
1242     void setOperandsInOrder() {
1243       assert(Operands.empty() && "Already initialized?");
1244       auto *I0 = cast<Instruction>(Scalars[0]);
1245       Operands.resize(I0->getNumOperands());
1246       unsigned NumLanes = Scalars.size();
1247       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1248            OpIdx != NumOperands; ++OpIdx) {
1249         Operands[OpIdx].resize(NumLanes);
1250         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1251           auto *I = cast<Instruction>(Scalars[Lane]);
1252           assert(I->getNumOperands() == NumOperands &&
1253                  "Expected same number of operands");
1254           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
1255         }
1256       }
1257     }
1258 
1259     /// \returns the \p OpIdx operand of this TreeEntry.
1260     ValueList &getOperand(unsigned OpIdx) {
1261       assert(OpIdx < Operands.size() && "Off bounds");
1262       return Operands[OpIdx];
1263     }
1264 
1265     /// \returns the number of operands.
1266     unsigned getNumOperands() const { return Operands.size(); }
1267 
1268     /// \return the single \p OpIdx operand.
1269     Value *getSingleOperand(unsigned OpIdx) const {
1270       assert(OpIdx < Operands.size() && "Off bounds");
1271       assert(!Operands[OpIdx].empty() && "No operand available");
1272       return Operands[OpIdx][0];
1273     }
1274 
1275     /// Some of the instructions in the list have alternate opcodes.
1276     bool isAltShuffle() const {
1277       return getOpcode() != getAltOpcode();
1278     }
1279 
1280     bool isOpcodeOrAlt(Instruction *I) const {
1281       unsigned CheckedOpcode = I->getOpcode();
1282       return (getOpcode() == CheckedOpcode ||
1283               getAltOpcode() == CheckedOpcode);
1284     }
1285 
1286     /// Chooses the correct key for scheduling data. If \p Op has the same (or
1287     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
1288     /// \p OpValue.
1289     Value *isOneOf(Value *Op) const {
1290       auto *I = dyn_cast<Instruction>(Op);
1291       if (I && isOpcodeOrAlt(I))
1292         return Op;
1293       return MainOp;
1294     }
1295 
1296     void setOperations(const InstructionsState &S) {
1297       MainOp = S.MainOp;
1298       AltOp = S.AltOp;
1299     }
1300 
1301     Instruction *getMainOp() const {
1302       return MainOp;
1303     }
1304 
1305     Instruction *getAltOp() const {
1306       return AltOp;
1307     }
1308 
1309     /// The main/alternate opcodes for the list of instructions.
1310     unsigned getOpcode() const {
1311       return MainOp ? MainOp->getOpcode() : 0;
1312     }
1313 
1314     unsigned getAltOpcode() const {
1315       return AltOp ? AltOp->getOpcode() : 0;
1316     }
1317 
1318     /// Update operations state of this entry if reorder occurred.
1319     bool updateStateIfReorder() {
1320       if (ReorderIndices.empty())
1321         return false;
1322       InstructionsState S = getSameOpcode(Scalars, ReorderIndices.front());
1323       setOperations(S);
1324       return true;
1325     }
1326 
1327 #ifndef NDEBUG
1328     /// Debug printer.
1329     LLVM_DUMP_METHOD void dump() const {
1330       dbgs() << Idx << ".\n";
1331       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
1332         dbgs() << "Operand " << OpI << ":\n";
1333         for (const Value *V : Operands[OpI])
1334           dbgs().indent(2) << *V << "\n";
1335       }
1336       dbgs() << "Scalars: \n";
1337       for (Value *V : Scalars)
1338         dbgs().indent(2) << *V << "\n";
1339       dbgs() << "NeedToGather: " << NeedToGather << "\n";
1340       dbgs() << "MainOp: " << *MainOp << "\n";
1341       dbgs() << "AltOp: " << *AltOp << "\n";
1342       dbgs() << "VectorizedValue: ";
1343       if (VectorizedValue)
1344         dbgs() << *VectorizedValue;
1345       else
1346         dbgs() << "NULL";
1347       dbgs() << "\n";
1348       dbgs() << "ReuseShuffleIndices: ";
1349       if (ReuseShuffleIndices.empty())
1350         dbgs() << "Emtpy";
1351       else
1352         for (unsigned ReuseIdx : ReuseShuffleIndices)
1353           dbgs() << ReuseIdx << ", ";
1354       dbgs() << "\n";
1355       dbgs() << "ReorderIndices: ";
1356       for (unsigned ReorderIdx : ReorderIndices)
1357         dbgs() << ReorderIdx << ", ";
1358       dbgs() << "\n";
1359       dbgs() << "UserTreeIndices: ";
1360       for (const auto &EInfo : UserTreeIndices)
1361         dbgs() << EInfo << ", ";
1362       dbgs() << "\n";
1363     }
1364 #endif
1365   };
1366 
1367   /// Create a new VectorizableTree entry.
1368   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
1369                           const InstructionsState &S,
1370                           const EdgeInfo &UserTreeIdx,
1371                           ArrayRef<unsigned> ReuseShuffleIndices = None,
1372                           ArrayRef<unsigned> ReorderIndices = None) {
1373     bool Vectorized = (bool)Bundle;
1374     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
1375     TreeEntry *Last = VectorizableTree.back().get();
1376     Last->Idx = VectorizableTree.size() - 1;
1377     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
1378     Last->NeedToGather = !Vectorized;
1379     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
1380                                      ReuseShuffleIndices.end());
1381     Last->ReorderIndices = ReorderIndices;
1382     Last->setOperations(S);
1383     if (Vectorized) {
1384       for (int i = 0, e = VL.size(); i != e; ++i) {
1385         assert(!getTreeEntry(VL[i]) && "Scalar already in tree!");
1386         ScalarToTreeEntry[VL[i]] = Last;
1387       }
1388       // Update the scheduler bundle to point to this TreeEntry.
1389       unsigned Lane = 0;
1390       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
1391            BundleMember = BundleMember->NextInBundle) {
1392         BundleMember->TE = Last;
1393         BundleMember->Lane = Lane;
1394         ++Lane;
1395       }
1396       assert((!Bundle.getValue() || Lane == VL.size()) &&
1397              "Bundle and VL out of sync");
1398     } else {
1399       MustGather.insert(VL.begin(), VL.end());
1400     }
1401 
1402     if (UserTreeIdx.UserTE)
1403       Last->UserTreeIndices.push_back(UserTreeIdx);
1404 
1405     return Last;
1406   }
1407 
1408   /// -- Vectorization State --
1409   /// Holds all of the tree entries.
1410   TreeEntry::VecTreeTy VectorizableTree;
1411 
1412 #ifndef NDEBUG
1413   /// Debug printer.
1414   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
1415     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
1416       VectorizableTree[Id]->dump();
1417       dbgs() << "\n";
1418     }
1419   }
1420 #endif
1421 
1422   TreeEntry *getTreeEntry(Value *V) {
1423     auto I = ScalarToTreeEntry.find(V);
1424     if (I != ScalarToTreeEntry.end())
1425       return I->second;
1426     return nullptr;
1427   }
1428 
1429   const TreeEntry *getTreeEntry(Value *V) const {
1430     auto I = ScalarToTreeEntry.find(V);
1431     if (I != ScalarToTreeEntry.end())
1432       return I->second;
1433     return nullptr;
1434   }
1435 
1436   /// Maps a specific scalar to its tree entry.
1437   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
1438 
1439   /// A list of scalars that we found that we need to keep as scalars.
1440   ValueSet MustGather;
1441 
1442   /// This POD struct describes one external user in the vectorized tree.
1443   struct ExternalUser {
1444     ExternalUser(Value *S, llvm::User *U, int L)
1445         : Scalar(S), User(U), Lane(L) {}
1446 
1447     // Which scalar in our function.
1448     Value *Scalar;
1449 
1450     // Which user that uses the scalar.
1451     llvm::User *User;
1452 
1453     // Which lane does the scalar belong to.
1454     int Lane;
1455   };
1456   using UserList = SmallVector<ExternalUser, 16>;
1457 
1458   /// Checks if two instructions may access the same memory.
1459   ///
1460   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
1461   /// is invariant in the calling loop.
1462   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
1463                  Instruction *Inst2) {
1464     // First check if the result is already in the cache.
1465     AliasCacheKey key = std::make_pair(Inst1, Inst2);
1466     Optional<bool> &result = AliasCache[key];
1467     if (result.hasValue()) {
1468       return result.getValue();
1469     }
1470     MemoryLocation Loc2 = getLocation(Inst2, AA);
1471     bool aliased = true;
1472     if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
1473       // Do the alias check.
1474       aliased = AA->alias(Loc1, Loc2);
1475     }
1476     // Store the result in the cache.
1477     result = aliased;
1478     return aliased;
1479   }
1480 
1481   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
1482 
1483   /// Cache for alias results.
1484   /// TODO: consider moving this to the AliasAnalysis itself.
1485   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
1486 
1487   /// Removes an instruction from its block and eventually deletes it.
1488   /// It's like Instruction::eraseFromParent() except that the actual deletion
1489   /// is delayed until BoUpSLP is destructed.
1490   /// This is required to ensure that there are no incorrect collisions in the
1491   /// AliasCache, which can happen if a new instruction is allocated at the
1492   /// same address as a previously deleted instruction.
1493   void eraseInstruction(Instruction *I) {
1494     I->removeFromParent();
1495     I->dropAllReferences();
1496     DeletedInstructions.emplace_back(I);
1497   }
1498 
1499   /// Temporary store for deleted instructions. Instructions will be deleted
1500   /// eventually when the BoUpSLP is destructed.
1501   SmallVector<unique_value, 8> DeletedInstructions;
1502 
1503   /// A list of values that need to extracted out of the tree.
1504   /// This list holds pairs of (Internal Scalar : External User). External User
1505   /// can be nullptr, it means that this Internal Scalar will be used later,
1506   /// after vectorization.
1507   UserList ExternalUses;
1508 
1509   /// Values used only by @llvm.assume calls.
1510   SmallPtrSet<const Value *, 32> EphValues;
1511 
1512   /// Holds all of the instructions that we gathered.
1513   SetVector<Instruction *> GatherSeq;
1514 
1515   /// A list of blocks that we are going to CSE.
1516   SetVector<BasicBlock *> CSEBlocks;
1517 
1518   /// Contains all scheduling relevant data for an instruction.
1519   /// A ScheduleData either represents a single instruction or a member of an
1520   /// instruction bundle (= a group of instructions which is combined into a
1521   /// vector instruction).
1522   struct ScheduleData {
1523     // The initial value for the dependency counters. It means that the
1524     // dependencies are not calculated yet.
1525     enum { InvalidDeps = -1 };
1526 
1527     ScheduleData() = default;
1528 
1529     void init(int BlockSchedulingRegionID, Value *OpVal) {
1530       FirstInBundle = this;
1531       NextInBundle = nullptr;
1532       NextLoadStore = nullptr;
1533       IsScheduled = false;
1534       SchedulingRegionID = BlockSchedulingRegionID;
1535       UnscheduledDepsInBundle = UnscheduledDeps;
1536       clearDependencies();
1537       OpValue = OpVal;
1538       TE = nullptr;
1539       Lane = -1;
1540     }
1541 
1542     /// Returns true if the dependency information has been calculated.
1543     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
1544 
1545     /// Returns true for single instructions and for bundle representatives
1546     /// (= the head of a bundle).
1547     bool isSchedulingEntity() const { return FirstInBundle == this; }
1548 
1549     /// Returns true if it represents an instruction bundle and not only a
1550     /// single instruction.
1551     bool isPartOfBundle() const {
1552       return NextInBundle != nullptr || FirstInBundle != this;
1553     }
1554 
1555     /// Returns true if it is ready for scheduling, i.e. it has no more
1556     /// unscheduled depending instructions/bundles.
1557     bool isReady() const {
1558       assert(isSchedulingEntity() &&
1559              "can't consider non-scheduling entity for ready list");
1560       return UnscheduledDepsInBundle == 0 && !IsScheduled;
1561     }
1562 
1563     /// Modifies the number of unscheduled dependencies, also updating it for
1564     /// the whole bundle.
1565     int incrementUnscheduledDeps(int Incr) {
1566       UnscheduledDeps += Incr;
1567       return FirstInBundle->UnscheduledDepsInBundle += Incr;
1568     }
1569 
1570     /// Sets the number of unscheduled dependencies to the number of
1571     /// dependencies.
1572     void resetUnscheduledDeps() {
1573       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
1574     }
1575 
1576     /// Clears all dependency information.
1577     void clearDependencies() {
1578       Dependencies = InvalidDeps;
1579       resetUnscheduledDeps();
1580       MemoryDependencies.clear();
1581     }
1582 
1583     void dump(raw_ostream &os) const {
1584       if (!isSchedulingEntity()) {
1585         os << "/ " << *Inst;
1586       } else if (NextInBundle) {
1587         os << '[' << *Inst;
1588         ScheduleData *SD = NextInBundle;
1589         while (SD) {
1590           os << ';' << *SD->Inst;
1591           SD = SD->NextInBundle;
1592         }
1593         os << ']';
1594       } else {
1595         os << *Inst;
1596       }
1597     }
1598 
1599     Instruction *Inst = nullptr;
1600 
1601     /// Points to the head in an instruction bundle (and always to this for
1602     /// single instructions).
1603     ScheduleData *FirstInBundle = nullptr;
1604 
1605     /// Single linked list of all instructions in a bundle. Null if it is a
1606     /// single instruction.
1607     ScheduleData *NextInBundle = nullptr;
1608 
1609     /// Single linked list of all memory instructions (e.g. load, store, call)
1610     /// in the block - until the end of the scheduling region.
1611     ScheduleData *NextLoadStore = nullptr;
1612 
1613     /// The dependent memory instructions.
1614     /// This list is derived on demand in calculateDependencies().
1615     SmallVector<ScheduleData *, 4> MemoryDependencies;
1616 
1617     /// This ScheduleData is in the current scheduling region if this matches
1618     /// the current SchedulingRegionID of BlockScheduling.
1619     int SchedulingRegionID = 0;
1620 
1621     /// Used for getting a "good" final ordering of instructions.
1622     int SchedulingPriority = 0;
1623 
1624     /// The number of dependencies. Constitutes of the number of users of the
1625     /// instruction plus the number of dependent memory instructions (if any).
1626     /// This value is calculated on demand.
1627     /// If InvalidDeps, the number of dependencies is not calculated yet.
1628     int Dependencies = InvalidDeps;
1629 
1630     /// The number of dependencies minus the number of dependencies of scheduled
1631     /// instructions. As soon as this is zero, the instruction/bundle gets ready
1632     /// for scheduling.
1633     /// Note that this is negative as long as Dependencies is not calculated.
1634     int UnscheduledDeps = InvalidDeps;
1635 
1636     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
1637     /// single instructions.
1638     int UnscheduledDepsInBundle = InvalidDeps;
1639 
1640     /// True if this instruction is scheduled (or considered as scheduled in the
1641     /// dry-run).
1642     bool IsScheduled = false;
1643 
1644     /// Opcode of the current instruction in the schedule data.
1645     Value *OpValue = nullptr;
1646 
1647     /// The TreeEntry that this instruction corresponds to.
1648     TreeEntry *TE = nullptr;
1649 
1650     /// The lane of this node in the TreeEntry.
1651     int Lane = -1;
1652   };
1653 
1654 #ifndef NDEBUG
1655   friend inline raw_ostream &operator<<(raw_ostream &os,
1656                                         const BoUpSLP::ScheduleData &SD) {
1657     SD.dump(os);
1658     return os;
1659   }
1660 #endif
1661 
1662   friend struct GraphTraits<BoUpSLP *>;
1663   friend struct DOTGraphTraits<BoUpSLP *>;
1664 
1665   /// Contains all scheduling data for a basic block.
1666   struct BlockScheduling {
1667     BlockScheduling(BasicBlock *BB)
1668         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
1669 
1670     void clear() {
1671       ReadyInsts.clear();
1672       ScheduleStart = nullptr;
1673       ScheduleEnd = nullptr;
1674       FirstLoadStoreInRegion = nullptr;
1675       LastLoadStoreInRegion = nullptr;
1676 
1677       // Reduce the maximum schedule region size by the size of the
1678       // previous scheduling run.
1679       ScheduleRegionSizeLimit -= ScheduleRegionSize;
1680       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
1681         ScheduleRegionSizeLimit = MinScheduleRegionSize;
1682       ScheduleRegionSize = 0;
1683 
1684       // Make a new scheduling region, i.e. all existing ScheduleData is not
1685       // in the new region yet.
1686       ++SchedulingRegionID;
1687     }
1688 
1689     ScheduleData *getScheduleData(Value *V) {
1690       ScheduleData *SD = ScheduleDataMap[V];
1691       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1692         return SD;
1693       return nullptr;
1694     }
1695 
1696     ScheduleData *getScheduleData(Value *V, Value *Key) {
1697       if (V == Key)
1698         return getScheduleData(V);
1699       auto I = ExtraScheduleDataMap.find(V);
1700       if (I != ExtraScheduleDataMap.end()) {
1701         ScheduleData *SD = I->second[Key];
1702         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1703           return SD;
1704       }
1705       return nullptr;
1706     }
1707 
1708     bool isInSchedulingRegion(ScheduleData *SD) {
1709       return SD->SchedulingRegionID == SchedulingRegionID;
1710     }
1711 
1712     /// Marks an instruction as scheduled and puts all dependent ready
1713     /// instructions into the ready-list.
1714     template <typename ReadyListType>
1715     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
1716       SD->IsScheduled = true;
1717       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
1718 
1719       ScheduleData *BundleMember = SD;
1720       while (BundleMember) {
1721         if (BundleMember->Inst != BundleMember->OpValue) {
1722           BundleMember = BundleMember->NextInBundle;
1723           continue;
1724         }
1725         // Handle the def-use chain dependencies.
1726 
1727         // Decrement the unscheduled counter and insert to ready list if ready.
1728         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
1729           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
1730             if (OpDef && OpDef->hasValidDependencies() &&
1731                 OpDef->incrementUnscheduledDeps(-1) == 0) {
1732               // There are no more unscheduled dependencies after
1733               // decrementing, so we can put the dependent instruction
1734               // into the ready list.
1735               ScheduleData *DepBundle = OpDef->FirstInBundle;
1736               assert(!DepBundle->IsScheduled &&
1737                      "already scheduled bundle gets ready");
1738               ReadyList.insert(DepBundle);
1739               LLVM_DEBUG(dbgs()
1740                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
1741             }
1742           });
1743         };
1744 
1745         // If BundleMember is a vector bundle, its operands may have been
1746         // reordered duiring buildTree(). We therefore need to get its operands
1747         // through the TreeEntry.
1748         if (TreeEntry *TE = BundleMember->TE) {
1749           int Lane = BundleMember->Lane;
1750           assert(Lane >= 0 && "Lane not set");
1751           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
1752                OpIdx != NumOperands; ++OpIdx)
1753             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
1754               DecrUnsched(I);
1755         } else {
1756           // If BundleMember is a stand-alone instruction, no operand reordering
1757           // has taken place, so we directly access its operands.
1758           for (Use &U : BundleMember->Inst->operands())
1759             if (auto *I = dyn_cast<Instruction>(U.get()))
1760               DecrUnsched(I);
1761         }
1762         // Handle the memory dependencies.
1763         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
1764           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
1765             // There are no more unscheduled dependencies after decrementing,
1766             // so we can put the dependent instruction into the ready list.
1767             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
1768             assert(!DepBundle->IsScheduled &&
1769                    "already scheduled bundle gets ready");
1770             ReadyList.insert(DepBundle);
1771             LLVM_DEBUG(dbgs()
1772                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
1773           }
1774         }
1775         BundleMember = BundleMember->NextInBundle;
1776       }
1777     }
1778 
1779     void doForAllOpcodes(Value *V,
1780                          function_ref<void(ScheduleData *SD)> Action) {
1781       if (ScheduleData *SD = getScheduleData(V))
1782         Action(SD);
1783       auto I = ExtraScheduleDataMap.find(V);
1784       if (I != ExtraScheduleDataMap.end())
1785         for (auto &P : I->second)
1786           if (P.second->SchedulingRegionID == SchedulingRegionID)
1787             Action(P.second);
1788     }
1789 
1790     /// Put all instructions into the ReadyList which are ready for scheduling.
1791     template <typename ReadyListType>
1792     void initialFillReadyList(ReadyListType &ReadyList) {
1793       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
1794         doForAllOpcodes(I, [&](ScheduleData *SD) {
1795           if (SD->isSchedulingEntity() && SD->isReady()) {
1796             ReadyList.insert(SD);
1797             LLVM_DEBUG(dbgs()
1798                        << "SLP:    initially in ready list: " << *I << "\n");
1799           }
1800         });
1801       }
1802     }
1803 
1804     /// Checks if a bundle of instructions can be scheduled, i.e. has no
1805     /// cyclic dependencies. This is only a dry-run, no instructions are
1806     /// actually moved at this stage.
1807     /// \returns the scheduling bundle. The returned Optional value is non-None
1808     /// if \p VL is allowed to be scheduled.
1809     Optional<ScheduleData *>
1810     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
1811                       const InstructionsState &S);
1812 
1813     /// Un-bundles a group of instructions.
1814     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
1815 
1816     /// Allocates schedule data chunk.
1817     ScheduleData *allocateScheduleDataChunks();
1818 
1819     /// Extends the scheduling region so that V is inside the region.
1820     /// \returns true if the region size is within the limit.
1821     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
1822 
1823     /// Initialize the ScheduleData structures for new instructions in the
1824     /// scheduling region.
1825     void initScheduleData(Instruction *FromI, Instruction *ToI,
1826                           ScheduleData *PrevLoadStore,
1827                           ScheduleData *NextLoadStore);
1828 
1829     /// Updates the dependency information of a bundle and of all instructions/
1830     /// bundles which depend on the original bundle.
1831     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
1832                                BoUpSLP *SLP);
1833 
1834     /// Sets all instruction in the scheduling region to un-scheduled.
1835     void resetSchedule();
1836 
1837     BasicBlock *BB;
1838 
1839     /// Simple memory allocation for ScheduleData.
1840     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
1841 
1842     /// The size of a ScheduleData array in ScheduleDataChunks.
1843     int ChunkSize;
1844 
1845     /// The allocator position in the current chunk, which is the last entry
1846     /// of ScheduleDataChunks.
1847     int ChunkPos;
1848 
1849     /// Attaches ScheduleData to Instruction.
1850     /// Note that the mapping survives during all vectorization iterations, i.e.
1851     /// ScheduleData structures are recycled.
1852     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
1853 
1854     /// Attaches ScheduleData to Instruction with the leading key.
1855     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
1856         ExtraScheduleDataMap;
1857 
1858     struct ReadyList : SmallVector<ScheduleData *, 8> {
1859       void insert(ScheduleData *SD) { push_back(SD); }
1860     };
1861 
1862     /// The ready-list for scheduling (only used for the dry-run).
1863     ReadyList ReadyInsts;
1864 
1865     /// The first instruction of the scheduling region.
1866     Instruction *ScheduleStart = nullptr;
1867 
1868     /// The first instruction _after_ the scheduling region.
1869     Instruction *ScheduleEnd = nullptr;
1870 
1871     /// The first memory accessing instruction in the scheduling region
1872     /// (can be null).
1873     ScheduleData *FirstLoadStoreInRegion = nullptr;
1874 
1875     /// The last memory accessing instruction in the scheduling region
1876     /// (can be null).
1877     ScheduleData *LastLoadStoreInRegion = nullptr;
1878 
1879     /// The current size of the scheduling region.
1880     int ScheduleRegionSize = 0;
1881 
1882     /// The maximum size allowed for the scheduling region.
1883     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
1884 
1885     /// The ID of the scheduling region. For a new vectorization iteration this
1886     /// is incremented which "removes" all ScheduleData from the region.
1887     // Make sure that the initial SchedulingRegionID is greater than the
1888     // initial SchedulingRegionID in ScheduleData (which is 0).
1889     int SchedulingRegionID = 1;
1890   };
1891 
1892   /// Attaches the BlockScheduling structures to basic blocks.
1893   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
1894 
1895   /// Performs the "real" scheduling. Done before vectorization is actually
1896   /// performed in a basic block.
1897   void scheduleBlock(BlockScheduling *BS);
1898 
1899   /// List of users to ignore during scheduling and that don't need extracting.
1900   ArrayRef<Value *> UserIgnoreList;
1901 
1902   using OrdersType = SmallVector<unsigned, 4>;
1903   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
1904   /// sorted SmallVectors of unsigned.
1905   struct OrdersTypeDenseMapInfo {
1906     static OrdersType getEmptyKey() {
1907       OrdersType V;
1908       V.push_back(~1U);
1909       return V;
1910     }
1911 
1912     static OrdersType getTombstoneKey() {
1913       OrdersType V;
1914       V.push_back(~2U);
1915       return V;
1916     }
1917 
1918     static unsigned getHashValue(const OrdersType &V) {
1919       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1920     }
1921 
1922     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
1923       return LHS == RHS;
1924     }
1925   };
1926 
1927   /// Contains orders of operations along with the number of bundles that have
1928   /// operations in this order. It stores only those orders that require
1929   /// reordering, if reordering is not required it is counted using \a
1930   /// NumOpsWantToKeepOriginalOrder.
1931   DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder;
1932   /// Number of bundles that do not require reordering.
1933   unsigned NumOpsWantToKeepOriginalOrder = 0;
1934 
1935   // Analysis and block reference.
1936   Function *F;
1937   ScalarEvolution *SE;
1938   TargetTransformInfo *TTI;
1939   TargetLibraryInfo *TLI;
1940   AliasAnalysis *AA;
1941   LoopInfo *LI;
1942   DominatorTree *DT;
1943   AssumptionCache *AC;
1944   DemandedBits *DB;
1945   const DataLayout *DL;
1946   OptimizationRemarkEmitter *ORE;
1947 
1948   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
1949   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
1950 
1951   /// Instruction builder to construct the vectorized tree.
1952   IRBuilder<> Builder;
1953 
1954   /// A map of scalar integer values to the smallest bit width with which they
1955   /// can legally be represented. The values map to (width, signed) pairs,
1956   /// where "width" indicates the minimum bit width and "signed" is True if the
1957   /// value must be signed-extended, rather than zero-extended, back to its
1958   /// original width.
1959   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
1960 };
1961 
1962 } // end namespace slpvectorizer
1963 
1964 template <> struct GraphTraits<BoUpSLP *> {
1965   using TreeEntry = BoUpSLP::TreeEntry;
1966 
1967   /// NodeRef has to be a pointer per the GraphWriter.
1968   using NodeRef = TreeEntry *;
1969 
1970   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
1971 
1972   /// Add the VectorizableTree to the index iterator to be able to return
1973   /// TreeEntry pointers.
1974   struct ChildIteratorType
1975       : public iterator_adaptor_base<
1976             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
1977     ContainerTy &VectorizableTree;
1978 
1979     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
1980                       ContainerTy &VT)
1981         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
1982 
1983     NodeRef operator*() { return I->UserTE; }
1984   };
1985 
1986   static NodeRef getEntryNode(BoUpSLP &R) {
1987     return R.VectorizableTree[0].get();
1988   }
1989 
1990   static ChildIteratorType child_begin(NodeRef N) {
1991     return {N->UserTreeIndices.begin(), N->Container};
1992   }
1993 
1994   static ChildIteratorType child_end(NodeRef N) {
1995     return {N->UserTreeIndices.end(), N->Container};
1996   }
1997 
1998   /// For the node iterator we just need to turn the TreeEntry iterator into a
1999   /// TreeEntry* iterator so that it dereferences to NodeRef.
2000   class nodes_iterator {
2001     using ItTy = ContainerTy::iterator;
2002     ItTy It;
2003 
2004   public:
2005     nodes_iterator(const ItTy &It2) : It(It2) {}
2006     NodeRef operator*() { return It->get(); }
2007     nodes_iterator operator++() {
2008       ++It;
2009       return *this;
2010     }
2011     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2012   };
2013 
2014   static nodes_iterator nodes_begin(BoUpSLP *R) {
2015     return nodes_iterator(R->VectorizableTree.begin());
2016   }
2017 
2018   static nodes_iterator nodes_end(BoUpSLP *R) {
2019     return nodes_iterator(R->VectorizableTree.end());
2020   }
2021 
2022   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2023 };
2024 
2025 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2026   using TreeEntry = BoUpSLP::TreeEntry;
2027 
2028   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2029 
2030   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2031     std::string Str;
2032     raw_string_ostream OS(Str);
2033     if (isSplat(Entry->Scalars)) {
2034       OS << "<splat> " << *Entry->Scalars[0];
2035       return Str;
2036     }
2037     for (auto V : Entry->Scalars) {
2038       OS << *V;
2039       if (std::any_of(
2040               R->ExternalUses.begin(), R->ExternalUses.end(),
2041               [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
2042         OS << " <extract>";
2043       OS << "\n";
2044     }
2045     return Str;
2046   }
2047 
2048   static std::string getNodeAttributes(const TreeEntry *Entry,
2049                                        const BoUpSLP *) {
2050     if (Entry->NeedToGather)
2051       return "color=red";
2052     return "";
2053   }
2054 };
2055 
2056 } // end namespace llvm
2057 
2058 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2059                         ArrayRef<Value *> UserIgnoreLst) {
2060   ExtraValueToDebugLocsMap ExternallyUsedValues;
2061   buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
2062 }
2063 
2064 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2065                         ExtraValueToDebugLocsMap &ExternallyUsedValues,
2066                         ArrayRef<Value *> UserIgnoreLst) {
2067   deleteTree();
2068   UserIgnoreList = UserIgnoreLst;
2069   if (!allSameType(Roots))
2070     return;
2071   buildTree_rec(Roots, 0, EdgeInfo());
2072 
2073   // Collect the values that we need to extract from the tree.
2074   for (auto &TEPtr : VectorizableTree) {
2075     TreeEntry *Entry = TEPtr.get();
2076 
2077     // No need to handle users of gathered values.
2078     if (Entry->NeedToGather)
2079       continue;
2080 
2081     // For each lane:
2082     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2083       Value *Scalar = Entry->Scalars[Lane];
2084       int FoundLane = Lane;
2085       if (!Entry->ReuseShuffleIndices.empty()) {
2086         FoundLane =
2087             std::distance(Entry->ReuseShuffleIndices.begin(),
2088                           llvm::find(Entry->ReuseShuffleIndices, FoundLane));
2089       }
2090 
2091       // Check if the scalar is externally used as an extra arg.
2092       auto ExtI = ExternallyUsedValues.find(Scalar);
2093       if (ExtI != ExternallyUsedValues.end()) {
2094         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
2095                           << Lane << " from " << *Scalar << ".\n");
2096         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
2097       }
2098       for (User *U : Scalar->users()) {
2099         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
2100 
2101         Instruction *UserInst = dyn_cast<Instruction>(U);
2102         if (!UserInst)
2103           continue;
2104 
2105         // Skip in-tree scalars that become vectors
2106         if (TreeEntry *UseEntry = getTreeEntry(U)) {
2107           Value *UseScalar = UseEntry->Scalars[0];
2108           // Some in-tree scalars will remain as scalar in vectorized
2109           // instructions. If that is the case, the one in Lane 0 will
2110           // be used.
2111           if (UseScalar != U ||
2112               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
2113             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
2114                               << ".\n");
2115             assert(!UseEntry->NeedToGather && "Bad state");
2116             continue;
2117           }
2118         }
2119 
2120         // Ignore users in the user ignore list.
2121         if (is_contained(UserIgnoreList, UserInst))
2122           continue;
2123 
2124         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
2125                           << Lane << " from " << *Scalar << ".\n");
2126         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
2127       }
2128     }
2129   }
2130 }
2131 
2132 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
2133                             const EdgeInfo &UserTreeIdx) {
2134   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
2135 
2136   InstructionsState S = getSameOpcode(VL);
2137   if (Depth == RecursionMaxDepth) {
2138     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
2139     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2140     return;
2141   }
2142 
2143   // Don't handle vectors.
2144   if (S.OpValue->getType()->isVectorTy()) {
2145     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
2146     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2147     return;
2148   }
2149 
2150   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2151     if (SI->getValueOperand()->getType()->isVectorTy()) {
2152       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
2153       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2154       return;
2155     }
2156 
2157   // If all of the operands are identical or constant we have a simple solution.
2158   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) {
2159     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
2160     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2161     return;
2162   }
2163 
2164   // We now know that this is a vector of instructions of the same type from
2165   // the same block.
2166 
2167   // Don't vectorize ephemeral values.
2168   for (Value *V : VL) {
2169     if (EphValues.count(V)) {
2170       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2171                         << ") is ephemeral.\n");
2172       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2173       return;
2174     }
2175   }
2176 
2177   // Check if this is a duplicate of another entry.
2178   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2179     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
2180     if (!E->isSame(VL)) {
2181       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
2182       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2183       return;
2184     }
2185     // Record the reuse of the tree node.  FIXME, currently this is only used to
2186     // properly draw the graph rather than for the actual vectorization.
2187     E->UserTreeIndices.push_back(UserTreeIdx);
2188     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
2189                       << ".\n");
2190     return;
2191   }
2192 
2193   // Check that none of the instructions in the bundle are already in the tree.
2194   for (Value *V : VL) {
2195     auto *I = dyn_cast<Instruction>(V);
2196     if (!I)
2197       continue;
2198     if (getTreeEntry(I)) {
2199       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2200                         << ") is already in tree.\n");
2201       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2202       return;
2203     }
2204   }
2205 
2206   // If any of the scalars is marked as a value that needs to stay scalar, then
2207   // we need to gather the scalars.
2208   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
2209   for (Value *V : VL) {
2210     if (MustGather.count(V) || is_contained(UserIgnoreList, V)) {
2211       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
2212       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2213       return;
2214     }
2215   }
2216 
2217   // Check that all of the users of the scalars that we want to vectorize are
2218   // schedulable.
2219   auto *VL0 = cast<Instruction>(S.OpValue);
2220   BasicBlock *BB = VL0->getParent();
2221 
2222   if (!DT->isReachableFromEntry(BB)) {
2223     // Don't go into unreachable blocks. They may contain instructions with
2224     // dependency cycles which confuse the final scheduling.
2225     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
2226     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2227     return;
2228   }
2229 
2230   // Check that every instruction appears once in this bundle.
2231   SmallVector<unsigned, 4> ReuseShuffleIndicies;
2232   SmallVector<Value *, 4> UniqueValues;
2233   DenseMap<Value *, unsigned> UniquePositions;
2234   for (Value *V : VL) {
2235     auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
2236     ReuseShuffleIndicies.emplace_back(Res.first->second);
2237     if (Res.second)
2238       UniqueValues.emplace_back(V);
2239   }
2240   size_t NumUniqueScalarValues = UniqueValues.size();
2241   if (NumUniqueScalarValues == VL.size()) {
2242     ReuseShuffleIndicies.clear();
2243   } else {
2244     LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
2245     if (NumUniqueScalarValues <= 1 ||
2246         !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
2247       LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
2248       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2249       return;
2250     }
2251     VL = UniqueValues;
2252   }
2253 
2254   auto &BSRef = BlocksSchedules[BB];
2255   if (!BSRef)
2256     BSRef = std::make_unique<BlockScheduling>(BB);
2257 
2258   BlockScheduling &BS = *BSRef.get();
2259 
2260   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
2261   if (!Bundle) {
2262     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
2263     assert((!BS.getScheduleData(VL0) ||
2264             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
2265            "tryScheduleBundle should cancelScheduling on failure");
2266     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2267                  ReuseShuffleIndicies);
2268     return;
2269   }
2270   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
2271 
2272   unsigned ShuffleOrOp = S.isAltShuffle() ?
2273                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
2274   switch (ShuffleOrOp) {
2275     case Instruction::PHI: {
2276       auto *PH = cast<PHINode>(VL0);
2277 
2278       // Check for terminator values (e.g. invoke).
2279       for (unsigned j = 0; j < VL.size(); ++j)
2280         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2281           Instruction *Term = dyn_cast<Instruction>(
2282               cast<PHINode>(VL[j])->getIncomingValueForBlock(
2283                   PH->getIncomingBlock(i)));
2284           if (Term && Term->isTerminator()) {
2285             LLVM_DEBUG(dbgs()
2286                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
2287             BS.cancelScheduling(VL, VL0);
2288             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2289                          ReuseShuffleIndicies);
2290             return;
2291           }
2292         }
2293 
2294       TreeEntry *TE =
2295           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
2296       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
2297 
2298       // Keeps the reordered operands to avoid code duplication.
2299       SmallVector<ValueList, 2> OperandsVec;
2300       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2301         ValueList Operands;
2302         // Prepare the operand vector.
2303         for (Value *j : VL)
2304           Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
2305               PH->getIncomingBlock(i)));
2306         TE->setOperand(i, Operands);
2307         OperandsVec.push_back(Operands);
2308       }
2309       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
2310         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
2311       return;
2312     }
2313     case Instruction::ExtractValue:
2314     case Instruction::ExtractElement: {
2315       OrdersType CurrentOrder;
2316       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
2317       if (Reuse) {
2318         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
2319         ++NumOpsWantToKeepOriginalOrder;
2320         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2321                      ReuseShuffleIndicies);
2322         // This is a special case, as it does not gather, but at the same time
2323         // we are not extending buildTree_rec() towards the operands.
2324         ValueList Op0;
2325         Op0.assign(VL.size(), VL0->getOperand(0));
2326         VectorizableTree.back()->setOperand(0, Op0);
2327         return;
2328       }
2329       if (!CurrentOrder.empty()) {
2330         LLVM_DEBUG({
2331           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
2332                     "with order";
2333           for (unsigned Idx : CurrentOrder)
2334             dbgs() << " " << Idx;
2335           dbgs() << "\n";
2336         });
2337         // Insert new order with initial value 0, if it does not exist,
2338         // otherwise return the iterator to the existing one.
2339         auto StoredCurrentOrderAndNum =
2340             NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
2341         ++StoredCurrentOrderAndNum->getSecond();
2342         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2343                      ReuseShuffleIndicies,
2344                      StoredCurrentOrderAndNum->getFirst());
2345         // This is a special case, as it does not gather, but at the same time
2346         // we are not extending buildTree_rec() towards the operands.
2347         ValueList Op0;
2348         Op0.assign(VL.size(), VL0->getOperand(0));
2349         VectorizableTree.back()->setOperand(0, Op0);
2350         return;
2351       }
2352       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
2353       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2354                    ReuseShuffleIndicies);
2355       BS.cancelScheduling(VL, VL0);
2356       return;
2357     }
2358     case Instruction::Load: {
2359       // Check that a vectorized load would load the same memory as a scalar
2360       // load. For example, we don't want to vectorize loads that are smaller
2361       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
2362       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
2363       // from such a struct, we read/write packed bits disagreeing with the
2364       // unvectorized version.
2365       Type *ScalarTy = VL0->getType();
2366 
2367       if (DL->getTypeSizeInBits(ScalarTy) !=
2368           DL->getTypeAllocSizeInBits(ScalarTy)) {
2369         BS.cancelScheduling(VL, VL0);
2370         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2371                      ReuseShuffleIndicies);
2372         LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
2373         return;
2374       }
2375 
2376       // Make sure all loads in the bundle are simple - we can't vectorize
2377       // atomic or volatile loads.
2378       SmallVector<Value *, 4> PointerOps(VL.size());
2379       auto POIter = PointerOps.begin();
2380       for (Value *V : VL) {
2381         auto *L = cast<LoadInst>(V);
2382         if (!L->isSimple()) {
2383           BS.cancelScheduling(VL, VL0);
2384           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2385                        ReuseShuffleIndicies);
2386           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
2387           return;
2388         }
2389         *POIter = L->getPointerOperand();
2390         ++POIter;
2391       }
2392 
2393       OrdersType CurrentOrder;
2394       // Check the order of pointer operands.
2395       if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
2396         Value *Ptr0;
2397         Value *PtrN;
2398         if (CurrentOrder.empty()) {
2399           Ptr0 = PointerOps.front();
2400           PtrN = PointerOps.back();
2401         } else {
2402           Ptr0 = PointerOps[CurrentOrder.front()];
2403           PtrN = PointerOps[CurrentOrder.back()];
2404         }
2405         const SCEV *Scev0 = SE->getSCEV(Ptr0);
2406         const SCEV *ScevN = SE->getSCEV(PtrN);
2407         const auto *Diff =
2408             dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
2409         uint64_t Size = DL->getTypeAllocSize(ScalarTy);
2410         // Check that the sorted loads are consecutive.
2411         if (Diff && Diff->getAPInt().getZExtValue() == (VL.size() - 1) * Size) {
2412           if (CurrentOrder.empty()) {
2413             // Original loads are consecutive and does not require reordering.
2414             ++NumOpsWantToKeepOriginalOrder;
2415             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
2416                                          UserTreeIdx, ReuseShuffleIndicies);
2417             TE->setOperandsInOrder();
2418             LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
2419           } else {
2420             // Need to reorder.
2421             auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
2422             ++I->getSecond();
2423             TreeEntry *TE =
2424                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2425                              ReuseShuffleIndicies, I->getFirst());
2426             TE->setOperandsInOrder();
2427             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
2428           }
2429           return;
2430         }
2431       }
2432 
2433       LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
2434       BS.cancelScheduling(VL, VL0);
2435       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2436                    ReuseShuffleIndicies);
2437       return;
2438     }
2439     case Instruction::ZExt:
2440     case Instruction::SExt:
2441     case Instruction::FPToUI:
2442     case Instruction::FPToSI:
2443     case Instruction::FPExt:
2444     case Instruction::PtrToInt:
2445     case Instruction::IntToPtr:
2446     case Instruction::SIToFP:
2447     case Instruction::UIToFP:
2448     case Instruction::Trunc:
2449     case Instruction::FPTrunc:
2450     case Instruction::BitCast: {
2451       Type *SrcTy = VL0->getOperand(0)->getType();
2452       for (Value *V : VL) {
2453         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
2454         if (Ty != SrcTy || !isValidElementType(Ty)) {
2455           BS.cancelScheduling(VL, VL0);
2456           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2457                        ReuseShuffleIndicies);
2458           LLVM_DEBUG(dbgs()
2459                      << "SLP: Gathering casts with different src types.\n");
2460           return;
2461         }
2462       }
2463       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2464                                    ReuseShuffleIndicies);
2465       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
2466 
2467       TE->setOperandsInOrder();
2468       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
2469         ValueList Operands;
2470         // Prepare the operand vector.
2471         for (Value *V : VL)
2472           Operands.push_back(cast<Instruction>(V)->getOperand(i));
2473 
2474         buildTree_rec(Operands, Depth + 1, {TE, i});
2475       }
2476       return;
2477     }
2478     case Instruction::ICmp:
2479     case Instruction::FCmp: {
2480       // Check that all of the compares have the same predicate.
2481       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2482       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
2483       Type *ComparedTy = VL0->getOperand(0)->getType();
2484       for (Value *V : VL) {
2485         CmpInst *Cmp = cast<CmpInst>(V);
2486         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
2487             Cmp->getOperand(0)->getType() != ComparedTy) {
2488           BS.cancelScheduling(VL, VL0);
2489           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2490                        ReuseShuffleIndicies);
2491           LLVM_DEBUG(dbgs()
2492                      << "SLP: Gathering cmp with different predicate.\n");
2493           return;
2494         }
2495       }
2496 
2497       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2498                                    ReuseShuffleIndicies);
2499       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
2500 
2501       ValueList Left, Right;
2502       if (cast<CmpInst>(VL0)->isCommutative()) {
2503         // Commutative predicate - collect + sort operands of the instructions
2504         // so that each side is more likely to have the same opcode.
2505         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
2506         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE);
2507       } else {
2508         // Collect operands - commute if it uses the swapped predicate.
2509         for (Value *V : VL) {
2510           auto *Cmp = cast<CmpInst>(V);
2511           Value *LHS = Cmp->getOperand(0);
2512           Value *RHS = Cmp->getOperand(1);
2513           if (Cmp->getPredicate() != P0)
2514             std::swap(LHS, RHS);
2515           Left.push_back(LHS);
2516           Right.push_back(RHS);
2517         }
2518       }
2519       TE->setOperand(0, Left);
2520       TE->setOperand(1, Right);
2521       buildTree_rec(Left, Depth + 1, {TE, 0});
2522       buildTree_rec(Right, Depth + 1, {TE, 1});
2523       return;
2524     }
2525     case Instruction::Select:
2526     case Instruction::FNeg:
2527     case Instruction::Add:
2528     case Instruction::FAdd:
2529     case Instruction::Sub:
2530     case Instruction::FSub:
2531     case Instruction::Mul:
2532     case Instruction::FMul:
2533     case Instruction::UDiv:
2534     case Instruction::SDiv:
2535     case Instruction::FDiv:
2536     case Instruction::URem:
2537     case Instruction::SRem:
2538     case Instruction::FRem:
2539     case Instruction::Shl:
2540     case Instruction::LShr:
2541     case Instruction::AShr:
2542     case Instruction::And:
2543     case Instruction::Or:
2544     case Instruction::Xor: {
2545       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2546                                    ReuseShuffleIndicies);
2547       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
2548 
2549       // Sort operands of the instructions so that each side is more likely to
2550       // have the same opcode.
2551       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
2552         ValueList Left, Right;
2553         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE);
2554         TE->setOperand(0, Left);
2555         TE->setOperand(1, Right);
2556         buildTree_rec(Left, Depth + 1, {TE, 0});
2557         buildTree_rec(Right, Depth + 1, {TE, 1});
2558         return;
2559       }
2560 
2561       TE->setOperandsInOrder();
2562       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
2563         ValueList Operands;
2564         // Prepare the operand vector.
2565         for (Value *j : VL)
2566           Operands.push_back(cast<Instruction>(j)->getOperand(i));
2567 
2568         buildTree_rec(Operands, Depth + 1, {TE, i});
2569       }
2570       return;
2571     }
2572     case Instruction::GetElementPtr: {
2573       // We don't combine GEPs with complicated (nested) indexing.
2574       for (Value *V : VL) {
2575         if (cast<Instruction>(V)->getNumOperands() != 2) {
2576           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
2577           BS.cancelScheduling(VL, VL0);
2578           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2579                        ReuseShuffleIndicies);
2580           return;
2581         }
2582       }
2583 
2584       // We can't combine several GEPs into one vector if they operate on
2585       // different types.
2586       Type *Ty0 = VL0->getOperand(0)->getType();
2587       for (Value *V : VL) {
2588         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
2589         if (Ty0 != CurTy) {
2590           LLVM_DEBUG(dbgs()
2591                      << "SLP: not-vectorizable GEP (different types).\n");
2592           BS.cancelScheduling(VL, VL0);
2593           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2594                        ReuseShuffleIndicies);
2595           return;
2596         }
2597       }
2598 
2599       // We don't combine GEPs with non-constant indexes.
2600       for (Value *V : VL) {
2601         auto Op = cast<Instruction>(V)->getOperand(1);
2602         if (!isa<ConstantInt>(Op)) {
2603           LLVM_DEBUG(dbgs()
2604                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
2605           BS.cancelScheduling(VL, VL0);
2606           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2607                        ReuseShuffleIndicies);
2608           return;
2609         }
2610       }
2611 
2612       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2613                                    ReuseShuffleIndicies);
2614       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
2615       TE->setOperandsInOrder();
2616       for (unsigned i = 0, e = 2; i < e; ++i) {
2617         ValueList Operands;
2618         // Prepare the operand vector.
2619         for (Value *V : VL)
2620           Operands.push_back(cast<Instruction>(V)->getOperand(i));
2621 
2622         buildTree_rec(Operands, Depth + 1, {TE, i});
2623       }
2624       return;
2625     }
2626     case Instruction::Store: {
2627       // Check if the stores are consecutive or if we need to swizzle them.
2628       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
2629         if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
2630           BS.cancelScheduling(VL, VL0);
2631           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2632                        ReuseShuffleIndicies);
2633           LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
2634           return;
2635         }
2636 
2637       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2638                                    ReuseShuffleIndicies);
2639       LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
2640 
2641       ValueList Operands;
2642       for (Value *V : VL)
2643         Operands.push_back(cast<Instruction>(V)->getOperand(0));
2644       TE->setOperandsInOrder();
2645       buildTree_rec(Operands, Depth + 1, {TE, 0});
2646       return;
2647     }
2648     case Instruction::Call: {
2649       // Check if the calls are all to the same vectorizable intrinsic.
2650       CallInst *CI = cast<CallInst>(VL0);
2651       // Check if this is an Intrinsic call or something that can be
2652       // represented by an intrinsic call
2653       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2654       if (!isTriviallyVectorizable(ID)) {
2655         BS.cancelScheduling(VL, VL0);
2656         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2657                      ReuseShuffleIndicies);
2658         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
2659         return;
2660       }
2661       Function *Int = CI->getCalledFunction();
2662       unsigned NumArgs = CI->getNumArgOperands();
2663       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
2664       for (unsigned j = 0; j != NumArgs; ++j)
2665         if (hasVectorInstrinsicScalarOpd(ID, j))
2666           ScalarArgs[j] = CI->getArgOperand(j);
2667       for (Value *V : VL) {
2668         CallInst *CI2 = dyn_cast<CallInst>(V);
2669         if (!CI2 || CI2->getCalledFunction() != Int ||
2670             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
2671             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
2672           BS.cancelScheduling(VL, VL0);
2673           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2674                        ReuseShuffleIndicies);
2675           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
2676                             << "\n");
2677           return;
2678         }
2679         // Some intrinsics have scalar arguments and should be same in order for
2680         // them to be vectorized.
2681         for (unsigned j = 0; j != NumArgs; ++j) {
2682           if (hasVectorInstrinsicScalarOpd(ID, j)) {
2683             Value *A1J = CI2->getArgOperand(j);
2684             if (ScalarArgs[j] != A1J) {
2685               BS.cancelScheduling(VL, VL0);
2686               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2687                            ReuseShuffleIndicies);
2688               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
2689                                 << " argument " << ScalarArgs[j] << "!=" << A1J
2690                                 << "\n");
2691               return;
2692             }
2693           }
2694         }
2695         // Verify that the bundle operands are identical between the two calls.
2696         if (CI->hasOperandBundles() &&
2697             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
2698                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
2699                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
2700           BS.cancelScheduling(VL, VL0);
2701           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2702                        ReuseShuffleIndicies);
2703           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
2704                             << *CI << "!=" << *V << '\n');
2705           return;
2706         }
2707       }
2708 
2709       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2710                                    ReuseShuffleIndicies);
2711       TE->setOperandsInOrder();
2712       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
2713         ValueList Operands;
2714         // Prepare the operand vector.
2715         for (Value *V : VL) {
2716           auto *CI2 = cast<CallInst>(V);
2717           Operands.push_back(CI2->getArgOperand(i));
2718         }
2719         buildTree_rec(Operands, Depth + 1, {TE, i});
2720       }
2721       return;
2722     }
2723     case Instruction::ShuffleVector: {
2724       // If this is not an alternate sequence of opcode like add-sub
2725       // then do not vectorize this instruction.
2726       if (!S.isAltShuffle()) {
2727         BS.cancelScheduling(VL, VL0);
2728         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2729                      ReuseShuffleIndicies);
2730         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
2731         return;
2732       }
2733       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2734                                    ReuseShuffleIndicies);
2735       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
2736 
2737       // Reorder operands if reordering would enable vectorization.
2738       if (isa<BinaryOperator>(VL0)) {
2739         ValueList Left, Right;
2740         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE);
2741         TE->setOperand(0, Left);
2742         TE->setOperand(1, Right);
2743         buildTree_rec(Left, Depth + 1, {TE, 0});
2744         buildTree_rec(Right, Depth + 1, {TE, 1});
2745         return;
2746       }
2747 
2748       TE->setOperandsInOrder();
2749       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
2750         ValueList Operands;
2751         // Prepare the operand vector.
2752         for (Value *V : VL)
2753           Operands.push_back(cast<Instruction>(V)->getOperand(i));
2754 
2755         buildTree_rec(Operands, Depth + 1, {TE, i});
2756       }
2757       return;
2758     }
2759     default:
2760       BS.cancelScheduling(VL, VL0);
2761       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2762                    ReuseShuffleIndicies);
2763       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
2764       return;
2765   }
2766 }
2767 
2768 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
2769   unsigned N;
2770   Type *EltTy;
2771   auto *ST = dyn_cast<StructType>(T);
2772   if (ST) {
2773     N = ST->getNumElements();
2774     EltTy = *ST->element_begin();
2775   } else {
2776     N = cast<ArrayType>(T)->getNumElements();
2777     EltTy = cast<ArrayType>(T)->getElementType();
2778   }
2779   if (!isValidElementType(EltTy))
2780     return 0;
2781   uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
2782   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
2783     return 0;
2784   if (ST) {
2785     // Check that struct is homogeneous.
2786     for (const auto *Ty : ST->elements())
2787       if (Ty != EltTy)
2788         return 0;
2789   }
2790   return N;
2791 }
2792 
2793 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2794                               SmallVectorImpl<unsigned> &CurrentOrder) const {
2795   Instruction *E0 = cast<Instruction>(OpValue);
2796   assert(E0->getOpcode() == Instruction::ExtractElement ||
2797          E0->getOpcode() == Instruction::ExtractValue);
2798   assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
2799   // Check if all of the extracts come from the same vector and from the
2800   // correct offset.
2801   Value *Vec = E0->getOperand(0);
2802 
2803   CurrentOrder.clear();
2804 
2805   // We have to extract from a vector/aggregate with the same number of elements.
2806   unsigned NElts;
2807   if (E0->getOpcode() == Instruction::ExtractValue) {
2808     const DataLayout &DL = E0->getModule()->getDataLayout();
2809     NElts = canMapToVector(Vec->getType(), DL);
2810     if (!NElts)
2811       return false;
2812     // Check if load can be rewritten as load of vector.
2813     LoadInst *LI = dyn_cast<LoadInst>(Vec);
2814     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
2815       return false;
2816   } else {
2817     NElts = Vec->getType()->getVectorNumElements();
2818   }
2819 
2820   if (NElts != VL.size())
2821     return false;
2822 
2823   // Check that all of the indices extract from the correct offset.
2824   bool ShouldKeepOrder = true;
2825   unsigned E = VL.size();
2826   // Assign to all items the initial value E + 1 so we can check if the extract
2827   // instruction index was used already.
2828   // Also, later we can check that all the indices are used and we have a
2829   // consecutive access in the extract instructions, by checking that no
2830   // element of CurrentOrder still has value E + 1.
2831   CurrentOrder.assign(E, E + 1);
2832   unsigned I = 0;
2833   for (; I < E; ++I) {
2834     auto *Inst = cast<Instruction>(VL[I]);
2835     if (Inst->getOperand(0) != Vec)
2836       break;
2837     Optional<unsigned> Idx = getExtractIndex(Inst);
2838     if (!Idx)
2839       break;
2840     const unsigned ExtIdx = *Idx;
2841     if (ExtIdx != I) {
2842       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
2843         break;
2844       ShouldKeepOrder = false;
2845       CurrentOrder[ExtIdx] = I;
2846     } else {
2847       if (CurrentOrder[I] != E + 1)
2848         break;
2849       CurrentOrder[I] = I;
2850     }
2851   }
2852   if (I < E) {
2853     CurrentOrder.clear();
2854     return false;
2855   }
2856 
2857   return ShouldKeepOrder;
2858 }
2859 
2860 bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
2861   return I->hasOneUse() ||
2862          std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
2863            return ScalarToTreeEntry.count(U) > 0;
2864          });
2865 }
2866 
2867 int BoUpSLP::getEntryCost(TreeEntry *E) {
2868   ArrayRef<Value*> VL = E->Scalars;
2869 
2870   Type *ScalarTy = VL[0]->getType();
2871   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2872     ScalarTy = SI->getValueOperand()->getType();
2873   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
2874     ScalarTy = CI->getOperand(0)->getType();
2875   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2876 
2877   // If we have computed a smaller type for the expression, update VecTy so
2878   // that the costs will be accurate.
2879   if (MinBWs.count(VL[0]))
2880     VecTy = VectorType::get(
2881         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
2882 
2883   unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
2884   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
2885   int ReuseShuffleCost = 0;
2886   if (NeedToShuffleReuses) {
2887     ReuseShuffleCost =
2888         TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
2889   }
2890   if (E->NeedToGather) {
2891     if (allConstant(VL))
2892       return 0;
2893     if (isSplat(VL)) {
2894       return ReuseShuffleCost +
2895              TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
2896     }
2897     if (E->getOpcode() == Instruction::ExtractElement &&
2898         allSameType(VL) && allSameBlock(VL)) {
2899       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL);
2900       if (ShuffleKind.hasValue()) {
2901         int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy);
2902         for (auto *V : VL) {
2903           // If all users of instruction are going to be vectorized and this
2904           // instruction itself is not going to be vectorized, consider this
2905           // instruction as dead and remove its cost from the final cost of the
2906           // vectorized tree.
2907           if (areAllUsersVectorized(cast<Instruction>(V)) &&
2908               !ScalarToTreeEntry.count(V)) {
2909             auto *IO = cast<ConstantInt>(
2910                 cast<ExtractElementInst>(V)->getIndexOperand());
2911             Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
2912                                             IO->getZExtValue());
2913           }
2914         }
2915         return ReuseShuffleCost + Cost;
2916       }
2917     }
2918     return ReuseShuffleCost + getGatherCost(VL);
2919   }
2920   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
2921   Instruction *VL0 = E->getMainOp();
2922   unsigned ShuffleOrOp =
2923       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
2924   switch (ShuffleOrOp) {
2925     case Instruction::PHI:
2926       return 0;
2927 
2928     case Instruction::ExtractValue:
2929     case Instruction::ExtractElement:
2930       if (NeedToShuffleReuses) {
2931         unsigned Idx = 0;
2932         for (unsigned I : E->ReuseShuffleIndices) {
2933           if (ShuffleOrOp == Instruction::ExtractElement) {
2934             auto *IO = cast<ConstantInt>(
2935                 cast<ExtractElementInst>(VL[I])->getIndexOperand());
2936             Idx = IO->getZExtValue();
2937             ReuseShuffleCost -= TTI->getVectorInstrCost(
2938                 Instruction::ExtractElement, VecTy, Idx);
2939           } else {
2940             ReuseShuffleCost -= TTI->getVectorInstrCost(
2941                 Instruction::ExtractElement, VecTy, Idx);
2942             ++Idx;
2943           }
2944         }
2945         Idx = ReuseShuffleNumbers;
2946         for (Value *V : VL) {
2947           if (ShuffleOrOp == Instruction::ExtractElement) {
2948             auto *IO = cast<ConstantInt>(
2949                 cast<ExtractElementInst>(V)->getIndexOperand());
2950             Idx = IO->getZExtValue();
2951           } else {
2952             --Idx;
2953           }
2954           ReuseShuffleCost +=
2955               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
2956         }
2957       }
2958       if (!E->NeedToGather) {
2959         int DeadCost = ReuseShuffleCost;
2960         if (!E->ReorderIndices.empty()) {
2961           // TODO: Merge this shuffle with the ReuseShuffleCost.
2962           DeadCost += TTI->getShuffleCost(
2963               TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
2964         }
2965         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2966           Instruction *E = cast<Instruction>(VL[i]);
2967           // If all users are going to be vectorized, instruction can be
2968           // considered as dead.
2969           // The same, if have only one user, it will be vectorized for sure.
2970           if (areAllUsersVectorized(E)) {
2971             // Take credit for instruction that will become dead.
2972             if (E->hasOneUse()) {
2973               Instruction *Ext = E->user_back();
2974               if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2975                   all_of(Ext->users(),
2976                          [](User *U) { return isa<GetElementPtrInst>(U); })) {
2977                 // Use getExtractWithExtendCost() to calculate the cost of
2978                 // extractelement/ext pair.
2979                 DeadCost -= TTI->getExtractWithExtendCost(
2980                     Ext->getOpcode(), Ext->getType(), VecTy, i);
2981                 // Add back the cost of s|zext which is subtracted separately.
2982                 DeadCost += TTI->getCastInstrCost(
2983                     Ext->getOpcode(), Ext->getType(), E->getType(), Ext);
2984                 continue;
2985               }
2986             }
2987             DeadCost -=
2988                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
2989           }
2990         }
2991         return DeadCost;
2992       }
2993       return ReuseShuffleCost + getGatherCost(VL);
2994 
2995     case Instruction::ZExt:
2996     case Instruction::SExt:
2997     case Instruction::FPToUI:
2998     case Instruction::FPToSI:
2999     case Instruction::FPExt:
3000     case Instruction::PtrToInt:
3001     case Instruction::IntToPtr:
3002     case Instruction::SIToFP:
3003     case Instruction::UIToFP:
3004     case Instruction::Trunc:
3005     case Instruction::FPTrunc:
3006     case Instruction::BitCast: {
3007       Type *SrcTy = VL0->getOperand(0)->getType();
3008       int ScalarEltCost =
3009           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, VL0);
3010       if (NeedToShuffleReuses) {
3011         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3012       }
3013 
3014       // Calculate the cost of this instruction.
3015       int ScalarCost = VL.size() * ScalarEltCost;
3016 
3017       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
3018       int VecCost = 0;
3019       // Check if the values are candidates to demote.
3020       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
3021         VecCost = ReuseShuffleCost +
3022                   TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy, VL0);
3023       }
3024       return VecCost - ScalarCost;
3025     }
3026     case Instruction::FCmp:
3027     case Instruction::ICmp:
3028     case Instruction::Select: {
3029       // Calculate the cost of this instruction.
3030       int ScalarEltCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
3031                                                   Builder.getInt1Ty(), VL0);
3032       if (NeedToShuffleReuses) {
3033         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3034       }
3035       VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
3036       int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3037       int VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), VecTy, MaskTy, VL0);
3038       return ReuseShuffleCost + VecCost - ScalarCost;
3039     }
3040     case Instruction::FNeg:
3041     case Instruction::Add:
3042     case Instruction::FAdd:
3043     case Instruction::Sub:
3044     case Instruction::FSub:
3045     case Instruction::Mul:
3046     case Instruction::FMul:
3047     case Instruction::UDiv:
3048     case Instruction::SDiv:
3049     case Instruction::FDiv:
3050     case Instruction::URem:
3051     case Instruction::SRem:
3052     case Instruction::FRem:
3053     case Instruction::Shl:
3054     case Instruction::LShr:
3055     case Instruction::AShr:
3056     case Instruction::And:
3057     case Instruction::Or:
3058     case Instruction::Xor: {
3059       // Certain instructions can be cheaper to vectorize if they have a
3060       // constant second vector operand.
3061       TargetTransformInfo::OperandValueKind Op1VK =
3062           TargetTransformInfo::OK_AnyValue;
3063       TargetTransformInfo::OperandValueKind Op2VK =
3064           TargetTransformInfo::OK_UniformConstantValue;
3065       TargetTransformInfo::OperandValueProperties Op1VP =
3066           TargetTransformInfo::OP_None;
3067       TargetTransformInfo::OperandValueProperties Op2VP =
3068           TargetTransformInfo::OP_PowerOf2;
3069 
3070       // If all operands are exactly the same ConstantInt then set the
3071       // operand kind to OK_UniformConstantValue.
3072       // If instead not all operands are constants, then set the operand kind
3073       // to OK_AnyValue. If all operands are constants but not the same,
3074       // then set the operand kind to OK_NonUniformConstantValue.
3075       ConstantInt *CInt0 = nullptr;
3076       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3077         const Instruction *I = cast<Instruction>(VL[i]);
3078         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
3079         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
3080         if (!CInt) {
3081           Op2VK = TargetTransformInfo::OK_AnyValue;
3082           Op2VP = TargetTransformInfo::OP_None;
3083           break;
3084         }
3085         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
3086             !CInt->getValue().isPowerOf2())
3087           Op2VP = TargetTransformInfo::OP_None;
3088         if (i == 0) {
3089           CInt0 = CInt;
3090           continue;
3091         }
3092         if (CInt0 != CInt)
3093           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
3094       }
3095 
3096       SmallVector<const Value *, 4> Operands(VL0->operand_values());
3097       int ScalarEltCost = TTI->getArithmeticInstrCost(
3098           E->getOpcode(), ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands);
3099       if (NeedToShuffleReuses) {
3100         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3101       }
3102       int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3103       int VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, Op1VK,
3104                                                 Op2VK, Op1VP, Op2VP, Operands);
3105       return ReuseShuffleCost + VecCost - ScalarCost;
3106     }
3107     case Instruction::GetElementPtr: {
3108       TargetTransformInfo::OperandValueKind Op1VK =
3109           TargetTransformInfo::OK_AnyValue;
3110       TargetTransformInfo::OperandValueKind Op2VK =
3111           TargetTransformInfo::OK_UniformConstantValue;
3112 
3113       int ScalarEltCost =
3114           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
3115       if (NeedToShuffleReuses) {
3116         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3117       }
3118       int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3119       int VecCost =
3120           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
3121       return ReuseShuffleCost + VecCost - ScalarCost;
3122     }
3123     case Instruction::Load: {
3124       // Cost of wide load - cost of scalar loads.
3125       unsigned alignment = cast<LoadInst>(VL0)->getAlignment();
3126       int ScalarEltCost =
3127           TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
3128       if (NeedToShuffleReuses) {
3129         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3130       }
3131       int ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
3132       int VecLdCost =
3133           TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0, VL0);
3134       if (!E->ReorderIndices.empty()) {
3135         // TODO: Merge this shuffle with the ReuseShuffleCost.
3136         VecLdCost += TTI->getShuffleCost(
3137             TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
3138       }
3139       return ReuseShuffleCost + VecLdCost - ScalarLdCost;
3140     }
3141     case Instruction::Store: {
3142       // We know that we can merge the stores. Calculate the cost.
3143       unsigned alignment = cast<StoreInst>(VL0)->getAlignment();
3144       int ScalarEltCost =
3145           TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
3146       if (NeedToShuffleReuses) {
3147         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3148       }
3149       int ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
3150       int VecStCost =
3151           TTI->getMemoryOpCost(Instruction::Store, VecTy, alignment, 0, VL0);
3152       return ReuseShuffleCost + VecStCost - ScalarStCost;
3153     }
3154     case Instruction::Call: {
3155       CallInst *CI = cast<CallInst>(VL0);
3156       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3157 
3158       // Calculate the cost of the scalar and vector calls.
3159       SmallVector<Type *, 4> ScalarTys;
3160       for (unsigned op = 0, opc = CI->getNumArgOperands(); op != opc; ++op)
3161         ScalarTys.push_back(CI->getArgOperand(op)->getType());
3162 
3163       FastMathFlags FMF;
3164       if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3165         FMF = FPMO->getFastMathFlags();
3166 
3167       int ScalarEltCost =
3168           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
3169       if (NeedToShuffleReuses) {
3170         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3171       }
3172       int ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
3173 
3174       SmallVector<Value *, 4> Args(CI->arg_operands());
3175       int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
3176                                                    VecTy->getNumElements());
3177 
3178       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
3179                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
3180                         << " for " << *CI << "\n");
3181 
3182       return ReuseShuffleCost + VecCallCost - ScalarCallCost;
3183     }
3184     case Instruction::ShuffleVector: {
3185       assert(E->isAltShuffle() &&
3186              ((Instruction::isBinaryOp(E->getOpcode()) &&
3187                Instruction::isBinaryOp(E->getAltOpcode())) ||
3188               (Instruction::isCast(E->getOpcode()) &&
3189                Instruction::isCast(E->getAltOpcode()))) &&
3190              "Invalid Shuffle Vector Operand");
3191       int ScalarCost = 0;
3192       if (NeedToShuffleReuses) {
3193         for (unsigned Idx : E->ReuseShuffleIndices) {
3194           Instruction *I = cast<Instruction>(VL[Idx]);
3195           ReuseShuffleCost -= TTI->getInstructionCost(
3196               I, TargetTransformInfo::TCK_RecipThroughput);
3197         }
3198         for (Value *V : VL) {
3199           Instruction *I = cast<Instruction>(V);
3200           ReuseShuffleCost += TTI->getInstructionCost(
3201               I, TargetTransformInfo::TCK_RecipThroughput);
3202         }
3203       }
3204       for (Value *V : VL) {
3205         Instruction *I = cast<Instruction>(V);
3206         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
3207         ScalarCost += TTI->getInstructionCost(
3208             I, TargetTransformInfo::TCK_RecipThroughput);
3209       }
3210       // VecCost is equal to sum of the cost of creating 2 vectors
3211       // and the cost of creating shuffle.
3212       int VecCost = 0;
3213       if (Instruction::isBinaryOp(E->getOpcode())) {
3214         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy);
3215         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy);
3216       } else {
3217         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
3218         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
3219         VectorType *Src0Ty = VectorType::get(Src0SclTy, VL.size());
3220         VectorType *Src1Ty = VectorType::get(Src1SclTy, VL.size());
3221         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty);
3222         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty);
3223       }
3224       VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
3225       return ReuseShuffleCost + VecCost - ScalarCost;
3226     }
3227     default:
3228       llvm_unreachable("Unknown instruction");
3229   }
3230 }
3231 
3232 bool BoUpSLP::isFullyVectorizableTinyTree() const {
3233   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
3234                     << VectorizableTree.size() << " is fully vectorizable .\n");
3235 
3236   // We only handle trees of heights 1 and 2.
3237   if (VectorizableTree.size() == 1 && !VectorizableTree[0]->NeedToGather)
3238     return true;
3239 
3240   if (VectorizableTree.size() != 2)
3241     return false;
3242 
3243   // Handle splat and all-constants stores.
3244   if (!VectorizableTree[0]->NeedToGather &&
3245       (allConstant(VectorizableTree[1]->Scalars) ||
3246        isSplat(VectorizableTree[1]->Scalars)))
3247     return true;
3248 
3249   // Gathering cost would be too much for tiny trees.
3250   if (VectorizableTree[0]->NeedToGather || VectorizableTree[1]->NeedToGather)
3251     return false;
3252 
3253   return true;
3254 }
3255 
3256 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
3257   // We can vectorize the tree if its size is greater than or equal to the
3258   // minimum size specified by the MinTreeSize command line option.
3259   if (VectorizableTree.size() >= MinTreeSize)
3260     return false;
3261 
3262   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
3263   // can vectorize it if we can prove it fully vectorizable.
3264   if (isFullyVectorizableTinyTree())
3265     return false;
3266 
3267   assert(VectorizableTree.empty()
3268              ? ExternalUses.empty()
3269              : true && "We shouldn't have any external users");
3270 
3271   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
3272   // vectorizable.
3273   return true;
3274 }
3275 
3276 int BoUpSLP::getSpillCost() const {
3277   // Walk from the bottom of the tree to the top, tracking which values are
3278   // live. When we see a call instruction that is not part of our tree,
3279   // query TTI to see if there is a cost to keeping values live over it
3280   // (for example, if spills and fills are required).
3281   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
3282   int Cost = 0;
3283 
3284   SmallPtrSet<Instruction*, 4> LiveValues;
3285   Instruction *PrevInst = nullptr;
3286 
3287   for (const auto &TEPtr : VectorizableTree) {
3288     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
3289     if (!Inst)
3290       continue;
3291 
3292     if (!PrevInst) {
3293       PrevInst = Inst;
3294       continue;
3295     }
3296 
3297     // Update LiveValues.
3298     LiveValues.erase(PrevInst);
3299     for (auto &J : PrevInst->operands()) {
3300       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
3301         LiveValues.insert(cast<Instruction>(&*J));
3302     }
3303 
3304     LLVM_DEBUG({
3305       dbgs() << "SLP: #LV: " << LiveValues.size();
3306       for (auto *X : LiveValues)
3307         dbgs() << " " << X->getName();
3308       dbgs() << ", Looking at ";
3309       Inst->dump();
3310     });
3311 
3312     // Now find the sequence of instructions between PrevInst and Inst.
3313     unsigned NumCalls = 0;
3314     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
3315                                  PrevInstIt =
3316                                      PrevInst->getIterator().getReverse();
3317     while (InstIt != PrevInstIt) {
3318       if (PrevInstIt == PrevInst->getParent()->rend()) {
3319         PrevInstIt = Inst->getParent()->rbegin();
3320         continue;
3321       }
3322 
3323       // Debug informations don't impact spill cost.
3324       if ((isa<CallInst>(&*PrevInstIt) &&
3325            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
3326           &*PrevInstIt != PrevInst)
3327         NumCalls++;
3328 
3329       ++PrevInstIt;
3330     }
3331 
3332     if (NumCalls) {
3333       SmallVector<Type*, 4> V;
3334       for (auto *II : LiveValues)
3335         V.push_back(VectorType::get(II->getType(), BundleWidth));
3336       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
3337     }
3338 
3339     PrevInst = Inst;
3340   }
3341 
3342   return Cost;
3343 }
3344 
3345 int BoUpSLP::getTreeCost() {
3346   int Cost = 0;
3347   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
3348                     << VectorizableTree.size() << ".\n");
3349 
3350   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
3351 
3352   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
3353     TreeEntry &TE = *VectorizableTree[I].get();
3354 
3355     // We create duplicate tree entries for gather sequences that have multiple
3356     // uses. However, we should not compute the cost of duplicate sequences.
3357     // For example, if we have a build vector (i.e., insertelement sequence)
3358     // that is used by more than one vector instruction, we only need to
3359     // compute the cost of the insertelement instructions once. The redundant
3360     // instructions will be eliminated by CSE.
3361     //
3362     // We should consider not creating duplicate tree entries for gather
3363     // sequences, and instead add additional edges to the tree representing
3364     // their uses. Since such an approach results in fewer total entries,
3365     // existing heuristics based on tree size may yield different results.
3366     //
3367     if (TE.NeedToGather &&
3368         std::any_of(
3369             std::next(VectorizableTree.begin(), I + 1), VectorizableTree.end(),
3370             [TE](const std::unique_ptr<TreeEntry> &EntryPtr) {
3371               return EntryPtr->NeedToGather && EntryPtr->isSame(TE.Scalars);
3372             }))
3373       continue;
3374 
3375     int C = getEntryCost(&TE);
3376     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
3377                       << " for bundle that starts with " << *TE.Scalars[0]
3378                       << ".\n");
3379     Cost += C;
3380   }
3381 
3382   SmallPtrSet<Value *, 16> ExtractCostCalculated;
3383   int ExtractCost = 0;
3384   for (ExternalUser &EU : ExternalUses) {
3385     // We only add extract cost once for the same scalar.
3386     if (!ExtractCostCalculated.insert(EU.Scalar).second)
3387       continue;
3388 
3389     // Uses by ephemeral values are free (because the ephemeral value will be
3390     // removed prior to code generation, and so the extraction will be
3391     // removed as well).
3392     if (EphValues.count(EU.User))
3393       continue;
3394 
3395     // If we plan to rewrite the tree in a smaller type, we will need to sign
3396     // extend the extracted value back to the original type. Here, we account
3397     // for the extract and the added cost of the sign extend if needed.
3398     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
3399     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
3400     if (MinBWs.count(ScalarRoot)) {
3401       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3402       auto Extend =
3403           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
3404       VecTy = VectorType::get(MinTy, BundleWidth);
3405       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
3406                                                    VecTy, EU.Lane);
3407     } else {
3408       ExtractCost +=
3409           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
3410     }
3411   }
3412 
3413   int SpillCost = getSpillCost();
3414   Cost += SpillCost + ExtractCost;
3415 
3416   std::string Str;
3417   {
3418     raw_string_ostream OS(Str);
3419     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
3420        << "SLP: Extract Cost = " << ExtractCost << ".\n"
3421        << "SLP: Total Cost = " << Cost << ".\n";
3422   }
3423   LLVM_DEBUG(dbgs() << Str);
3424 
3425   if (ViewSLPTree)
3426     ViewGraph(this, "SLP" + F->getName(), false, Str);
3427 
3428   return Cost;
3429 }
3430 
3431 int BoUpSLP::getGatherCost(Type *Ty,
3432                            const DenseSet<unsigned> &ShuffledIndices) const {
3433   int Cost = 0;
3434   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
3435     if (!ShuffledIndices.count(i))
3436       Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
3437   if (!ShuffledIndices.empty())
3438     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
3439   return Cost;
3440 }
3441 
3442 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
3443   // Find the type of the operands in VL.
3444   Type *ScalarTy = VL[0]->getType();
3445   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
3446     ScalarTy = SI->getValueOperand()->getType();
3447   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
3448   // Find the cost of inserting/extracting values from the vector.
3449   // Check if the same elements are inserted several times and count them as
3450   // shuffle candidates.
3451   DenseSet<unsigned> ShuffledElements;
3452   DenseSet<Value *> UniqueElements;
3453   // Iterate in reverse order to consider insert elements with the high cost.
3454   for (unsigned I = VL.size(); I > 0; --I) {
3455     unsigned Idx = I - 1;
3456     if (!UniqueElements.insert(VL[Idx]).second)
3457       ShuffledElements.insert(Idx);
3458   }
3459   return getGatherCost(VecTy, ShuffledElements);
3460 }
3461 
3462 // Perform operand reordering on the instructions in VL and return the reordered
3463 // operands in Left and Right.
3464 void BoUpSLP::reorderInputsAccordingToOpcode(
3465     ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left,
3466     SmallVectorImpl<Value *> &Right, const DataLayout &DL,
3467     ScalarEvolution &SE) {
3468   if (VL.empty())
3469     return;
3470   VLOperands Ops(VL, DL, SE);
3471   // Reorder the operands in place.
3472   Ops.reorder();
3473   Left = Ops.getVL(0);
3474   Right = Ops.getVL(1);
3475 }
3476 
3477 void BoUpSLP::setInsertPointAfterBundle(TreeEntry *E) {
3478   // Get the basic block this bundle is in. All instructions in the bundle
3479   // should be in this block.
3480   auto *Front = E->getMainOp();
3481   auto *BB = Front->getParent();
3482   assert(llvm::all_of(make_range(E->Scalars.begin(), E->Scalars.end()),
3483                       [=](Value *V) -> bool {
3484                         auto *I = cast<Instruction>(V);
3485                         return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
3486                       }));
3487 
3488   // The last instruction in the bundle in program order.
3489   Instruction *LastInst = nullptr;
3490 
3491   // Find the last instruction. The common case should be that BB has been
3492   // scheduled, and the last instruction is VL.back(). So we start with
3493   // VL.back() and iterate over schedule data until we reach the end of the
3494   // bundle. The end of the bundle is marked by null ScheduleData.
3495   if (BlocksSchedules.count(BB)) {
3496     auto *Bundle =
3497         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
3498     if (Bundle && Bundle->isPartOfBundle())
3499       for (; Bundle; Bundle = Bundle->NextInBundle)
3500         if (Bundle->OpValue == Bundle->Inst)
3501           LastInst = Bundle->Inst;
3502   }
3503 
3504   // LastInst can still be null at this point if there's either not an entry
3505   // for BB in BlocksSchedules or there's no ScheduleData available for
3506   // VL.back(). This can be the case if buildTree_rec aborts for various
3507   // reasons (e.g., the maximum recursion depth is reached, the maximum region
3508   // size is reached, etc.). ScheduleData is initialized in the scheduling
3509   // "dry-run".
3510   //
3511   // If this happens, we can still find the last instruction by brute force. We
3512   // iterate forwards from Front (inclusive) until we either see all
3513   // instructions in the bundle or reach the end of the block. If Front is the
3514   // last instruction in program order, LastInst will be set to Front, and we
3515   // will visit all the remaining instructions in the block.
3516   //
3517   // One of the reasons we exit early from buildTree_rec is to place an upper
3518   // bound on compile-time. Thus, taking an additional compile-time hit here is
3519   // not ideal. However, this should be exceedingly rare since it requires that
3520   // we both exit early from buildTree_rec and that the bundle be out-of-order
3521   // (causing us to iterate all the way to the end of the block).
3522   if (!LastInst) {
3523     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
3524     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
3525       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
3526         LastInst = &I;
3527       if (Bundle.empty())
3528         break;
3529     }
3530   }
3531   assert(LastInst && "Failed to find last instruction in bundle");
3532 
3533   // Set the insertion point after the last instruction in the bundle. Set the
3534   // debug location to Front.
3535   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
3536   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
3537 }
3538 
3539 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
3540   Value *Vec = UndefValue::get(Ty);
3541   // Generate the 'InsertElement' instruction.
3542   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
3543     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
3544     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
3545       GatherSeq.insert(Insrt);
3546       CSEBlocks.insert(Insrt->getParent());
3547 
3548       // Add to our 'need-to-extract' list.
3549       if (TreeEntry *E = getTreeEntry(VL[i])) {
3550         // Find which lane we need to extract.
3551         int FoundLane = -1;
3552         for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
3553           // Is this the lane of the scalar that we are looking for ?
3554           if (E->Scalars[Lane] == VL[i]) {
3555             FoundLane = Lane;
3556             break;
3557           }
3558         }
3559         assert(FoundLane >= 0 && "Could not find the correct lane");
3560         if (!E->ReuseShuffleIndices.empty()) {
3561           FoundLane =
3562               std::distance(E->ReuseShuffleIndices.begin(),
3563                             llvm::find(E->ReuseShuffleIndices, FoundLane));
3564         }
3565         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
3566       }
3567     }
3568   }
3569 
3570   return Vec;
3571 }
3572 
3573 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
3574   InstructionsState S = getSameOpcode(VL);
3575   if (S.getOpcode()) {
3576     if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3577       if (E->isSame(VL)) {
3578         Value *V = vectorizeTree(E);
3579         if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
3580           // We need to get the vectorized value but without shuffle.
3581           if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
3582             V = SV->getOperand(0);
3583           } else {
3584             // Reshuffle to get only unique values.
3585             SmallVector<unsigned, 4> UniqueIdxs;
3586             SmallSet<unsigned, 4> UsedIdxs;
3587             for(unsigned Idx : E->ReuseShuffleIndices)
3588               if (UsedIdxs.insert(Idx).second)
3589                 UniqueIdxs.emplace_back(Idx);
3590             V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
3591                                             UniqueIdxs);
3592           }
3593         }
3594         return V;
3595       }
3596     }
3597   }
3598 
3599   Type *ScalarTy = S.OpValue->getType();
3600   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3601     ScalarTy = SI->getValueOperand()->getType();
3602 
3603   // Check that every instruction appears once in this bundle.
3604   SmallVector<unsigned, 4> ReuseShuffleIndicies;
3605   SmallVector<Value *, 4> UniqueValues;
3606   if (VL.size() > 2) {
3607     DenseMap<Value *, unsigned> UniquePositions;
3608     for (Value *V : VL) {
3609       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3610       ReuseShuffleIndicies.emplace_back(Res.first->second);
3611       if (Res.second || isa<Constant>(V))
3612         UniqueValues.emplace_back(V);
3613     }
3614     // Do not shuffle single element or if number of unique values is not power
3615     // of 2.
3616     if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
3617         !llvm::isPowerOf2_32(UniqueValues.size()))
3618       ReuseShuffleIndicies.clear();
3619     else
3620       VL = UniqueValues;
3621   }
3622   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
3623 
3624   Value *V = Gather(VL, VecTy);
3625   if (!ReuseShuffleIndicies.empty()) {
3626     V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3627                                     ReuseShuffleIndicies, "shuffle");
3628     if (auto *I = dyn_cast<Instruction>(V)) {
3629       GatherSeq.insert(I);
3630       CSEBlocks.insert(I->getParent());
3631     }
3632   }
3633   return V;
3634 }
3635 
3636 static void inversePermutation(ArrayRef<unsigned> Indices,
3637                                SmallVectorImpl<unsigned> &Mask) {
3638   Mask.clear();
3639   const unsigned E = Indices.size();
3640   Mask.resize(E);
3641   for (unsigned I = 0; I < E; ++I)
3642     Mask[Indices[I]] = I;
3643 }
3644 
3645 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
3646   IRBuilder<>::InsertPointGuard Guard(Builder);
3647 
3648   if (E->VectorizedValue) {
3649     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
3650     return E->VectorizedValue;
3651   }
3652 
3653   Instruction *VL0 = E->getMainOp();
3654   Type *ScalarTy = VL0->getType();
3655   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
3656     ScalarTy = SI->getValueOperand()->getType();
3657   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
3658 
3659   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
3660 
3661   if (E->NeedToGather) {
3662     setInsertPointAfterBundle(E);
3663     auto *V = Gather(E->Scalars, VecTy);
3664     if (NeedToShuffleReuses) {
3665       V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3666                                       E->ReuseShuffleIndices, "shuffle");
3667       if (auto *I = dyn_cast<Instruction>(V)) {
3668         GatherSeq.insert(I);
3669         CSEBlocks.insert(I->getParent());
3670       }
3671     }
3672     E->VectorizedValue = V;
3673     return V;
3674   }
3675 
3676   unsigned ShuffleOrOp =
3677       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
3678   switch (ShuffleOrOp) {
3679     case Instruction::PHI: {
3680       auto *PH = cast<PHINode>(VL0);
3681       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
3682       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3683       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
3684       Value *V = NewPhi;
3685       if (NeedToShuffleReuses) {
3686         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3687                                         E->ReuseShuffleIndices, "shuffle");
3688       }
3689       E->VectorizedValue = V;
3690 
3691       // PHINodes may have multiple entries from the same block. We want to
3692       // visit every block once.
3693       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
3694 
3695       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
3696         ValueList Operands;
3697         BasicBlock *IBB = PH->getIncomingBlock(i);
3698 
3699         if (!VisitedBBs.insert(IBB).second) {
3700           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
3701           continue;
3702         }
3703 
3704         Builder.SetInsertPoint(IBB->getTerminator());
3705         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3706         Value *Vec = vectorizeTree(E->getOperand(i));
3707         NewPhi->addIncoming(Vec, IBB);
3708       }
3709 
3710       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
3711              "Invalid number of incoming values");
3712       return V;
3713     }
3714 
3715     case Instruction::ExtractElement: {
3716       if (!E->NeedToGather) {
3717         Value *V = E->getSingleOperand(0);
3718         if (!E->ReorderIndices.empty()) {
3719           OrdersType Mask;
3720           inversePermutation(E->ReorderIndices, Mask);
3721           Builder.SetInsertPoint(VL0);
3722           V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask,
3723                                           "reorder_shuffle");
3724         }
3725         if (NeedToShuffleReuses) {
3726           // TODO: Merge this shuffle with the ReorderShuffleMask.
3727           if (E->ReorderIndices.empty())
3728             Builder.SetInsertPoint(VL0);
3729           V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3730                                           E->ReuseShuffleIndices, "shuffle");
3731         }
3732         E->VectorizedValue = V;
3733         return V;
3734       }
3735       setInsertPointAfterBundle(E);
3736       auto *V = Gather(E->Scalars, VecTy);
3737       if (NeedToShuffleReuses) {
3738         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3739                                         E->ReuseShuffleIndices, "shuffle");
3740         if (auto *I = dyn_cast<Instruction>(V)) {
3741           GatherSeq.insert(I);
3742           CSEBlocks.insert(I->getParent());
3743         }
3744       }
3745       E->VectorizedValue = V;
3746       return V;
3747     }
3748     case Instruction::ExtractValue: {
3749       if (!E->NeedToGather) {
3750         LoadInst *LI = cast<LoadInst>(E->getSingleOperand(0));
3751         Builder.SetInsertPoint(LI);
3752         PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
3753         Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
3754         LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlignment());
3755         Value *NewV = propagateMetadata(V, E->Scalars);
3756         if (!E->ReorderIndices.empty()) {
3757           OrdersType Mask;
3758           inversePermutation(E->ReorderIndices, Mask);
3759           NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask,
3760                                              "reorder_shuffle");
3761         }
3762         if (NeedToShuffleReuses) {
3763           // TODO: Merge this shuffle with the ReorderShuffleMask.
3764           NewV = Builder.CreateShuffleVector(
3765               NewV, UndefValue::get(VecTy), E->ReuseShuffleIndices, "shuffle");
3766         }
3767         E->VectorizedValue = NewV;
3768         return NewV;
3769       }
3770       setInsertPointAfterBundle(E);
3771       auto *V = Gather(E->Scalars, VecTy);
3772       if (NeedToShuffleReuses) {
3773         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3774                                         E->ReuseShuffleIndices, "shuffle");
3775         if (auto *I = dyn_cast<Instruction>(V)) {
3776           GatherSeq.insert(I);
3777           CSEBlocks.insert(I->getParent());
3778         }
3779       }
3780       E->VectorizedValue = V;
3781       return V;
3782     }
3783     case Instruction::ZExt:
3784     case Instruction::SExt:
3785     case Instruction::FPToUI:
3786     case Instruction::FPToSI:
3787     case Instruction::FPExt:
3788     case Instruction::PtrToInt:
3789     case Instruction::IntToPtr:
3790     case Instruction::SIToFP:
3791     case Instruction::UIToFP:
3792     case Instruction::Trunc:
3793     case Instruction::FPTrunc:
3794     case Instruction::BitCast: {
3795       setInsertPointAfterBundle(E);
3796 
3797       Value *InVec = vectorizeTree(E->getOperand(0));
3798 
3799       if (E->VectorizedValue) {
3800         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3801         return E->VectorizedValue;
3802       }
3803 
3804       auto *CI = cast<CastInst>(VL0);
3805       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
3806       if (NeedToShuffleReuses) {
3807         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3808                                         E->ReuseShuffleIndices, "shuffle");
3809       }
3810       E->VectorizedValue = V;
3811       ++NumVectorInstructions;
3812       return V;
3813     }
3814     case Instruction::FCmp:
3815     case Instruction::ICmp: {
3816       setInsertPointAfterBundle(E);
3817 
3818       Value *L = vectorizeTree(E->getOperand(0));
3819       Value *R = vectorizeTree(E->getOperand(1));
3820 
3821       if (E->VectorizedValue) {
3822         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3823         return E->VectorizedValue;
3824       }
3825 
3826       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3827       Value *V;
3828       if (E->getOpcode() == Instruction::FCmp)
3829         V = Builder.CreateFCmp(P0, L, R);
3830       else
3831         V = Builder.CreateICmp(P0, L, R);
3832 
3833       propagateIRFlags(V, E->Scalars, VL0);
3834       if (NeedToShuffleReuses) {
3835         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3836                                         E->ReuseShuffleIndices, "shuffle");
3837       }
3838       E->VectorizedValue = V;
3839       ++NumVectorInstructions;
3840       return V;
3841     }
3842     case Instruction::Select: {
3843       setInsertPointAfterBundle(E);
3844 
3845       Value *Cond = vectorizeTree(E->getOperand(0));
3846       Value *True = vectorizeTree(E->getOperand(1));
3847       Value *False = vectorizeTree(E->getOperand(2));
3848 
3849       if (E->VectorizedValue) {
3850         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3851         return E->VectorizedValue;
3852       }
3853 
3854       Value *V = Builder.CreateSelect(Cond, True, False);
3855       if (NeedToShuffleReuses) {
3856         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3857                                         E->ReuseShuffleIndices, "shuffle");
3858       }
3859       E->VectorizedValue = V;
3860       ++NumVectorInstructions;
3861       return V;
3862     }
3863     case Instruction::FNeg: {
3864       setInsertPointAfterBundle(E);
3865 
3866       Value *Op = vectorizeTree(E->getOperand(0));
3867 
3868       if (E->VectorizedValue) {
3869         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3870         return E->VectorizedValue;
3871       }
3872 
3873       Value *V = Builder.CreateUnOp(
3874           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
3875       propagateIRFlags(V, E->Scalars, VL0);
3876       if (auto *I = dyn_cast<Instruction>(V))
3877         V = propagateMetadata(I, E->Scalars);
3878 
3879       if (NeedToShuffleReuses) {
3880         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3881                                         E->ReuseShuffleIndices, "shuffle");
3882       }
3883       E->VectorizedValue = V;
3884       ++NumVectorInstructions;
3885 
3886       return V;
3887     }
3888     case Instruction::Add:
3889     case Instruction::FAdd:
3890     case Instruction::Sub:
3891     case Instruction::FSub:
3892     case Instruction::Mul:
3893     case Instruction::FMul:
3894     case Instruction::UDiv:
3895     case Instruction::SDiv:
3896     case Instruction::FDiv:
3897     case Instruction::URem:
3898     case Instruction::SRem:
3899     case Instruction::FRem:
3900     case Instruction::Shl:
3901     case Instruction::LShr:
3902     case Instruction::AShr:
3903     case Instruction::And:
3904     case Instruction::Or:
3905     case Instruction::Xor: {
3906       setInsertPointAfterBundle(E);
3907 
3908       Value *LHS = vectorizeTree(E->getOperand(0));
3909       Value *RHS = vectorizeTree(E->getOperand(1));
3910 
3911       if (E->VectorizedValue) {
3912         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3913         return E->VectorizedValue;
3914       }
3915 
3916       Value *V = Builder.CreateBinOp(
3917           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
3918           RHS);
3919       propagateIRFlags(V, E->Scalars, VL0);
3920       if (auto *I = dyn_cast<Instruction>(V))
3921         V = propagateMetadata(I, E->Scalars);
3922 
3923       if (NeedToShuffleReuses) {
3924         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3925                                         E->ReuseShuffleIndices, "shuffle");
3926       }
3927       E->VectorizedValue = V;
3928       ++NumVectorInstructions;
3929 
3930       return V;
3931     }
3932     case Instruction::Load: {
3933       // Loads are inserted at the head of the tree because we don't want to
3934       // sink them all the way down past store instructions.
3935       bool IsReorder = E->updateStateIfReorder();
3936       if (IsReorder)
3937         VL0 = E->getMainOp();
3938       setInsertPointAfterBundle(E);
3939 
3940       LoadInst *LI = cast<LoadInst>(VL0);
3941       Type *ScalarLoadTy = LI->getType();
3942       unsigned AS = LI->getPointerAddressSpace();
3943 
3944       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
3945                                             VecTy->getPointerTo(AS));
3946 
3947       // The pointer operand uses an in-tree scalar so we add the new BitCast to
3948       // ExternalUses list to make sure that an extract will be generated in the
3949       // future.
3950       Value *PO = LI->getPointerOperand();
3951       if (getTreeEntry(PO))
3952         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
3953 
3954       unsigned Alignment = LI->getAlignment();
3955       LI = Builder.CreateLoad(VecTy, VecPtr);
3956       if (!Alignment) {
3957         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
3958       }
3959       LI->setAlignment(Alignment);
3960       Value *V = propagateMetadata(LI, E->Scalars);
3961       if (IsReorder) {
3962         OrdersType Mask;
3963         inversePermutation(E->ReorderIndices, Mask);
3964         V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
3965                                         Mask, "reorder_shuffle");
3966       }
3967       if (NeedToShuffleReuses) {
3968         // TODO: Merge this shuffle with the ReorderShuffleMask.
3969         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3970                                         E->ReuseShuffleIndices, "shuffle");
3971       }
3972       E->VectorizedValue = V;
3973       ++NumVectorInstructions;
3974       return V;
3975     }
3976     case Instruction::Store: {
3977       StoreInst *SI = cast<StoreInst>(VL0);
3978       unsigned Alignment = SI->getAlignment();
3979       unsigned AS = SI->getPointerAddressSpace();
3980 
3981       setInsertPointAfterBundle(E);
3982 
3983       Value *VecValue = vectorizeTree(E->getOperand(0));
3984       Value *ScalarPtr = SI->getPointerOperand();
3985       Value *VecPtr = Builder.CreateBitCast(ScalarPtr, VecTy->getPointerTo(AS));
3986       StoreInst *ST = Builder.CreateStore(VecValue, VecPtr);
3987 
3988       // The pointer operand uses an in-tree scalar, so add the new BitCast to
3989       // ExternalUses to make sure that an extract will be generated in the
3990       // future.
3991       if (getTreeEntry(ScalarPtr))
3992         ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
3993 
3994       if (!Alignment)
3995         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
3996 
3997       ST->setAlignment(Alignment);
3998       Value *V = propagateMetadata(ST, E->Scalars);
3999       if (NeedToShuffleReuses) {
4000         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4001                                         E->ReuseShuffleIndices, "shuffle");
4002       }
4003       E->VectorizedValue = V;
4004       ++NumVectorInstructions;
4005       return V;
4006     }
4007     case Instruction::GetElementPtr: {
4008       setInsertPointAfterBundle(E);
4009 
4010       Value *Op0 = vectorizeTree(E->getOperand(0));
4011 
4012       std::vector<Value *> OpVecs;
4013       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
4014            ++j) {
4015         Value *OpVec = vectorizeTree(E->getOperand(j));
4016         OpVecs.push_back(OpVec);
4017       }
4018 
4019       Value *V = Builder.CreateGEP(
4020           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
4021       if (Instruction *I = dyn_cast<Instruction>(V))
4022         V = propagateMetadata(I, E->Scalars);
4023 
4024       if (NeedToShuffleReuses) {
4025         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4026                                         E->ReuseShuffleIndices, "shuffle");
4027       }
4028       E->VectorizedValue = V;
4029       ++NumVectorInstructions;
4030 
4031       return V;
4032     }
4033     case Instruction::Call: {
4034       CallInst *CI = cast<CallInst>(VL0);
4035       setInsertPointAfterBundle(E);
4036 
4037       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
4038       if (Function *FI = CI->getCalledFunction())
4039         IID = FI->getIntrinsicID();
4040 
4041       Value *ScalarArg = nullptr;
4042       std::vector<Value *> OpVecs;
4043       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
4044         ValueList OpVL;
4045         // Some intrinsics have scalar arguments. This argument should not be
4046         // vectorized.
4047         if (hasVectorInstrinsicScalarOpd(IID, j)) {
4048           CallInst *CEI = cast<CallInst>(VL0);
4049           ScalarArg = CEI->getArgOperand(j);
4050           OpVecs.push_back(CEI->getArgOperand(j));
4051           continue;
4052         }
4053 
4054         Value *OpVec = vectorizeTree(E->getOperand(j));
4055         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
4056         OpVecs.push_back(OpVec);
4057       }
4058 
4059       Module *M = F->getParent();
4060       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4061       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
4062       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
4063       SmallVector<OperandBundleDef, 1> OpBundles;
4064       CI->getOperandBundlesAsDefs(OpBundles);
4065       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
4066 
4067       // The scalar argument uses an in-tree scalar so we add the new vectorized
4068       // call to ExternalUses list to make sure that an extract will be
4069       // generated in the future.
4070       if (ScalarArg && getTreeEntry(ScalarArg))
4071         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
4072 
4073       propagateIRFlags(V, E->Scalars, VL0);
4074       if (NeedToShuffleReuses) {
4075         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4076                                         E->ReuseShuffleIndices, "shuffle");
4077       }
4078       E->VectorizedValue = V;
4079       ++NumVectorInstructions;
4080       return V;
4081     }
4082     case Instruction::ShuffleVector: {
4083       assert(E->isAltShuffle() &&
4084              ((Instruction::isBinaryOp(E->getOpcode()) &&
4085                Instruction::isBinaryOp(E->getAltOpcode())) ||
4086               (Instruction::isCast(E->getOpcode()) &&
4087                Instruction::isCast(E->getAltOpcode()))) &&
4088              "Invalid Shuffle Vector Operand");
4089 
4090       Value *LHS = nullptr, *RHS = nullptr;
4091       if (Instruction::isBinaryOp(E->getOpcode())) {
4092         setInsertPointAfterBundle(E);
4093         LHS = vectorizeTree(E->getOperand(0));
4094         RHS = vectorizeTree(E->getOperand(1));
4095       } else {
4096         setInsertPointAfterBundle(E);
4097         LHS = vectorizeTree(E->getOperand(0));
4098       }
4099 
4100       if (E->VectorizedValue) {
4101         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4102         return E->VectorizedValue;
4103       }
4104 
4105       Value *V0, *V1;
4106       if (Instruction::isBinaryOp(E->getOpcode())) {
4107         V0 = Builder.CreateBinOp(
4108             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
4109         V1 = Builder.CreateBinOp(
4110             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
4111       } else {
4112         V0 = Builder.CreateCast(
4113             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
4114         V1 = Builder.CreateCast(
4115             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
4116       }
4117 
4118       // Create shuffle to take alternate operations from the vector.
4119       // Also, gather up main and alt scalar ops to propagate IR flags to
4120       // each vector operation.
4121       ValueList OpScalars, AltScalars;
4122       unsigned e = E->Scalars.size();
4123       SmallVector<Constant *, 8> Mask(e);
4124       for (unsigned i = 0; i < e; ++i) {
4125         auto *OpInst = cast<Instruction>(E->Scalars[i]);
4126         assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
4127         if (OpInst->getOpcode() == E->getAltOpcode()) {
4128           Mask[i] = Builder.getInt32(e + i);
4129           AltScalars.push_back(E->Scalars[i]);
4130         } else {
4131           Mask[i] = Builder.getInt32(i);
4132           OpScalars.push_back(E->Scalars[i]);
4133         }
4134       }
4135 
4136       Value *ShuffleMask = ConstantVector::get(Mask);
4137       propagateIRFlags(V0, OpScalars);
4138       propagateIRFlags(V1, AltScalars);
4139 
4140       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
4141       if (Instruction *I = dyn_cast<Instruction>(V))
4142         V = propagateMetadata(I, E->Scalars);
4143       if (NeedToShuffleReuses) {
4144         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4145                                         E->ReuseShuffleIndices, "shuffle");
4146       }
4147       E->VectorizedValue = V;
4148       ++NumVectorInstructions;
4149 
4150       return V;
4151     }
4152     default:
4153     llvm_unreachable("unknown inst");
4154   }
4155   return nullptr;
4156 }
4157 
4158 Value *BoUpSLP::vectorizeTree() {
4159   ExtraValueToDebugLocsMap ExternallyUsedValues;
4160   return vectorizeTree(ExternallyUsedValues);
4161 }
4162 
4163 Value *
4164 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4165   // All blocks must be scheduled before any instructions are inserted.
4166   for (auto &BSIter : BlocksSchedules) {
4167     scheduleBlock(BSIter.second.get());
4168   }
4169 
4170   Builder.SetInsertPoint(&F->getEntryBlock().front());
4171   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
4172 
4173   // If the vectorized tree can be rewritten in a smaller type, we truncate the
4174   // vectorized root. InstCombine will then rewrite the entire expression. We
4175   // sign extend the extracted values below.
4176   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4177   if (MinBWs.count(ScalarRoot)) {
4178     if (auto *I = dyn_cast<Instruction>(VectorRoot))
4179       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
4180     auto BundleWidth = VectorizableTree[0]->Scalars.size();
4181     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4182     auto *VecTy = VectorType::get(MinTy, BundleWidth);
4183     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
4184     VectorizableTree[0]->VectorizedValue = Trunc;
4185   }
4186 
4187   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
4188                     << " values .\n");
4189 
4190   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4191   // specified by ScalarType.
4192   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
4193     if (!MinBWs.count(ScalarRoot))
4194       return Ex;
4195     if (MinBWs[ScalarRoot].second)
4196       return Builder.CreateSExt(Ex, ScalarType);
4197     return Builder.CreateZExt(Ex, ScalarType);
4198   };
4199 
4200   // Extract all of the elements with the external uses.
4201   for (const auto &ExternalUse : ExternalUses) {
4202     Value *Scalar = ExternalUse.Scalar;
4203     llvm::User *User = ExternalUse.User;
4204 
4205     // Skip users that we already RAUW. This happens when one instruction
4206     // has multiple uses of the same value.
4207     if (User && !is_contained(Scalar->users(), User))
4208       continue;
4209     TreeEntry *E = getTreeEntry(Scalar);
4210     assert(E && "Invalid scalar");
4211     assert(!E->NeedToGather && "Extracting from a gather list");
4212 
4213     Value *Vec = E->VectorizedValue;
4214     assert(Vec && "Can't find vectorizable value");
4215 
4216     Value *Lane = Builder.getInt32(ExternalUse.Lane);
4217     // If User == nullptr, the Scalar is used as extra arg. Generate
4218     // ExtractElement instruction and update the record for this scalar in
4219     // ExternallyUsedValues.
4220     if (!User) {
4221       assert(ExternallyUsedValues.count(Scalar) &&
4222              "Scalar with nullptr as an external user must be registered in "
4223              "ExternallyUsedValues map");
4224       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4225         Builder.SetInsertPoint(VecI->getParent(),
4226                                std::next(VecI->getIterator()));
4227       } else {
4228         Builder.SetInsertPoint(&F->getEntryBlock().front());
4229       }
4230       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4231       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4232       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
4233       auto &Locs = ExternallyUsedValues[Scalar];
4234       ExternallyUsedValues.insert({Ex, Locs});
4235       ExternallyUsedValues.erase(Scalar);
4236       // Required to update internally referenced instructions.
4237       Scalar->replaceAllUsesWith(Ex);
4238       continue;
4239     }
4240 
4241     // Generate extracts for out-of-tree users.
4242     // Find the insertion point for the extractelement lane.
4243     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4244       if (PHINode *PH = dyn_cast<PHINode>(User)) {
4245         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
4246           if (PH->getIncomingValue(i) == Scalar) {
4247             Instruction *IncomingTerminator =
4248                 PH->getIncomingBlock(i)->getTerminator();
4249             if (isa<CatchSwitchInst>(IncomingTerminator)) {
4250               Builder.SetInsertPoint(VecI->getParent(),
4251                                      std::next(VecI->getIterator()));
4252             } else {
4253               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
4254             }
4255             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4256             Ex = extend(ScalarRoot, Ex, Scalar->getType());
4257             CSEBlocks.insert(PH->getIncomingBlock(i));
4258             PH->setOperand(i, Ex);
4259           }
4260         }
4261       } else {
4262         Builder.SetInsertPoint(cast<Instruction>(User));
4263         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4264         Ex = extend(ScalarRoot, Ex, Scalar->getType());
4265         CSEBlocks.insert(cast<Instruction>(User)->getParent());
4266         User->replaceUsesOfWith(Scalar, Ex);
4267       }
4268     } else {
4269       Builder.SetInsertPoint(&F->getEntryBlock().front());
4270       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4271       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4272       CSEBlocks.insert(&F->getEntryBlock());
4273       User->replaceUsesOfWith(Scalar, Ex);
4274     }
4275 
4276     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
4277   }
4278 
4279   // For each vectorized value:
4280   for (auto &TEPtr : VectorizableTree) {
4281     TreeEntry *Entry = TEPtr.get();
4282 
4283     // No need to handle users of gathered values.
4284     if (Entry->NeedToGather)
4285       continue;
4286 
4287     assert(Entry->VectorizedValue && "Can't find vectorizable value");
4288 
4289     // For each lane:
4290     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4291       Value *Scalar = Entry->Scalars[Lane];
4292 
4293       Type *Ty = Scalar->getType();
4294       if (!Ty->isVoidTy()) {
4295 #ifndef NDEBUG
4296         for (User *U : Scalar->users()) {
4297           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
4298 
4299           // It is legal to replace users in the ignorelist by undef.
4300           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
4301                  "Replacing out-of-tree value with undef");
4302         }
4303 #endif
4304         Value *Undef = UndefValue::get(Ty);
4305         Scalar->replaceAllUsesWith(Undef);
4306       }
4307       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
4308       eraseInstruction(cast<Instruction>(Scalar));
4309     }
4310   }
4311 
4312   Builder.ClearInsertionPoint();
4313 
4314   return VectorizableTree[0]->VectorizedValue;
4315 }
4316 
4317 void BoUpSLP::optimizeGatherSequence() {
4318   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
4319                     << " gather sequences instructions.\n");
4320   // LICM InsertElementInst sequences.
4321   for (Instruction *I : GatherSeq) {
4322     if (!isa<InsertElementInst>(I) && !isa<ShuffleVectorInst>(I))
4323       continue;
4324 
4325     // Check if this block is inside a loop.
4326     Loop *L = LI->getLoopFor(I->getParent());
4327     if (!L)
4328       continue;
4329 
4330     // Check if it has a preheader.
4331     BasicBlock *PreHeader = L->getLoopPreheader();
4332     if (!PreHeader)
4333       continue;
4334 
4335     // If the vector or the element that we insert into it are
4336     // instructions that are defined in this basic block then we can't
4337     // hoist this instruction.
4338     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4339     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4340     if (Op0 && L->contains(Op0))
4341       continue;
4342     if (Op1 && L->contains(Op1))
4343       continue;
4344 
4345     // We can hoist this instruction. Move it to the pre-header.
4346     I->moveBefore(PreHeader->getTerminator());
4347   }
4348 
4349   // Make a list of all reachable blocks in our CSE queue.
4350   SmallVector<const DomTreeNode *, 8> CSEWorkList;
4351   CSEWorkList.reserve(CSEBlocks.size());
4352   for (BasicBlock *BB : CSEBlocks)
4353     if (DomTreeNode *N = DT->getNode(BB)) {
4354       assert(DT->isReachableFromEntry(N));
4355       CSEWorkList.push_back(N);
4356     }
4357 
4358   // Sort blocks by domination. This ensures we visit a block after all blocks
4359   // dominating it are visited.
4360   llvm::stable_sort(CSEWorkList,
4361                     [this](const DomTreeNode *A, const DomTreeNode *B) {
4362                       return DT->properlyDominates(A, B);
4363                     });
4364 
4365   // Perform O(N^2) search over the gather sequences and merge identical
4366   // instructions. TODO: We can further optimize this scan if we split the
4367   // instructions into different buckets based on the insert lane.
4368   SmallVector<Instruction *, 16> Visited;
4369   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
4370     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
4371            "Worklist not sorted properly!");
4372     BasicBlock *BB = (*I)->getBlock();
4373     // For all instructions in blocks containing gather sequences:
4374     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
4375       Instruction *In = &*it++;
4376       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
4377         continue;
4378 
4379       // Check if we can replace this instruction with any of the
4380       // visited instructions.
4381       for (Instruction *v : Visited) {
4382         if (In->isIdenticalTo(v) &&
4383             DT->dominates(v->getParent(), In->getParent())) {
4384           In->replaceAllUsesWith(v);
4385           eraseInstruction(In);
4386           In = nullptr;
4387           break;
4388         }
4389       }
4390       if (In) {
4391         assert(!is_contained(Visited, In));
4392         Visited.push_back(In);
4393       }
4394     }
4395   }
4396   CSEBlocks.clear();
4397   GatherSeq.clear();
4398 }
4399 
4400 // Groups the instructions to a bundle (which is then a single scheduling entity)
4401 // and schedules instructions until the bundle gets ready.
4402 Optional<BoUpSLP::ScheduleData *>
4403 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
4404                                             const InstructionsState &S) {
4405   if (isa<PHINode>(S.OpValue))
4406     return nullptr;
4407 
4408   // Initialize the instruction bundle.
4409   Instruction *OldScheduleEnd = ScheduleEnd;
4410   ScheduleData *PrevInBundle = nullptr;
4411   ScheduleData *Bundle = nullptr;
4412   bool ReSchedule = false;
4413   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
4414 
4415   // Make sure that the scheduling region contains all
4416   // instructions of the bundle.
4417   for (Value *V : VL) {
4418     if (!extendSchedulingRegion(V, S))
4419       return None;
4420   }
4421 
4422   for (Value *V : VL) {
4423     ScheduleData *BundleMember = getScheduleData(V);
4424     assert(BundleMember &&
4425            "no ScheduleData for bundle member (maybe not in same basic block)");
4426     if (BundleMember->IsScheduled) {
4427       // A bundle member was scheduled as single instruction before and now
4428       // needs to be scheduled as part of the bundle. We just get rid of the
4429       // existing schedule.
4430       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
4431                         << " was already scheduled\n");
4432       ReSchedule = true;
4433     }
4434     assert(BundleMember->isSchedulingEntity() &&
4435            "bundle member already part of other bundle");
4436     if (PrevInBundle) {
4437       PrevInBundle->NextInBundle = BundleMember;
4438     } else {
4439       Bundle = BundleMember;
4440     }
4441     BundleMember->UnscheduledDepsInBundle = 0;
4442     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
4443 
4444     // Group the instructions to a bundle.
4445     BundleMember->FirstInBundle = Bundle;
4446     PrevInBundle = BundleMember;
4447   }
4448   if (ScheduleEnd != OldScheduleEnd) {
4449     // The scheduling region got new instructions at the lower end (or it is a
4450     // new region for the first bundle). This makes it necessary to
4451     // recalculate all dependencies.
4452     // It is seldom that this needs to be done a second time after adding the
4453     // initial bundle to the region.
4454     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
4455       doForAllOpcodes(I, [](ScheduleData *SD) {
4456         SD->clearDependencies();
4457       });
4458     }
4459     ReSchedule = true;
4460   }
4461   if (ReSchedule) {
4462     resetSchedule();
4463     initialFillReadyList(ReadyInsts);
4464   }
4465   assert(Bundle && "Failed to find schedule bundle");
4466 
4467   LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
4468                     << BB->getName() << "\n");
4469 
4470   calculateDependencies(Bundle, true, SLP);
4471 
4472   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
4473   // means that there are no cyclic dependencies and we can schedule it.
4474   // Note that's important that we don't "schedule" the bundle yet (see
4475   // cancelScheduling).
4476   while (!Bundle->isReady() && !ReadyInsts.empty()) {
4477 
4478     ScheduleData *pickedSD = ReadyInsts.back();
4479     ReadyInsts.pop_back();
4480 
4481     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
4482       schedule(pickedSD, ReadyInsts);
4483     }
4484   }
4485   if (!Bundle->isReady()) {
4486     cancelScheduling(VL, S.OpValue);
4487     return None;
4488   }
4489   return Bundle;
4490 }
4491 
4492 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
4493                                                 Value *OpValue) {
4494   if (isa<PHINode>(OpValue))
4495     return;
4496 
4497   ScheduleData *Bundle = getScheduleData(OpValue);
4498   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
4499   assert(!Bundle->IsScheduled &&
4500          "Can't cancel bundle which is already scheduled");
4501   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
4502          "tried to unbundle something which is not a bundle");
4503 
4504   // Un-bundle: make single instructions out of the bundle.
4505   ScheduleData *BundleMember = Bundle;
4506   while (BundleMember) {
4507     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
4508     BundleMember->FirstInBundle = BundleMember;
4509     ScheduleData *Next = BundleMember->NextInBundle;
4510     BundleMember->NextInBundle = nullptr;
4511     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
4512     if (BundleMember->UnscheduledDepsInBundle == 0) {
4513       ReadyInsts.insert(BundleMember);
4514     }
4515     BundleMember = Next;
4516   }
4517 }
4518 
4519 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
4520   // Allocate a new ScheduleData for the instruction.
4521   if (ChunkPos >= ChunkSize) {
4522     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
4523     ChunkPos = 0;
4524   }
4525   return &(ScheduleDataChunks.back()[ChunkPos++]);
4526 }
4527 
4528 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
4529                                                       const InstructionsState &S) {
4530   if (getScheduleData(V, isOneOf(S, V)))
4531     return true;
4532   Instruction *I = dyn_cast<Instruction>(V);
4533   assert(I && "bundle member must be an instruction");
4534   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
4535   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
4536     ScheduleData *ISD = getScheduleData(I);
4537     if (!ISD)
4538       return false;
4539     assert(isInSchedulingRegion(ISD) &&
4540            "ScheduleData not in scheduling region");
4541     ScheduleData *SD = allocateScheduleDataChunks();
4542     SD->Inst = I;
4543     SD->init(SchedulingRegionID, S.OpValue);
4544     ExtraScheduleDataMap[I][S.OpValue] = SD;
4545     return true;
4546   };
4547   if (CheckSheduleForI(I))
4548     return true;
4549   if (!ScheduleStart) {
4550     // It's the first instruction in the new region.
4551     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
4552     ScheduleStart = I;
4553     ScheduleEnd = I->getNextNode();
4554     if (isOneOf(S, I) != I)
4555       CheckSheduleForI(I);
4556     assert(ScheduleEnd && "tried to vectorize a terminator?");
4557     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
4558     return true;
4559   }
4560   // Search up and down at the same time, because we don't know if the new
4561   // instruction is above or below the existing scheduling region.
4562   BasicBlock::reverse_iterator UpIter =
4563       ++ScheduleStart->getIterator().getReverse();
4564   BasicBlock::reverse_iterator UpperEnd = BB->rend();
4565   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
4566   BasicBlock::iterator LowerEnd = BB->end();
4567   while (true) {
4568     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
4569       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
4570       return false;
4571     }
4572 
4573     if (UpIter != UpperEnd) {
4574       if (&*UpIter == I) {
4575         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
4576         ScheduleStart = I;
4577         if (isOneOf(S, I) != I)
4578           CheckSheduleForI(I);
4579         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
4580                           << "\n");
4581         return true;
4582       }
4583       ++UpIter;
4584     }
4585     if (DownIter != LowerEnd) {
4586       if (&*DownIter == I) {
4587         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
4588                          nullptr);
4589         ScheduleEnd = I->getNextNode();
4590         if (isOneOf(S, I) != I)
4591           CheckSheduleForI(I);
4592         assert(ScheduleEnd && "tried to vectorize a terminator?");
4593         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I
4594                           << "\n");
4595         return true;
4596       }
4597       ++DownIter;
4598     }
4599     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
4600            "instruction not found in block");
4601   }
4602   return true;
4603 }
4604 
4605 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
4606                                                 Instruction *ToI,
4607                                                 ScheduleData *PrevLoadStore,
4608                                                 ScheduleData *NextLoadStore) {
4609   ScheduleData *CurrentLoadStore = PrevLoadStore;
4610   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
4611     ScheduleData *SD = ScheduleDataMap[I];
4612     if (!SD) {
4613       SD = allocateScheduleDataChunks();
4614       ScheduleDataMap[I] = SD;
4615       SD->Inst = I;
4616     }
4617     assert(!isInSchedulingRegion(SD) &&
4618            "new ScheduleData already in scheduling region");
4619     SD->init(SchedulingRegionID, I);
4620 
4621     if (I->mayReadOrWriteMemory() &&
4622         (!isa<IntrinsicInst>(I) ||
4623          cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
4624       // Update the linked list of memory accessing instructions.
4625       if (CurrentLoadStore) {
4626         CurrentLoadStore->NextLoadStore = SD;
4627       } else {
4628         FirstLoadStoreInRegion = SD;
4629       }
4630       CurrentLoadStore = SD;
4631     }
4632   }
4633   if (NextLoadStore) {
4634     if (CurrentLoadStore)
4635       CurrentLoadStore->NextLoadStore = NextLoadStore;
4636   } else {
4637     LastLoadStoreInRegion = CurrentLoadStore;
4638   }
4639 }
4640 
4641 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
4642                                                      bool InsertInReadyList,
4643                                                      BoUpSLP *SLP) {
4644   assert(SD->isSchedulingEntity());
4645 
4646   SmallVector<ScheduleData *, 10> WorkList;
4647   WorkList.push_back(SD);
4648 
4649   while (!WorkList.empty()) {
4650     ScheduleData *SD = WorkList.back();
4651     WorkList.pop_back();
4652 
4653     ScheduleData *BundleMember = SD;
4654     while (BundleMember) {
4655       assert(isInSchedulingRegion(BundleMember));
4656       if (!BundleMember->hasValidDependencies()) {
4657 
4658         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
4659                           << "\n");
4660         BundleMember->Dependencies = 0;
4661         BundleMember->resetUnscheduledDeps();
4662 
4663         // Handle def-use chain dependencies.
4664         if (BundleMember->OpValue != BundleMember->Inst) {
4665           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
4666           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4667             BundleMember->Dependencies++;
4668             ScheduleData *DestBundle = UseSD->FirstInBundle;
4669             if (!DestBundle->IsScheduled)
4670               BundleMember->incrementUnscheduledDeps(1);
4671             if (!DestBundle->hasValidDependencies())
4672               WorkList.push_back(DestBundle);
4673           }
4674         } else {
4675           for (User *U : BundleMember->Inst->users()) {
4676             if (isa<Instruction>(U)) {
4677               ScheduleData *UseSD = getScheduleData(U);
4678               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4679                 BundleMember->Dependencies++;
4680                 ScheduleData *DestBundle = UseSD->FirstInBundle;
4681                 if (!DestBundle->IsScheduled)
4682                   BundleMember->incrementUnscheduledDeps(1);
4683                 if (!DestBundle->hasValidDependencies())
4684                   WorkList.push_back(DestBundle);
4685               }
4686             } else {
4687               // I'm not sure if this can ever happen. But we need to be safe.
4688               // This lets the instruction/bundle never be scheduled and
4689               // eventually disable vectorization.
4690               BundleMember->Dependencies++;
4691               BundleMember->incrementUnscheduledDeps(1);
4692             }
4693           }
4694         }
4695 
4696         // Handle the memory dependencies.
4697         ScheduleData *DepDest = BundleMember->NextLoadStore;
4698         if (DepDest) {
4699           Instruction *SrcInst = BundleMember->Inst;
4700           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
4701           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
4702           unsigned numAliased = 0;
4703           unsigned DistToSrc = 1;
4704 
4705           while (DepDest) {
4706             assert(isInSchedulingRegion(DepDest));
4707 
4708             // We have two limits to reduce the complexity:
4709             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
4710             //    SLP->isAliased (which is the expensive part in this loop).
4711             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
4712             //    the whole loop (even if the loop is fast, it's quadratic).
4713             //    It's important for the loop break condition (see below) to
4714             //    check this limit even between two read-only instructions.
4715             if (DistToSrc >= MaxMemDepDistance ||
4716                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
4717                      (numAliased >= AliasedCheckLimit ||
4718                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
4719 
4720               // We increment the counter only if the locations are aliased
4721               // (instead of counting all alias checks). This gives a better
4722               // balance between reduced runtime and accurate dependencies.
4723               numAliased++;
4724 
4725               DepDest->MemoryDependencies.push_back(BundleMember);
4726               BundleMember->Dependencies++;
4727               ScheduleData *DestBundle = DepDest->FirstInBundle;
4728               if (!DestBundle->IsScheduled) {
4729                 BundleMember->incrementUnscheduledDeps(1);
4730               }
4731               if (!DestBundle->hasValidDependencies()) {
4732                 WorkList.push_back(DestBundle);
4733               }
4734             }
4735             DepDest = DepDest->NextLoadStore;
4736 
4737             // Example, explaining the loop break condition: Let's assume our
4738             // starting instruction is i0 and MaxMemDepDistance = 3.
4739             //
4740             //                      +--------v--v--v
4741             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
4742             //             +--------^--^--^
4743             //
4744             // MaxMemDepDistance let us stop alias-checking at i3 and we add
4745             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
4746             // Previously we already added dependencies from i3 to i6,i7,i8
4747             // (because of MaxMemDepDistance). As we added a dependency from
4748             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
4749             // and we can abort this loop at i6.
4750             if (DistToSrc >= 2 * MaxMemDepDistance)
4751               break;
4752             DistToSrc++;
4753           }
4754         }
4755       }
4756       BundleMember = BundleMember->NextInBundle;
4757     }
4758     if (InsertInReadyList && SD->isReady()) {
4759       ReadyInsts.push_back(SD);
4760       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
4761                         << "\n");
4762     }
4763   }
4764 }
4765 
4766 void BoUpSLP::BlockScheduling::resetSchedule() {
4767   assert(ScheduleStart &&
4768          "tried to reset schedule on block which has not been scheduled");
4769   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
4770     doForAllOpcodes(I, [&](ScheduleData *SD) {
4771       assert(isInSchedulingRegion(SD) &&
4772              "ScheduleData not in scheduling region");
4773       SD->IsScheduled = false;
4774       SD->resetUnscheduledDeps();
4775     });
4776   }
4777   ReadyInsts.clear();
4778 }
4779 
4780 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
4781   if (!BS->ScheduleStart)
4782     return;
4783 
4784   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
4785 
4786   BS->resetSchedule();
4787 
4788   // For the real scheduling we use a more sophisticated ready-list: it is
4789   // sorted by the original instruction location. This lets the final schedule
4790   // be as  close as possible to the original instruction order.
4791   struct ScheduleDataCompare {
4792     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
4793       return SD2->SchedulingPriority < SD1->SchedulingPriority;
4794     }
4795   };
4796   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
4797 
4798   // Ensure that all dependency data is updated and fill the ready-list with
4799   // initial instructions.
4800   int Idx = 0;
4801   int NumToSchedule = 0;
4802   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
4803        I = I->getNextNode()) {
4804     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
4805       assert(SD->isPartOfBundle() ==
4806                  (getTreeEntry(SD->Inst) != nullptr) &&
4807              "scheduler and vectorizer bundle mismatch");
4808       SD->FirstInBundle->SchedulingPriority = Idx++;
4809       if (SD->isSchedulingEntity()) {
4810         BS->calculateDependencies(SD, false, this);
4811         NumToSchedule++;
4812       }
4813     });
4814   }
4815   BS->initialFillReadyList(ReadyInsts);
4816 
4817   Instruction *LastScheduledInst = BS->ScheduleEnd;
4818 
4819   // Do the "real" scheduling.
4820   while (!ReadyInsts.empty()) {
4821     ScheduleData *picked = *ReadyInsts.begin();
4822     ReadyInsts.erase(ReadyInsts.begin());
4823 
4824     // Move the scheduled instruction(s) to their dedicated places, if not
4825     // there yet.
4826     ScheduleData *BundleMember = picked;
4827     while (BundleMember) {
4828       Instruction *pickedInst = BundleMember->Inst;
4829       if (LastScheduledInst->getNextNode() != pickedInst) {
4830         BS->BB->getInstList().remove(pickedInst);
4831         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
4832                                      pickedInst);
4833       }
4834       LastScheduledInst = pickedInst;
4835       BundleMember = BundleMember->NextInBundle;
4836     }
4837 
4838     BS->schedule(picked, ReadyInsts);
4839     NumToSchedule--;
4840   }
4841   assert(NumToSchedule == 0 && "could not schedule all instructions");
4842 
4843   // Avoid duplicate scheduling of the block.
4844   BS->ScheduleStart = nullptr;
4845 }
4846 
4847 unsigned BoUpSLP::getVectorElementSize(Value *V) const {
4848   // If V is a store, just return the width of the stored value without
4849   // traversing the expression tree. This is the common case.
4850   if (auto *Store = dyn_cast<StoreInst>(V))
4851     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
4852 
4853   // If V is not a store, we can traverse the expression tree to find loads
4854   // that feed it. The type of the loaded value may indicate a more suitable
4855   // width than V's type. We want to base the vector element size on the width
4856   // of memory operations where possible.
4857   SmallVector<Instruction *, 16> Worklist;
4858   SmallPtrSet<Instruction *, 16> Visited;
4859   if (auto *I = dyn_cast<Instruction>(V))
4860     Worklist.push_back(I);
4861 
4862   // Traverse the expression tree in bottom-up order looking for loads. If we
4863   // encounter an instruction we don't yet handle, we give up.
4864   auto MaxWidth = 0u;
4865   auto FoundUnknownInst = false;
4866   while (!Worklist.empty() && !FoundUnknownInst) {
4867     auto *I = Worklist.pop_back_val();
4868     Visited.insert(I);
4869 
4870     // We should only be looking at scalar instructions here. If the current
4871     // instruction has a vector type, give up.
4872     auto *Ty = I->getType();
4873     if (isa<VectorType>(Ty))
4874       FoundUnknownInst = true;
4875 
4876     // If the current instruction is a load, update MaxWidth to reflect the
4877     // width of the loaded value.
4878     else if (isa<LoadInst>(I))
4879       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
4880 
4881     // Otherwise, we need to visit the operands of the instruction. We only
4882     // handle the interesting cases from buildTree here. If an operand is an
4883     // instruction we haven't yet visited, we add it to the worklist.
4884     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
4885              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
4886       for (Use &U : I->operands())
4887         if (auto *J = dyn_cast<Instruction>(U.get()))
4888           if (!Visited.count(J))
4889             Worklist.push_back(J);
4890     }
4891 
4892     // If we don't yet handle the instruction, give up.
4893     else
4894       FoundUnknownInst = true;
4895   }
4896 
4897   // If we didn't encounter a memory access in the expression tree, or if we
4898   // gave up for some reason, just return the width of V.
4899   if (!MaxWidth || FoundUnknownInst)
4900     return DL->getTypeSizeInBits(V->getType());
4901 
4902   // Otherwise, return the maximum width we found.
4903   return MaxWidth;
4904 }
4905 
4906 // Determine if a value V in a vectorizable expression Expr can be demoted to a
4907 // smaller type with a truncation. We collect the values that will be demoted
4908 // in ToDemote and additional roots that require investigating in Roots.
4909 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
4910                                   SmallVectorImpl<Value *> &ToDemote,
4911                                   SmallVectorImpl<Value *> &Roots) {
4912   // We can always demote constants.
4913   if (isa<Constant>(V)) {
4914     ToDemote.push_back(V);
4915     return true;
4916   }
4917 
4918   // If the value is not an instruction in the expression with only one use, it
4919   // cannot be demoted.
4920   auto *I = dyn_cast<Instruction>(V);
4921   if (!I || !I->hasOneUse() || !Expr.count(I))
4922     return false;
4923 
4924   switch (I->getOpcode()) {
4925 
4926   // We can always demote truncations and extensions. Since truncations can
4927   // seed additional demotion, we save the truncated value.
4928   case Instruction::Trunc:
4929     Roots.push_back(I->getOperand(0));
4930     break;
4931   case Instruction::ZExt:
4932   case Instruction::SExt:
4933     break;
4934 
4935   // We can demote certain binary operations if we can demote both of their
4936   // operands.
4937   case Instruction::Add:
4938   case Instruction::Sub:
4939   case Instruction::Mul:
4940   case Instruction::And:
4941   case Instruction::Or:
4942   case Instruction::Xor:
4943     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
4944         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
4945       return false;
4946     break;
4947 
4948   // We can demote selects if we can demote their true and false values.
4949   case Instruction::Select: {
4950     SelectInst *SI = cast<SelectInst>(I);
4951     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
4952         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
4953       return false;
4954     break;
4955   }
4956 
4957   // We can demote phis if we can demote all their incoming operands. Note that
4958   // we don't need to worry about cycles since we ensure single use above.
4959   case Instruction::PHI: {
4960     PHINode *PN = cast<PHINode>(I);
4961     for (Value *IncValue : PN->incoming_values())
4962       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
4963         return false;
4964     break;
4965   }
4966 
4967   // Otherwise, conservatively give up.
4968   default:
4969     return false;
4970   }
4971 
4972   // Record the value that we can demote.
4973   ToDemote.push_back(V);
4974   return true;
4975 }
4976 
4977 void BoUpSLP::computeMinimumValueSizes() {
4978   // If there are no external uses, the expression tree must be rooted by a
4979   // store. We can't demote in-memory values, so there is nothing to do here.
4980   if (ExternalUses.empty())
4981     return;
4982 
4983   // We only attempt to truncate integer expressions.
4984   auto &TreeRoot = VectorizableTree[0]->Scalars;
4985   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
4986   if (!TreeRootIT)
4987     return;
4988 
4989   // If the expression is not rooted by a store, these roots should have
4990   // external uses. We will rely on InstCombine to rewrite the expression in
4991   // the narrower type. However, InstCombine only rewrites single-use values.
4992   // This means that if a tree entry other than a root is used externally, it
4993   // must have multiple uses and InstCombine will not rewrite it. The code
4994   // below ensures that only the roots are used externally.
4995   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
4996   for (auto &EU : ExternalUses)
4997     if (!Expr.erase(EU.Scalar))
4998       return;
4999   if (!Expr.empty())
5000     return;
5001 
5002   // Collect the scalar values of the vectorizable expression. We will use this
5003   // context to determine which values can be demoted. If we see a truncation,
5004   // we mark it as seeding another demotion.
5005   for (auto &EntryPtr : VectorizableTree)
5006     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
5007 
5008   // Ensure the roots of the vectorizable tree don't form a cycle. They must
5009   // have a single external user that is not in the vectorizable tree.
5010   for (auto *Root : TreeRoot)
5011     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
5012       return;
5013 
5014   // Conservatively determine if we can actually truncate the roots of the
5015   // expression. Collect the values that can be demoted in ToDemote and
5016   // additional roots that require investigating in Roots.
5017   SmallVector<Value *, 32> ToDemote;
5018   SmallVector<Value *, 4> Roots;
5019   for (auto *Root : TreeRoot)
5020     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
5021       return;
5022 
5023   // The maximum bit width required to represent all the values that can be
5024   // demoted without loss of precision. It would be safe to truncate the roots
5025   // of the expression to this width.
5026   auto MaxBitWidth = 8u;
5027 
5028   // We first check if all the bits of the roots are demanded. If they're not,
5029   // we can truncate the roots to this narrower type.
5030   for (auto *Root : TreeRoot) {
5031     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
5032     MaxBitWidth = std::max<unsigned>(
5033         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
5034   }
5035 
5036   // True if the roots can be zero-extended back to their original type, rather
5037   // than sign-extended. We know that if the leading bits are not demanded, we
5038   // can safely zero-extend. So we initialize IsKnownPositive to True.
5039   bool IsKnownPositive = true;
5040 
5041   // If all the bits of the roots are demanded, we can try a little harder to
5042   // compute a narrower type. This can happen, for example, if the roots are
5043   // getelementptr indices. InstCombine promotes these indices to the pointer
5044   // width. Thus, all their bits are technically demanded even though the
5045   // address computation might be vectorized in a smaller type.
5046   //
5047   // We start by looking at each entry that can be demoted. We compute the
5048   // maximum bit width required to store the scalar by using ValueTracking to
5049   // compute the number of high-order bits we can truncate.
5050   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
5051       llvm::all_of(TreeRoot, [](Value *R) {
5052         assert(R->hasOneUse() && "Root should have only one use!");
5053         return isa<GetElementPtrInst>(R->user_back());
5054       })) {
5055     MaxBitWidth = 8u;
5056 
5057     // Determine if the sign bit of all the roots is known to be zero. If not,
5058     // IsKnownPositive is set to False.
5059     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
5060       KnownBits Known = computeKnownBits(R, *DL);
5061       return Known.isNonNegative();
5062     });
5063 
5064     // Determine the maximum number of bits required to store the scalar
5065     // values.
5066     for (auto *Scalar : ToDemote) {
5067       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
5068       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
5069       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
5070     }
5071 
5072     // If we can't prove that the sign bit is zero, we must add one to the
5073     // maximum bit width to account for the unknown sign bit. This preserves
5074     // the existing sign bit so we can safely sign-extend the root back to the
5075     // original type. Otherwise, if we know the sign bit is zero, we will
5076     // zero-extend the root instead.
5077     //
5078     // FIXME: This is somewhat suboptimal, as there will be cases where adding
5079     //        one to the maximum bit width will yield a larger-than-necessary
5080     //        type. In general, we need to add an extra bit only if we can't
5081     //        prove that the upper bit of the original type is equal to the
5082     //        upper bit of the proposed smaller type. If these two bits are the
5083     //        same (either zero or one) we know that sign-extending from the
5084     //        smaller type will result in the same value. Here, since we can't
5085     //        yet prove this, we are just making the proposed smaller type
5086     //        larger to ensure correctness.
5087     if (!IsKnownPositive)
5088       ++MaxBitWidth;
5089   }
5090 
5091   // Round MaxBitWidth up to the next power-of-two.
5092   if (!isPowerOf2_64(MaxBitWidth))
5093     MaxBitWidth = NextPowerOf2(MaxBitWidth);
5094 
5095   // If the maximum bit width we compute is less than the with of the roots'
5096   // type, we can proceed with the narrowing. Otherwise, do nothing.
5097   if (MaxBitWidth >= TreeRootIT->getBitWidth())
5098     return;
5099 
5100   // If we can truncate the root, we must collect additional values that might
5101   // be demoted as a result. That is, those seeded by truncations we will
5102   // modify.
5103   while (!Roots.empty())
5104     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
5105 
5106   // Finally, map the values we can demote to the maximum bit with we computed.
5107   for (auto *Scalar : ToDemote)
5108     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
5109 }
5110 
5111 namespace {
5112 
5113 /// The SLPVectorizer Pass.
5114 struct SLPVectorizer : public FunctionPass {
5115   SLPVectorizerPass Impl;
5116 
5117   /// Pass identification, replacement for typeid
5118   static char ID;
5119 
5120   explicit SLPVectorizer() : FunctionPass(ID) {
5121     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5122   }
5123 
5124   bool doInitialization(Module &M) override {
5125     return false;
5126   }
5127 
5128   bool runOnFunction(Function &F) override {
5129     if (skipFunction(F))
5130       return false;
5131 
5132     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5133     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5134     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5135     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
5136     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5137     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5138     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5139     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5140     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
5141     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5142 
5143     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5144   }
5145 
5146   void getAnalysisUsage(AnalysisUsage &AU) const override {
5147     FunctionPass::getAnalysisUsage(AU);
5148     AU.addRequired<AssumptionCacheTracker>();
5149     AU.addRequired<ScalarEvolutionWrapperPass>();
5150     AU.addRequired<AAResultsWrapperPass>();
5151     AU.addRequired<TargetTransformInfoWrapperPass>();
5152     AU.addRequired<LoopInfoWrapperPass>();
5153     AU.addRequired<DominatorTreeWrapperPass>();
5154     AU.addRequired<DemandedBitsWrapperPass>();
5155     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5156     AU.addPreserved<LoopInfoWrapperPass>();
5157     AU.addPreserved<DominatorTreeWrapperPass>();
5158     AU.addPreserved<AAResultsWrapperPass>();
5159     AU.addPreserved<GlobalsAAWrapperPass>();
5160     AU.setPreservesCFG();
5161   }
5162 };
5163 
5164 } // end anonymous namespace
5165 
5166 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
5167   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
5168   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
5169   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
5170   auto *AA = &AM.getResult<AAManager>(F);
5171   auto *LI = &AM.getResult<LoopAnalysis>(F);
5172   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
5173   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
5174   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
5175   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5176 
5177   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5178   if (!Changed)
5179     return PreservedAnalyses::all();
5180 
5181   PreservedAnalyses PA;
5182   PA.preserveSet<CFGAnalyses>();
5183   PA.preserve<AAManager>();
5184   PA.preserve<GlobalsAA>();
5185   return PA;
5186 }
5187 
5188 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
5189                                 TargetTransformInfo *TTI_,
5190                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
5191                                 LoopInfo *LI_, DominatorTree *DT_,
5192                                 AssumptionCache *AC_, DemandedBits *DB_,
5193                                 OptimizationRemarkEmitter *ORE_) {
5194   SE = SE_;
5195   TTI = TTI_;
5196   TLI = TLI_;
5197   AA = AA_;
5198   LI = LI_;
5199   DT = DT_;
5200   AC = AC_;
5201   DB = DB_;
5202   DL = &F.getParent()->getDataLayout();
5203 
5204   Stores.clear();
5205   GEPs.clear();
5206   bool Changed = false;
5207 
5208   // If the target claims to have no vector registers don't attempt
5209   // vectorization.
5210   if (!TTI->getNumberOfRegisters(true))
5211     return false;
5212 
5213   // Don't vectorize when the attribute NoImplicitFloat is used.
5214   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
5215     return false;
5216 
5217   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
5218 
5219   // Use the bottom up slp vectorizer to construct chains that start with
5220   // store instructions.
5221   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
5222 
5223   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5224   // delete instructions.
5225 
5226   // Scan the blocks in the function in post order.
5227   for (auto BB : post_order(&F.getEntryBlock())) {
5228     collectSeedInstructions(BB);
5229 
5230     // Vectorize trees that end at stores.
5231     if (!Stores.empty()) {
5232       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
5233                         << " underlying objects.\n");
5234       Changed |= vectorizeStoreChains(R);
5235     }
5236 
5237     // Vectorize trees that end at reductions.
5238     Changed |= vectorizeChainsInBlock(BB, R);
5239 
5240     // Vectorize the index computations of getelementptr instructions. This
5241     // is primarily intended to catch gather-like idioms ending at
5242     // non-consecutive loads.
5243     if (!GEPs.empty()) {
5244       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
5245                         << " underlying objects.\n");
5246       Changed |= vectorizeGEPIndices(BB, R);
5247     }
5248   }
5249 
5250   if (Changed) {
5251     R.optimizeGatherSequence();
5252     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
5253     LLVM_DEBUG(verifyFunction(F));
5254   }
5255   return Changed;
5256 }
5257 
5258 /// Check that the Values in the slice in VL array are still existent in
5259 /// the WeakTrackingVH array.
5260 /// Vectorization of part of the VL array may cause later values in the VL array
5261 /// to become invalid. We track when this has happened in the WeakTrackingVH
5262 /// array.
5263 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
5264                                ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
5265                                unsigned SliceSize) {
5266   VL = VL.slice(SliceBegin, SliceSize);
5267   VH = VH.slice(SliceBegin, SliceSize);
5268   return !std::equal(VL.begin(), VL.end(), VH.begin());
5269 }
5270 
5271 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
5272                                             unsigned VecRegSize) {
5273   const unsigned ChainLen = Chain.size();
5274   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
5275                     << "\n");
5276   const unsigned Sz = R.getVectorElementSize(Chain[0]);
5277   const unsigned VF = VecRegSize / Sz;
5278 
5279   if (!isPowerOf2_32(Sz) || VF < 2)
5280     return false;
5281 
5282   // Keep track of values that were deleted by vectorizing in the loop below.
5283   const SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
5284 
5285   bool Changed = false;
5286   // Look for profitable vectorizable trees at all offsets, starting at zero.
5287   for (unsigned i = 0, e = ChainLen; i + VF <= e; ++i) {
5288 
5289     // Check that a previous iteration of this loop did not delete the Value.
5290     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
5291       continue;
5292 
5293     LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
5294                       << "\n");
5295     ArrayRef<Value *> Operands = Chain.slice(i, VF);
5296 
5297     R.buildTree(Operands);
5298     if (R.isTreeTinyAndNotFullyVectorizable())
5299       continue;
5300 
5301     R.computeMinimumValueSizes();
5302 
5303     int Cost = R.getTreeCost();
5304 
5305     LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF
5306                       << "\n");
5307     if (Cost < -SLPCostThreshold) {
5308       LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
5309 
5310       using namespace ore;
5311 
5312       R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
5313                                           cast<StoreInst>(Chain[i]))
5314                        << "Stores SLP vectorized with cost " << NV("Cost", Cost)
5315                        << " and with tree size "
5316                        << NV("TreeSize", R.getTreeSize()));
5317 
5318       R.vectorizeTree();
5319 
5320       // Move to the next bundle.
5321       i += VF - 1;
5322       Changed = true;
5323     }
5324   }
5325 
5326   return Changed;
5327 }
5328 
5329 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
5330                                         BoUpSLP &R) {
5331   SetVector<StoreInst *> Heads;
5332   SmallDenseSet<StoreInst *> Tails;
5333   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
5334 
5335   // We may run into multiple chains that merge into a single chain. We mark the
5336   // stores that we vectorized so that we don't visit the same store twice.
5337   BoUpSLP::ValueSet VectorizedStores;
5338   bool Changed = false;
5339 
5340   auto &&FindConsecutiveAccess =
5341       [this, &Stores, &Heads, &Tails, &ConsecutiveChain] (int K, int Idx) {
5342         if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE))
5343           return false;
5344 
5345         Tails.insert(Stores[Idx]);
5346         Heads.insert(Stores[K]);
5347         ConsecutiveChain[Stores[K]] = Stores[Idx];
5348         return true;
5349       };
5350 
5351   // Do a quadratic search on all of the given stores in reverse order and find
5352   // all of the pairs of stores that follow each other.
5353   int E = Stores.size();
5354   for (int Idx = E - 1; Idx >= 0; --Idx) {
5355     // If a store has multiple consecutive store candidates, search according
5356     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
5357     // This is because usually pairing with immediate succeeding or preceding
5358     // candidate create the best chance to find slp vectorization opportunity.
5359     for (int Offset = 1, F = std::max(E - Idx, Idx + 1); Offset < F; ++Offset)
5360       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
5361           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
5362         break;
5363   }
5364 
5365   // For stores that start but don't end a link in the chain:
5366   for (auto *SI : llvm::reverse(Heads)) {
5367     if (Tails.count(SI))
5368       continue;
5369 
5370     // We found a store instr that starts a chain. Now follow the chain and try
5371     // to vectorize it.
5372     BoUpSLP::ValueList Operands;
5373     StoreInst *I = SI;
5374     // Collect the chain into a list.
5375     while ((Tails.count(I) || Heads.count(I)) && !VectorizedStores.count(I)) {
5376       Operands.push_back(I);
5377       // Move to the next value in the chain.
5378       I = ConsecutiveChain[I];
5379     }
5380 
5381     // FIXME: Is division-by-2 the correct step? Should we assert that the
5382     // register size is a power-of-2?
5383     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
5384          Size /= 2) {
5385       if (vectorizeStoreChain(Operands, R, Size)) {
5386         // Mark the vectorized stores so that we don't vectorize them again.
5387         VectorizedStores.insert(Operands.begin(), Operands.end());
5388         Changed = true;
5389         break;
5390       }
5391     }
5392   }
5393 
5394   return Changed;
5395 }
5396 
5397 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
5398   // Initialize the collections. We will make a single pass over the block.
5399   Stores.clear();
5400   GEPs.clear();
5401 
5402   // Visit the store and getelementptr instructions in BB and organize them in
5403   // Stores and GEPs according to the underlying objects of their pointer
5404   // operands.
5405   for (Instruction &I : *BB) {
5406     // Ignore store instructions that are volatile or have a pointer operand
5407     // that doesn't point to a scalar type.
5408     if (auto *SI = dyn_cast<StoreInst>(&I)) {
5409       if (!SI->isSimple())
5410         continue;
5411       if (!isValidElementType(SI->getValueOperand()->getType()))
5412         continue;
5413       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
5414     }
5415 
5416     // Ignore getelementptr instructions that have more than one index, a
5417     // constant index, or a pointer operand that doesn't point to a scalar
5418     // type.
5419     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
5420       auto Idx = GEP->idx_begin()->get();
5421       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
5422         continue;
5423       if (!isValidElementType(Idx->getType()))
5424         continue;
5425       if (GEP->getType()->isVectorTy())
5426         continue;
5427       GEPs[GEP->getPointerOperand()].push_back(GEP);
5428     }
5429   }
5430 }
5431 
5432 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
5433   if (!A || !B)
5434     return false;
5435   Value *VL[] = { A, B };
5436   return tryToVectorizeList(VL, R, /*UserCost=*/0, true);
5437 }
5438 
5439 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
5440                                            int UserCost, bool AllowReorder) {
5441   if (VL.size() < 2)
5442     return false;
5443 
5444   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
5445                     << VL.size() << ".\n");
5446 
5447   // Check that all of the parts are scalar instructions of the same type,
5448   // we permit an alternate opcode via InstructionsState.
5449   InstructionsState S = getSameOpcode(VL);
5450   if (!S.getOpcode())
5451     return false;
5452 
5453   Instruction *I0 = cast<Instruction>(S.OpValue);
5454   unsigned Sz = R.getVectorElementSize(I0);
5455   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
5456   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
5457   if (MaxVF < 2) {
5458     R.getORE()->emit([&]() {
5459       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
5460              << "Cannot SLP vectorize list: vectorization factor "
5461              << "less than 2 is not supported";
5462     });
5463     return false;
5464   }
5465 
5466   for (Value *V : VL) {
5467     Type *Ty = V->getType();
5468     if (!isValidElementType(Ty)) {
5469       // NOTE: the following will give user internal llvm type name, which may
5470       // not be useful.
5471       R.getORE()->emit([&]() {
5472         std::string type_str;
5473         llvm::raw_string_ostream rso(type_str);
5474         Ty->print(rso);
5475         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
5476                << "Cannot SLP vectorize list: type "
5477                << rso.str() + " is unsupported by vectorizer";
5478       });
5479       return false;
5480     }
5481   }
5482 
5483   bool Changed = false;
5484   bool CandidateFound = false;
5485   int MinCost = SLPCostThreshold;
5486 
5487   // Keep track of values that were deleted by vectorizing in the loop below.
5488   SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
5489 
5490   unsigned NextInst = 0, MaxInst = VL.size();
5491   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
5492     // No actual vectorization should happen, if number of parts is the same as
5493     // provided vectorization factor (i.e. the scalar type is used for vector
5494     // code during codegen).
5495     auto *VecTy = VectorType::get(VL[0]->getType(), VF);
5496     if (TTI->getNumberOfParts(VecTy) == VF)
5497       continue;
5498     for (unsigned I = NextInst; I < MaxInst; ++I) {
5499       unsigned OpsWidth = 0;
5500 
5501       if (I + VF > MaxInst)
5502         OpsWidth = MaxInst - I;
5503       else
5504         OpsWidth = VF;
5505 
5506       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
5507         break;
5508 
5509       // Check that a previous iteration of this loop did not delete the Value.
5510       if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
5511         continue;
5512 
5513       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
5514                         << "\n");
5515       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
5516 
5517       R.buildTree(Ops);
5518       Optional<ArrayRef<unsigned>> Order = R.bestOrder();
5519       // TODO: check if we can allow reordering for more cases.
5520       if (AllowReorder && Order) {
5521         // TODO: reorder tree nodes without tree rebuilding.
5522         // Conceptually, there is nothing actually preventing us from trying to
5523         // reorder a larger list. In fact, we do exactly this when vectorizing
5524         // reductions. However, at this point, we only expect to get here when
5525         // there are exactly two operations.
5526         assert(Ops.size() == 2);
5527         Value *ReorderedOps[] = {Ops[1], Ops[0]};
5528         R.buildTree(ReorderedOps, None);
5529       }
5530       if (R.isTreeTinyAndNotFullyVectorizable())
5531         continue;
5532 
5533       R.computeMinimumValueSizes();
5534       int Cost = R.getTreeCost() - UserCost;
5535       CandidateFound = true;
5536       MinCost = std::min(MinCost, Cost);
5537 
5538       if (Cost < -SLPCostThreshold) {
5539         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
5540         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
5541                                                     cast<Instruction>(Ops[0]))
5542                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
5543                                  << " and with tree size "
5544                                  << ore::NV("TreeSize", R.getTreeSize()));
5545 
5546         R.vectorizeTree();
5547         // Move to the next bundle.
5548         I += VF - 1;
5549         NextInst = I + 1;
5550         Changed = true;
5551       }
5552     }
5553   }
5554 
5555   if (!Changed && CandidateFound) {
5556     R.getORE()->emit([&]() {
5557       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
5558              << "List vectorization was possible but not beneficial with cost "
5559              << ore::NV("Cost", MinCost) << " >= "
5560              << ore::NV("Treshold", -SLPCostThreshold);
5561     });
5562   } else if (!Changed) {
5563     R.getORE()->emit([&]() {
5564       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
5565              << "Cannot SLP vectorize list: vectorization was impossible"
5566              << " with available vectorization factors";
5567     });
5568   }
5569   return Changed;
5570 }
5571 
5572 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
5573   if (!I)
5574     return false;
5575 
5576   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
5577     return false;
5578 
5579   Value *P = I->getParent();
5580 
5581   // Vectorize in current basic block only.
5582   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
5583   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
5584   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
5585     return false;
5586 
5587   // Try to vectorize V.
5588   if (tryToVectorizePair(Op0, Op1, R))
5589     return true;
5590 
5591   auto *A = dyn_cast<BinaryOperator>(Op0);
5592   auto *B = dyn_cast<BinaryOperator>(Op1);
5593   // Try to skip B.
5594   if (B && B->hasOneUse()) {
5595     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
5596     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
5597     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
5598       return true;
5599     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
5600       return true;
5601   }
5602 
5603   // Try to skip A.
5604   if (A && A->hasOneUse()) {
5605     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
5606     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
5607     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
5608       return true;
5609     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
5610       return true;
5611   }
5612   return false;
5613 }
5614 
5615 /// Generate a shuffle mask to be used in a reduction tree.
5616 ///
5617 /// \param VecLen The length of the vector to be reduced.
5618 /// \param NumEltsToRdx The number of elements that should be reduced in the
5619 ///        vector.
5620 /// \param IsPairwise Whether the reduction is a pairwise or splitting
5621 ///        reduction. A pairwise reduction will generate a mask of
5622 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
5623 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
5624 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
5625 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
5626                                    bool IsPairwise, bool IsLeft,
5627                                    IRBuilder<> &Builder) {
5628   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
5629 
5630   SmallVector<Constant *, 32> ShuffleMask(
5631       VecLen, UndefValue::get(Builder.getInt32Ty()));
5632 
5633   if (IsPairwise)
5634     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
5635     for (unsigned i = 0; i != NumEltsToRdx; ++i)
5636       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
5637   else
5638     // Move the upper half of the vector to the lower half.
5639     for (unsigned i = 0; i != NumEltsToRdx; ++i)
5640       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
5641 
5642   return ConstantVector::get(ShuffleMask);
5643 }
5644 
5645 namespace {
5646 
5647 /// Model horizontal reductions.
5648 ///
5649 /// A horizontal reduction is a tree of reduction operations (currently add and
5650 /// fadd) that has operations that can be put into a vector as its leaf.
5651 /// For example, this tree:
5652 ///
5653 /// mul mul mul mul
5654 ///  \  /    \  /
5655 ///   +       +
5656 ///    \     /
5657 ///       +
5658 /// This tree has "mul" as its reduced values and "+" as its reduction
5659 /// operations. A reduction might be feeding into a store or a binary operation
5660 /// feeding a phi.
5661 ///    ...
5662 ///    \  /
5663 ///     +
5664 ///     |
5665 ///  phi +=
5666 ///
5667 ///  Or:
5668 ///    ...
5669 ///    \  /
5670 ///     +
5671 ///     |
5672 ///   *p =
5673 ///
5674 class HorizontalReduction {
5675   using ReductionOpsType = SmallVector<Value *, 16>;
5676   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
5677   ReductionOpsListType  ReductionOps;
5678   SmallVector<Value *, 32> ReducedVals;
5679   // Use map vector to make stable output.
5680   MapVector<Instruction *, Value *> ExtraArgs;
5681 
5682   /// Kind of the reduction data.
5683   enum ReductionKind {
5684     RK_None,       /// Not a reduction.
5685     RK_Arithmetic, /// Binary reduction data.
5686     RK_Min,        /// Minimum reduction data.
5687     RK_UMin,       /// Unsigned minimum reduction data.
5688     RK_Max,        /// Maximum reduction data.
5689     RK_UMax,       /// Unsigned maximum reduction data.
5690   };
5691 
5692   /// Contains info about operation, like its opcode, left and right operands.
5693   class OperationData {
5694     /// Opcode of the instruction.
5695     unsigned Opcode = 0;
5696 
5697     /// Left operand of the reduction operation.
5698     Value *LHS = nullptr;
5699 
5700     /// Right operand of the reduction operation.
5701     Value *RHS = nullptr;
5702 
5703     /// Kind of the reduction operation.
5704     ReductionKind Kind = RK_None;
5705 
5706     /// True if float point min/max reduction has no NaNs.
5707     bool NoNaN = false;
5708 
5709     /// Checks if the reduction operation can be vectorized.
5710     bool isVectorizable() const {
5711       return LHS && RHS &&
5712              // We currently only support add/mul/logical && min/max reductions.
5713              ((Kind == RK_Arithmetic &&
5714                (Opcode == Instruction::Add || Opcode == Instruction::FAdd ||
5715                 Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
5716                 Opcode == Instruction::And || Opcode == Instruction::Or ||
5717                 Opcode == Instruction::Xor)) ||
5718               ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
5719                (Kind == RK_Min || Kind == RK_Max)) ||
5720               (Opcode == Instruction::ICmp &&
5721                (Kind == RK_UMin || Kind == RK_UMax)));
5722     }
5723 
5724     /// Creates reduction operation with the current opcode.
5725     Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
5726       assert(isVectorizable() &&
5727              "Expected add|fadd or min/max reduction operation.");
5728       Value *Cmp = nullptr;
5729       switch (Kind) {
5730       case RK_Arithmetic:
5731         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
5732                                    Name);
5733       case RK_Min:
5734         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
5735                                           : Builder.CreateFCmpOLT(LHS, RHS);
5736         break;
5737       case RK_Max:
5738         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
5739                                           : Builder.CreateFCmpOGT(LHS, RHS);
5740         break;
5741       case RK_UMin:
5742         assert(Opcode == Instruction::ICmp && "Expected integer types.");
5743         Cmp = Builder.CreateICmpULT(LHS, RHS);
5744         break;
5745       case RK_UMax:
5746         assert(Opcode == Instruction::ICmp && "Expected integer types.");
5747         Cmp = Builder.CreateICmpUGT(LHS, RHS);
5748         break;
5749       case RK_None:
5750         llvm_unreachable("Unknown reduction operation.");
5751       }
5752       return Builder.CreateSelect(Cmp, LHS, RHS, Name);
5753     }
5754 
5755   public:
5756     explicit OperationData() = default;
5757 
5758     /// Construction for reduced values. They are identified by opcode only and
5759     /// don't have associated LHS/RHS values.
5760     explicit OperationData(Value *V) {
5761       if (auto *I = dyn_cast<Instruction>(V))
5762         Opcode = I->getOpcode();
5763     }
5764 
5765     /// Constructor for reduction operations with opcode and its left and
5766     /// right operands.
5767     OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
5768                   bool NoNaN = false)
5769         : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
5770       assert(Kind != RK_None && "One of the reduction operations is expected.");
5771     }
5772 
5773     explicit operator bool() const { return Opcode; }
5774 
5775     /// Get the index of the first operand.
5776     unsigned getFirstOperandIndex() const {
5777       assert(!!*this && "The opcode is not set.");
5778       switch (Kind) {
5779       case RK_Min:
5780       case RK_UMin:
5781       case RK_Max:
5782       case RK_UMax:
5783         return 1;
5784       case RK_Arithmetic:
5785       case RK_None:
5786         break;
5787       }
5788       return 0;
5789     }
5790 
5791     /// Total number of operands in the reduction operation.
5792     unsigned getNumberOfOperands() const {
5793       assert(Kind != RK_None && !!*this && LHS && RHS &&
5794              "Expected reduction operation.");
5795       switch (Kind) {
5796       case RK_Arithmetic:
5797         return 2;
5798       case RK_Min:
5799       case RK_UMin:
5800       case RK_Max:
5801       case RK_UMax:
5802         return 3;
5803       case RK_None:
5804         break;
5805       }
5806       llvm_unreachable("Reduction kind is not set");
5807     }
5808 
5809     /// Checks if the operation has the same parent as \p P.
5810     bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
5811       assert(Kind != RK_None && !!*this && LHS && RHS &&
5812              "Expected reduction operation.");
5813       if (!IsRedOp)
5814         return I->getParent() == P;
5815       switch (Kind) {
5816       case RK_Arithmetic:
5817         // Arithmetic reduction operation must be used once only.
5818         return I->getParent() == P;
5819       case RK_Min:
5820       case RK_UMin:
5821       case RK_Max:
5822       case RK_UMax: {
5823         // SelectInst must be used twice while the condition op must have single
5824         // use only.
5825         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
5826         return I->getParent() == P && Cmp && Cmp->getParent() == P;
5827       }
5828       case RK_None:
5829         break;
5830       }
5831       llvm_unreachable("Reduction kind is not set");
5832     }
5833     /// Expected number of uses for reduction operations/reduced values.
5834     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
5835       assert(Kind != RK_None && !!*this && LHS && RHS &&
5836              "Expected reduction operation.");
5837       switch (Kind) {
5838       case RK_Arithmetic:
5839         return I->hasOneUse();
5840       case RK_Min:
5841       case RK_UMin:
5842       case RK_Max:
5843       case RK_UMax:
5844         return I->hasNUses(2) &&
5845                (!IsReductionOp ||
5846                 cast<SelectInst>(I)->getCondition()->hasOneUse());
5847       case RK_None:
5848         break;
5849       }
5850       llvm_unreachable("Reduction kind is not set");
5851     }
5852 
5853     /// Initializes the list of reduction operations.
5854     void initReductionOps(ReductionOpsListType &ReductionOps) {
5855       assert(Kind != RK_None && !!*this && LHS && RHS &&
5856              "Expected reduction operation.");
5857       switch (Kind) {
5858       case RK_Arithmetic:
5859         ReductionOps.assign(1, ReductionOpsType());
5860         break;
5861       case RK_Min:
5862       case RK_UMin:
5863       case RK_Max:
5864       case RK_UMax:
5865         ReductionOps.assign(2, ReductionOpsType());
5866         break;
5867       case RK_None:
5868         llvm_unreachable("Reduction kind is not set");
5869       }
5870     }
5871     /// Add all reduction operations for the reduction instruction \p I.
5872     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
5873       assert(Kind != RK_None && !!*this && LHS && RHS &&
5874              "Expected reduction operation.");
5875       switch (Kind) {
5876       case RK_Arithmetic:
5877         ReductionOps[0].emplace_back(I);
5878         break;
5879       case RK_Min:
5880       case RK_UMin:
5881       case RK_Max:
5882       case RK_UMax:
5883         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
5884         ReductionOps[1].emplace_back(I);
5885         break;
5886       case RK_None:
5887         llvm_unreachable("Reduction kind is not set");
5888       }
5889     }
5890 
5891     /// Checks if instruction is associative and can be vectorized.
5892     bool isAssociative(Instruction *I) const {
5893       assert(Kind != RK_None && *this && LHS && RHS &&
5894              "Expected reduction operation.");
5895       switch (Kind) {
5896       case RK_Arithmetic:
5897         return I->isAssociative();
5898       case RK_Min:
5899       case RK_Max:
5900         return Opcode == Instruction::ICmp ||
5901                cast<Instruction>(I->getOperand(0))->isFast();
5902       case RK_UMin:
5903       case RK_UMax:
5904         assert(Opcode == Instruction::ICmp &&
5905                "Only integer compare operation is expected.");
5906         return true;
5907       case RK_None:
5908         break;
5909       }
5910       llvm_unreachable("Reduction kind is not set");
5911     }
5912 
5913     /// Checks if the reduction operation can be vectorized.
5914     bool isVectorizable(Instruction *I) const {
5915       return isVectorizable() && isAssociative(I);
5916     }
5917 
5918     /// Checks if two operation data are both a reduction op or both a reduced
5919     /// value.
5920     bool operator==(const OperationData &OD) {
5921       assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
5922              "One of the comparing operations is incorrect.");
5923       return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
5924     }
5925     bool operator!=(const OperationData &OD) { return !(*this == OD); }
5926     void clear() {
5927       Opcode = 0;
5928       LHS = nullptr;
5929       RHS = nullptr;
5930       Kind = RK_None;
5931       NoNaN = false;
5932     }
5933 
5934     /// Get the opcode of the reduction operation.
5935     unsigned getOpcode() const {
5936       assert(isVectorizable() && "Expected vectorizable operation.");
5937       return Opcode;
5938     }
5939 
5940     /// Get kind of reduction data.
5941     ReductionKind getKind() const { return Kind; }
5942     Value *getLHS() const { return LHS; }
5943     Value *getRHS() const { return RHS; }
5944     Type *getConditionType() const {
5945       switch (Kind) {
5946       case RK_Arithmetic:
5947         return nullptr;
5948       case RK_Min:
5949       case RK_Max:
5950       case RK_UMin:
5951       case RK_UMax:
5952         return CmpInst::makeCmpResultType(LHS->getType());
5953       case RK_None:
5954         break;
5955       }
5956       llvm_unreachable("Reduction kind is not set");
5957     }
5958 
5959     /// Creates reduction operation with the current opcode with the IR flags
5960     /// from \p ReductionOps.
5961     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5962                     const ReductionOpsListType &ReductionOps) const {
5963       assert(isVectorizable() &&
5964              "Expected add|fadd or min/max reduction operation.");
5965       auto *Op = createOp(Builder, Name);
5966       switch (Kind) {
5967       case RK_Arithmetic:
5968         propagateIRFlags(Op, ReductionOps[0]);
5969         return Op;
5970       case RK_Min:
5971       case RK_Max:
5972       case RK_UMin:
5973       case RK_UMax:
5974         if (auto *SI = dyn_cast<SelectInst>(Op))
5975           propagateIRFlags(SI->getCondition(), ReductionOps[0]);
5976         propagateIRFlags(Op, ReductionOps[1]);
5977         return Op;
5978       case RK_None:
5979         break;
5980       }
5981       llvm_unreachable("Unknown reduction operation.");
5982     }
5983     /// Creates reduction operation with the current opcode with the IR flags
5984     /// from \p I.
5985     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5986                     Instruction *I) const {
5987       assert(isVectorizable() &&
5988              "Expected add|fadd or min/max reduction operation.");
5989       auto *Op = createOp(Builder, Name);
5990       switch (Kind) {
5991       case RK_Arithmetic:
5992         propagateIRFlags(Op, I);
5993         return Op;
5994       case RK_Min:
5995       case RK_Max:
5996       case RK_UMin:
5997       case RK_UMax:
5998         if (auto *SI = dyn_cast<SelectInst>(Op)) {
5999           propagateIRFlags(SI->getCondition(),
6000                            cast<SelectInst>(I)->getCondition());
6001         }
6002         propagateIRFlags(Op, I);
6003         return Op;
6004       case RK_None:
6005         break;
6006       }
6007       llvm_unreachable("Unknown reduction operation.");
6008     }
6009 
6010     TargetTransformInfo::ReductionFlags getFlags() const {
6011       TargetTransformInfo::ReductionFlags Flags;
6012       Flags.NoNaN = NoNaN;
6013       switch (Kind) {
6014       case RK_Arithmetic:
6015         break;
6016       case RK_Min:
6017         Flags.IsSigned = Opcode == Instruction::ICmp;
6018         Flags.IsMaxOp = false;
6019         break;
6020       case RK_Max:
6021         Flags.IsSigned = Opcode == Instruction::ICmp;
6022         Flags.IsMaxOp = true;
6023         break;
6024       case RK_UMin:
6025         Flags.IsSigned = false;
6026         Flags.IsMaxOp = false;
6027         break;
6028       case RK_UMax:
6029         Flags.IsSigned = false;
6030         Flags.IsMaxOp = true;
6031         break;
6032       case RK_None:
6033         llvm_unreachable("Reduction kind is not set");
6034       }
6035       return Flags;
6036     }
6037   };
6038 
6039   WeakTrackingVH ReductionRoot;
6040 
6041   /// The operation data of the reduction operation.
6042   OperationData ReductionData;
6043 
6044   /// The operation data of the values we perform a reduction on.
6045   OperationData ReducedValueData;
6046 
6047   /// Should we model this reduction as a pairwise reduction tree or a tree that
6048   /// splits the vector in halves and adds those halves.
6049   bool IsPairwiseReduction = false;
6050 
6051   /// Checks if the ParentStackElem.first should be marked as a reduction
6052   /// operation with an extra argument or as extra argument itself.
6053   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
6054                     Value *ExtraArg) {
6055     if (ExtraArgs.count(ParentStackElem.first)) {
6056       ExtraArgs[ParentStackElem.first] = nullptr;
6057       // We ran into something like:
6058       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6059       // The whole ParentStackElem.first should be considered as an extra value
6060       // in this case.
6061       // Do not perform analysis of remaining operands of ParentStackElem.first
6062       // instruction, this whole instruction is an extra argument.
6063       ParentStackElem.second = ParentStackElem.first->getNumOperands();
6064     } else {
6065       // We ran into something like:
6066       // ParentStackElem.first += ... + ExtraArg + ...
6067       ExtraArgs[ParentStackElem.first] = ExtraArg;
6068     }
6069   }
6070 
6071   static OperationData getOperationData(Value *V) {
6072     if (!V)
6073       return OperationData();
6074 
6075     Value *LHS;
6076     Value *RHS;
6077     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
6078       return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
6079                            RK_Arithmetic);
6080     }
6081     if (auto *Select = dyn_cast<SelectInst>(V)) {
6082       // Look for a min/max pattern.
6083       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6084         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6085       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6086         return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6087       } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
6088                  m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6089         return OperationData(
6090             Instruction::FCmp, LHS, RHS, RK_Min,
6091             cast<Instruction>(Select->getCondition())->hasNoNaNs());
6092       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6093         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6094       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6095         return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6096       } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
6097                  m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6098         return OperationData(
6099             Instruction::FCmp, LHS, RHS, RK_Max,
6100             cast<Instruction>(Select->getCondition())->hasNoNaNs());
6101       } else {
6102         // Try harder: look for min/max pattern based on instructions producing
6103         // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6104         // During the intermediate stages of SLP, it's very common to have
6105         // pattern like this (since optimizeGatherSequence is run only once
6106         // at the end):
6107         // %1 = extractelement <2 x i32> %a, i32 0
6108         // %2 = extractelement <2 x i32> %a, i32 1
6109         // %cond = icmp sgt i32 %1, %2
6110         // %3 = extractelement <2 x i32> %a, i32 0
6111         // %4 = extractelement <2 x i32> %a, i32 1
6112         // %select = select i1 %cond, i32 %3, i32 %4
6113         CmpInst::Predicate Pred;
6114         Instruction *L1;
6115         Instruction *L2;
6116 
6117         LHS = Select->getTrueValue();
6118         RHS = Select->getFalseValue();
6119         Value *Cond = Select->getCondition();
6120 
6121         // TODO: Support inverse predicates.
6122         if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
6123           if (!isa<ExtractElementInst>(RHS) ||
6124               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6125             return OperationData(V);
6126         } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
6127           if (!isa<ExtractElementInst>(LHS) ||
6128               !L1->isIdenticalTo(cast<Instruction>(LHS)))
6129             return OperationData(V);
6130         } else {
6131           if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
6132             return OperationData(V);
6133           if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
6134               !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
6135               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6136             return OperationData(V);
6137         }
6138         switch (Pred) {
6139         default:
6140           return OperationData(V);
6141 
6142         case CmpInst::ICMP_ULT:
6143         case CmpInst::ICMP_ULE:
6144           return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6145 
6146         case CmpInst::ICMP_SLT:
6147         case CmpInst::ICMP_SLE:
6148           return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6149 
6150         case CmpInst::FCMP_OLT:
6151         case CmpInst::FCMP_OLE:
6152         case CmpInst::FCMP_ULT:
6153         case CmpInst::FCMP_ULE:
6154           return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
6155                                cast<Instruction>(Cond)->hasNoNaNs());
6156 
6157         case CmpInst::ICMP_UGT:
6158         case CmpInst::ICMP_UGE:
6159           return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6160 
6161         case CmpInst::ICMP_SGT:
6162         case CmpInst::ICMP_SGE:
6163           return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6164 
6165         case CmpInst::FCMP_OGT:
6166         case CmpInst::FCMP_OGE:
6167         case CmpInst::FCMP_UGT:
6168         case CmpInst::FCMP_UGE:
6169           return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
6170                                cast<Instruction>(Cond)->hasNoNaNs());
6171         }
6172       }
6173     }
6174     return OperationData(V);
6175   }
6176 
6177 public:
6178   HorizontalReduction() = default;
6179 
6180   /// Try to find a reduction tree.
6181   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
6182     assert((!Phi || is_contained(Phi->operands(), B)) &&
6183            "Thi phi needs to use the binary operator");
6184 
6185     ReductionData = getOperationData(B);
6186 
6187     // We could have a initial reductions that is not an add.
6188     //  r *= v1 + v2 + v3 + v4
6189     // In such a case start looking for a tree rooted in the first '+'.
6190     if (Phi) {
6191       if (ReductionData.getLHS() == Phi) {
6192         Phi = nullptr;
6193         B = dyn_cast<Instruction>(ReductionData.getRHS());
6194         ReductionData = getOperationData(B);
6195       } else if (ReductionData.getRHS() == Phi) {
6196         Phi = nullptr;
6197         B = dyn_cast<Instruction>(ReductionData.getLHS());
6198         ReductionData = getOperationData(B);
6199       }
6200     }
6201 
6202     if (!ReductionData.isVectorizable(B))
6203       return false;
6204 
6205     Type *Ty = B->getType();
6206     if (!isValidElementType(Ty))
6207       return false;
6208     if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
6209       return false;
6210 
6211     ReducedValueData.clear();
6212     ReductionRoot = B;
6213 
6214     // Post order traverse the reduction tree starting at B. We only handle true
6215     // trees containing only binary operators.
6216     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
6217     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
6218     ReductionData.initReductionOps(ReductionOps);
6219     while (!Stack.empty()) {
6220       Instruction *TreeN = Stack.back().first;
6221       unsigned EdgeToVist = Stack.back().second++;
6222       OperationData OpData = getOperationData(TreeN);
6223       bool IsReducedValue = OpData != ReductionData;
6224 
6225       // Postorder vist.
6226       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
6227         if (IsReducedValue)
6228           ReducedVals.push_back(TreeN);
6229         else {
6230           auto I = ExtraArgs.find(TreeN);
6231           if (I != ExtraArgs.end() && !I->second) {
6232             // Check if TreeN is an extra argument of its parent operation.
6233             if (Stack.size() <= 1) {
6234               // TreeN can't be an extra argument as it is a root reduction
6235               // operation.
6236               return false;
6237             }
6238             // Yes, TreeN is an extra argument, do not add it to a list of
6239             // reduction operations.
6240             // Stack[Stack.size() - 2] always points to the parent operation.
6241             markExtraArg(Stack[Stack.size() - 2], TreeN);
6242             ExtraArgs.erase(TreeN);
6243           } else
6244             ReductionData.addReductionOps(TreeN, ReductionOps);
6245         }
6246         // Retract.
6247         Stack.pop_back();
6248         continue;
6249       }
6250 
6251       // Visit left or right.
6252       Value *NextV = TreeN->getOperand(EdgeToVist);
6253       if (NextV != Phi) {
6254         auto *I = dyn_cast<Instruction>(NextV);
6255         OpData = getOperationData(I);
6256         // Continue analysis if the next operand is a reduction operation or
6257         // (possibly) a reduced value. If the reduced value opcode is not set,
6258         // the first met operation != reduction operation is considered as the
6259         // reduced value class.
6260         if (I && (!ReducedValueData || OpData == ReducedValueData ||
6261                   OpData == ReductionData)) {
6262           const bool IsReductionOperation = OpData == ReductionData;
6263           // Only handle trees in the current basic block.
6264           if (!ReductionData.hasSameParent(I, B->getParent(),
6265                                            IsReductionOperation)) {
6266             // I is an extra argument for TreeN (its parent operation).
6267             markExtraArg(Stack.back(), I);
6268             continue;
6269           }
6270 
6271           // Each tree node needs to have minimal number of users except for the
6272           // ultimate reduction.
6273           if (!ReductionData.hasRequiredNumberOfUses(I,
6274                                                      OpData == ReductionData) &&
6275               I != B) {
6276             // I is an extra argument for TreeN (its parent operation).
6277             markExtraArg(Stack.back(), I);
6278             continue;
6279           }
6280 
6281           if (IsReductionOperation) {
6282             // We need to be able to reassociate the reduction operations.
6283             if (!OpData.isAssociative(I)) {
6284               // I is an extra argument for TreeN (its parent operation).
6285               markExtraArg(Stack.back(), I);
6286               continue;
6287             }
6288           } else if (ReducedValueData &&
6289                      ReducedValueData != OpData) {
6290             // Make sure that the opcodes of the operations that we are going to
6291             // reduce match.
6292             // I is an extra argument for TreeN (its parent operation).
6293             markExtraArg(Stack.back(), I);
6294             continue;
6295           } else if (!ReducedValueData)
6296             ReducedValueData = OpData;
6297 
6298           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
6299           continue;
6300         }
6301       }
6302       // NextV is an extra argument for TreeN (its parent operation).
6303       markExtraArg(Stack.back(), NextV);
6304     }
6305     return true;
6306   }
6307 
6308   /// Attempt to vectorize the tree found by
6309   /// matchAssociativeReduction.
6310   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
6311     if (ReducedVals.empty())
6312       return false;
6313 
6314     // If there is a sufficient number of reduction values, reduce
6315     // to a nearby power-of-2. Can safely generate oversized
6316     // vectors and rely on the backend to split them to legal sizes.
6317     unsigned NumReducedVals = ReducedVals.size();
6318     if (NumReducedVals < 4)
6319       return false;
6320 
6321     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
6322 
6323     Value *VectorizedTree = nullptr;
6324 
6325     // FIXME: Fast-math-flags should be set based on the instructions in the
6326     //        reduction (not all of 'fast' are required).
6327     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
6328     FastMathFlags Unsafe;
6329     Unsafe.setFast();
6330     Builder.setFastMathFlags(Unsafe);
6331     unsigned i = 0;
6332 
6333     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
6334     // The same extra argument may be used several time, so log each attempt
6335     // to use it.
6336     for (auto &Pair : ExtraArgs) {
6337       assert(Pair.first && "DebugLoc must be set.");
6338       ExternallyUsedValues[Pair.second].push_back(Pair.first);
6339     }
6340     // The reduction root is used as the insertion point for new instructions,
6341     // so set it as externally used to prevent it from being deleted.
6342     ExternallyUsedValues[ReductionRoot];
6343     SmallVector<Value *, 16> IgnoreList;
6344     for (auto &V : ReductionOps)
6345       IgnoreList.append(V.begin(), V.end());
6346     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
6347       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
6348       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
6349       Optional<ArrayRef<unsigned>> Order = V.bestOrder();
6350       // TODO: Handle orders of size less than number of elements in the vector.
6351       if (Order && Order->size() == VL.size()) {
6352         // TODO: reorder tree nodes without tree rebuilding.
6353         SmallVector<Value *, 4> ReorderedOps(VL.size());
6354         llvm::transform(*Order, ReorderedOps.begin(),
6355                         [VL](const unsigned Idx) { return VL[Idx]; });
6356         V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
6357       }
6358       if (V.isTreeTinyAndNotFullyVectorizable())
6359         break;
6360 
6361       V.computeMinimumValueSizes();
6362 
6363       // Estimate cost.
6364       int TreeCost = V.getTreeCost();
6365       int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
6366       int Cost = TreeCost + ReductionCost;
6367       if (Cost >= -SLPCostThreshold) {
6368           V.getORE()->emit([&]() {
6369               return OptimizationRemarkMissed(
6370                          SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
6371                      << "Vectorizing horizontal reduction is possible"
6372                      << "but not beneficial with cost "
6373                      << ore::NV("Cost", Cost) << " and threshold "
6374                      << ore::NV("Threshold", -SLPCostThreshold);
6375           });
6376           break;
6377       }
6378 
6379       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
6380                         << Cost << ". (HorRdx)\n");
6381       V.getORE()->emit([&]() {
6382           return OptimizationRemark(
6383                      SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
6384           << "Vectorized horizontal reduction with cost "
6385           << ore::NV("Cost", Cost) << " and with tree size "
6386           << ore::NV("TreeSize", V.getTreeSize());
6387       });
6388 
6389       // Vectorize a tree.
6390       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
6391       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
6392 
6393       // Emit a reduction.
6394       Builder.SetInsertPoint(cast<Instruction>(ReductionRoot));
6395       Value *ReducedSubTree =
6396           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
6397       if (VectorizedTree) {
6398         Builder.SetCurrentDebugLocation(Loc);
6399         OperationData VectReductionData(ReductionData.getOpcode(),
6400                                         VectorizedTree, ReducedSubTree,
6401                                         ReductionData.getKind());
6402         VectorizedTree =
6403             VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
6404       } else
6405         VectorizedTree = ReducedSubTree;
6406       i += ReduxWidth;
6407       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
6408     }
6409 
6410     if (VectorizedTree) {
6411       // Finish the reduction.
6412       for (; i < NumReducedVals; ++i) {
6413         auto *I = cast<Instruction>(ReducedVals[i]);
6414         Builder.SetCurrentDebugLocation(I->getDebugLoc());
6415         OperationData VectReductionData(ReductionData.getOpcode(),
6416                                         VectorizedTree, I,
6417                                         ReductionData.getKind());
6418         VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
6419       }
6420       for (auto &Pair : ExternallyUsedValues) {
6421         // Add each externally used value to the final reduction.
6422         for (auto *I : Pair.second) {
6423           Builder.SetCurrentDebugLocation(I->getDebugLoc());
6424           OperationData VectReductionData(ReductionData.getOpcode(),
6425                                           VectorizedTree, Pair.first,
6426                                           ReductionData.getKind());
6427           VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
6428         }
6429       }
6430       // Update users.
6431       ReductionRoot->replaceAllUsesWith(VectorizedTree);
6432     }
6433     return VectorizedTree != nullptr;
6434   }
6435 
6436   unsigned numReductionValues() const {
6437     return ReducedVals.size();
6438   }
6439 
6440 private:
6441   /// Calculate the cost of a reduction.
6442   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
6443                        unsigned ReduxWidth) {
6444     Type *ScalarTy = FirstReducedVal->getType();
6445     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
6446 
6447     int PairwiseRdxCost;
6448     int SplittingRdxCost;
6449     switch (ReductionData.getKind()) {
6450     case RK_Arithmetic:
6451       PairwiseRdxCost =
6452           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
6453                                           /*IsPairwiseForm=*/true);
6454       SplittingRdxCost =
6455           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
6456                                           /*IsPairwiseForm=*/false);
6457       break;
6458     case RK_Min:
6459     case RK_Max:
6460     case RK_UMin:
6461     case RK_UMax: {
6462       Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
6463       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
6464                         ReductionData.getKind() == RK_UMax;
6465       PairwiseRdxCost =
6466           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
6467                                       /*IsPairwiseForm=*/true, IsUnsigned);
6468       SplittingRdxCost =
6469           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
6470                                       /*IsPairwiseForm=*/false, IsUnsigned);
6471       break;
6472     }
6473     case RK_None:
6474       llvm_unreachable("Expected arithmetic or min/max reduction operation");
6475     }
6476 
6477     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
6478     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
6479 
6480     int ScalarReduxCost = 0;
6481     switch (ReductionData.getKind()) {
6482     case RK_Arithmetic:
6483       ScalarReduxCost =
6484           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
6485       break;
6486     case RK_Min:
6487     case RK_Max:
6488     case RK_UMin:
6489     case RK_UMax:
6490       ScalarReduxCost =
6491           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
6492           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
6493                                   CmpInst::makeCmpResultType(ScalarTy));
6494       break;
6495     case RK_None:
6496       llvm_unreachable("Expected arithmetic or min/max reduction operation");
6497     }
6498     ScalarReduxCost *= (ReduxWidth - 1);
6499 
6500     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
6501                       << " for reduction that starts with " << *FirstReducedVal
6502                       << " (It is a "
6503                       << (IsPairwiseReduction ? "pairwise" : "splitting")
6504                       << " reduction)\n");
6505 
6506     return VecReduxCost - ScalarReduxCost;
6507   }
6508 
6509   /// Emit a horizontal reduction of the vectorized value.
6510   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
6511                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
6512     assert(VectorizedValue && "Need to have a vectorized tree node");
6513     assert(isPowerOf2_32(ReduxWidth) &&
6514            "We only handle power-of-two reductions for now");
6515 
6516     if (!IsPairwiseReduction) {
6517       // FIXME: The builder should use an FMF guard. It should not be hard-coded
6518       //        to 'fast'.
6519       assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF");
6520       return createSimpleTargetReduction(
6521           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
6522           ReductionData.getFlags(), ReductionOps.back());
6523     }
6524 
6525     Value *TmpVec = VectorizedValue;
6526     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
6527       Value *LeftMask =
6528           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
6529       Value *RightMask =
6530           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
6531 
6532       Value *LeftShuf = Builder.CreateShuffleVector(
6533           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
6534       Value *RightShuf = Builder.CreateShuffleVector(
6535           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
6536           "rdx.shuf.r");
6537       OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
6538                                       RightShuf, ReductionData.getKind());
6539       TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
6540     }
6541 
6542     // The result is in the first element of the vector.
6543     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
6544   }
6545 };
6546 
6547 } // end anonymous namespace
6548 
6549 /// Recognize construction of vectors like
6550 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
6551 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
6552 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
6553 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
6554 ///  starting from the last insertelement instruction.
6555 ///
6556 /// Returns true if it matches
6557 static bool findBuildVector(InsertElementInst *LastInsertElem,
6558                             TargetTransformInfo *TTI,
6559                             SmallVectorImpl<Value *> &BuildVectorOpds,
6560                             int &UserCost) {
6561   UserCost = 0;
6562   Value *V = nullptr;
6563   do {
6564     if (auto *CI = dyn_cast<ConstantInt>(LastInsertElem->getOperand(2))) {
6565       UserCost += TTI->getVectorInstrCost(Instruction::InsertElement,
6566                                           LastInsertElem->getType(),
6567                                           CI->getZExtValue());
6568     }
6569     BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
6570     V = LastInsertElem->getOperand(0);
6571     if (isa<UndefValue>(V))
6572       break;
6573     LastInsertElem = dyn_cast<InsertElementInst>(V);
6574     if (!LastInsertElem || !LastInsertElem->hasOneUse())
6575       return false;
6576   } while (true);
6577   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
6578   return true;
6579 }
6580 
6581 /// Like findBuildVector, but looks for construction of aggregate.
6582 ///
6583 /// \return true if it matches.
6584 static bool findBuildAggregate(InsertValueInst *IV,
6585                                SmallVectorImpl<Value *> &BuildVectorOpds) {
6586   do {
6587     BuildVectorOpds.push_back(IV->getInsertedValueOperand());
6588     Value *V = IV->getAggregateOperand();
6589     if (isa<UndefValue>(V))
6590       break;
6591     IV = dyn_cast<InsertValueInst>(V);
6592     if (!IV || !IV->hasOneUse())
6593       return false;
6594   } while (true);
6595   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
6596   return true;
6597 }
6598 
6599 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
6600   return V->getType() < V2->getType();
6601 }
6602 
6603 /// Try and get a reduction value from a phi node.
6604 ///
6605 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
6606 /// if they come from either \p ParentBB or a containing loop latch.
6607 ///
6608 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
6609 /// if not possible.
6610 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
6611                                 BasicBlock *ParentBB, LoopInfo *LI) {
6612   // There are situations where the reduction value is not dominated by the
6613   // reduction phi. Vectorizing such cases has been reported to cause
6614   // miscompiles. See PR25787.
6615   auto DominatedReduxValue = [&](Value *R) {
6616     return isa<Instruction>(R) &&
6617            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
6618   };
6619 
6620   Value *Rdx = nullptr;
6621 
6622   // Return the incoming value if it comes from the same BB as the phi node.
6623   if (P->getIncomingBlock(0) == ParentBB) {
6624     Rdx = P->getIncomingValue(0);
6625   } else if (P->getIncomingBlock(1) == ParentBB) {
6626     Rdx = P->getIncomingValue(1);
6627   }
6628 
6629   if (Rdx && DominatedReduxValue(Rdx))
6630     return Rdx;
6631 
6632   // Otherwise, check whether we have a loop latch to look at.
6633   Loop *BBL = LI->getLoopFor(ParentBB);
6634   if (!BBL)
6635     return nullptr;
6636   BasicBlock *BBLatch = BBL->getLoopLatch();
6637   if (!BBLatch)
6638     return nullptr;
6639 
6640   // There is a loop latch, return the incoming value if it comes from
6641   // that. This reduction pattern occasionally turns up.
6642   if (P->getIncomingBlock(0) == BBLatch) {
6643     Rdx = P->getIncomingValue(0);
6644   } else if (P->getIncomingBlock(1) == BBLatch) {
6645     Rdx = P->getIncomingValue(1);
6646   }
6647 
6648   if (Rdx && DominatedReduxValue(Rdx))
6649     return Rdx;
6650 
6651   return nullptr;
6652 }
6653 
6654 /// Attempt to reduce a horizontal reduction.
6655 /// If it is legal to match a horizontal reduction feeding the phi node \a P
6656 /// with reduction operators \a Root (or one of its operands) in a basic block
6657 /// \a BB, then check if it can be done. If horizontal reduction is not found
6658 /// and root instruction is a binary operation, vectorization of the operands is
6659 /// attempted.
6660 /// \returns true if a horizontal reduction was matched and reduced or operands
6661 /// of one of the binary instruction were vectorized.
6662 /// \returns false if a horizontal reduction was not matched (or not possible)
6663 /// or no vectorization of any binary operation feeding \a Root instruction was
6664 /// performed.
6665 static bool tryToVectorizeHorReductionOrInstOperands(
6666     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
6667     TargetTransformInfo *TTI,
6668     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
6669   if (!ShouldVectorizeHor)
6670     return false;
6671 
6672   if (!Root)
6673     return false;
6674 
6675   if (Root->getParent() != BB || isa<PHINode>(Root))
6676     return false;
6677   // Start analysis starting from Root instruction. If horizontal reduction is
6678   // found, try to vectorize it. If it is not a horizontal reduction or
6679   // vectorization is not possible or not effective, and currently analyzed
6680   // instruction is a binary operation, try to vectorize the operands, using
6681   // pre-order DFS traversal order. If the operands were not vectorized, repeat
6682   // the same procedure considering each operand as a possible root of the
6683   // horizontal reduction.
6684   // Interrupt the process if the Root instruction itself was vectorized or all
6685   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
6686   SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
6687   SmallPtrSet<Value *, 8> VisitedInstrs;
6688   bool Res = false;
6689   while (!Stack.empty()) {
6690     Value *V;
6691     unsigned Level;
6692     std::tie(V, Level) = Stack.pop_back_val();
6693     if (!V)
6694       continue;
6695     auto *Inst = dyn_cast<Instruction>(V);
6696     if (!Inst)
6697       continue;
6698     auto *BI = dyn_cast<BinaryOperator>(Inst);
6699     auto *SI = dyn_cast<SelectInst>(Inst);
6700     if (BI || SI) {
6701       HorizontalReduction HorRdx;
6702       if (HorRdx.matchAssociativeReduction(P, Inst)) {
6703         if (HorRdx.tryToReduce(R, TTI)) {
6704           Res = true;
6705           // Set P to nullptr to avoid re-analysis of phi node in
6706           // matchAssociativeReduction function unless this is the root node.
6707           P = nullptr;
6708           continue;
6709         }
6710       }
6711       if (P && BI) {
6712         Inst = dyn_cast<Instruction>(BI->getOperand(0));
6713         if (Inst == P)
6714           Inst = dyn_cast<Instruction>(BI->getOperand(1));
6715         if (!Inst) {
6716           // Set P to nullptr to avoid re-analysis of phi node in
6717           // matchAssociativeReduction function unless this is the root node.
6718           P = nullptr;
6719           continue;
6720         }
6721       }
6722     }
6723     // Set P to nullptr to avoid re-analysis of phi node in
6724     // matchAssociativeReduction function unless this is the root node.
6725     P = nullptr;
6726     if (Vectorize(Inst, R)) {
6727       Res = true;
6728       continue;
6729     }
6730 
6731     // Try to vectorize operands.
6732     // Continue analysis for the instruction from the same basic block only to
6733     // save compile time.
6734     if (++Level < RecursionMaxDepth)
6735       for (auto *Op : Inst->operand_values())
6736         if (VisitedInstrs.insert(Op).second)
6737           if (auto *I = dyn_cast<Instruction>(Op))
6738             if (!isa<PHINode>(I) && I->getParent() == BB)
6739               Stack.emplace_back(Op, Level);
6740   }
6741   return Res;
6742 }
6743 
6744 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
6745                                                  BasicBlock *BB, BoUpSLP &R,
6746                                                  TargetTransformInfo *TTI) {
6747   if (!V)
6748     return false;
6749   auto *I = dyn_cast<Instruction>(V);
6750   if (!I)
6751     return false;
6752 
6753   if (!isa<BinaryOperator>(I))
6754     P = nullptr;
6755   // Try to match and vectorize a horizontal reduction.
6756   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
6757     return tryToVectorize(I, R);
6758   };
6759   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
6760                                                   ExtraVectorization);
6761 }
6762 
6763 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
6764                                                  BasicBlock *BB, BoUpSLP &R) {
6765   const DataLayout &DL = BB->getModule()->getDataLayout();
6766   if (!R.canMapToVector(IVI->getType(), DL))
6767     return false;
6768 
6769   SmallVector<Value *, 16> BuildVectorOpds;
6770   if (!findBuildAggregate(IVI, BuildVectorOpds))
6771     return false;
6772 
6773   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
6774   // Aggregate value is unlikely to be processed in vector register, we need to
6775   // extract scalars into scalar registers, so NeedExtraction is set true.
6776   return tryToVectorizeList(BuildVectorOpds, R);
6777 }
6778 
6779 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
6780                                                    BasicBlock *BB, BoUpSLP &R) {
6781   int UserCost;
6782   SmallVector<Value *, 16> BuildVectorOpds;
6783   if (!findBuildVector(IEI, TTI, BuildVectorOpds, UserCost) ||
6784       (llvm::all_of(BuildVectorOpds,
6785                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
6786        isShuffle(BuildVectorOpds)))
6787     return false;
6788 
6789   // Vectorize starting with the build vector operands ignoring the BuildVector
6790   // instructions for the purpose of scheduling and user extraction.
6791   return tryToVectorizeList(BuildVectorOpds, R, UserCost);
6792 }
6793 
6794 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
6795                                          BoUpSLP &R) {
6796   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
6797     return true;
6798 
6799   bool OpsChanged = false;
6800   for (int Idx = 0; Idx < 2; ++Idx) {
6801     OpsChanged |=
6802         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
6803   }
6804   return OpsChanged;
6805 }
6806 
6807 bool SLPVectorizerPass::vectorizeSimpleInstructions(
6808     SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
6809   bool OpsChanged = false;
6810   for (auto &VH : reverse(Instructions)) {
6811     auto *I = dyn_cast_or_null<Instruction>(VH);
6812     if (!I)
6813       continue;
6814     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
6815       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
6816     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
6817       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
6818     else if (auto *CI = dyn_cast<CmpInst>(I))
6819       OpsChanged |= vectorizeCmpInst(CI, BB, R);
6820   }
6821   Instructions.clear();
6822   return OpsChanged;
6823 }
6824 
6825 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
6826   bool Changed = false;
6827   SmallVector<Value *, 4> Incoming;
6828   SmallPtrSet<Value *, 16> VisitedInstrs;
6829 
6830   bool HaveVectorizedPhiNodes = true;
6831   while (HaveVectorizedPhiNodes) {
6832     HaveVectorizedPhiNodes = false;
6833 
6834     // Collect the incoming values from the PHIs.
6835     Incoming.clear();
6836     for (Instruction &I : *BB) {
6837       PHINode *P = dyn_cast<PHINode>(&I);
6838       if (!P)
6839         break;
6840 
6841       if (!VisitedInstrs.count(P))
6842         Incoming.push_back(P);
6843     }
6844 
6845     // Sort by type.
6846     llvm::stable_sort(Incoming, PhiTypeSorterFunc);
6847 
6848     // Try to vectorize elements base on their type.
6849     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
6850                                            E = Incoming.end();
6851          IncIt != E;) {
6852 
6853       // Look for the next elements with the same type.
6854       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
6855       while (SameTypeIt != E &&
6856              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
6857         VisitedInstrs.insert(*SameTypeIt);
6858         ++SameTypeIt;
6859       }
6860 
6861       // Try to vectorize them.
6862       unsigned NumElts = (SameTypeIt - IncIt);
6863       LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
6864                         << NumElts << ")\n");
6865       // The order in which the phi nodes appear in the program does not matter.
6866       // So allow tryToVectorizeList to reorder them if it is beneficial. This
6867       // is done when there are exactly two elements since tryToVectorizeList
6868       // asserts that there are only two values when AllowReorder is true.
6869       bool AllowReorder = NumElts == 2;
6870       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
6871                                             /*UserCost=*/0, AllowReorder)) {
6872         // Success start over because instructions might have been changed.
6873         HaveVectorizedPhiNodes = true;
6874         Changed = true;
6875         break;
6876       }
6877 
6878       // Start over at the next instruction of a different type (or the end).
6879       IncIt = SameTypeIt;
6880     }
6881   }
6882 
6883   VisitedInstrs.clear();
6884 
6885   SmallVector<WeakVH, 8> PostProcessInstructions;
6886   SmallDenseSet<Instruction *, 4> KeyNodes;
6887   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
6888     // We may go through BB multiple times so skip the one we have checked.
6889     if (!VisitedInstrs.insert(&*it).second) {
6890       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
6891           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
6892         // We would like to start over since some instructions are deleted
6893         // and the iterator may become invalid value.
6894         Changed = true;
6895         it = BB->begin();
6896         e = BB->end();
6897       }
6898       continue;
6899     }
6900 
6901     if (isa<DbgInfoIntrinsic>(it))
6902       continue;
6903 
6904     // Try to vectorize reductions that use PHINodes.
6905     if (PHINode *P = dyn_cast<PHINode>(it)) {
6906       // Check that the PHI is a reduction PHI.
6907       if (P->getNumIncomingValues() != 2)
6908         return Changed;
6909 
6910       // Try to match and vectorize a horizontal reduction.
6911       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
6912                                    TTI)) {
6913         Changed = true;
6914         it = BB->begin();
6915         e = BB->end();
6916         continue;
6917       }
6918       continue;
6919     }
6920 
6921     // Ran into an instruction without users, like terminator, or function call
6922     // with ignored return value, store. Ignore unused instructions (basing on
6923     // instruction type, except for CallInst and InvokeInst).
6924     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
6925                             isa<InvokeInst>(it))) {
6926       KeyNodes.insert(&*it);
6927       bool OpsChanged = false;
6928       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
6929         for (auto *V : it->operand_values()) {
6930           // Try to match and vectorize a horizontal reduction.
6931           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
6932         }
6933       }
6934       // Start vectorization of post-process list of instructions from the
6935       // top-tree instructions to try to vectorize as many instructions as
6936       // possible.
6937       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
6938       if (OpsChanged) {
6939         // We would like to start over since some instructions are deleted
6940         // and the iterator may become invalid value.
6941         Changed = true;
6942         it = BB->begin();
6943         e = BB->end();
6944         continue;
6945       }
6946     }
6947 
6948     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
6949         isa<InsertValueInst>(it))
6950       PostProcessInstructions.push_back(&*it);
6951   }
6952 
6953   return Changed;
6954 }
6955 
6956 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
6957   auto Changed = false;
6958   for (auto &Entry : GEPs) {
6959     // If the getelementptr list has fewer than two elements, there's nothing
6960     // to do.
6961     if (Entry.second.size() < 2)
6962       continue;
6963 
6964     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
6965                       << Entry.second.size() << ".\n");
6966 
6967     // We process the getelementptr list in chunks of 16 (like we do for
6968     // stores) to minimize compile-time.
6969     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
6970       auto Len = std::min<unsigned>(BE - BI, 16);
6971       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
6972 
6973       // Initialize a set a candidate getelementptrs. Note that we use a
6974       // SetVector here to preserve program order. If the index computations
6975       // are vectorizable and begin with loads, we want to minimize the chance
6976       // of having to reorder them later.
6977       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
6978 
6979       // Some of the candidates may have already been vectorized after we
6980       // initially collected them. If so, the WeakTrackingVHs will have
6981       // nullified the
6982       // values, so remove them from the set of candidates.
6983       Candidates.remove(nullptr);
6984 
6985       // Remove from the set of candidates all pairs of getelementptrs with
6986       // constant differences. Such getelementptrs are likely not good
6987       // candidates for vectorization in a bottom-up phase since one can be
6988       // computed from the other. We also ensure all candidate getelementptr
6989       // indices are unique.
6990       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
6991         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
6992         if (!Candidates.count(GEPI))
6993           continue;
6994         auto *SCEVI = SE->getSCEV(GEPList[I]);
6995         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
6996           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
6997           auto *SCEVJ = SE->getSCEV(GEPList[J]);
6998           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
6999             Candidates.remove(GEPList[I]);
7000             Candidates.remove(GEPList[J]);
7001           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
7002             Candidates.remove(GEPList[J]);
7003           }
7004         }
7005       }
7006 
7007       // We break out of the above computation as soon as we know there are
7008       // fewer than two candidates remaining.
7009       if (Candidates.size() < 2)
7010         continue;
7011 
7012       // Add the single, non-constant index of each candidate to the bundle. We
7013       // ensured the indices met these constraints when we originally collected
7014       // the getelementptrs.
7015       SmallVector<Value *, 16> Bundle(Candidates.size());
7016       auto BundleIndex = 0u;
7017       for (auto *V : Candidates) {
7018         auto *GEP = cast<GetElementPtrInst>(V);
7019         auto *GEPIdx = GEP->idx_begin()->get();
7020         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
7021         Bundle[BundleIndex++] = GEPIdx;
7022       }
7023 
7024       // Try and vectorize the indices. We are currently only interested in
7025       // gather-like cases of the form:
7026       //
7027       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7028       //
7029       // where the loads of "a", the loads of "b", and the subtractions can be
7030       // performed in parallel. It's likely that detecting this pattern in a
7031       // bottom-up phase will be simpler and less costly than building a
7032       // full-blown top-down phase beginning at the consecutive loads.
7033       Changed |= tryToVectorizeList(Bundle, R);
7034     }
7035   }
7036   return Changed;
7037 }
7038 
7039 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
7040   bool Changed = false;
7041   // Attempt to sort and vectorize each of the store-groups.
7042   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
7043        ++it) {
7044     if (it->second.size() < 2)
7045       continue;
7046 
7047     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7048                       << it->second.size() << ".\n");
7049 
7050     // Process the stores in chunks of 16.
7051     // TODO: The limit of 16 inhibits greater vectorization factors.
7052     //       For example, AVX2 supports v32i8. Increasing this limit, however,
7053     //       may cause a significant compile-time increase.
7054     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI += 16) {
7055       unsigned Len = std::min<unsigned>(CE - CI, 16);
7056       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
7057     }
7058   }
7059   return Changed;
7060 }
7061 
7062 char SLPVectorizer::ID = 0;
7063 
7064 static const char lv_name[] = "SLP Vectorizer";
7065 
7066 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
7067 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7068 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7069 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7070 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7071 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
7072 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7073 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7074 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
7075 
7076 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
7077