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