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