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