1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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.
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.
17 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Utils/VectorUtils.h"
47 #define SV_NAME "slp-vectorizer"
48 #define DEBUG_TYPE "SLP"
51 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
52 cl::desc("Only vectorize if you gain more than this "
56 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
57 cl::desc("Attempt to vectorize horizontal reductions"));
59 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
60 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
62 "Attempt to vectorize horizontal reductions feeding into a store"));
66 static const unsigned MinVecRegSize = 128;
68 static const unsigned RecursionMaxDepth = 12;
70 /// A helper class for numbering instructions in multiple blocks.
71 /// Numbers start at zero for each basic block.
72 struct BlockNumbering {
74 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
76 void numberInstructions() {
80 // Number the instructions in the block.
81 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
83 InstrVec.push_back(it);
84 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
89 int getIndex(Instruction *I) {
90 assert(I->getParent() == BB && "Invalid instruction");
93 assert(InstrIdx.count(I) && "Unknown instruction");
97 Instruction *getInstruction(unsigned loc) {
100 assert(InstrVec.size() > loc && "Invalid Index");
101 return InstrVec[loc];
104 void forget() { Valid = false; }
107 /// The block we are numbering.
109 /// Is the block numbered.
111 /// Maps instructions to numbers and back.
112 SmallDenseMap<Instruction *, int> InstrIdx;
113 /// Maps integers to Instructions.
114 SmallVector<Instruction *, 32> InstrVec;
117 /// \returns the parent basic block if all of the instructions in \p VL
118 /// are in the same block or null otherwise.
119 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
120 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
123 BasicBlock *BB = I0->getParent();
124 for (int i = 1, e = VL.size(); i < e; i++) {
125 Instruction *I = dyn_cast<Instruction>(VL[i]);
129 if (BB != I->getParent())
135 /// \returns True if all of the values in \p VL are constants.
136 static bool allConstant(ArrayRef<Value *> VL) {
137 for (unsigned i = 0, e = VL.size(); i < e; ++i)
138 if (!isa<Constant>(VL[i]))
143 /// \returns True if all of the values in \p VL are identical.
144 static bool isSplat(ArrayRef<Value *> VL) {
145 for (unsigned i = 1, e = VL.size(); i < e; ++i)
151 /// \returns The opcode if all of the Instructions in \p VL have the same
153 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
154 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
157 unsigned Opcode = I0->getOpcode();
158 for (int i = 1, e = VL.size(); i < e; i++) {
159 Instruction *I = dyn_cast<Instruction>(VL[i]);
160 if (!I || Opcode != I->getOpcode())
166 /// \returns \p I after propagating metadata from \p VL.
167 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
168 Instruction *I0 = cast<Instruction>(VL[0]);
169 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
170 I0->getAllMetadataOtherThanDebugLoc(Metadata);
172 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
173 unsigned Kind = Metadata[i].first;
174 MDNode *MD = Metadata[i].second;
176 for (int i = 1, e = VL.size(); MD && i != e; i++) {
177 Instruction *I = cast<Instruction>(VL[i]);
178 MDNode *IMD = I->getMetadata(Kind);
182 MD = nullptr; // Remove unknown metadata
184 case LLVMContext::MD_tbaa:
185 MD = MDNode::getMostGenericTBAA(MD, IMD);
187 case LLVMContext::MD_fpmath:
188 MD = MDNode::getMostGenericFPMath(MD, IMD);
192 I->setMetadata(Kind, MD);
197 /// \returns The type that all of the values in \p VL have or null if there
198 /// are different types.
199 static Type* getSameType(ArrayRef<Value *> VL) {
200 Type *Ty = VL[0]->getType();
201 for (int i = 1, e = VL.size(); i < e; i++)
202 if (VL[i]->getType() != Ty)
208 /// \returns True if the ExtractElement instructions in VL can be vectorized
209 /// to use the original vector.
210 static bool CanReuseExtract(ArrayRef<Value *> VL) {
211 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
212 // Check if all of the extracts come from the same vector and from the
215 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
216 Value *Vec = E0->getOperand(0);
218 // We have to extract from the same vector type.
219 unsigned NElts = Vec->getType()->getVectorNumElements();
221 if (NElts != VL.size())
224 // Check that all of the indices extract from the correct offset.
225 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
226 if (!CI || CI->getZExtValue())
229 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
230 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
231 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
233 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
240 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
241 SmallVectorImpl<Value *> &Left,
242 SmallVectorImpl<Value *> &Right) {
244 SmallVector<Value *, 16> OrigLeft, OrigRight;
246 bool AllSameOpcodeLeft = true;
247 bool AllSameOpcodeRight = true;
248 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
249 Instruction *I = cast<Instruction>(VL[i]);
250 Value *V0 = I->getOperand(0);
251 Value *V1 = I->getOperand(1);
253 OrigLeft.push_back(V0);
254 OrigRight.push_back(V1);
256 Instruction *I0 = dyn_cast<Instruction>(V0);
257 Instruction *I1 = dyn_cast<Instruction>(V1);
259 // Check whether all operands on one side have the same opcode. In this case
260 // we want to preserve the original order and not make things worse by
262 AllSameOpcodeLeft = I0;
263 AllSameOpcodeRight = I1;
265 if (i && AllSameOpcodeLeft) {
266 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
267 if(P0->getOpcode() != I0->getOpcode())
268 AllSameOpcodeLeft = false;
270 AllSameOpcodeLeft = false;
272 if (i && AllSameOpcodeRight) {
273 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
274 if(P1->getOpcode() != I1->getOpcode())
275 AllSameOpcodeRight = false;
277 AllSameOpcodeRight = false;
280 // Sort two opcodes. In the code below we try to preserve the ability to use
281 // broadcast of values instead of individual inserts.
288 // If we just sorted according to opcode we would leave the first line in
289 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
292 // Because vr2 and vr1 are from the same load we loose the opportunity of a
293 // broadcast for the packed right side in the backend: we have [vr1, vl2]
294 // instead of [vr1, vr2=vr1].
296 if(!i && I0->getOpcode() > I1->getOpcode()) {
299 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
300 // Try not to destroy a broad cast for no apparent benefit.
303 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
304 // Try preserve broadcasts.
307 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
308 // Try preserve broadcasts.
317 // One opcode, put the instruction on the right.
327 bool LeftBroadcast = isSplat(Left);
328 bool RightBroadcast = isSplat(Right);
330 // Don't reorder if the operands where good to begin with.
331 if (!(LeftBroadcast || RightBroadcast) &&
332 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
338 /// Bottom Up SLP Vectorizer.
341 typedef SmallVector<Value *, 8> ValueList;
342 typedef SmallVector<Instruction *, 16> InstrList;
343 typedef SmallPtrSet<Value *, 16> ValueSet;
344 typedef SmallVector<StoreInst *, 8> StoreList;
346 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
347 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
348 LoopInfo *Li, DominatorTree *Dt)
349 : F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
350 Builder(Se->getContext()) {}
352 /// \brief Vectorize the tree that starts with the elements in \p VL.
353 /// Returns the vectorized root.
354 Value *vectorizeTree();
356 /// \returns the vectorization cost of the subtree that starts at \p VL.
357 /// A negative number means that this is profitable.
360 /// Construct a vectorizable tree that starts at \p Roots and is possibly
361 /// used by a reduction of \p RdxOps.
362 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
364 /// Clear the internal data structures that are created by 'buildTree'.
367 VectorizableTree.clear();
368 ScalarToTreeEntry.clear();
370 ExternalUses.clear();
371 MemBarrierIgnoreList.clear();
374 /// \returns true if the memory operations A and B are consecutive.
375 bool isConsecutiveAccess(Value *A, Value *B);
377 /// \brief Perform LICM and CSE on the newly generated gather sequences.
378 void optimizeGatherSequence();
382 /// \returns the cost of the vectorizable entry.
383 int getEntryCost(TreeEntry *E);
385 /// This is the recursive part of buildTree.
386 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
388 /// Vectorize a single entry in the tree.
389 Value *vectorizeTree(TreeEntry *E);
391 /// Vectorize a single entry in the tree, starting in \p VL.
392 Value *vectorizeTree(ArrayRef<Value *> VL);
394 /// \returns the pointer to the vectorized value if \p VL is already
395 /// vectorized, or NULL. They may happen in cycles.
396 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
398 /// \brief Take the pointer operand from the Load/Store instruction.
399 /// \returns NULL if this is not a valid Load/Store instruction.
400 static Value *getPointerOperand(Value *I);
402 /// \brief Take the address space operand from the Load/Store instruction.
403 /// \returns -1 if this is not a valid Load/Store instruction.
404 static unsigned getAddressSpaceOperand(Value *I);
406 /// \returns the scalarization cost for this type. Scalarization in this
407 /// context means the creation of vectors from a group of scalars.
408 int getGatherCost(Type *Ty);
410 /// \returns the scalarization cost for this list of values. Assuming that
411 /// this subtree gets vectorized, we may need to extract the values from the
412 /// roots. This method calculates the cost of extracting the values.
413 int getGatherCost(ArrayRef<Value *> VL);
415 /// \returns the AA location that is being access by the instruction.
416 AliasAnalysis::Location getLocation(Instruction *I);
418 /// \brief Checks if it is possible to sink an instruction from
419 /// \p Src to \p Dst.
420 /// \returns the pointer to the barrier instruction if we can't sink.
421 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
423 /// \returns the index of the last instruction in the BB from \p VL.
424 int getLastIndex(ArrayRef<Value *> VL);
426 /// \returns the Instruction in the bundle \p VL.
427 Instruction *getLastInstruction(ArrayRef<Value *> VL);
429 /// \brief Set the Builder insert point to one after the last instruction in
431 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
433 /// \returns a vector from a collection of scalars in \p VL.
434 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
436 /// \returns whether the VectorizableTree is fully vectoriable and will
437 /// be beneficial even the tree height is tiny.
438 bool isFullyVectorizableTinyTree();
441 TreeEntry() : Scalars(), VectorizedValue(nullptr), LastScalarIndex(0),
444 /// \returns true if the scalars in VL are equal to this entry.
445 bool isSame(ArrayRef<Value *> VL) const {
446 assert(VL.size() == Scalars.size() && "Invalid size");
447 return std::equal(VL.begin(), VL.end(), Scalars.begin());
450 /// A vector of scalars.
453 /// The Scalars are vectorized into this value. It is initialized to Null.
454 Value *VectorizedValue;
456 /// The index in the basic block of the last scalar.
459 /// Do we need to gather this sequence ?
463 /// Create a new VectorizableTree entry.
464 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
465 VectorizableTree.push_back(TreeEntry());
466 int idx = VectorizableTree.size() - 1;
467 TreeEntry *Last = &VectorizableTree[idx];
468 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
469 Last->NeedToGather = !Vectorized;
471 Last->LastScalarIndex = getLastIndex(VL);
472 for (int i = 0, e = VL.size(); i != e; ++i) {
473 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
474 ScalarToTreeEntry[VL[i]] = idx;
477 Last->LastScalarIndex = 0;
478 MustGather.insert(VL.begin(), VL.end());
483 /// -- Vectorization State --
484 /// Holds all of the tree entries.
485 std::vector<TreeEntry> VectorizableTree;
487 /// Maps a specific scalar to its tree entry.
488 SmallDenseMap<Value*, int> ScalarToTreeEntry;
490 /// A list of scalars that we found that we need to keep as scalars.
493 /// This POD struct describes one external user in the vectorized tree.
494 struct ExternalUser {
495 ExternalUser (Value *S, llvm::User *U, int L) :
496 Scalar(S), User(U), Lane(L){};
497 // Which scalar in our function.
499 // Which user that uses the scalar.
501 // Which lane does the scalar belong to.
504 typedef SmallVector<ExternalUser, 16> UserList;
506 /// A list of values that need to extracted out of the tree.
507 /// This list holds pairs of (Internal Scalar : External User).
508 UserList ExternalUses;
510 /// A list of instructions to ignore while sinking
511 /// memory instructions. This map must be reset between runs of getCost.
512 ValueSet MemBarrierIgnoreList;
514 /// Holds all of the instructions that we gathered.
515 SetVector<Instruction *> GatherSeq;
516 /// A list of blocks that we are going to CSE.
517 SetVector<BasicBlock *> CSEBlocks;
519 /// Numbers instructions in different blocks.
520 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
522 /// \brief Get the corresponding instruction numbering list for a given
523 /// BasicBlock. The list is allocated lazily.
524 BlockNumbering &getBlockNumbering(BasicBlock *BB) {
525 auto I = BlocksNumbers.insert(std::make_pair(BB, BlockNumbering(BB)));
526 return I.first->second;
529 /// Reduction operators.
532 // Analysis and block reference.
535 const DataLayout *DL;
536 TargetTransformInfo *TTI;
537 TargetLibraryInfo *TLI;
541 /// Instruction builder to construct the vectorized tree.
545 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
548 if (!getSameType(Roots))
550 buildTree_rec(Roots, 0);
552 // Collect the values that we need to extract from the tree.
553 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
554 TreeEntry *Entry = &VectorizableTree[EIdx];
557 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
558 Value *Scalar = Entry->Scalars[Lane];
560 // No need to handle users of gathered values.
561 if (Entry->NeedToGather)
564 for (User *U : Scalar->users()) {
565 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
567 // Skip in-tree scalars that become vectors.
568 if (ScalarToTreeEntry.count(U)) {
569 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
571 int Idx = ScalarToTreeEntry[U]; (void) Idx;
572 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
575 Instruction *UserInst = dyn_cast<Instruction>(U);
579 // Ignore uses that are part of the reduction.
580 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
583 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
584 Lane << " from " << *Scalar << ".\n");
585 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
592 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
593 bool SameTy = getSameType(VL); (void)SameTy;
594 assert(SameTy && "Invalid types!");
596 if (Depth == RecursionMaxDepth) {
597 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
598 newTreeEntry(VL, false);
602 // Don't handle vectors.
603 if (VL[0]->getType()->isVectorTy()) {
604 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
605 newTreeEntry(VL, false);
609 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
610 if (SI->getValueOperand()->getType()->isVectorTy()) {
611 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
612 newTreeEntry(VL, false);
616 // If all of the operands are identical or constant we have a simple solution.
617 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
618 !getSameOpcode(VL)) {
619 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
620 newTreeEntry(VL, false);
624 // We now know that this is a vector of instructions of the same type from
627 // Check if this is a duplicate of another entry.
628 if (ScalarToTreeEntry.count(VL[0])) {
629 int Idx = ScalarToTreeEntry[VL[0]];
630 TreeEntry *E = &VectorizableTree[Idx];
631 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
632 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
633 if (E->Scalars[i] != VL[i]) {
634 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
635 newTreeEntry(VL, false);
639 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
643 // Check that none of the instructions in the bundle are already in the tree.
644 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
645 if (ScalarToTreeEntry.count(VL[i])) {
646 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
647 ") is already in tree.\n");
648 newTreeEntry(VL, false);
653 // If any of the scalars appears in the table OR it is marked as a value that
654 // needs to stat scalar then we need to gather the scalars.
655 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
656 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
657 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
658 newTreeEntry(VL, false);
663 // Check that all of the users of the scalars that we want to vectorize are
665 Instruction *VL0 = cast<Instruction>(VL[0]);
666 int MyLastIndex = getLastIndex(VL);
667 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
669 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
670 Instruction *Scalar = cast<Instruction>(VL[i]);
671 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
672 for (User *U : Scalar->users()) {
673 DEBUG(dbgs() << "SLP: \tUser " << *U << ". \n");
674 Instruction *UI = dyn_cast<Instruction>(U);
676 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
677 newTreeEntry(VL, false);
681 // We don't care if the user is in a different basic block.
682 BasicBlock *UserBlock = UI->getParent();
683 if (UserBlock != BB) {
684 DEBUG(dbgs() << "SLP: User from a different basic block "
689 // If this is a PHINode within this basic block then we can place the
690 // extract wherever we want.
691 if (isa<PHINode>(*UI)) {
692 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *UI << ". \n");
696 // Check if this is a safe in-tree user.
697 if (ScalarToTreeEntry.count(UI)) {
698 int Idx = ScalarToTreeEntry[UI];
699 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
700 if (VecLocation <= MyLastIndex) {
701 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
702 newTreeEntry(VL, false);
705 DEBUG(dbgs() << "SLP: In-tree user (" << *UI << ") at #" <<
706 VecLocation << " vector value (" << *Scalar << ") at #"
707 << MyLastIndex << ".\n");
711 // This user is part of the reduction.
712 if (RdxOps && RdxOps->count(UI))
715 // Make sure that we can schedule this unknown user.
716 BlockNumbering &BN = getBlockNumbering(BB);
717 int UserIndex = BN.getIndex(UI);
718 if (UserIndex < MyLastIndex) {
720 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
722 newTreeEntry(VL, false);
728 // Check that every instructions appears once in this bundle.
729 for (unsigned i = 0, e = VL.size(); i < e; ++i)
730 for (unsigned j = i+1; j < e; ++j)
731 if (VL[i] == VL[j]) {
732 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
733 newTreeEntry(VL, false);
737 // Check that instructions in this bundle don't reference other instructions.
738 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
739 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
740 for (User *U : VL[i]->users()) {
741 for (unsigned j = 0; j < e; ++j) {
742 if (i != j && U == VL[j]) {
743 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << *U << ". \n");
744 newTreeEntry(VL, false);
751 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
753 unsigned Opcode = getSameOpcode(VL);
755 // Check if it is safe to sink the loads or the stores.
756 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
757 Instruction *Last = getLastInstruction(VL);
759 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
762 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
764 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
765 << "\n because of " << *Barrier << ". Gathering.\n");
766 newTreeEntry(VL, false);
773 case Instruction::PHI: {
774 PHINode *PH = dyn_cast<PHINode>(VL0);
776 // Check for terminator values (e.g. invoke).
777 for (unsigned j = 0; j < VL.size(); ++j)
778 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
779 TerminatorInst *Term = dyn_cast<TerminatorInst>(
780 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
782 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
783 newTreeEntry(VL, false);
788 newTreeEntry(VL, true);
789 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
791 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
793 // Prepare the operand vector.
794 for (unsigned j = 0; j < VL.size(); ++j)
795 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
796 PH->getIncomingBlock(i)));
798 buildTree_rec(Operands, Depth + 1);
802 case Instruction::ExtractElement: {
803 bool Reuse = CanReuseExtract(VL);
805 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
807 newTreeEntry(VL, Reuse);
810 case Instruction::Load: {
811 // Check if the loads are consecutive or of we need to swizzle them.
812 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
813 LoadInst *L = cast<LoadInst>(VL[i]);
814 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
815 newTreeEntry(VL, false);
816 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
820 newTreeEntry(VL, true);
821 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
824 case Instruction::ZExt:
825 case Instruction::SExt:
826 case Instruction::FPToUI:
827 case Instruction::FPToSI:
828 case Instruction::FPExt:
829 case Instruction::PtrToInt:
830 case Instruction::IntToPtr:
831 case Instruction::SIToFP:
832 case Instruction::UIToFP:
833 case Instruction::Trunc:
834 case Instruction::FPTrunc:
835 case Instruction::BitCast: {
836 Type *SrcTy = VL0->getOperand(0)->getType();
837 for (unsigned i = 0; i < VL.size(); ++i) {
838 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
839 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
840 newTreeEntry(VL, false);
841 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
845 newTreeEntry(VL, true);
846 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
848 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
850 // Prepare the operand vector.
851 for (unsigned j = 0; j < VL.size(); ++j)
852 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
854 buildTree_rec(Operands, Depth+1);
858 case Instruction::ICmp:
859 case Instruction::FCmp: {
860 // Check that all of the compares have the same predicate.
861 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
862 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
863 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
864 CmpInst *Cmp = cast<CmpInst>(VL[i]);
865 if (Cmp->getPredicate() != P0 ||
866 Cmp->getOperand(0)->getType() != ComparedTy) {
867 newTreeEntry(VL, false);
868 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
873 newTreeEntry(VL, true);
874 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
876 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
878 // Prepare the operand vector.
879 for (unsigned j = 0; j < VL.size(); ++j)
880 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
882 buildTree_rec(Operands, Depth+1);
886 case Instruction::Select:
887 case Instruction::Add:
888 case Instruction::FAdd:
889 case Instruction::Sub:
890 case Instruction::FSub:
891 case Instruction::Mul:
892 case Instruction::FMul:
893 case Instruction::UDiv:
894 case Instruction::SDiv:
895 case Instruction::FDiv:
896 case Instruction::URem:
897 case Instruction::SRem:
898 case Instruction::FRem:
899 case Instruction::Shl:
900 case Instruction::LShr:
901 case Instruction::AShr:
902 case Instruction::And:
903 case Instruction::Or:
904 case Instruction::Xor: {
905 newTreeEntry(VL, true);
906 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
908 // Sort operands of the instructions so that each side is more likely to
909 // have the same opcode.
910 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
911 ValueList Left, Right;
912 reorderInputsAccordingToOpcode(VL, Left, Right);
913 buildTree_rec(Left, Depth + 1);
914 buildTree_rec(Right, Depth + 1);
918 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
920 // Prepare the operand vector.
921 for (unsigned j = 0; j < VL.size(); ++j)
922 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
924 buildTree_rec(Operands, Depth+1);
928 case Instruction::Store: {
929 // Check if the stores are consecutive or of we need to swizzle them.
930 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
931 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
932 newTreeEntry(VL, false);
933 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
937 newTreeEntry(VL, true);
938 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
941 for (unsigned j = 0; j < VL.size(); ++j)
942 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
944 // We can ignore these values because we are sinking them down.
945 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
946 buildTree_rec(Operands, Depth + 1);
949 case Instruction::Call: {
950 // Check if the calls are all to the same vectorizable intrinsic.
951 CallInst *CI = cast<CallInst>(VL[0]);
952 // Check if this is an Intrinsic call or something that can be
953 // represented by an intrinsic call
954 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
955 if (!isTriviallyVectorizable(ID)) {
956 newTreeEntry(VL, false);
957 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
961 Function *Int = CI->getCalledFunction();
963 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
964 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
965 if (!CI2 || CI2->getCalledFunction() != Int ||
966 getIntrinsicIDForCall(CI2, TLI) != ID) {
967 newTreeEntry(VL, false);
968 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
974 newTreeEntry(VL, true);
975 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
977 // Prepare the operand vector.
978 for (unsigned j = 0; j < VL.size(); ++j) {
979 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
980 Operands.push_back(CI2->getArgOperand(i));
982 buildTree_rec(Operands, Depth + 1);
987 newTreeEntry(VL, false);
988 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
993 int BoUpSLP::getEntryCost(TreeEntry *E) {
994 ArrayRef<Value*> VL = E->Scalars;
996 Type *ScalarTy = VL[0]->getType();
997 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
998 ScalarTy = SI->getValueOperand()->getType();
999 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1001 if (E->NeedToGather) {
1002 if (allConstant(VL))
1005 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1007 return getGatherCost(E->Scalars);
1010 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
1012 Instruction *VL0 = cast<Instruction>(VL[0]);
1013 unsigned Opcode = VL0->getOpcode();
1015 case Instruction::PHI: {
1018 case Instruction::ExtractElement: {
1019 if (CanReuseExtract(VL)) {
1021 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1022 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1024 // Take credit for instruction that will become dead.
1026 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1030 return getGatherCost(VecTy);
1032 case Instruction::ZExt:
1033 case Instruction::SExt:
1034 case Instruction::FPToUI:
1035 case Instruction::FPToSI:
1036 case Instruction::FPExt:
1037 case Instruction::PtrToInt:
1038 case Instruction::IntToPtr:
1039 case Instruction::SIToFP:
1040 case Instruction::UIToFP:
1041 case Instruction::Trunc:
1042 case Instruction::FPTrunc:
1043 case Instruction::BitCast: {
1044 Type *SrcTy = VL0->getOperand(0)->getType();
1046 // Calculate the cost of this instruction.
1047 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1048 VL0->getType(), SrcTy);
1050 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1051 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1052 return VecCost - ScalarCost;
1054 case Instruction::FCmp:
1055 case Instruction::ICmp:
1056 case Instruction::Select:
1057 case Instruction::Add:
1058 case Instruction::FAdd:
1059 case Instruction::Sub:
1060 case Instruction::FSub:
1061 case Instruction::Mul:
1062 case Instruction::FMul:
1063 case Instruction::UDiv:
1064 case Instruction::SDiv:
1065 case Instruction::FDiv:
1066 case Instruction::URem:
1067 case Instruction::SRem:
1068 case Instruction::FRem:
1069 case Instruction::Shl:
1070 case Instruction::LShr:
1071 case Instruction::AShr:
1072 case Instruction::And:
1073 case Instruction::Or:
1074 case Instruction::Xor: {
1075 // Calculate the cost of this instruction.
1078 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1079 Opcode == Instruction::Select) {
1080 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1081 ScalarCost = VecTy->getNumElements() *
1082 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1083 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1085 // Certain instructions can be cheaper to vectorize if they have a
1086 // constant second vector operand.
1087 TargetTransformInfo::OperandValueKind Op1VK =
1088 TargetTransformInfo::OK_AnyValue;
1089 TargetTransformInfo::OperandValueKind Op2VK =
1090 TargetTransformInfo::OK_UniformConstantValue;
1092 // If all operands are exactly the same ConstantInt then set the
1093 // operand kind to OK_UniformConstantValue.
1094 // If instead not all operands are constants, then set the operand kind
1095 // to OK_AnyValue. If all operands are constants but not the same,
1096 // then set the operand kind to OK_NonUniformConstantValue.
1097 ConstantInt *CInt = nullptr;
1098 for (unsigned i = 0; i < VL.size(); ++i) {
1099 const Instruction *I = cast<Instruction>(VL[i]);
1100 if (!isa<ConstantInt>(I->getOperand(1))) {
1101 Op2VK = TargetTransformInfo::OK_AnyValue;
1105 CInt = cast<ConstantInt>(I->getOperand(1));
1108 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1109 CInt != cast<ConstantInt>(I->getOperand(1)))
1110 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1114 VecTy->getNumElements() *
1115 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1116 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1118 return VecCost - ScalarCost;
1120 case Instruction::Load: {
1121 // Cost of wide load - cost of scalar loads.
1122 int ScalarLdCost = VecTy->getNumElements() *
1123 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1124 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1125 return VecLdCost - ScalarLdCost;
1127 case Instruction::Store: {
1128 // We know that we can merge the stores. Calculate the cost.
1129 int ScalarStCost = VecTy->getNumElements() *
1130 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1131 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1132 return VecStCost - ScalarStCost;
1134 case Instruction::Call: {
1135 CallInst *CI = cast<CallInst>(VL0);
1136 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1138 // Calculate the cost of the scalar and vector calls.
1139 SmallVector<Type*, 4> ScalarTys, VecTys;
1140 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1141 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1142 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1143 VecTy->getNumElements()));
1146 int ScalarCallCost = VecTy->getNumElements() *
1147 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1149 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1151 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1152 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1153 << " for " << *CI << "\n");
1155 return VecCallCost - ScalarCallCost;
1158 llvm_unreachable("Unknown instruction");
1162 bool BoUpSLP::isFullyVectorizableTinyTree() {
1163 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1164 VectorizableTree.size() << " is fully vectorizable .\n");
1166 // We only handle trees of height 2.
1167 if (VectorizableTree.size() != 2)
1170 // Handle splat stores.
1171 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1174 // Gathering cost would be too much for tiny trees.
1175 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1181 int BoUpSLP::getTreeCost() {
1183 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1184 VectorizableTree.size() << ".\n");
1186 // We only vectorize tiny trees if it is fully vectorizable.
1187 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1188 if (!VectorizableTree.size()) {
1189 assert(!ExternalUses.size() && "We should not have any external users");
1194 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1196 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1197 int C = getEntryCost(&VectorizableTree[i]);
1198 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1199 << *VectorizableTree[i].Scalars[0] << " .\n");
1203 SmallSet<Value *, 16> ExtractCostCalculated;
1204 int ExtractCost = 0;
1205 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1207 // We only add extract cost once for the same scalar.
1208 if (!ExtractCostCalculated.insert(I->Scalar))
1211 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1212 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1216 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1217 return Cost + ExtractCost;
1220 int BoUpSLP::getGatherCost(Type *Ty) {
1222 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1223 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1227 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1228 // Find the type of the operands in VL.
1229 Type *ScalarTy = VL[0]->getType();
1230 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1231 ScalarTy = SI->getValueOperand()->getType();
1232 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1233 // Find the cost of inserting/extracting values from the vector.
1234 return getGatherCost(VecTy);
1237 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1238 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1239 return AA->getLocation(SI);
1240 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1241 return AA->getLocation(LI);
1242 return AliasAnalysis::Location();
1245 Value *BoUpSLP::getPointerOperand(Value *I) {
1246 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1247 return LI->getPointerOperand();
1248 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1249 return SI->getPointerOperand();
1253 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1254 if (LoadInst *L = dyn_cast<LoadInst>(I))
1255 return L->getPointerAddressSpace();
1256 if (StoreInst *S = dyn_cast<StoreInst>(I))
1257 return S->getPointerAddressSpace();
1261 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1262 Value *PtrA = getPointerOperand(A);
1263 Value *PtrB = getPointerOperand(B);
1264 unsigned ASA = getAddressSpaceOperand(A);
1265 unsigned ASB = getAddressSpaceOperand(B);
1267 // Check that the address spaces match and that the pointers are valid.
1268 if (!PtrA || !PtrB || (ASA != ASB))
1271 // Make sure that A and B are different pointers of the same type.
1272 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1275 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1276 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1277 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1279 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1280 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1281 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1283 APInt OffsetDelta = OffsetB - OffsetA;
1285 // Check if they are based on the same pointer. That makes the offsets
1288 return OffsetDelta == Size;
1290 // Compute the necessary base pointer delta to have the necessary final delta
1291 // equal to the size.
1292 APInt BaseDelta = Size - OffsetDelta;
1294 // Otherwise compute the distance with SCEV between the base pointers.
1295 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1296 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1297 const SCEV *C = SE->getConstant(BaseDelta);
1298 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1299 return X == PtrSCEVB;
1302 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1303 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1304 BasicBlock::iterator I = Src, E = Dst;
1305 /// Scan all of the instruction from SRC to DST and check if
1306 /// the source may alias.
1307 for (++I; I != E; ++I) {
1308 // Ignore store instructions that are marked as 'ignore'.
1309 if (MemBarrierIgnoreList.count(I))
1311 if (Src->mayWriteToMemory()) /* Write */ {
1312 if (!I->mayReadOrWriteMemory())
1315 if (!I->mayWriteToMemory())
1318 AliasAnalysis::Location A = getLocation(&*I);
1319 AliasAnalysis::Location B = getLocation(Src);
1321 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1327 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1328 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1329 assert(BB == getSameBlock(VL) && "Invalid block");
1330 BlockNumbering &BN = getBlockNumbering(BB);
1332 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1333 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1334 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1338 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1339 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1340 assert(BB == getSameBlock(VL) && "Invalid block");
1341 BlockNumbering &BN = getBlockNumbering(BB);
1343 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1344 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1345 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1346 Instruction *I = BN.getInstruction(MaxIdx);
1347 assert(I && "bad location");
1351 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1352 Instruction *VL0 = cast<Instruction>(VL[0]);
1353 Instruction *LastInst = getLastInstruction(VL);
1354 BasicBlock::iterator NextInst = LastInst;
1356 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1357 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1360 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1361 Value *Vec = UndefValue::get(Ty);
1362 // Generate the 'InsertElement' instruction.
1363 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1364 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1365 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1366 GatherSeq.insert(Insrt);
1367 CSEBlocks.insert(Insrt->getParent());
1369 // Add to our 'need-to-extract' list.
1370 if (ScalarToTreeEntry.count(VL[i])) {
1371 int Idx = ScalarToTreeEntry[VL[i]];
1372 TreeEntry *E = &VectorizableTree[Idx];
1373 // Find which lane we need to extract.
1375 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1376 // Is this the lane of the scalar that we are looking for ?
1377 if (E->Scalars[Lane] == VL[i]) {
1382 assert(FoundLane >= 0 && "Could not find the correct lane");
1383 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1391 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1392 SmallDenseMap<Value*, int>::const_iterator Entry
1393 = ScalarToTreeEntry.find(VL[0]);
1394 if (Entry != ScalarToTreeEntry.end()) {
1395 int Idx = Entry->second;
1396 const TreeEntry *En = &VectorizableTree[Idx];
1397 if (En->isSame(VL) && En->VectorizedValue)
1398 return En->VectorizedValue;
1403 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1404 if (ScalarToTreeEntry.count(VL[0])) {
1405 int Idx = ScalarToTreeEntry[VL[0]];
1406 TreeEntry *E = &VectorizableTree[Idx];
1408 return vectorizeTree(E);
1411 Type *ScalarTy = VL[0]->getType();
1412 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1413 ScalarTy = SI->getValueOperand()->getType();
1414 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1416 return Gather(VL, VecTy);
1419 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1420 IRBuilder<>::InsertPointGuard Guard(Builder);
1422 if (E->VectorizedValue) {
1423 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1424 return E->VectorizedValue;
1427 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1428 Type *ScalarTy = VL0->getType();
1429 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1430 ScalarTy = SI->getValueOperand()->getType();
1431 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1433 if (E->NeedToGather) {
1434 setInsertPointAfterBundle(E->Scalars);
1435 return Gather(E->Scalars, VecTy);
1438 unsigned Opcode = VL0->getOpcode();
1439 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1442 case Instruction::PHI: {
1443 PHINode *PH = dyn_cast<PHINode>(VL0);
1444 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1445 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1446 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1447 E->VectorizedValue = NewPhi;
1449 // PHINodes may have multiple entries from the same block. We want to
1450 // visit every block once.
1451 SmallSet<BasicBlock*, 4> VisitedBBs;
1453 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1455 BasicBlock *IBB = PH->getIncomingBlock(i);
1457 if (!VisitedBBs.insert(IBB)) {
1458 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1462 // Prepare the operand vector.
1463 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1464 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1465 getIncomingValueForBlock(IBB));
1467 Builder.SetInsertPoint(IBB->getTerminator());
1468 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1469 Value *Vec = vectorizeTree(Operands);
1470 NewPhi->addIncoming(Vec, IBB);
1473 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1474 "Invalid number of incoming values");
1478 case Instruction::ExtractElement: {
1479 if (CanReuseExtract(E->Scalars)) {
1480 Value *V = VL0->getOperand(0);
1481 E->VectorizedValue = V;
1484 return Gather(E->Scalars, VecTy);
1486 case Instruction::ZExt:
1487 case Instruction::SExt:
1488 case Instruction::FPToUI:
1489 case Instruction::FPToSI:
1490 case Instruction::FPExt:
1491 case Instruction::PtrToInt:
1492 case Instruction::IntToPtr:
1493 case Instruction::SIToFP:
1494 case Instruction::UIToFP:
1495 case Instruction::Trunc:
1496 case Instruction::FPTrunc:
1497 case Instruction::BitCast: {
1499 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1500 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1502 setInsertPointAfterBundle(E->Scalars);
1504 Value *InVec = vectorizeTree(INVL);
1506 if (Value *V = alreadyVectorized(E->Scalars))
1509 CastInst *CI = dyn_cast<CastInst>(VL0);
1510 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1511 E->VectorizedValue = V;
1514 case Instruction::FCmp:
1515 case Instruction::ICmp: {
1516 ValueList LHSV, RHSV;
1517 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1518 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1519 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1522 setInsertPointAfterBundle(E->Scalars);
1524 Value *L = vectorizeTree(LHSV);
1525 Value *R = vectorizeTree(RHSV);
1527 if (Value *V = alreadyVectorized(E->Scalars))
1530 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1532 if (Opcode == Instruction::FCmp)
1533 V = Builder.CreateFCmp(P0, L, R);
1535 V = Builder.CreateICmp(P0, L, R);
1537 E->VectorizedValue = V;
1540 case Instruction::Select: {
1541 ValueList TrueVec, FalseVec, CondVec;
1542 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1543 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1544 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1545 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1548 setInsertPointAfterBundle(E->Scalars);
1550 Value *Cond = vectorizeTree(CondVec);
1551 Value *True = vectorizeTree(TrueVec);
1552 Value *False = vectorizeTree(FalseVec);
1554 if (Value *V = alreadyVectorized(E->Scalars))
1557 Value *V = Builder.CreateSelect(Cond, True, False);
1558 E->VectorizedValue = V;
1561 case Instruction::Add:
1562 case Instruction::FAdd:
1563 case Instruction::Sub:
1564 case Instruction::FSub:
1565 case Instruction::Mul:
1566 case Instruction::FMul:
1567 case Instruction::UDiv:
1568 case Instruction::SDiv:
1569 case Instruction::FDiv:
1570 case Instruction::URem:
1571 case Instruction::SRem:
1572 case Instruction::FRem:
1573 case Instruction::Shl:
1574 case Instruction::LShr:
1575 case Instruction::AShr:
1576 case Instruction::And:
1577 case Instruction::Or:
1578 case Instruction::Xor: {
1579 ValueList LHSVL, RHSVL;
1580 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1581 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1583 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1584 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1585 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1588 setInsertPointAfterBundle(E->Scalars);
1590 Value *LHS = vectorizeTree(LHSVL);
1591 Value *RHS = vectorizeTree(RHSVL);
1593 if (LHS == RHS && isa<Instruction>(LHS)) {
1594 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1597 if (Value *V = alreadyVectorized(E->Scalars))
1600 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1601 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1602 E->VectorizedValue = V;
1604 if (Instruction *I = dyn_cast<Instruction>(V))
1605 return propagateMetadata(I, E->Scalars);
1609 case Instruction::Load: {
1610 // Loads are inserted at the head of the tree because we don't want to
1611 // sink them all the way down past store instructions.
1612 setInsertPointAfterBundle(E->Scalars);
1614 LoadInst *LI = cast<LoadInst>(VL0);
1615 unsigned AS = LI->getPointerAddressSpace();
1617 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1618 VecTy->getPointerTo(AS));
1619 unsigned Alignment = LI->getAlignment();
1620 LI = Builder.CreateLoad(VecPtr);
1621 LI->setAlignment(Alignment);
1622 E->VectorizedValue = LI;
1623 return propagateMetadata(LI, E->Scalars);
1625 case Instruction::Store: {
1626 StoreInst *SI = cast<StoreInst>(VL0);
1627 unsigned Alignment = SI->getAlignment();
1628 unsigned AS = SI->getPointerAddressSpace();
1631 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1632 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1634 setInsertPointAfterBundle(E->Scalars);
1636 Value *VecValue = vectorizeTree(ValueOp);
1637 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1638 VecTy->getPointerTo(AS));
1639 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1640 S->setAlignment(Alignment);
1641 E->VectorizedValue = S;
1642 return propagateMetadata(S, E->Scalars);
1644 case Instruction::Call: {
1645 CallInst *CI = cast<CallInst>(VL0);
1646 setInsertPointAfterBundle(E->Scalars);
1647 std::vector<Value *> OpVecs;
1648 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1650 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1651 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1652 OpVL.push_back(CEI->getArgOperand(j));
1655 Value *OpVec = vectorizeTree(OpVL);
1656 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1657 OpVecs.push_back(OpVec);
1660 Module *M = F->getParent();
1661 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1662 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1663 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1664 Value *V = Builder.CreateCall(CF, OpVecs);
1665 E->VectorizedValue = V;
1669 llvm_unreachable("unknown inst");
1674 Value *BoUpSLP::vectorizeTree() {
1675 Builder.SetInsertPoint(F->getEntryBlock().begin());
1676 vectorizeTree(&VectorizableTree[0]);
1678 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1680 // Extract all of the elements with the external uses.
1681 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1683 Value *Scalar = it->Scalar;
1684 llvm::User *User = it->User;
1686 // Skip users that we already RAUW. This happens when one instruction
1687 // has multiple uses of the same value.
1688 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
1691 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1693 int Idx = ScalarToTreeEntry[Scalar];
1694 TreeEntry *E = &VectorizableTree[Idx];
1695 assert(!E->NeedToGather && "Extracting from a gather list");
1697 Value *Vec = E->VectorizedValue;
1698 assert(Vec && "Can't find vectorizable value");
1700 Value *Lane = Builder.getInt32(it->Lane);
1701 // Generate extracts for out-of-tree users.
1702 // Find the insertion point for the extractelement lane.
1703 if (isa<Instruction>(Vec)){
1704 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1705 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1706 if (PH->getIncomingValue(i) == Scalar) {
1707 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1708 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1709 CSEBlocks.insert(PH->getIncomingBlock(i));
1710 PH->setOperand(i, Ex);
1714 Builder.SetInsertPoint(cast<Instruction>(User));
1715 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1716 CSEBlocks.insert(cast<Instruction>(User)->getParent());
1717 User->replaceUsesOfWith(Scalar, Ex);
1720 Builder.SetInsertPoint(F->getEntryBlock().begin());
1721 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1722 CSEBlocks.insert(&F->getEntryBlock());
1723 User->replaceUsesOfWith(Scalar, Ex);
1726 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1729 // For each vectorized value:
1730 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1731 TreeEntry *Entry = &VectorizableTree[EIdx];
1734 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1735 Value *Scalar = Entry->Scalars[Lane];
1737 // No need to handle users of gathered values.
1738 if (Entry->NeedToGather)
1741 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1743 Type *Ty = Scalar->getType();
1744 if (!Ty->isVoidTy()) {
1746 for (User *U : Scalar->users()) {
1747 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
1749 assert((ScalarToTreeEntry.count(U) ||
1750 // It is legal to replace the reduction users by undef.
1751 (RdxOps && RdxOps->count(U))) &&
1752 "Replacing out-of-tree value with undef");
1755 Value *Undef = UndefValue::get(Ty);
1756 Scalar->replaceAllUsesWith(Undef);
1758 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1759 cast<Instruction>(Scalar)->eraseFromParent();
1763 for (auto &BN : BlocksNumbers)
1766 Builder.ClearInsertionPoint();
1768 return VectorizableTree[0].VectorizedValue;
1771 void BoUpSLP::optimizeGatherSequence() {
1772 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1773 << " gather sequences instructions.\n");
1774 // LICM InsertElementInst sequences.
1775 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1776 e = GatherSeq.end(); it != e; ++it) {
1777 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1782 // Check if this block is inside a loop.
1783 Loop *L = LI->getLoopFor(Insert->getParent());
1787 // Check if it has a preheader.
1788 BasicBlock *PreHeader = L->getLoopPreheader();
1792 // If the vector or the element that we insert into it are
1793 // instructions that are defined in this basic block then we can't
1794 // hoist this instruction.
1795 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1796 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1797 if (CurrVec && L->contains(CurrVec))
1799 if (NewElem && L->contains(NewElem))
1802 // We can hoist this instruction. Move it to the pre-header.
1803 Insert->moveBefore(PreHeader->getTerminator());
1806 // Sort blocks by domination. This ensures we visit a block after all blocks
1807 // dominating it are visited.
1808 SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end());
1809 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
1810 [this](const BasicBlock *A, const BasicBlock *B) {
1811 return DT->properlyDominates(A, B);
1814 // Perform O(N^2) search over the gather sequences and merge identical
1815 // instructions. TODO: We can further optimize this scan if we split the
1816 // instructions into different buckets based on the insert lane.
1817 SmallVector<Instruction *, 16> Visited;
1818 for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1819 E = CSEWorkList.end();
1821 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
1822 "Worklist not sorted properly!");
1823 BasicBlock *BB = *I;
1824 // For all instructions in blocks containing gather sequences:
1825 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1826 Instruction *In = it++;
1827 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1830 // Check if we can replace this instruction with any of the
1831 // visited instructions.
1832 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1835 if (In->isIdenticalTo(*v) &&
1836 DT->dominates((*v)->getParent(), In->getParent())) {
1837 In->replaceAllUsesWith(*v);
1838 In->eraseFromParent();
1844 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1845 Visited.push_back(In);
1853 /// The SLPVectorizer Pass.
1854 struct SLPVectorizer : public FunctionPass {
1855 typedef SmallVector<StoreInst *, 8> StoreList;
1856 typedef MapVector<Value *, StoreList> StoreListMap;
1858 /// Pass identification, replacement for typeid
1861 explicit SLPVectorizer() : FunctionPass(ID) {
1862 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1865 ScalarEvolution *SE;
1866 const DataLayout *DL;
1867 TargetTransformInfo *TTI;
1868 TargetLibraryInfo *TLI;
1873 bool runOnFunction(Function &F) override {
1874 if (skipOptnoneFunction(F))
1877 SE = &getAnalysis<ScalarEvolution>();
1878 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1879 DL = DLP ? &DLP->getDataLayout() : nullptr;
1880 TTI = &getAnalysis<TargetTransformInfo>();
1881 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1882 AA = &getAnalysis<AliasAnalysis>();
1883 LI = &getAnalysis<LoopInfo>();
1884 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1887 bool Changed = false;
1889 // If the target claims to have no vector registers don't attempt
1891 if (!TTI->getNumberOfRegisters(true))
1894 // Must have DataLayout. We can't require it because some tests run w/o
1899 // Don't vectorize when the attribute NoImplicitFloat is used.
1900 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1903 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1905 // Use the bottom up slp vectorizer to construct chains that start with
1906 // he store instructions.
1907 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
1909 // Scan the blocks in the function in post order.
1910 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1911 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1912 BasicBlock *BB = *it;
1914 // Vectorize trees that end at stores.
1915 if (unsigned count = collectStores(BB, R)) {
1917 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1918 Changed |= vectorizeStoreChains(R);
1921 // Vectorize trees that end at reductions.
1922 Changed |= vectorizeChainsInBlock(BB, R);
1926 R.optimizeGatherSequence();
1927 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1928 DEBUG(verifyFunction(F));
1933 void getAnalysisUsage(AnalysisUsage &AU) const override {
1934 FunctionPass::getAnalysisUsage(AU);
1935 AU.addRequired<ScalarEvolution>();
1936 AU.addRequired<AliasAnalysis>();
1937 AU.addRequired<TargetTransformInfo>();
1938 AU.addRequired<LoopInfo>();
1939 AU.addRequired<DominatorTreeWrapperPass>();
1940 AU.addPreserved<LoopInfo>();
1941 AU.addPreserved<DominatorTreeWrapperPass>();
1942 AU.setPreservesCFG();
1947 /// \brief Collect memory references and sort them according to their base
1948 /// object. We sort the stores to their base objects to reduce the cost of the
1949 /// quadratic search on the stores. TODO: We can further reduce this cost
1950 /// if we flush the chain creation every time we run into a memory barrier.
1951 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1953 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1954 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1956 /// \brief Try to vectorize a list of operands.
1957 /// \returns true if a value was vectorized.
1958 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1960 /// \brief Try to vectorize a chain that may start at the operands of \V;
1961 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1963 /// \brief Vectorize the stores that were collected in StoreRefs.
1964 bool vectorizeStoreChains(BoUpSLP &R);
1966 /// \brief Scan the basic block and look for patterns that are likely to start
1967 /// a vectorization chain.
1968 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1970 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1973 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1976 StoreListMap StoreRefs;
1979 /// \brief Check that the Values in the slice in VL array are still existent in
1980 /// the WeakVH array.
1981 /// Vectorization of part of the VL array may cause later values in the VL array
1982 /// to become invalid. We track when this has happened in the WeakVH array.
1983 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
1984 SmallVectorImpl<WeakVH> &VH,
1985 unsigned SliceBegin,
1986 unsigned SliceSize) {
1987 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
1994 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1995 int CostThreshold, BoUpSLP &R) {
1996 unsigned ChainLen = Chain.size();
1997 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1999 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2000 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2001 unsigned VF = MinVecRegSize / Sz;
2003 if (!isPowerOf2_32(Sz) || VF < 2)
2006 // Keep track of values that were deleted by vectorizing in the loop below.
2007 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2009 bool Changed = false;
2010 // Look for profitable vectorizable trees at all offsets, starting at zero.
2011 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2015 // Check that a previous iteration of this loop did not delete the Value.
2016 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2019 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2021 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2023 R.buildTree(Operands);
2025 int Cost = R.getTreeCost();
2027 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2028 if (Cost < CostThreshold) {
2029 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2032 // Move to the next bundle.
2041 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2042 int costThreshold, BoUpSLP &R) {
2043 SetVector<Value *> Heads, Tails;
2044 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2046 // We may run into multiple chains that merge into a single chain. We mark the
2047 // stores that we vectorized so that we don't visit the same store twice.
2048 BoUpSLP::ValueSet VectorizedStores;
2049 bool Changed = false;
2051 // Do a quadratic search on all of the given stores and find
2052 // all of the pairs of stores that follow each other.
2053 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2054 for (unsigned j = 0; j < e; ++j) {
2058 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2059 Tails.insert(Stores[j]);
2060 Heads.insert(Stores[i]);
2061 ConsecutiveChain[Stores[i]] = Stores[j];
2066 // For stores that start but don't end a link in the chain:
2067 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2069 if (Tails.count(*it))
2072 // We found a store instr that starts a chain. Now follow the chain and try
2074 BoUpSLP::ValueList Operands;
2076 // Collect the chain into a list.
2077 while (Tails.count(I) || Heads.count(I)) {
2078 if (VectorizedStores.count(I))
2080 Operands.push_back(I);
2081 // Move to the next value in the chain.
2082 I = ConsecutiveChain[I];
2085 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2087 // Mark the vectorized stores so that we don't vectorize them again.
2089 VectorizedStores.insert(Operands.begin(), Operands.end());
2090 Changed |= Vectorized;
2097 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2100 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2101 StoreInst *SI = dyn_cast<StoreInst>(it);
2105 // Don't touch volatile stores.
2106 if (!SI->isSimple())
2109 // Check that the pointer points to scalars.
2110 Type *Ty = SI->getValueOperand()->getType();
2111 if (Ty->isAggregateType() || Ty->isVectorTy())
2114 // Find the base pointer.
2115 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2117 // Save the store locations.
2118 StoreRefs[Ptr].push_back(SI);
2124 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2127 Value *VL[] = { A, B };
2128 return tryToVectorizeList(VL, R);
2131 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
2135 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2137 // Check that all of the parts are scalar instructions of the same type.
2138 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2142 unsigned Opcode0 = I0->getOpcode();
2144 Type *Ty0 = I0->getType();
2145 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2146 unsigned VF = MinVecRegSize / Sz;
2148 for (int i = 0, e = VL.size(); i < e; ++i) {
2149 Type *Ty = VL[i]->getType();
2150 if (Ty->isAggregateType() || Ty->isVectorTy())
2152 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2153 if (!Inst || Inst->getOpcode() != Opcode0)
2157 bool Changed = false;
2159 // Keep track of values that were deleted by vectorizing in the loop below.
2160 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2162 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2163 unsigned OpsWidth = 0;
2170 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2173 // Check that a previous iteration of this loop did not delete the Value.
2174 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2177 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2179 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2182 int Cost = R.getTreeCost();
2184 if (Cost < -SLPCostThreshold) {
2185 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2188 // Move to the next bundle.
2197 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2201 // Try to vectorize V.
2202 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2205 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2206 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2208 if (B && B->hasOneUse()) {
2209 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2210 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2211 if (tryToVectorizePair(A, B0, R)) {
2215 if (tryToVectorizePair(A, B1, R)) {
2222 if (A && A->hasOneUse()) {
2223 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2224 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2225 if (tryToVectorizePair(A0, B, R)) {
2229 if (tryToVectorizePair(A1, B, R)) {
2237 /// \brief Generate a shuffle mask to be used in a reduction tree.
2239 /// \param VecLen The length of the vector to be reduced.
2240 /// \param NumEltsToRdx The number of elements that should be reduced in the
2242 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2243 /// reduction. A pairwise reduction will generate a mask of
2244 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2245 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2246 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2247 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2248 bool IsPairwise, bool IsLeft,
2249 IRBuilder<> &Builder) {
2250 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2252 SmallVector<Constant *, 32> ShuffleMask(
2253 VecLen, UndefValue::get(Builder.getInt32Ty()));
2256 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2257 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2258 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2260 // Move the upper half of the vector to the lower half.
2261 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2262 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2264 return ConstantVector::get(ShuffleMask);
2268 /// Model horizontal reductions.
2270 /// A horizontal reduction is a tree of reduction operations (currently add and
2271 /// fadd) that has operations that can be put into a vector as its leaf.
2272 /// For example, this tree:
2279 /// This tree has "mul" as its reduced values and "+" as its reduction
2280 /// operations. A reduction might be feeding into a store or a binary operation
2295 class HorizontalReduction {
2296 SmallPtrSet<Value *, 16> ReductionOps;
2297 SmallVector<Value *, 32> ReducedVals;
2299 BinaryOperator *ReductionRoot;
2300 PHINode *ReductionPHI;
2302 /// The opcode of the reduction.
2303 unsigned ReductionOpcode;
2304 /// The opcode of the values we perform a reduction on.
2305 unsigned ReducedValueOpcode;
2306 /// The width of one full horizontal reduction operation.
2307 unsigned ReduxWidth;
2308 /// Should we model this reduction as a pairwise reduction tree or a tree that
2309 /// splits the vector in halves and adds those halves.
2310 bool IsPairwiseReduction;
2313 HorizontalReduction()
2314 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
2315 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2317 /// \brief Try to find a reduction tree.
2318 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2319 const DataLayout *DL) {
2321 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2322 "Thi phi needs to use the binary operator");
2324 // We could have a initial reductions that is not an add.
2325 // r *= v1 + v2 + v3 + v4
2326 // In such a case start looking for a tree rooted in the first '+'.
2328 if (B->getOperand(0) == Phi) {
2330 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2331 } else if (B->getOperand(1) == Phi) {
2333 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2340 Type *Ty = B->getType();
2341 if (Ty->isVectorTy())
2344 ReductionOpcode = B->getOpcode();
2345 ReducedValueOpcode = 0;
2346 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2353 // We currently only support adds.
2354 if (ReductionOpcode != Instruction::Add &&
2355 ReductionOpcode != Instruction::FAdd)
2358 // Post order traverse the reduction tree starting at B. We only handle true
2359 // trees containing only binary operators.
2360 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2361 Stack.push_back(std::make_pair(B, 0));
2362 while (!Stack.empty()) {
2363 BinaryOperator *TreeN = Stack.back().first;
2364 unsigned EdgeToVist = Stack.back().second++;
2365 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2367 // Only handle trees in the current basic block.
2368 if (TreeN->getParent() != B->getParent())
2371 // Each tree node needs to have one user except for the ultimate
2373 if (!TreeN->hasOneUse() && TreeN != B)
2377 if (EdgeToVist == 2 || IsReducedValue) {
2378 if (IsReducedValue) {
2379 // Make sure that the opcodes of the operations that we are going to
2381 if (!ReducedValueOpcode)
2382 ReducedValueOpcode = TreeN->getOpcode();
2383 else if (ReducedValueOpcode != TreeN->getOpcode())
2385 ReducedVals.push_back(TreeN);
2387 // We need to be able to reassociate the adds.
2388 if (!TreeN->isAssociative())
2390 ReductionOps.insert(TreeN);
2397 // Visit left or right.
2398 Value *NextV = TreeN->getOperand(EdgeToVist);
2399 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2401 Stack.push_back(std::make_pair(Next, 0));
2402 else if (NextV != Phi)
2408 /// \brief Attempt to vectorize the tree found by
2409 /// matchAssociativeReduction.
2410 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2411 if (ReducedVals.empty())
2414 unsigned NumReducedVals = ReducedVals.size();
2415 if (NumReducedVals < ReduxWidth)
2418 Value *VectorizedTree = nullptr;
2419 IRBuilder<> Builder(ReductionRoot);
2420 FastMathFlags Unsafe;
2421 Unsafe.setUnsafeAlgebra();
2422 Builder.SetFastMathFlags(Unsafe);
2425 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2426 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2427 V.buildTree(ValsToReduce, &ReductionOps);
2430 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2431 if (Cost >= -SLPCostThreshold)
2434 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2437 // Vectorize a tree.
2438 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2439 Value *VectorizedRoot = V.vectorizeTree();
2441 // Emit a reduction.
2442 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2443 if (VectorizedTree) {
2444 Builder.SetCurrentDebugLocation(Loc);
2445 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2446 ReducedSubTree, "bin.rdx");
2448 VectorizedTree = ReducedSubTree;
2451 if (VectorizedTree) {
2452 // Finish the reduction.
2453 for (; i < NumReducedVals; ++i) {
2454 Builder.SetCurrentDebugLocation(
2455 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2456 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2461 assert(ReductionRoot && "Need a reduction operation");
2462 ReductionRoot->setOperand(0, VectorizedTree);
2463 ReductionRoot->setOperand(1, ReductionPHI);
2465 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2467 return VectorizedTree != nullptr;
2472 /// \brief Calcuate the cost of a reduction.
2473 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2474 Type *ScalarTy = FirstReducedVal->getType();
2475 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2477 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2478 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2480 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2481 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2483 int ScalarReduxCost =
2484 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2486 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2487 << " for reduction that starts with " << *FirstReducedVal
2489 << (IsPairwiseReduction ? "pairwise" : "splitting")
2490 << " reduction)\n");
2492 return VecReduxCost - ScalarReduxCost;
2495 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2496 Value *R, const Twine &Name = "") {
2497 if (Opcode == Instruction::FAdd)
2498 return Builder.CreateFAdd(L, R, Name);
2499 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2502 /// \brief Emit a horizontal reduction of the vectorized value.
2503 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2504 assert(VectorizedValue && "Need to have a vectorized tree node");
2505 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2506 assert(isPowerOf2_32(ReduxWidth) &&
2507 "We only handle power-of-two reductions for now");
2509 Value *TmpVec = ValToReduce;
2510 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2511 if (IsPairwiseReduction) {
2513 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2515 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2517 Value *LeftShuf = Builder.CreateShuffleVector(
2518 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2519 Value *RightShuf = Builder.CreateShuffleVector(
2520 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2522 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2526 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2527 Value *Shuf = Builder.CreateShuffleVector(
2528 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2529 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2533 // The result is in the first element of the vector.
2534 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2538 /// \brief Recognize construction of vectors like
2539 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2540 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2541 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2542 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2544 /// Returns true if it matches
2546 static bool findBuildVector(InsertElementInst *IE,
2547 SmallVectorImpl<Value *> &Ops) {
2548 if (!isa<UndefValue>(IE->getOperand(0)))
2552 Ops.push_back(IE->getOperand(1));
2554 if (IE->use_empty())
2557 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2561 // If this isn't the final use, make sure the next insertelement is the only
2562 // use. It's OK if the final constructed vector is used multiple times
2563 if (!IE->hasOneUse())
2572 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2573 return V->getType() < V2->getType();
2576 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2577 bool Changed = false;
2578 SmallVector<Value *, 4> Incoming;
2579 SmallSet<Value *, 16> VisitedInstrs;
2581 bool HaveVectorizedPhiNodes = true;
2582 while (HaveVectorizedPhiNodes) {
2583 HaveVectorizedPhiNodes = false;
2585 // Collect the incoming values from the PHIs.
2587 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2589 PHINode *P = dyn_cast<PHINode>(instr);
2593 if (!VisitedInstrs.count(P))
2594 Incoming.push_back(P);
2598 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2600 // Try to vectorize elements base on their type.
2601 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2605 // Look for the next elements with the same type.
2606 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2607 while (SameTypeIt != E &&
2608 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2609 VisitedInstrs.insert(*SameTypeIt);
2613 // Try to vectorize them.
2614 unsigned NumElts = (SameTypeIt - IncIt);
2615 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2617 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2618 // Success start over because instructions might have been changed.
2619 HaveVectorizedPhiNodes = true;
2624 // Start over at the next instruction of a different type (or the end).
2629 VisitedInstrs.clear();
2631 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2632 // We may go through BB multiple times so skip the one we have checked.
2633 if (!VisitedInstrs.insert(it))
2636 if (isa<DbgInfoIntrinsic>(it))
2639 // Try to vectorize reductions that use PHINodes.
2640 if (PHINode *P = dyn_cast<PHINode>(it)) {
2641 // Check that the PHI is a reduction PHI.
2642 if (P->getNumIncomingValues() != 2)
2645 (P->getIncomingBlock(0) == BB
2646 ? (P->getIncomingValue(0))
2647 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
2649 // Check if this is a Binary Operator.
2650 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2654 // Try to match and vectorize a horizontal reduction.
2655 HorizontalReduction HorRdx;
2656 if (ShouldVectorizeHor &&
2657 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2658 HorRdx.tryToReduce(R, TTI)) {
2665 Value *Inst = BI->getOperand(0);
2667 Inst = BI->getOperand(1);
2669 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2670 // We would like to start over since some instructions are deleted
2671 // and the iterator may become invalid value.
2681 // Try to vectorize horizontal reductions feeding into a store.
2682 if (ShouldStartVectorizeHorAtStore)
2683 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2684 if (BinaryOperator *BinOp =
2685 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2686 HorizontalReduction HorRdx;
2687 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
2688 HorRdx.tryToReduce(R, TTI)) ||
2689 tryToVectorize(BinOp, R))) {
2697 // Try to vectorize trees that start at compare instructions.
2698 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2699 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2701 // We would like to start over since some instructions are deleted
2702 // and the iterator may become invalid value.
2708 for (int i = 0; i < 2; ++i) {
2709 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2710 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2712 // We would like to start over since some instructions are deleted
2713 // and the iterator may become invalid value.
2722 // Try to vectorize trees that start at insertelement instructions.
2723 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2724 SmallVector<Value *, 8> Ops;
2725 if (!findBuildVector(IE, Ops))
2728 if (tryToVectorizeList(Ops, R)) {
2741 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2742 bool Changed = false;
2743 // Attempt to sort and vectorize each of the store-groups.
2744 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2746 if (it->second.size() < 2)
2749 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2750 << it->second.size() << ".\n");
2752 // Process the stores in chunks of 16.
2753 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2754 unsigned Len = std::min<unsigned>(CE - CI, 16);
2755 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2756 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2762 } // end anonymous namespace
2764 char SLPVectorizer::ID = 0;
2765 static const char lv_name[] = "SLP Vectorizer";
2766 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2767 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2768 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2769 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2770 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2771 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2774 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }