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