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