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