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 #define SV_NAME "slp-vectorizer"
19 #define DEBUG_TYPE "SLP"
21 #include "llvm/Transforms/Vectorize.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/IR/Verifier.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
50 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
51 cl::desc("Only vectorize if you gain more than this "
55 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
56 cl::desc("Attempt to vectorize horizontal reductions"));
58 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
59 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
61 "Attempt to vectorize horizontal reductions feeding into a store"));
65 static const unsigned MinVecRegSize = 128;
67 static const unsigned RecursionMaxDepth = 12;
69 /// A helper class for numbering instructions in multiple blocks.
70 /// Numbers start at zero for each basic block.
71 struct BlockNumbering {
73 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
75 BlockNumbering() : BB(0), Valid(false) {}
77 void numberInstructions() {
81 // Number the instructions in the block.
82 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
84 InstrVec.push_back(it);
85 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
90 int getIndex(Instruction *I) {
91 assert(I->getParent() == BB && "Invalid instruction");
94 assert(InstrIdx.count(I) && "Unknown instruction");
98 Instruction *getInstruction(unsigned loc) {
100 numberInstructions();
101 assert(InstrVec.size() > loc && "Invalid Index");
102 return InstrVec[loc];
105 void forget() { Valid = false; }
108 /// The block we are numbering.
110 /// Is the block numbered.
112 /// Maps instructions to numbers and back.
113 SmallDenseMap<Instruction *, int> InstrIdx;
114 /// Maps integers to Instructions.
115 SmallVector<Instruction *, 32> InstrVec;
118 /// \returns the parent basic block if all of the instructions in \p VL
119 /// are in the same block or null otherwise.
120 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
121 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
124 BasicBlock *BB = I0->getParent();
125 for (int i = 1, e = VL.size(); i < e; i++) {
126 Instruction *I = dyn_cast<Instruction>(VL[i]);
130 if (BB != I->getParent())
136 /// \returns True if all of the values in \p VL are constants.
137 static bool allConstant(ArrayRef<Value *> VL) {
138 for (unsigned i = 0, e = VL.size(); i < e; ++i)
139 if (!isa<Constant>(VL[i]))
144 /// \returns True if all of the values in \p VL are identical.
145 static bool isSplat(ArrayRef<Value *> VL) {
146 for (unsigned i = 1, e = VL.size(); i < e; ++i)
152 /// \returns The opcode if all of the Instructions in \p VL have the same
154 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
155 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
158 unsigned Opcode = I0->getOpcode();
159 for (int i = 1, e = VL.size(); i < e; i++) {
160 Instruction *I = dyn_cast<Instruction>(VL[i]);
161 if (!I || Opcode != I->getOpcode())
167 /// \returns \p I after propagating metadata from \p VL.
168 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
169 Instruction *I0 = cast<Instruction>(VL[0]);
170 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
171 I0->getAllMetadataOtherThanDebugLoc(Metadata);
173 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
174 unsigned Kind = Metadata[i].first;
175 MDNode *MD = Metadata[i].second;
177 for (int i = 1, e = VL.size(); MD && i != e; i++) {
178 Instruction *I = cast<Instruction>(VL[i]);
179 MDNode *IMD = I->getMetadata(Kind);
183 MD = 0; // Remove unknown metadata
185 case LLVMContext::MD_tbaa:
186 MD = MDNode::getMostGenericTBAA(MD, IMD);
188 case LLVMContext::MD_fpmath:
189 MD = MDNode::getMostGenericFPMath(MD, IMD);
193 I->setMetadata(Kind, MD);
198 /// \returns The type that all of the values in \p VL have or null if there
199 /// are different types.
200 static Type* getSameType(ArrayRef<Value *> VL) {
201 Type *Ty = VL[0]->getType();
202 for (int i = 1, e = VL.size(); i < e; i++)
203 if (VL[i]->getType() != Ty)
209 /// \returns True if the ExtractElement instructions in VL can be vectorized
210 /// to use the original vector.
211 static bool CanReuseExtract(ArrayRef<Value *> VL) {
212 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
213 // Check if all of the extracts come from the same vector and from the
216 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
217 Value *Vec = E0->getOperand(0);
219 // We have to extract from the same vector type.
220 unsigned NElts = Vec->getType()->getVectorNumElements();
222 if (NElts != VL.size())
225 // Check that all of the indices extract from the correct offset.
226 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
227 if (!CI || CI->getZExtValue())
230 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
231 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
232 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
234 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
241 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
242 SmallVectorImpl<Value *> &Left,
243 SmallVectorImpl<Value *> &Right) {
245 SmallVector<Value *, 16> OrigLeft, OrigRight;
247 bool AllSameOpcodeLeft = true;
248 bool AllSameOpcodeRight = true;
249 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
250 Instruction *I = cast<Instruction>(VL[i]);
251 Value *V0 = I->getOperand(0);
252 Value *V1 = I->getOperand(1);
254 OrigLeft.push_back(V0);
255 OrigRight.push_back(V1);
257 Instruction *I0 = dyn_cast<Instruction>(V0);
258 Instruction *I1 = dyn_cast<Instruction>(V1);
260 // Check whether all operands on one side have the same opcode. In this case
261 // we want to preserve the original order and not make things worse by
263 AllSameOpcodeLeft = I0;
264 AllSameOpcodeRight = I1;
266 if (i && AllSameOpcodeLeft) {
267 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
268 if(P0->getOpcode() != I0->getOpcode())
269 AllSameOpcodeLeft = false;
271 AllSameOpcodeLeft = false;
273 if (i && AllSameOpcodeRight) {
274 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
275 if(P1->getOpcode() != I1->getOpcode())
276 AllSameOpcodeRight = false;
278 AllSameOpcodeRight = false;
281 // Sort two opcodes. In the code below we try to preserve the ability to use
282 // broadcast of values instead of individual inserts.
289 // If we just sorted according to opcode we would leave the first line in
290 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
293 // Because vr2 and vr1 are from the same load we loose the opportunity of a
294 // broadcast for the packed right side in the backend: we have [vr1, vl2]
295 // instead of [vr1, vr2=vr1].
297 if(!i && I0->getOpcode() > I1->getOpcode()) {
300 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
301 // Try not to destroy a broad cast for no apparent benefit.
304 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
305 // Try preserve broadcasts.
308 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
309 // Try preserve broadcasts.
318 // One opcode, put the instruction on the right.
328 bool LeftBroadcast = isSplat(Left);
329 bool RightBroadcast = isSplat(Right);
331 // Don't reorder if the operands where good to begin with.
332 if (!(LeftBroadcast || RightBroadcast) &&
333 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
339 /// Bottom Up SLP Vectorizer.
342 typedef SmallVector<Value *, 8> ValueList;
343 typedef SmallVector<Instruction *, 16> InstrList;
344 typedef SmallPtrSet<Value *, 16> ValueSet;
345 typedef SmallVector<StoreInst *, 8> StoreList;
347 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
348 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
350 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
351 Builder(Se->getContext()) {
352 // Setup the block numbering utility for all of the blocks in the
354 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
356 BlocksNumbers[BB] = BlockNumbering(BB);
360 /// \brief Vectorize the tree that starts with the elements in \p VL.
361 /// Returns the vectorized root.
362 Value *vectorizeTree();
364 /// \returns the vectorization cost of the subtree that starts at \p VL.
365 /// A negative number means that this is profitable.
368 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
369 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
370 void buildTree(ArrayRef<Value *> Roots,
371 ArrayRef<Value *> UserIgnoreLst = None);
373 /// Clear the internal data structures that are created by 'buildTree'.
375 VectorizableTree.clear();
376 ScalarToTreeEntry.clear();
378 ExternalUses.clear();
379 MemBarrierIgnoreList.clear();
382 /// \returns true if the memory operations A and B are consecutive.
383 bool isConsecutiveAccess(Value *A, Value *B);
385 /// \brief Perform LICM and CSE on the newly generated gather sequences.
386 void optimizeGatherSequence();
390 /// \returns the cost of the vectorizable entry.
391 int getEntryCost(TreeEntry *E);
393 /// This is the recursive part of buildTree.
394 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
396 /// Vectorize a single entry in the tree.
397 Value *vectorizeTree(TreeEntry *E);
399 /// Vectorize a single entry in the tree, starting in \p VL.
400 Value *vectorizeTree(ArrayRef<Value *> VL);
402 /// \returns the pointer to the vectorized value if \p VL is already
403 /// vectorized, or NULL. They may happen in cycles.
404 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
406 /// \brief Take the pointer operand from the Load/Store instruction.
407 /// \returns NULL if this is not a valid Load/Store instruction.
408 static Value *getPointerOperand(Value *I);
410 /// \brief Take the address space operand from the Load/Store instruction.
411 /// \returns -1 if this is not a valid Load/Store instruction.
412 static unsigned getAddressSpaceOperand(Value *I);
414 /// \returns the scalarization cost for this type. Scalarization in this
415 /// context means the creation of vectors from a group of scalars.
416 int getGatherCost(Type *Ty);
418 /// \returns the scalarization cost for this list of values. Assuming that
419 /// this subtree gets vectorized, we may need to extract the values from the
420 /// roots. This method calculates the cost of extracting the values.
421 int getGatherCost(ArrayRef<Value *> VL);
423 /// \returns the AA location that is being access by the instruction.
424 AliasAnalysis::Location getLocation(Instruction *I);
426 /// \brief Checks if it is possible to sink an instruction from
427 /// \p Src to \p Dst.
428 /// \returns the pointer to the barrier instruction if we can't sink.
429 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
431 /// \returns the index of the last instruction in the BB from \p VL.
432 int getLastIndex(ArrayRef<Value *> VL);
434 /// \returns the Instruction in the bundle \p VL.
435 Instruction *getLastInstruction(ArrayRef<Value *> VL);
437 /// \brief Set the Builder insert point to one after the last instruction in
439 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
441 /// \returns a vector from a collection of scalars in \p VL.
442 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
444 /// \returns whether the VectorizableTree is fully vectoriable and will
445 /// be beneficial even the tree height is tiny.
446 bool isFullyVectorizableTinyTree();
449 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
452 /// \returns true if the scalars in VL are equal to this entry.
453 bool isSame(ArrayRef<Value *> VL) const {
454 assert(VL.size() == Scalars.size() && "Invalid size");
455 return std::equal(VL.begin(), VL.end(), Scalars.begin());
458 /// A vector of scalars.
461 /// The Scalars are vectorized into this value. It is initialized to Null.
462 Value *VectorizedValue;
464 /// The index in the basic block of the last scalar.
467 /// Do we need to gather this sequence ?
471 /// Create a new VectorizableTree entry.
472 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
473 VectorizableTree.push_back(TreeEntry());
474 int idx = VectorizableTree.size() - 1;
475 TreeEntry *Last = &VectorizableTree[idx];
476 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
477 Last->NeedToGather = !Vectorized;
479 Last->LastScalarIndex = getLastIndex(VL);
480 for (int i = 0, e = VL.size(); i != e; ++i) {
481 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
482 ScalarToTreeEntry[VL[i]] = idx;
485 Last->LastScalarIndex = 0;
486 MustGather.insert(VL.begin(), VL.end());
491 /// -- Vectorization State --
492 /// Holds all of the tree entries.
493 std::vector<TreeEntry> VectorizableTree;
495 /// Maps a specific scalar to its tree entry.
496 SmallDenseMap<Value*, int> ScalarToTreeEntry;
498 /// A list of scalars that we found that we need to keep as scalars.
501 /// This POD struct describes one external user in the vectorized tree.
502 struct ExternalUser {
503 ExternalUser (Value *S, llvm::User *U, int L) :
504 Scalar(S), User(U), Lane(L){};
505 // Which scalar in our function.
507 // Which user that uses the scalar.
509 // Which lane does the scalar belong to.
512 typedef SmallVector<ExternalUser, 16> UserList;
514 /// A list of values that need to extracted out of the tree.
515 /// This list holds pairs of (Internal Scalar : External User).
516 UserList ExternalUses;
518 /// A list of instructions to ignore while sinking
519 /// memory instructions. This map must be reset between runs of getCost.
520 ValueSet MemBarrierIgnoreList;
522 /// Holds all of the instructions that we gathered.
523 SetVector<Instruction *> GatherSeq;
524 /// A list of blocks that we are going to CSE.
525 SetVector<BasicBlock *> CSEBlocks;
527 /// Numbers instructions in different blocks.
528 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
530 /// List of users to ignore during scheduling and that don't need extracting.
531 ArrayRef<Value *> UserIgnoreList;
533 // Analysis and block reference.
536 const DataLayout *DL;
537 TargetTransformInfo *TTI;
541 /// Instruction builder to construct the vectorized tree.
545 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
546 ArrayRef<Value *> UserIgnoreLst) {
548 UserIgnoreList = UserIgnoreLst;
549 if (!getSameType(Roots))
551 buildTree_rec(Roots, 0);
553 // Collect the values that we need to extract from the tree.
554 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
555 TreeEntry *Entry = &VectorizableTree[EIdx];
558 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
559 Value *Scalar = Entry->Scalars[Lane];
561 // No need to handle users of gathered values.
562 if (Entry->NeedToGather)
565 for (User *U : Scalar->users()) {
566 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
568 // Skip in-tree scalars that become vectors.
569 if (ScalarToTreeEntry.count(U)) {
570 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
572 int Idx = ScalarToTreeEntry[U]; (void) Idx;
573 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
576 Instruction *UserInst = dyn_cast<Instruction>(U);
580 // Ignore users in the user ignore list.
581 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
582 UserIgnoreList.end())
585 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
586 Lane << " from " << *Scalar << ".\n");
587 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
594 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
595 bool SameTy = getSameType(VL); (void)SameTy;
596 assert(SameTy && "Invalid types!");
598 if (Depth == RecursionMaxDepth) {
599 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
600 newTreeEntry(VL, false);
604 // Don't handle vectors.
605 if (VL[0]->getType()->isVectorTy()) {
606 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
607 newTreeEntry(VL, false);
611 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
612 if (SI->getValueOperand()->getType()->isVectorTy()) {
613 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
614 newTreeEntry(VL, false);
618 // If all of the operands are identical or constant we have a simple solution.
619 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
620 !getSameOpcode(VL)) {
621 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
622 newTreeEntry(VL, false);
626 // We now know that this is a vector of instructions of the same type from
629 // Check if this is a duplicate of another entry.
630 if (ScalarToTreeEntry.count(VL[0])) {
631 int Idx = ScalarToTreeEntry[VL[0]];
632 TreeEntry *E = &VectorizableTree[Idx];
633 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
634 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
635 if (E->Scalars[i] != VL[i]) {
636 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
637 newTreeEntry(VL, false);
641 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
645 // Check that none of the instructions in the bundle are already in the tree.
646 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
647 if (ScalarToTreeEntry.count(VL[i])) {
648 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
649 ") is already in tree.\n");
650 newTreeEntry(VL, false);
655 // If any of the scalars appears in the table OR it is marked as a value that
656 // needs to stat scalar then we need to gather the scalars.
657 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
658 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
659 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
660 newTreeEntry(VL, false);
665 // Check that all of the users of the scalars that we want to vectorize are
667 Instruction *VL0 = cast<Instruction>(VL[0]);
668 int MyLastIndex = getLastIndex(VL);
669 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
671 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
672 Instruction *Scalar = cast<Instruction>(VL[i]);
673 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
674 for (User *U : Scalar->users()) {
675 DEBUG(dbgs() << "SLP: \tUser " << *U << ". \n");
676 Instruction *UI = dyn_cast<Instruction>(U);
678 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
679 newTreeEntry(VL, false);
683 // We don't care if the user is in a different basic block.
684 BasicBlock *UserBlock = UI->getParent();
685 if (UserBlock != BB) {
686 DEBUG(dbgs() << "SLP: User from a different basic block "
691 // If this is a PHINode within this basic block then we can place the
692 // extract wherever we want.
693 if (isa<PHINode>(*UI)) {
694 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *UI << ". \n");
698 // Check if this is a safe in-tree user.
699 if (ScalarToTreeEntry.count(UI)) {
700 int Idx = ScalarToTreeEntry[UI];
701 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
702 if (VecLocation <= MyLastIndex) {
703 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
704 newTreeEntry(VL, false);
707 DEBUG(dbgs() << "SLP: In-tree user (" << *UI << ") at #" <<
708 VecLocation << " vector value (" << *Scalar << ") at #"
709 << MyLastIndex << ".\n");
713 // Ignore users in the user ignore list.
714 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UI) !=
715 UserIgnoreList.end())
718 // Make sure that we can schedule this unknown user.
719 BlockNumbering &BN = BlocksNumbers[BB];
720 int UserIndex = BN.getIndex(UI);
721 if (UserIndex < MyLastIndex) {
723 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
725 newTreeEntry(VL, false);
731 // Check that every instructions appears once in this bundle.
732 for (unsigned i = 0, e = VL.size(); i < e; ++i)
733 for (unsigned j = i+1; j < e; ++j)
734 if (VL[i] == VL[j]) {
735 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
736 newTreeEntry(VL, false);
740 // Check that instructions in this bundle don't reference other instructions.
741 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
742 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
743 for (User *U : VL[i]->users()) {
744 for (unsigned j = 0; j < e; ++j) {
745 if (i != j && U == VL[j]) {
746 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << *U << ". \n");
747 newTreeEntry(VL, false);
754 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
756 unsigned Opcode = getSameOpcode(VL);
758 // Check if it is safe to sink the loads or the stores.
759 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
760 Instruction *Last = getLastInstruction(VL);
762 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
765 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
767 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
768 << "\n because of " << *Barrier << ". Gathering.\n");
769 newTreeEntry(VL, false);
776 case Instruction::PHI: {
777 PHINode *PH = dyn_cast<PHINode>(VL0);
779 // Check for terminator values (e.g. invoke).
780 for (unsigned j = 0; j < VL.size(); ++j)
781 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
782 TerminatorInst *Term = dyn_cast<TerminatorInst>(
783 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
785 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
786 newTreeEntry(VL, false);
791 newTreeEntry(VL, true);
792 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
794 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
796 // Prepare the operand vector.
797 for (unsigned j = 0; j < VL.size(); ++j)
798 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
799 PH->getIncomingBlock(i)));
801 buildTree_rec(Operands, Depth + 1);
805 case Instruction::ExtractElement: {
806 bool Reuse = CanReuseExtract(VL);
808 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
810 newTreeEntry(VL, Reuse);
813 case Instruction::Load: {
814 // Check if the loads are consecutive or of we need to swizzle them.
815 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
816 LoadInst *L = cast<LoadInst>(VL[i]);
817 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
818 newTreeEntry(VL, false);
819 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
823 newTreeEntry(VL, true);
824 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
827 case Instruction::ZExt:
828 case Instruction::SExt:
829 case Instruction::FPToUI:
830 case Instruction::FPToSI:
831 case Instruction::FPExt:
832 case Instruction::PtrToInt:
833 case Instruction::IntToPtr:
834 case Instruction::SIToFP:
835 case Instruction::UIToFP:
836 case Instruction::Trunc:
837 case Instruction::FPTrunc:
838 case Instruction::BitCast: {
839 Type *SrcTy = VL0->getOperand(0)->getType();
840 for (unsigned i = 0; i < VL.size(); ++i) {
841 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
842 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
843 newTreeEntry(VL, false);
844 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
848 newTreeEntry(VL, true);
849 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
851 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
853 // Prepare the operand vector.
854 for (unsigned j = 0; j < VL.size(); ++j)
855 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
857 buildTree_rec(Operands, Depth+1);
861 case Instruction::ICmp:
862 case Instruction::FCmp: {
863 // Check that all of the compares have the same predicate.
864 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
865 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
866 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
867 CmpInst *Cmp = cast<CmpInst>(VL[i]);
868 if (Cmp->getPredicate() != P0 ||
869 Cmp->getOperand(0)->getType() != ComparedTy) {
870 newTreeEntry(VL, false);
871 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
876 newTreeEntry(VL, true);
877 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
879 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
881 // Prepare the operand vector.
882 for (unsigned j = 0; j < VL.size(); ++j)
883 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
885 buildTree_rec(Operands, Depth+1);
889 case Instruction::Select:
890 case Instruction::Add:
891 case Instruction::FAdd:
892 case Instruction::Sub:
893 case Instruction::FSub:
894 case Instruction::Mul:
895 case Instruction::FMul:
896 case Instruction::UDiv:
897 case Instruction::SDiv:
898 case Instruction::FDiv:
899 case Instruction::URem:
900 case Instruction::SRem:
901 case Instruction::FRem:
902 case Instruction::Shl:
903 case Instruction::LShr:
904 case Instruction::AShr:
905 case Instruction::And:
906 case Instruction::Or:
907 case Instruction::Xor: {
908 newTreeEntry(VL, true);
909 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
911 // Sort operands of the instructions so that each side is more likely to
912 // have the same opcode.
913 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
914 ValueList Left, Right;
915 reorderInputsAccordingToOpcode(VL, Left, Right);
916 buildTree_rec(Left, Depth + 1);
917 buildTree_rec(Right, Depth + 1);
921 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
923 // Prepare the operand vector.
924 for (unsigned j = 0; j < VL.size(); ++j)
925 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
927 buildTree_rec(Operands, Depth+1);
931 case Instruction::Store: {
932 // Check if the stores are consecutive or of we need to swizzle them.
933 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
934 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
935 newTreeEntry(VL, false);
936 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
940 newTreeEntry(VL, true);
941 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
944 for (unsigned j = 0; j < VL.size(); ++j)
945 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
947 // We can ignore these values because we are sinking them down.
948 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
949 buildTree_rec(Operands, Depth + 1);
952 case Instruction::Call: {
953 // Check if the calls are all to the same vectorizable intrinsic.
954 IntrinsicInst *II = dyn_cast<IntrinsicInst>(VL[0]);
956 newTreeEntry(VL, false);
957 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
961 Intrinsic::ID ID = II->getIntrinsicID();
963 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
964 IntrinsicInst *II2 = dyn_cast<IntrinsicInst>(VL[i]);
965 if (!II2 || II2->getIntrinsicID() != ID) {
966 newTreeEntry(VL, false);
967 DEBUG(dbgs() << "SLP: mismatched calls:" << *II << "!=" << *VL[i]
973 newTreeEntry(VL, true);
974 for (unsigned i = 0, e = II->getNumArgOperands(); i != e; ++i) {
976 // Prepare the operand vector.
977 for (unsigned j = 0; j < VL.size(); ++j) {
978 IntrinsicInst *II2 = dyn_cast<IntrinsicInst>(VL[j]);
979 Operands.push_back(II2->getArgOperand(i));
981 buildTree_rec(Operands, Depth + 1);
986 newTreeEntry(VL, false);
987 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
992 int BoUpSLP::getEntryCost(TreeEntry *E) {
993 ArrayRef<Value*> VL = E->Scalars;
995 Type *ScalarTy = VL[0]->getType();
996 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
997 ScalarTy = SI->getValueOperand()->getType();
998 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1000 if (E->NeedToGather) {
1001 if (allConstant(VL))
1004 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1006 return getGatherCost(E->Scalars);
1009 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
1011 Instruction *VL0 = cast<Instruction>(VL[0]);
1012 unsigned Opcode = VL0->getOpcode();
1014 case Instruction::PHI: {
1017 case Instruction::ExtractElement: {
1018 if (CanReuseExtract(VL))
1020 return getGatherCost(VecTy);
1022 case Instruction::ZExt:
1023 case Instruction::SExt:
1024 case Instruction::FPToUI:
1025 case Instruction::FPToSI:
1026 case Instruction::FPExt:
1027 case Instruction::PtrToInt:
1028 case Instruction::IntToPtr:
1029 case Instruction::SIToFP:
1030 case Instruction::UIToFP:
1031 case Instruction::Trunc:
1032 case Instruction::FPTrunc:
1033 case Instruction::BitCast: {
1034 Type *SrcTy = VL0->getOperand(0)->getType();
1036 // Calculate the cost of this instruction.
1037 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1038 VL0->getType(), SrcTy);
1040 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1041 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1042 return VecCost - ScalarCost;
1044 case Instruction::FCmp:
1045 case Instruction::ICmp:
1046 case Instruction::Select:
1047 case Instruction::Add:
1048 case Instruction::FAdd:
1049 case Instruction::Sub:
1050 case Instruction::FSub:
1051 case Instruction::Mul:
1052 case Instruction::FMul:
1053 case Instruction::UDiv:
1054 case Instruction::SDiv:
1055 case Instruction::FDiv:
1056 case Instruction::URem:
1057 case Instruction::SRem:
1058 case Instruction::FRem:
1059 case Instruction::Shl:
1060 case Instruction::LShr:
1061 case Instruction::AShr:
1062 case Instruction::And:
1063 case Instruction::Or:
1064 case Instruction::Xor: {
1065 // Calculate the cost of this instruction.
1068 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1069 Opcode == Instruction::Select) {
1070 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1071 ScalarCost = VecTy->getNumElements() *
1072 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1073 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1075 // Certain instructions can be cheaper to vectorize if they have a
1076 // constant second vector operand.
1077 TargetTransformInfo::OperandValueKind Op1VK =
1078 TargetTransformInfo::OK_AnyValue;
1079 TargetTransformInfo::OperandValueKind Op2VK =
1080 TargetTransformInfo::OK_UniformConstantValue;
1082 // If all operands are exactly the same ConstantInt then set the
1083 // operand kind to OK_UniformConstantValue.
1084 // If instead not all operands are constants, then set the operand kind
1085 // to OK_AnyValue. If all operands are constants but not the same,
1086 // then set the operand kind to OK_NonUniformConstantValue.
1087 ConstantInt *CInt = NULL;
1088 for (unsigned i = 0; i < VL.size(); ++i) {
1089 const Instruction *I = cast<Instruction>(VL[i]);
1090 if (!isa<ConstantInt>(I->getOperand(1))) {
1091 Op2VK = TargetTransformInfo::OK_AnyValue;
1095 CInt = cast<ConstantInt>(I->getOperand(1));
1098 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1099 CInt != cast<ConstantInt>(I->getOperand(1)))
1100 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1104 VecTy->getNumElements() *
1105 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1106 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1108 return VecCost - ScalarCost;
1110 case Instruction::Load: {
1111 // Cost of wide load - cost of scalar loads.
1112 int ScalarLdCost = VecTy->getNumElements() *
1113 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1114 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1115 return VecLdCost - ScalarLdCost;
1117 case Instruction::Store: {
1118 // We know that we can merge the stores. Calculate the cost.
1119 int ScalarStCost = VecTy->getNumElements() *
1120 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1121 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1122 return VecStCost - ScalarStCost;
1124 case Instruction::Call: {
1125 CallInst *CI = cast<CallInst>(VL0);
1126 IntrinsicInst *II = cast<IntrinsicInst>(CI);
1127 Intrinsic::ID ID = II->getIntrinsicID();
1129 // Calculate the cost of the scalar and vector calls.
1130 SmallVector<Type*, 4> ScalarTys, VecTys;
1131 for (unsigned op = 0, opc = II->getNumArgOperands(); op!= opc; ++op) {
1132 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1133 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1134 VecTy->getNumElements()));
1137 int ScalarCallCost = VecTy->getNumElements() *
1138 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1140 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1142 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1143 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1144 << " for " << *II << "\n");
1146 return VecCallCost - ScalarCallCost;
1149 llvm_unreachable("Unknown instruction");
1153 bool BoUpSLP::isFullyVectorizableTinyTree() {
1154 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1155 VectorizableTree.size() << " is fully vectorizable .\n");
1157 // We only handle trees of height 2.
1158 if (VectorizableTree.size() != 2)
1161 // Handle splat stores.
1162 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1165 // Gathering cost would be too much for tiny trees.
1166 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1172 int BoUpSLP::getTreeCost() {
1174 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1175 VectorizableTree.size() << ".\n");
1177 // We only vectorize tiny trees if it is fully vectorizable.
1178 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1179 if (!VectorizableTree.size()) {
1180 assert(!ExternalUses.size() && "We should not have any external users");
1185 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1187 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1188 int C = getEntryCost(&VectorizableTree[i]);
1189 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1190 << *VectorizableTree[i].Scalars[0] << " .\n");
1194 SmallSet<Value *, 16> ExtractCostCalculated;
1195 int ExtractCost = 0;
1196 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1198 // We only add extract cost once for the same scalar.
1199 if (!ExtractCostCalculated.insert(I->Scalar))
1202 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1203 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1207 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1208 return Cost + ExtractCost;
1211 int BoUpSLP::getGatherCost(Type *Ty) {
1213 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1214 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1218 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1219 // Find the type of the operands in VL.
1220 Type *ScalarTy = VL[0]->getType();
1221 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1222 ScalarTy = SI->getValueOperand()->getType();
1223 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1224 // Find the cost of inserting/extracting values from the vector.
1225 return getGatherCost(VecTy);
1228 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1229 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1230 return AA->getLocation(SI);
1231 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1232 return AA->getLocation(LI);
1233 return AliasAnalysis::Location();
1236 Value *BoUpSLP::getPointerOperand(Value *I) {
1237 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1238 return LI->getPointerOperand();
1239 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1240 return SI->getPointerOperand();
1244 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1245 if (LoadInst *L = dyn_cast<LoadInst>(I))
1246 return L->getPointerAddressSpace();
1247 if (StoreInst *S = dyn_cast<StoreInst>(I))
1248 return S->getPointerAddressSpace();
1252 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1253 Value *PtrA = getPointerOperand(A);
1254 Value *PtrB = getPointerOperand(B);
1255 unsigned ASA = getAddressSpaceOperand(A);
1256 unsigned ASB = getAddressSpaceOperand(B);
1258 // Check that the address spaces match and that the pointers are valid.
1259 if (!PtrA || !PtrB || (ASA != ASB))
1262 // Make sure that A and B are different pointers of the same type.
1263 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1266 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1267 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1268 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1270 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1271 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1272 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1274 APInt OffsetDelta = OffsetB - OffsetA;
1276 // Check if they are based on the same pointer. That makes the offsets
1279 return OffsetDelta == Size;
1281 // Compute the necessary base pointer delta to have the necessary final delta
1282 // equal to the size.
1283 APInt BaseDelta = Size - OffsetDelta;
1285 // Otherwise compute the distance with SCEV between the base pointers.
1286 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1287 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1288 const SCEV *C = SE->getConstant(BaseDelta);
1289 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1290 return X == PtrSCEVB;
1293 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1294 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1295 BasicBlock::iterator I = Src, E = Dst;
1296 /// Scan all of the instruction from SRC to DST and check if
1297 /// the source may alias.
1298 for (++I; I != E; ++I) {
1299 // Ignore store instructions that are marked as 'ignore'.
1300 if (MemBarrierIgnoreList.count(I))
1302 if (Src->mayWriteToMemory()) /* Write */ {
1303 if (!I->mayReadOrWriteMemory())
1306 if (!I->mayWriteToMemory())
1309 AliasAnalysis::Location A = getLocation(&*I);
1310 AliasAnalysis::Location B = getLocation(Src);
1312 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1318 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1319 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1320 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1321 BlockNumbering &BN = BlocksNumbers[BB];
1323 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1324 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1325 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1329 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1330 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1331 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1332 BlockNumbering &BN = BlocksNumbers[BB];
1334 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1335 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1336 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1337 Instruction *I = BN.getInstruction(MaxIdx);
1338 assert(I && "bad location");
1342 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1343 Instruction *VL0 = cast<Instruction>(VL[0]);
1344 Instruction *LastInst = getLastInstruction(VL);
1345 BasicBlock::iterator NextInst = LastInst;
1347 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1348 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1351 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1352 Value *Vec = UndefValue::get(Ty);
1353 // Generate the 'InsertElement' instruction.
1354 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1355 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1356 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1357 GatherSeq.insert(Insrt);
1358 CSEBlocks.insert(Insrt->getParent());
1360 // Add to our 'need-to-extract' list.
1361 if (ScalarToTreeEntry.count(VL[i])) {
1362 int Idx = ScalarToTreeEntry[VL[i]];
1363 TreeEntry *E = &VectorizableTree[Idx];
1364 // Find which lane we need to extract.
1366 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1367 // Is this the lane of the scalar that we are looking for ?
1368 if (E->Scalars[Lane] == VL[i]) {
1373 assert(FoundLane >= 0 && "Could not find the correct lane");
1374 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1382 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1383 SmallDenseMap<Value*, int>::const_iterator Entry
1384 = ScalarToTreeEntry.find(VL[0]);
1385 if (Entry != ScalarToTreeEntry.end()) {
1386 int Idx = Entry->second;
1387 const TreeEntry *En = &VectorizableTree[Idx];
1388 if (En->isSame(VL) && En->VectorizedValue)
1389 return En->VectorizedValue;
1394 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1395 if (ScalarToTreeEntry.count(VL[0])) {
1396 int Idx = ScalarToTreeEntry[VL[0]];
1397 TreeEntry *E = &VectorizableTree[Idx];
1399 return vectorizeTree(E);
1402 Type *ScalarTy = VL[0]->getType();
1403 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1404 ScalarTy = SI->getValueOperand()->getType();
1405 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1407 return Gather(VL, VecTy);
1410 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1411 IRBuilder<>::InsertPointGuard Guard(Builder);
1413 if (E->VectorizedValue) {
1414 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1415 return E->VectorizedValue;
1418 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1419 Type *ScalarTy = VL0->getType();
1420 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1421 ScalarTy = SI->getValueOperand()->getType();
1422 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1424 if (E->NeedToGather) {
1425 setInsertPointAfterBundle(E->Scalars);
1426 return Gather(E->Scalars, VecTy);
1429 unsigned Opcode = VL0->getOpcode();
1430 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1433 case Instruction::PHI: {
1434 PHINode *PH = dyn_cast<PHINode>(VL0);
1435 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1436 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1437 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1438 E->VectorizedValue = NewPhi;
1440 // PHINodes may have multiple entries from the same block. We want to
1441 // visit every block once.
1442 SmallSet<BasicBlock*, 4> VisitedBBs;
1444 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1446 BasicBlock *IBB = PH->getIncomingBlock(i);
1448 if (!VisitedBBs.insert(IBB)) {
1449 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1453 // Prepare the operand vector.
1454 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1455 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1456 getIncomingValueForBlock(IBB));
1458 Builder.SetInsertPoint(IBB->getTerminator());
1459 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1460 Value *Vec = vectorizeTree(Operands);
1461 NewPhi->addIncoming(Vec, IBB);
1464 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1465 "Invalid number of incoming values");
1469 case Instruction::ExtractElement: {
1470 if (CanReuseExtract(E->Scalars)) {
1471 Value *V = VL0->getOperand(0);
1472 E->VectorizedValue = V;
1475 return Gather(E->Scalars, VecTy);
1477 case Instruction::ZExt:
1478 case Instruction::SExt:
1479 case Instruction::FPToUI:
1480 case Instruction::FPToSI:
1481 case Instruction::FPExt:
1482 case Instruction::PtrToInt:
1483 case Instruction::IntToPtr:
1484 case Instruction::SIToFP:
1485 case Instruction::UIToFP:
1486 case Instruction::Trunc:
1487 case Instruction::FPTrunc:
1488 case Instruction::BitCast: {
1490 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1491 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1493 setInsertPointAfterBundle(E->Scalars);
1495 Value *InVec = vectorizeTree(INVL);
1497 if (Value *V = alreadyVectorized(E->Scalars))
1500 CastInst *CI = dyn_cast<CastInst>(VL0);
1501 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1502 E->VectorizedValue = V;
1505 case Instruction::FCmp:
1506 case Instruction::ICmp: {
1507 ValueList LHSV, RHSV;
1508 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1509 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1510 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1513 setInsertPointAfterBundle(E->Scalars);
1515 Value *L = vectorizeTree(LHSV);
1516 Value *R = vectorizeTree(RHSV);
1518 if (Value *V = alreadyVectorized(E->Scalars))
1521 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1523 if (Opcode == Instruction::FCmp)
1524 V = Builder.CreateFCmp(P0, L, R);
1526 V = Builder.CreateICmp(P0, L, R);
1528 E->VectorizedValue = V;
1531 case Instruction::Select: {
1532 ValueList TrueVec, FalseVec, CondVec;
1533 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1534 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1535 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1536 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1539 setInsertPointAfterBundle(E->Scalars);
1541 Value *Cond = vectorizeTree(CondVec);
1542 Value *True = vectorizeTree(TrueVec);
1543 Value *False = vectorizeTree(FalseVec);
1545 if (Value *V = alreadyVectorized(E->Scalars))
1548 Value *V = Builder.CreateSelect(Cond, True, False);
1549 E->VectorizedValue = V;
1552 case Instruction::Add:
1553 case Instruction::FAdd:
1554 case Instruction::Sub:
1555 case Instruction::FSub:
1556 case Instruction::Mul:
1557 case Instruction::FMul:
1558 case Instruction::UDiv:
1559 case Instruction::SDiv:
1560 case Instruction::FDiv:
1561 case Instruction::URem:
1562 case Instruction::SRem:
1563 case Instruction::FRem:
1564 case Instruction::Shl:
1565 case Instruction::LShr:
1566 case Instruction::AShr:
1567 case Instruction::And:
1568 case Instruction::Or:
1569 case Instruction::Xor: {
1570 ValueList LHSVL, RHSVL;
1571 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1572 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1574 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1575 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1576 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1579 setInsertPointAfterBundle(E->Scalars);
1581 Value *LHS = vectorizeTree(LHSVL);
1582 Value *RHS = vectorizeTree(RHSVL);
1584 if (LHS == RHS && isa<Instruction>(LHS)) {
1585 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1588 if (Value *V = alreadyVectorized(E->Scalars))
1591 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1592 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1593 E->VectorizedValue = V;
1595 if (Instruction *I = dyn_cast<Instruction>(V))
1596 return propagateMetadata(I, E->Scalars);
1600 case Instruction::Load: {
1601 // Loads are inserted at the head of the tree because we don't want to
1602 // sink them all the way down past store instructions.
1603 setInsertPointAfterBundle(E->Scalars);
1605 LoadInst *LI = cast<LoadInst>(VL0);
1606 unsigned AS = LI->getPointerAddressSpace();
1608 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1609 VecTy->getPointerTo(AS));
1610 unsigned Alignment = LI->getAlignment();
1611 LI = Builder.CreateLoad(VecPtr);
1612 LI->setAlignment(Alignment);
1613 E->VectorizedValue = LI;
1614 return propagateMetadata(LI, E->Scalars);
1616 case Instruction::Store: {
1617 StoreInst *SI = cast<StoreInst>(VL0);
1618 unsigned Alignment = SI->getAlignment();
1619 unsigned AS = SI->getPointerAddressSpace();
1622 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1623 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1625 setInsertPointAfterBundle(E->Scalars);
1627 Value *VecValue = vectorizeTree(ValueOp);
1628 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1629 VecTy->getPointerTo(AS));
1630 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1631 S->setAlignment(Alignment);
1632 E->VectorizedValue = S;
1633 return propagateMetadata(S, E->Scalars);
1635 case Instruction::Call: {
1636 CallInst *CI = cast<CallInst>(VL0);
1638 setInsertPointAfterBundle(E->Scalars);
1639 std::vector<Value *> OpVecs;
1640 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1642 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1643 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1644 OpVL.push_back(CEI->getArgOperand(j));
1647 Value *OpVec = vectorizeTree(OpVL);
1648 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1649 OpVecs.push_back(OpVec);
1652 Module *M = F->getParent();
1653 IntrinsicInst *II = cast<IntrinsicInst>(CI);
1654 Intrinsic::ID ID = II->getIntrinsicID();
1655 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1656 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1657 Value *V = Builder.CreateCall(CF, OpVecs);
1658 E->VectorizedValue = V;
1662 llvm_unreachable("unknown inst");
1667 Value *BoUpSLP::vectorizeTree() {
1668 Builder.SetInsertPoint(F->getEntryBlock().begin());
1669 vectorizeTree(&VectorizableTree[0]);
1671 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1673 // Extract all of the elements with the external uses.
1674 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1676 Value *Scalar = it->Scalar;
1677 llvm::User *User = it->User;
1679 // Skip users that we already RAUW. This happens when one instruction
1680 // has multiple uses of the same value.
1681 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
1684 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1686 int Idx = ScalarToTreeEntry[Scalar];
1687 TreeEntry *E = &VectorizableTree[Idx];
1688 assert(!E->NeedToGather && "Extracting from a gather list");
1690 Value *Vec = E->VectorizedValue;
1691 assert(Vec && "Can't find vectorizable value");
1693 Value *Lane = Builder.getInt32(it->Lane);
1694 // Generate extracts for out-of-tree users.
1695 // Find the insertion point for the extractelement lane.
1696 if (isa<Instruction>(Vec)){
1697 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1698 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1699 if (PH->getIncomingValue(i) == Scalar) {
1700 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1701 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1702 CSEBlocks.insert(PH->getIncomingBlock(i));
1703 PH->setOperand(i, Ex);
1707 Builder.SetInsertPoint(cast<Instruction>(User));
1708 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1709 CSEBlocks.insert(cast<Instruction>(User)->getParent());
1710 User->replaceUsesOfWith(Scalar, Ex);
1713 Builder.SetInsertPoint(F->getEntryBlock().begin());
1714 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1715 CSEBlocks.insert(&F->getEntryBlock());
1716 User->replaceUsesOfWith(Scalar, Ex);
1719 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1722 // For each vectorized value:
1723 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1724 TreeEntry *Entry = &VectorizableTree[EIdx];
1727 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1728 Value *Scalar = Entry->Scalars[Lane];
1730 // No need to handle users of gathered values.
1731 if (Entry->NeedToGather)
1734 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1736 Type *Ty = Scalar->getType();
1737 if (!Ty->isVoidTy()) {
1739 for (User *U : Scalar->users()) {
1740 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
1742 assert((ScalarToTreeEntry.count(U) ||
1743 // It is legal to replace users in the ignorelist by undef.
1744 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
1745 UserIgnoreList.end())) &&
1746 "Replacing out-of-tree value with undef");
1749 Value *Undef = UndefValue::get(Ty);
1750 Scalar->replaceAllUsesWith(Undef);
1752 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1753 cast<Instruction>(Scalar)->eraseFromParent();
1757 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1758 BlocksNumbers[it].forget();
1760 Builder.ClearInsertionPoint();
1762 return VectorizableTree[0].VectorizedValue;
1765 void BoUpSLP::optimizeGatherSequence() {
1766 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1767 << " gather sequences instructions.\n");
1768 // LICM InsertElementInst sequences.
1769 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1770 e = GatherSeq.end(); it != e; ++it) {
1771 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1776 // Check if this block is inside a loop.
1777 Loop *L = LI->getLoopFor(Insert->getParent());
1781 // Check if it has a preheader.
1782 BasicBlock *PreHeader = L->getLoopPreheader();
1786 // If the vector or the element that we insert into it are
1787 // instructions that are defined in this basic block then we can't
1788 // hoist this instruction.
1789 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1790 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1791 if (CurrVec && L->contains(CurrVec))
1793 if (NewElem && L->contains(NewElem))
1796 // We can hoist this instruction. Move it to the pre-header.
1797 Insert->moveBefore(PreHeader->getTerminator());
1800 // Sort blocks by domination. This ensures we visit a block after all blocks
1801 // dominating it are visited.
1802 SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end());
1803 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
1804 [this](const BasicBlock *A, const BasicBlock *B) {
1805 return DT->properlyDominates(A, B);
1808 // Perform O(N^2) search over the gather sequences and merge identical
1809 // instructions. TODO: We can further optimize this scan if we split the
1810 // instructions into different buckets based on the insert lane.
1811 SmallVector<Instruction *, 16> Visited;
1812 for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1813 E = CSEWorkList.end();
1815 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
1816 "Worklist not sorted properly!");
1817 BasicBlock *BB = *I;
1818 // For all instructions in blocks containing gather sequences:
1819 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1820 Instruction *In = it++;
1821 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1824 // Check if we can replace this instruction with any of the
1825 // visited instructions.
1826 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1829 if (In->isIdenticalTo(*v) &&
1830 DT->dominates((*v)->getParent(), In->getParent())) {
1831 In->replaceAllUsesWith(*v);
1832 In->eraseFromParent();
1838 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1839 Visited.push_back(In);
1847 /// The SLPVectorizer Pass.
1848 struct SLPVectorizer : public FunctionPass {
1849 typedef SmallVector<StoreInst *, 8> StoreList;
1850 typedef MapVector<Value *, StoreList> StoreListMap;
1852 /// Pass identification, replacement for typeid
1855 explicit SLPVectorizer() : FunctionPass(ID) {
1856 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1859 ScalarEvolution *SE;
1860 const DataLayout *DL;
1861 TargetTransformInfo *TTI;
1866 bool runOnFunction(Function &F) override {
1867 if (skipOptnoneFunction(F))
1870 SE = &getAnalysis<ScalarEvolution>();
1871 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1872 DL = DLP ? &DLP->getDataLayout() : 0;
1873 TTI = &getAnalysis<TargetTransformInfo>();
1874 AA = &getAnalysis<AliasAnalysis>();
1875 LI = &getAnalysis<LoopInfo>();
1876 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1879 bool Changed = false;
1881 // If the target claims to have no vector registers don't attempt
1883 if (!TTI->getNumberOfRegisters(true))
1886 // Must have DataLayout. We can't require it because some tests run w/o
1891 // Don't vectorize when the attribute NoImplicitFloat is used.
1892 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1895 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1897 // Use the bottom up slp vectorizer to construct chains that start with
1898 // he store instructions.
1899 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1901 // Scan the blocks in the function in post order.
1902 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1903 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1904 BasicBlock *BB = *it;
1906 // Vectorize trees that end at stores.
1907 if (unsigned count = collectStores(BB, R)) {
1909 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1910 Changed |= vectorizeStoreChains(R);
1913 // Vectorize trees that end at reductions.
1914 Changed |= vectorizeChainsInBlock(BB, R);
1918 R.optimizeGatherSequence();
1919 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1920 DEBUG(verifyFunction(F));
1925 void getAnalysisUsage(AnalysisUsage &AU) const override {
1926 FunctionPass::getAnalysisUsage(AU);
1927 AU.addRequired<ScalarEvolution>();
1928 AU.addRequired<AliasAnalysis>();
1929 AU.addRequired<TargetTransformInfo>();
1930 AU.addRequired<LoopInfo>();
1931 AU.addRequired<DominatorTreeWrapperPass>();
1932 AU.addPreserved<LoopInfo>();
1933 AU.addPreserved<DominatorTreeWrapperPass>();
1934 AU.setPreservesCFG();
1939 /// \brief Collect memory references and sort them according to their base
1940 /// object. We sort the stores to their base objects to reduce the cost of the
1941 /// quadratic search on the stores. TODO: We can further reduce this cost
1942 /// if we flush the chain creation every time we run into a memory barrier.
1943 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1945 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1946 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1948 /// \brief Try to vectorize a list of operands.
1949 /// \@param BuildVector A list of users to ignore for the purpose of
1950 /// scheduling and that don't need extracting.
1951 /// \returns true if a value was vectorized.
1952 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
1953 ArrayRef<Value *> BuildVector = None);
1955 /// \brief Try to vectorize a chain that may start at the operands of \V;
1956 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1958 /// \brief Vectorize the stores that were collected in StoreRefs.
1959 bool vectorizeStoreChains(BoUpSLP &R);
1961 /// \brief Scan the basic block and look for patterns that are likely to start
1962 /// a vectorization chain.
1963 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1965 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1968 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1971 StoreListMap StoreRefs;
1974 /// \brief Check that the Values in the slice in VL array are still existent in
1975 /// the WeakVH array.
1976 /// Vectorization of part of the VL array may cause later values in the VL array
1977 /// to become invalid. We track when this has happened in the WeakVH array.
1978 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
1979 SmallVectorImpl<WeakVH> &VH,
1980 unsigned SliceBegin,
1981 unsigned SliceSize) {
1982 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
1989 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1990 int CostThreshold, BoUpSLP &R) {
1991 unsigned ChainLen = Chain.size();
1992 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1994 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1995 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1996 unsigned VF = MinVecRegSize / Sz;
1998 if (!isPowerOf2_32(Sz) || VF < 2)
2001 // Keep track of values that were deleted by vectorizing in the loop below.
2002 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2004 bool Changed = false;
2005 // Look for profitable vectorizable trees at all offsets, starting at zero.
2006 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2010 // Check that a previous iteration of this loop did not delete the Value.
2011 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2014 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2016 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2018 R.buildTree(Operands);
2020 int Cost = R.getTreeCost();
2022 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2023 if (Cost < CostThreshold) {
2024 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2027 // Move to the next bundle.
2036 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2037 int costThreshold, BoUpSLP &R) {
2038 SetVector<Value *> Heads, Tails;
2039 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2041 // We may run into multiple chains that merge into a single chain. We mark the
2042 // stores that we vectorized so that we don't visit the same store twice.
2043 BoUpSLP::ValueSet VectorizedStores;
2044 bool Changed = false;
2046 // Do a quadratic search on all of the given stores and find
2047 // all of the pairs of stores that follow each other.
2048 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2049 for (unsigned j = 0; j < e; ++j) {
2053 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2054 Tails.insert(Stores[j]);
2055 Heads.insert(Stores[i]);
2056 ConsecutiveChain[Stores[i]] = Stores[j];
2061 // For stores that start but don't end a link in the chain:
2062 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2064 if (Tails.count(*it))
2067 // We found a store instr that starts a chain. Now follow the chain and try
2069 BoUpSLP::ValueList Operands;
2071 // Collect the chain into a list.
2072 while (Tails.count(I) || Heads.count(I)) {
2073 if (VectorizedStores.count(I))
2075 Operands.push_back(I);
2076 // Move to the next value in the chain.
2077 I = ConsecutiveChain[I];
2080 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2082 // Mark the vectorized stores so that we don't vectorize them again.
2084 VectorizedStores.insert(Operands.begin(), Operands.end());
2085 Changed |= Vectorized;
2092 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2095 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2096 StoreInst *SI = dyn_cast<StoreInst>(it);
2100 // Don't touch volatile stores.
2101 if (!SI->isSimple())
2104 // Check that the pointer points to scalars.
2105 Type *Ty = SI->getValueOperand()->getType();
2106 if (Ty->isAggregateType() || Ty->isVectorTy())
2109 // Find the base pointer.
2110 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2112 // Save the store locations.
2113 StoreRefs[Ptr].push_back(SI);
2119 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2122 Value *VL[] = { A, B };
2123 return tryToVectorizeList(VL, R);
2126 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2127 ArrayRef<Value *> BuildVector) {
2131 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2133 // Check that all of the parts are scalar instructions of the same type.
2134 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2138 unsigned Opcode0 = I0->getOpcode();
2140 Type *Ty0 = I0->getType();
2141 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2142 unsigned VF = MinVecRegSize / Sz;
2144 for (int i = 0, e = VL.size(); i < e; ++i) {
2145 Type *Ty = VL[i]->getType();
2146 if (Ty->isAggregateType() || Ty->isVectorTy())
2148 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2149 if (!Inst || Inst->getOpcode() != Opcode0)
2153 bool Changed = false;
2155 // Keep track of values that were delete by vectorizing in the loop below.
2156 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2158 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2159 unsigned OpsWidth = 0;
2166 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2169 // Check that a previous iteration of this loop did not delete the Value.
2170 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2173 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2175 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2177 ArrayRef<Value *> BuildVectorSlice;
2178 if (!BuildVector.empty())
2179 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2181 R.buildTree(Ops, BuildVectorSlice);
2182 int Cost = R.getTreeCost();
2184 if (Cost < -SLPCostThreshold) {
2185 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2186 Value *VectorizedRoot = R.vectorizeTree();
2188 // Reconstruct the build vector by extracting the vectorized root. This
2189 // way we handle the case where some elements of the vector are undefined.
2190 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2191 if (!BuildVectorSlice.empty()) {
2192 Instruction *InsertAfter = cast<Instruction>(VectorizedRoot);
2193 for (auto &V : BuildVectorSlice) {
2194 InsertElementInst *IE = cast<InsertElementInst>(V);
2195 IRBuilder<> Builder(++BasicBlock::iterator(InsertAfter));
2196 Instruction *Extract = cast<Instruction>(
2197 Builder.CreateExtractElement(VectorizedRoot, IE->getOperand(2)));
2198 IE->setOperand(1, Extract);
2199 IE->removeFromParent();
2200 IE->insertAfter(Extract);
2204 // Move to the next bundle.
2213 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2217 // Try to vectorize V.
2218 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2221 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2222 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2224 if (B && B->hasOneUse()) {
2225 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2226 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2227 if (tryToVectorizePair(A, B0, R)) {
2231 if (tryToVectorizePair(A, B1, R)) {
2238 if (A && A->hasOneUse()) {
2239 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2240 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2241 if (tryToVectorizePair(A0, B, R)) {
2245 if (tryToVectorizePair(A1, B, R)) {
2253 /// \brief Generate a shuffle mask to be used in a reduction tree.
2255 /// \param VecLen The length of the vector to be reduced.
2256 /// \param NumEltsToRdx The number of elements that should be reduced in the
2258 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2259 /// reduction. A pairwise reduction will generate a mask of
2260 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2261 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2262 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2263 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2264 bool IsPairwise, bool IsLeft,
2265 IRBuilder<> &Builder) {
2266 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2268 SmallVector<Constant *, 32> ShuffleMask(
2269 VecLen, UndefValue::get(Builder.getInt32Ty()));
2272 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2273 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2274 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2276 // Move the upper half of the vector to the lower half.
2277 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2278 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2280 return ConstantVector::get(ShuffleMask);
2284 /// Model horizontal reductions.
2286 /// A horizontal reduction is a tree of reduction operations (currently add and
2287 /// fadd) that has operations that can be put into a vector as its leaf.
2288 /// For example, this tree:
2295 /// This tree has "mul" as its reduced values and "+" as its reduction
2296 /// operations. A reduction might be feeding into a store or a binary operation
2311 class HorizontalReduction {
2312 SmallVector<Value *, 16> ReductionOps;
2313 SmallVector<Value *, 32> ReducedVals;
2315 BinaryOperator *ReductionRoot;
2316 PHINode *ReductionPHI;
2318 /// The opcode of the reduction.
2319 unsigned ReductionOpcode;
2320 /// The opcode of the values we perform a reduction on.
2321 unsigned ReducedValueOpcode;
2322 /// The width of one full horizontal reduction operation.
2323 unsigned ReduxWidth;
2324 /// Should we model this reduction as a pairwise reduction tree or a tree that
2325 /// splits the vector in halves and adds those halves.
2326 bool IsPairwiseReduction;
2329 HorizontalReduction()
2330 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2331 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2333 /// \brief Try to find a reduction tree.
2334 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2335 const DataLayout *DL) {
2337 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2338 "Thi phi needs to use the binary operator");
2340 // We could have a initial reductions that is not an add.
2341 // r *= v1 + v2 + v3 + v4
2342 // In such a case start looking for a tree rooted in the first '+'.
2344 if (B->getOperand(0) == Phi) {
2346 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2347 } else if (B->getOperand(1) == Phi) {
2349 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2356 Type *Ty = B->getType();
2357 if (Ty->isVectorTy())
2360 ReductionOpcode = B->getOpcode();
2361 ReducedValueOpcode = 0;
2362 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2369 // We currently only support adds.
2370 if (ReductionOpcode != Instruction::Add &&
2371 ReductionOpcode != Instruction::FAdd)
2374 // Post order traverse the reduction tree starting at B. We only handle true
2375 // trees containing only binary operators.
2376 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2377 Stack.push_back(std::make_pair(B, 0));
2378 while (!Stack.empty()) {
2379 BinaryOperator *TreeN = Stack.back().first;
2380 unsigned EdgeToVist = Stack.back().second++;
2381 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2383 // Only handle trees in the current basic block.
2384 if (TreeN->getParent() != B->getParent())
2387 // Each tree node needs to have one user except for the ultimate
2389 if (!TreeN->hasOneUse() && TreeN != B)
2393 if (EdgeToVist == 2 || IsReducedValue) {
2394 if (IsReducedValue) {
2395 // Make sure that the opcodes of the operations that we are going to
2397 if (!ReducedValueOpcode)
2398 ReducedValueOpcode = TreeN->getOpcode();
2399 else if (ReducedValueOpcode != TreeN->getOpcode())
2401 ReducedVals.push_back(TreeN);
2403 // We need to be able to reassociate the adds.
2404 if (!TreeN->isAssociative())
2406 ReductionOps.push_back(TreeN);
2413 // Visit left or right.
2414 Value *NextV = TreeN->getOperand(EdgeToVist);
2415 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2417 Stack.push_back(std::make_pair(Next, 0));
2418 else if (NextV != Phi)
2424 /// \brief Attempt to vectorize the tree found by
2425 /// matchAssociativeReduction.
2426 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2427 if (ReducedVals.empty())
2430 unsigned NumReducedVals = ReducedVals.size();
2431 if (NumReducedVals < ReduxWidth)
2434 Value *VectorizedTree = 0;
2435 IRBuilder<> Builder(ReductionRoot);
2436 FastMathFlags Unsafe;
2437 Unsafe.setUnsafeAlgebra();
2438 Builder.SetFastMathFlags(Unsafe);
2441 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2442 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2443 V.buildTree(ValsToReduce, ReductionOps);
2446 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2447 if (Cost >= -SLPCostThreshold)
2450 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2453 // Vectorize a tree.
2454 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2455 Value *VectorizedRoot = V.vectorizeTree();
2457 // Emit a reduction.
2458 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2459 if (VectorizedTree) {
2460 Builder.SetCurrentDebugLocation(Loc);
2461 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2462 ReducedSubTree, "bin.rdx");
2464 VectorizedTree = ReducedSubTree;
2467 if (VectorizedTree) {
2468 // Finish the reduction.
2469 for (; i < NumReducedVals; ++i) {
2470 Builder.SetCurrentDebugLocation(
2471 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2472 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2477 assert(ReductionRoot != NULL && "Need a reduction operation");
2478 ReductionRoot->setOperand(0, VectorizedTree);
2479 ReductionRoot->setOperand(1, ReductionPHI);
2481 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2483 return VectorizedTree != 0;
2488 /// \brief Calcuate the cost of a reduction.
2489 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2490 Type *ScalarTy = FirstReducedVal->getType();
2491 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2493 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2494 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2496 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2497 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2499 int ScalarReduxCost =
2500 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2502 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2503 << " for reduction that starts with " << *FirstReducedVal
2505 << (IsPairwiseReduction ? "pairwise" : "splitting")
2506 << " reduction)\n");
2508 return VecReduxCost - ScalarReduxCost;
2511 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2512 Value *R, const Twine &Name = "") {
2513 if (Opcode == Instruction::FAdd)
2514 return Builder.CreateFAdd(L, R, Name);
2515 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2518 /// \brief Emit a horizontal reduction of the vectorized value.
2519 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2520 assert(VectorizedValue && "Need to have a vectorized tree node");
2521 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2522 assert(isPowerOf2_32(ReduxWidth) &&
2523 "We only handle power-of-two reductions for now");
2525 Value *TmpVec = ValToReduce;
2526 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2527 if (IsPairwiseReduction) {
2529 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2531 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2533 Value *LeftShuf = Builder.CreateShuffleVector(
2534 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2535 Value *RightShuf = Builder.CreateShuffleVector(
2536 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2538 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2542 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2543 Value *Shuf = Builder.CreateShuffleVector(
2544 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2545 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2549 // The result is in the first element of the vector.
2550 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2554 /// \brief Recognize construction of vectors like
2555 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2556 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2557 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2558 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2560 /// Returns true if it matches
2562 static bool findBuildVector(InsertElementInst *FirstInsertElem,
2563 SmallVectorImpl<Value *> &BuildVector,
2564 SmallVectorImpl<Value *> &BuildVectorOpds) {
2565 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
2568 InsertElementInst *IE = FirstInsertElem;
2570 BuildVector.push_back(IE);
2571 BuildVectorOpds.push_back(IE->getOperand(1));
2573 if (IE->use_empty())
2576 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2580 // If this isn't the final use, make sure the next insertelement is the only
2581 // use. It's OK if the final constructed vector is used multiple times
2582 if (!IE->hasOneUse())
2591 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2592 return V->getType() < V2->getType();
2595 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2596 bool Changed = false;
2597 SmallVector<Value *, 4> Incoming;
2598 SmallSet<Value *, 16> VisitedInstrs;
2600 bool HaveVectorizedPhiNodes = true;
2601 while (HaveVectorizedPhiNodes) {
2602 HaveVectorizedPhiNodes = false;
2604 // Collect the incoming values from the PHIs.
2606 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2608 PHINode *P = dyn_cast<PHINode>(instr);
2612 if (!VisitedInstrs.count(P))
2613 Incoming.push_back(P);
2617 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2619 // Try to vectorize elements base on their type.
2620 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2624 // Look for the next elements with the same type.
2625 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2626 while (SameTypeIt != E &&
2627 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2628 VisitedInstrs.insert(*SameTypeIt);
2632 // Try to vectorize them.
2633 unsigned NumElts = (SameTypeIt - IncIt);
2634 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2636 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2637 // Success start over because instructions might have been changed.
2638 HaveVectorizedPhiNodes = true;
2643 // Start over at the next instruction of a different type (or the end).
2648 VisitedInstrs.clear();
2650 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2651 // We may go through BB multiple times so skip the one we have checked.
2652 if (!VisitedInstrs.insert(it))
2655 if (isa<DbgInfoIntrinsic>(it))
2658 // Try to vectorize reductions that use PHINodes.
2659 if (PHINode *P = dyn_cast<PHINode>(it)) {
2660 // Check that the PHI is a reduction PHI.
2661 if (P->getNumIncomingValues() != 2)
2664 (P->getIncomingBlock(0) == BB
2665 ? (P->getIncomingValue(0))
2666 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2667 // Check if this is a Binary Operator.
2668 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2672 // Try to match and vectorize a horizontal reduction.
2673 HorizontalReduction HorRdx;
2674 if (ShouldVectorizeHor &&
2675 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2676 HorRdx.tryToReduce(R, TTI)) {
2683 Value *Inst = BI->getOperand(0);
2685 Inst = BI->getOperand(1);
2687 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2688 // We would like to start over since some instructions are deleted
2689 // and the iterator may become invalid value.
2699 // Try to vectorize horizontal reductions feeding into a store.
2700 if (ShouldStartVectorizeHorAtStore)
2701 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2702 if (BinaryOperator *BinOp =
2703 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2704 HorizontalReduction HorRdx;
2705 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2706 HorRdx.tryToReduce(R, TTI)) ||
2707 tryToVectorize(BinOp, R))) {
2715 // Try to vectorize trees that start at compare instructions.
2716 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2717 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2719 // We would like to start over since some instructions are deleted
2720 // and the iterator may become invalid value.
2726 for (int i = 0; i < 2; ++i) {
2727 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2728 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2730 // We would like to start over since some instructions are deleted
2731 // and the iterator may become invalid value.
2740 // Try to vectorize trees that start at insertelement instructions.
2741 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
2742 SmallVector<Value *, 16> BuildVector;
2743 SmallVector<Value *, 16> BuildVectorOpds;
2744 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
2747 // Vectorize starting with the build vector operands ignoring the
2748 // BuildVector instructions for the purpose of scheduling and user
2750 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
2763 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2764 bool Changed = false;
2765 // Attempt to sort and vectorize each of the store-groups.
2766 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2768 if (it->second.size() < 2)
2771 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2772 << it->second.size() << ".\n");
2774 // Process the stores in chunks of 16.
2775 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2776 unsigned Len = std::min<unsigned>(CE - CI, 16);
2777 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2778 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2784 } // end anonymous namespace
2786 char SLPVectorizer::ID = 0;
2787 static const char lv_name[] = "SLP Vectorizer";
2788 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2789 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2790 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2791 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2792 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2793 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2796 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }