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/NoFolder.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/VectorUtils.h"
48 #define SV_NAME "slp-vectorizer"
49 #define DEBUG_TYPE "SLP"
52 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
53 cl::desc("Only vectorize if you gain more than this "
57 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
58 cl::desc("Attempt to vectorize horizontal reductions"));
60 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
61 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
63 "Attempt to vectorize horizontal reductions feeding into a store"));
67 static const unsigned MinVecRegSize = 128;
69 static const unsigned RecursionMaxDepth = 12;
71 /// A helper class for numbering instructions in multiple blocks.
72 /// Numbers start at zero for each basic block.
73 struct BlockNumbering {
75 BlockNumbering(BasicBlock *Bb) : BB(Bb), 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 Opcode that can be clubbed with \p Op to create an alternate
153 /// sequence which can later be merged as a ShuffleVector instruction.
154 static unsigned getAltOpcode(unsigned Op) {
156 case Instruction::FAdd:
157 return Instruction::FSub;
158 case Instruction::FSub:
159 return Instruction::FAdd;
160 case Instruction::Add:
161 return Instruction::Sub;
162 case Instruction::Sub:
163 return Instruction::Add;
169 ///\returns bool representing if Opcode \p Op can be part
170 /// of an alternate sequence which can later be merged as
171 /// a ShuffleVector instruction.
172 static bool canCombineAsAltInst(unsigned Op) {
173 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
174 Op == Instruction::Sub || Op == Instruction::Add)
179 /// \returns ShuffleVector instruction if intructions in \p VL have
180 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
181 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
182 static unsigned isAltInst(ArrayRef<Value *> VL) {
183 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
184 unsigned Opcode = I0->getOpcode();
185 unsigned AltOpcode = getAltOpcode(Opcode);
186 for (int i = 1, e = VL.size(); i < e; i++) {
187 Instruction *I = dyn_cast<Instruction>(VL[i]);
188 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
191 return Instruction::ShuffleVector;
194 /// \returns The opcode if all of the Instructions in \p VL have the same
196 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
197 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
200 unsigned Opcode = I0->getOpcode();
201 for (int i = 1, e = VL.size(); i < e; i++) {
202 Instruction *I = dyn_cast<Instruction>(VL[i]);
203 if (!I || Opcode != I->getOpcode()) {
204 if (canCombineAsAltInst(Opcode) && i == 1)
205 return isAltInst(VL);
212 /// \returns \p I after propagating metadata from \p VL.
213 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
214 Instruction *I0 = cast<Instruction>(VL[0]);
215 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
216 I0->getAllMetadataOtherThanDebugLoc(Metadata);
218 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
219 unsigned Kind = Metadata[i].first;
220 MDNode *MD = Metadata[i].second;
222 for (int i = 1, e = VL.size(); MD && i != e; i++) {
223 Instruction *I = cast<Instruction>(VL[i]);
224 MDNode *IMD = I->getMetadata(Kind);
228 MD = nullptr; // Remove unknown metadata
230 case LLVMContext::MD_tbaa:
231 MD = MDNode::getMostGenericTBAA(MD, IMD);
233 case LLVMContext::MD_alias_scope:
234 case LLVMContext::MD_noalias:
235 MD = MDNode::intersect(MD, IMD);
237 case LLVMContext::MD_fpmath:
238 MD = MDNode::getMostGenericFPMath(MD, IMD);
242 I->setMetadata(Kind, MD);
247 /// \returns The type that all of the values in \p VL have or null if there
248 /// are different types.
249 static Type* getSameType(ArrayRef<Value *> VL) {
250 Type *Ty = VL[0]->getType();
251 for (int i = 1, e = VL.size(); i < e; i++)
252 if (VL[i]->getType() != Ty)
258 /// \returns True if the ExtractElement instructions in VL can be vectorized
259 /// to use the original vector.
260 static bool CanReuseExtract(ArrayRef<Value *> VL) {
261 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
262 // Check if all of the extracts come from the same vector and from the
265 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
266 Value *Vec = E0->getOperand(0);
268 // We have to extract from the same vector type.
269 unsigned NElts = Vec->getType()->getVectorNumElements();
271 if (NElts != VL.size())
274 // Check that all of the indices extract from the correct offset.
275 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
276 if (!CI || CI->getZExtValue())
279 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
280 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
281 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
283 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
290 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
291 SmallVectorImpl<Value *> &Left,
292 SmallVectorImpl<Value *> &Right) {
294 SmallVector<Value *, 16> OrigLeft, OrigRight;
296 bool AllSameOpcodeLeft = true;
297 bool AllSameOpcodeRight = true;
298 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
299 Instruction *I = cast<Instruction>(VL[i]);
300 Value *V0 = I->getOperand(0);
301 Value *V1 = I->getOperand(1);
303 OrigLeft.push_back(V0);
304 OrigRight.push_back(V1);
306 Instruction *I0 = dyn_cast<Instruction>(V0);
307 Instruction *I1 = dyn_cast<Instruction>(V1);
309 // Check whether all operands on one side have the same opcode. In this case
310 // we want to preserve the original order and not make things worse by
312 AllSameOpcodeLeft = I0;
313 AllSameOpcodeRight = I1;
315 if (i && AllSameOpcodeLeft) {
316 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
317 if(P0->getOpcode() != I0->getOpcode())
318 AllSameOpcodeLeft = false;
320 AllSameOpcodeLeft = false;
322 if (i && AllSameOpcodeRight) {
323 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
324 if(P1->getOpcode() != I1->getOpcode())
325 AllSameOpcodeRight = false;
327 AllSameOpcodeRight = false;
330 // Sort two opcodes. In the code below we try to preserve the ability to use
331 // broadcast of values instead of individual inserts.
338 // If we just sorted according to opcode we would leave the first line in
339 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
342 // Because vr2 and vr1 are from the same load we loose the opportunity of a
343 // broadcast for the packed right side in the backend: we have [vr1, vl2]
344 // instead of [vr1, vr2=vr1].
346 if(!i && I0->getOpcode() > I1->getOpcode()) {
349 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
350 // Try not to destroy a broad cast for no apparent benefit.
353 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
354 // Try preserve broadcasts.
357 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
358 // Try preserve broadcasts.
367 // One opcode, put the instruction on the right.
377 bool LeftBroadcast = isSplat(Left);
378 bool RightBroadcast = isSplat(Right);
380 // Don't reorder if the operands where good to begin with.
381 if (!(LeftBroadcast || RightBroadcast) &&
382 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
388 /// Bottom Up SLP Vectorizer.
391 typedef SmallVector<Value *, 8> ValueList;
392 typedef SmallVector<Instruction *, 16> InstrList;
393 typedef SmallPtrSet<Value *, 16> ValueSet;
394 typedef SmallVector<StoreInst *, 8> StoreList;
396 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
397 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
398 LoopInfo *Li, DominatorTree *Dt)
399 : F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
400 Builder(Se->getContext()) {}
402 /// \brief Vectorize the tree that starts with the elements in \p VL.
403 /// Returns the vectorized root.
404 Value *vectorizeTree();
406 /// \returns the vectorization cost of the subtree that starts at \p VL.
407 /// A negative number means that this is profitable.
410 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
411 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
412 void buildTree(ArrayRef<Value *> Roots,
413 ArrayRef<Value *> UserIgnoreLst = None);
415 /// Clear the internal data structures that are created by 'buildTree'.
417 VectorizableTree.clear();
418 ScalarToTreeEntry.clear();
420 ExternalUses.clear();
421 MemBarrierIgnoreList.clear();
424 /// \returns true if the memory operations A and B are consecutive.
425 bool isConsecutiveAccess(Value *A, Value *B);
427 /// \brief Perform LICM and CSE on the newly generated gather sequences.
428 void optimizeGatherSequence();
430 /// \brief Get the instruction numbering for a given Instruction.
431 int getIndex(Instruction *I) {
432 BlockNumbering &BN = getBlockNumbering(I->getParent());
433 return BN.getIndex(I);
439 /// \returns the cost of the vectorizable entry.
440 int getEntryCost(TreeEntry *E);
442 /// This is the recursive part of buildTree.
443 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
445 /// Vectorize a single entry in the tree.
446 Value *vectorizeTree(TreeEntry *E);
448 /// Vectorize a single entry in the tree, starting in \p VL.
449 Value *vectorizeTree(ArrayRef<Value *> VL);
451 /// \returns the pointer to the vectorized value if \p VL is already
452 /// vectorized, or NULL. They may happen in cycles.
453 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
455 /// \brief Take the pointer operand from the Load/Store instruction.
456 /// \returns NULL if this is not a valid Load/Store instruction.
457 static Value *getPointerOperand(Value *I);
459 /// \brief Take the address space operand from the Load/Store instruction.
460 /// \returns -1 if this is not a valid Load/Store instruction.
461 static unsigned getAddressSpaceOperand(Value *I);
463 /// \returns the scalarization cost for this type. Scalarization in this
464 /// context means the creation of vectors from a group of scalars.
465 int getGatherCost(Type *Ty);
467 /// \returns the scalarization cost for this list of values. Assuming that
468 /// this subtree gets vectorized, we may need to extract the values from the
469 /// roots. This method calculates the cost of extracting the values.
470 int getGatherCost(ArrayRef<Value *> VL);
472 /// \returns the AA location that is being access by the instruction.
473 AliasAnalysis::Location getLocation(Instruction *I);
475 /// \brief Checks if it is possible to sink an instruction from
476 /// \p Src to \p Dst.
477 /// \returns the pointer to the barrier instruction if we can't sink.
478 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
480 /// \returns the index of the last instruction in the BB from \p VL.
481 int getLastIndex(ArrayRef<Value *> VL);
483 /// \returns the Instruction in the bundle \p VL.
484 Instruction *getLastInstruction(ArrayRef<Value *> VL);
486 /// \brief Set the Builder insert point to one after the last instruction in
488 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
490 /// \returns a vector from a collection of scalars in \p VL.
491 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
493 /// \returns whether the VectorizableTree is fully vectoriable and will
494 /// be beneficial even the tree height is tiny.
495 bool isFullyVectorizableTinyTree();
498 TreeEntry() : Scalars(), VectorizedValue(nullptr), LastScalarIndex(0),
501 /// \returns true if the scalars in VL are equal to this entry.
502 bool isSame(ArrayRef<Value *> VL) const {
503 assert(VL.size() == Scalars.size() && "Invalid size");
504 return std::equal(VL.begin(), VL.end(), Scalars.begin());
507 /// A vector of scalars.
510 /// The Scalars are vectorized into this value. It is initialized to Null.
511 Value *VectorizedValue;
513 /// The index in the basic block of the last scalar.
516 /// Do we need to gather this sequence ?
520 /// Create a new VectorizableTree entry.
521 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
522 VectorizableTree.push_back(TreeEntry());
523 int idx = VectorizableTree.size() - 1;
524 TreeEntry *Last = &VectorizableTree[idx];
525 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
526 Last->NeedToGather = !Vectorized;
528 Last->LastScalarIndex = getLastIndex(VL);
529 for (int i = 0, e = VL.size(); i != e; ++i) {
530 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
531 ScalarToTreeEntry[VL[i]] = idx;
534 Last->LastScalarIndex = 0;
535 MustGather.insert(VL.begin(), VL.end());
540 /// -- Vectorization State --
541 /// Holds all of the tree entries.
542 std::vector<TreeEntry> VectorizableTree;
544 /// Maps a specific scalar to its tree entry.
545 SmallDenseMap<Value*, int> ScalarToTreeEntry;
547 /// A list of scalars that we found that we need to keep as scalars.
550 /// This POD struct describes one external user in the vectorized tree.
551 struct ExternalUser {
552 ExternalUser (Value *S, llvm::User *U, int L) :
553 Scalar(S), User(U), Lane(L){};
554 // Which scalar in our function.
556 // Which user that uses the scalar.
558 // Which lane does the scalar belong to.
561 typedef SmallVector<ExternalUser, 16> UserList;
563 /// A list of values that need to extracted out of the tree.
564 /// This list holds pairs of (Internal Scalar : External User).
565 UserList ExternalUses;
567 /// A list of instructions to ignore while sinking
568 /// memory instructions. This map must be reset between runs of getCost.
569 ValueSet MemBarrierIgnoreList;
571 /// Holds all of the instructions that we gathered.
572 SetVector<Instruction *> GatherSeq;
573 /// A list of blocks that we are going to CSE.
574 SetVector<BasicBlock *> CSEBlocks;
576 /// Numbers instructions in different blocks.
577 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
579 /// \brief Get the corresponding instruction numbering list for a given
580 /// BasicBlock. The list is allocated lazily.
581 BlockNumbering &getBlockNumbering(BasicBlock *BB) {
582 auto I = BlocksNumbers.insert(std::make_pair(BB, BlockNumbering(BB)));
583 return I.first->second;
586 /// List of users to ignore during scheduling and that don't need extracting.
587 ArrayRef<Value *> UserIgnoreList;
589 // Analysis and block reference.
592 const DataLayout *DL;
593 TargetTransformInfo *TTI;
594 TargetLibraryInfo *TLI;
598 /// Instruction builder to construct the vectorized tree.
602 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
603 ArrayRef<Value *> UserIgnoreLst) {
605 UserIgnoreList = UserIgnoreLst;
606 if (!getSameType(Roots))
608 buildTree_rec(Roots, 0);
610 // Collect the values that we need to extract from the tree.
611 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
612 TreeEntry *Entry = &VectorizableTree[EIdx];
615 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
616 Value *Scalar = Entry->Scalars[Lane];
618 // No need to handle users of gathered values.
619 if (Entry->NeedToGather)
622 for (User *U : Scalar->users()) {
623 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
625 // Skip in-tree scalars that become vectors.
626 if (ScalarToTreeEntry.count(U)) {
627 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
629 int Idx = ScalarToTreeEntry[U]; (void) Idx;
630 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
633 Instruction *UserInst = dyn_cast<Instruction>(U);
637 // Ignore users in the user ignore list.
638 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
639 UserIgnoreList.end())
642 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
643 Lane << " from " << *Scalar << ".\n");
644 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
651 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
652 bool SameTy = getSameType(VL); (void)SameTy;
653 bool isAltShuffle = false;
654 assert(SameTy && "Invalid types!");
656 if (Depth == RecursionMaxDepth) {
657 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
658 newTreeEntry(VL, false);
662 // Don't handle vectors.
663 if (VL[0]->getType()->isVectorTy()) {
664 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
665 newTreeEntry(VL, false);
669 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
670 if (SI->getValueOperand()->getType()->isVectorTy()) {
671 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
672 newTreeEntry(VL, false);
675 unsigned Opcode = getSameOpcode(VL);
677 // Check that this shuffle vector refers to the alternate
678 // sequence of opcodes.
679 if (Opcode == Instruction::ShuffleVector) {
680 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
681 unsigned Op = I0->getOpcode();
682 if (Op != Instruction::ShuffleVector)
686 // If all of the operands are identical or constant we have a simple solution.
687 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
688 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
689 newTreeEntry(VL, false);
693 // We now know that this is a vector of instructions of the same type from
696 // Check if this is a duplicate of another entry.
697 if (ScalarToTreeEntry.count(VL[0])) {
698 int Idx = ScalarToTreeEntry[VL[0]];
699 TreeEntry *E = &VectorizableTree[Idx];
700 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
701 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
702 if (E->Scalars[i] != VL[i]) {
703 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
704 newTreeEntry(VL, false);
708 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
712 // Check that none of the instructions in the bundle are already in the tree.
713 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
714 if (ScalarToTreeEntry.count(VL[i])) {
715 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
716 ") is already in tree.\n");
717 newTreeEntry(VL, false);
722 // If any of the scalars appears in the table OR it is marked as a value that
723 // needs to stat scalar then we need to gather the scalars.
724 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
725 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
726 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
727 newTreeEntry(VL, false);
732 // Check that all of the users of the scalars that we want to vectorize are
734 Instruction *VL0 = cast<Instruction>(VL[0]);
735 int MyLastIndex = getLastIndex(VL);
736 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
738 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
739 Instruction *Scalar = cast<Instruction>(VL[i]);
740 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
741 for (User *U : Scalar->users()) {
742 DEBUG(dbgs() << "SLP: \tUser " << *U << ". \n");
743 Instruction *UI = dyn_cast<Instruction>(U);
745 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
746 newTreeEntry(VL, false);
750 // We don't care if the user is in a different basic block.
751 BasicBlock *UserBlock = UI->getParent();
752 if (UserBlock != BB) {
753 DEBUG(dbgs() << "SLP: User from a different basic block "
758 // If this is a PHINode within this basic block then we can place the
759 // extract wherever we want.
760 if (isa<PHINode>(*UI)) {
761 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *UI << ". \n");
765 // Check if this is a safe in-tree user.
766 if (ScalarToTreeEntry.count(UI)) {
767 int Idx = ScalarToTreeEntry[UI];
768 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
769 if (VecLocation <= MyLastIndex) {
770 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
771 newTreeEntry(VL, false);
774 DEBUG(dbgs() << "SLP: In-tree user (" << *UI << ") at #" <<
775 VecLocation << " vector value (" << *Scalar << ") at #"
776 << MyLastIndex << ".\n");
780 // Ignore users in the user ignore list.
781 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UI) !=
782 UserIgnoreList.end())
785 // Make sure that we can schedule this unknown user.
786 BlockNumbering &BN = getBlockNumbering(BB);
787 int UserIndex = BN.getIndex(UI);
788 if (UserIndex < MyLastIndex) {
790 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
792 newTreeEntry(VL, false);
798 // Check that every instructions appears once in this bundle.
799 for (unsigned i = 0, e = VL.size(); i < e; ++i)
800 for (unsigned j = i+1; j < e; ++j)
801 if (VL[i] == VL[j]) {
802 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
803 newTreeEntry(VL, false);
807 // Check that instructions in this bundle don't reference other instructions.
808 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
809 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
810 for (User *U : VL[i]->users()) {
811 for (unsigned j = 0; j < e; ++j) {
812 if (i != j && U == VL[j]) {
813 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << *U << ". \n");
814 newTreeEntry(VL, false);
821 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
823 // Check if it is safe to sink the loads or the stores.
824 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
825 Instruction *Last = getLastInstruction(VL);
827 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
830 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
832 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
833 << "\n because of " << *Barrier << ". Gathering.\n");
834 newTreeEntry(VL, false);
841 case Instruction::PHI: {
842 PHINode *PH = dyn_cast<PHINode>(VL0);
844 // Check for terminator values (e.g. invoke).
845 for (unsigned j = 0; j < VL.size(); ++j)
846 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
847 TerminatorInst *Term = dyn_cast<TerminatorInst>(
848 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
850 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
851 newTreeEntry(VL, false);
856 newTreeEntry(VL, true);
857 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
859 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
861 // Prepare the operand vector.
862 for (unsigned j = 0; j < VL.size(); ++j)
863 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
864 PH->getIncomingBlock(i)));
866 buildTree_rec(Operands, Depth + 1);
870 case Instruction::ExtractElement: {
871 bool Reuse = CanReuseExtract(VL);
873 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
875 newTreeEntry(VL, Reuse);
878 case Instruction::Load: {
879 // Check if the loads are consecutive or of we need to swizzle them.
880 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
881 LoadInst *L = cast<LoadInst>(VL[i]);
882 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
883 newTreeEntry(VL, false);
884 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
888 newTreeEntry(VL, true);
889 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
892 case Instruction::ZExt:
893 case Instruction::SExt:
894 case Instruction::FPToUI:
895 case Instruction::FPToSI:
896 case Instruction::FPExt:
897 case Instruction::PtrToInt:
898 case Instruction::IntToPtr:
899 case Instruction::SIToFP:
900 case Instruction::UIToFP:
901 case Instruction::Trunc:
902 case Instruction::FPTrunc:
903 case Instruction::BitCast: {
904 Type *SrcTy = VL0->getOperand(0)->getType();
905 for (unsigned i = 0; i < VL.size(); ++i) {
906 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
907 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
908 newTreeEntry(VL, false);
909 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
913 newTreeEntry(VL, true);
914 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
916 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
918 // Prepare the operand vector.
919 for (unsigned j = 0; j < VL.size(); ++j)
920 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
922 buildTree_rec(Operands, Depth+1);
926 case Instruction::ICmp:
927 case Instruction::FCmp: {
928 // Check that all of the compares have the same predicate.
929 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
930 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
931 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
932 CmpInst *Cmp = cast<CmpInst>(VL[i]);
933 if (Cmp->getPredicate() != P0 ||
934 Cmp->getOperand(0)->getType() != ComparedTy) {
935 newTreeEntry(VL, false);
936 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
941 newTreeEntry(VL, true);
942 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
944 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
946 // Prepare the operand vector.
947 for (unsigned j = 0; j < VL.size(); ++j)
948 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
950 buildTree_rec(Operands, Depth+1);
954 case Instruction::Select:
955 case Instruction::Add:
956 case Instruction::FAdd:
957 case Instruction::Sub:
958 case Instruction::FSub:
959 case Instruction::Mul:
960 case Instruction::FMul:
961 case Instruction::UDiv:
962 case Instruction::SDiv:
963 case Instruction::FDiv:
964 case Instruction::URem:
965 case Instruction::SRem:
966 case Instruction::FRem:
967 case Instruction::Shl:
968 case Instruction::LShr:
969 case Instruction::AShr:
970 case Instruction::And:
971 case Instruction::Or:
972 case Instruction::Xor: {
973 newTreeEntry(VL, true);
974 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
976 // Sort operands of the instructions so that each side is more likely to
977 // have the same opcode.
978 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
979 ValueList Left, Right;
980 reorderInputsAccordingToOpcode(VL, Left, Right);
981 BasicBlock *LeftBB = getSameBlock(Left);
982 BasicBlock *RightBB = getSameBlock(Right);
983 // If we have common uses on separate paths in the tree make sure we
984 // process the one with greater common depth first.
985 // We can use block numbering to determine the subtree traversal as
986 // earler user has to come in between the common use and the later user.
987 if (LeftBB && RightBB && LeftBB == RightBB &&
988 getLastIndex(Right) > getLastIndex(Left)) {
989 buildTree_rec(Right, Depth + 1);
990 buildTree_rec(Left, Depth + 1);
992 buildTree_rec(Left, Depth + 1);
993 buildTree_rec(Right, Depth + 1);
998 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1000 // Prepare the operand vector.
1001 for (unsigned j = 0; j < VL.size(); ++j)
1002 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1004 buildTree_rec(Operands, Depth+1);
1008 case Instruction::GetElementPtr: {
1009 // We don't combine GEPs with complicated (nested) indexing.
1010 for (unsigned j = 0; j < VL.size(); ++j) {
1011 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1012 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1013 newTreeEntry(VL, false);
1018 // We can't combine several GEPs into one vector if they operate on
1020 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1021 for (unsigned j = 0; j < VL.size(); ++j) {
1022 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1024 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1025 newTreeEntry(VL, false);
1030 // We don't combine GEPs with non-constant indexes.
1031 for (unsigned j = 0; j < VL.size(); ++j) {
1032 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1033 if (!isa<ConstantInt>(Op)) {
1035 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1036 newTreeEntry(VL, false);
1041 newTreeEntry(VL, true);
1042 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1043 for (unsigned i = 0, e = 2; i < e; ++i) {
1045 // Prepare the operand vector.
1046 for (unsigned j = 0; j < VL.size(); ++j)
1047 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1049 buildTree_rec(Operands, Depth + 1);
1053 case Instruction::Store: {
1054 // Check if the stores are consecutive or of we need to swizzle them.
1055 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1056 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1057 newTreeEntry(VL, false);
1058 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1062 newTreeEntry(VL, true);
1063 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1066 for (unsigned j = 0; j < VL.size(); ++j)
1067 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1069 // We can ignore these values because we are sinking them down.
1070 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
1071 buildTree_rec(Operands, Depth + 1);
1074 case Instruction::Call: {
1075 // Check if the calls are all to the same vectorizable intrinsic.
1076 CallInst *CI = cast<CallInst>(VL[0]);
1077 // Check if this is an Intrinsic call or something that can be
1078 // represented by an intrinsic call
1079 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1080 if (!isTriviallyVectorizable(ID)) {
1081 newTreeEntry(VL, false);
1082 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1085 Function *Int = CI->getCalledFunction();
1086 Value *A1I = nullptr;
1087 if (hasVectorInstrinsicScalarOpd(ID, 1))
1088 A1I = CI->getArgOperand(1);
1089 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1090 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1091 if (!CI2 || CI2->getCalledFunction() != Int ||
1092 getIntrinsicIDForCall(CI2, TLI) != ID) {
1093 newTreeEntry(VL, false);
1094 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1098 // ctlz,cttz and powi are special intrinsics whose second argument
1099 // should be same in order for them to be vectorized.
1100 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1101 Value *A1J = CI2->getArgOperand(1);
1103 newTreeEntry(VL, false);
1104 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1105 << " argument "<< A1I<<"!=" << A1J
1112 newTreeEntry(VL, true);
1113 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1115 // Prepare the operand vector.
1116 for (unsigned j = 0; j < VL.size(); ++j) {
1117 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1118 Operands.push_back(CI2->getArgOperand(i));
1120 buildTree_rec(Operands, Depth + 1);
1124 case Instruction::ShuffleVector: {
1125 // If this is not an alternate sequence of opcode like add-sub
1126 // then do not vectorize this instruction.
1127 if (!isAltShuffle) {
1128 newTreeEntry(VL, false);
1129 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1132 newTreeEntry(VL, true);
1133 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1134 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1136 // Prepare the operand vector.
1137 for (unsigned j = 0; j < VL.size(); ++j)
1138 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1140 buildTree_rec(Operands, Depth + 1);
1145 newTreeEntry(VL, false);
1146 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1151 int BoUpSLP::getEntryCost(TreeEntry *E) {
1152 ArrayRef<Value*> VL = E->Scalars;
1154 Type *ScalarTy = VL[0]->getType();
1155 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1156 ScalarTy = SI->getValueOperand()->getType();
1157 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1159 if (E->NeedToGather) {
1160 if (allConstant(VL))
1163 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1165 return getGatherCost(E->Scalars);
1167 unsigned Opcode = getSameOpcode(VL);
1168 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1169 Instruction *VL0 = cast<Instruction>(VL[0]);
1171 case Instruction::PHI: {
1174 case Instruction::ExtractElement: {
1175 if (CanReuseExtract(VL)) {
1177 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1178 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1180 // Take credit for instruction that will become dead.
1182 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1186 return getGatherCost(VecTy);
1188 case Instruction::ZExt:
1189 case Instruction::SExt:
1190 case Instruction::FPToUI:
1191 case Instruction::FPToSI:
1192 case Instruction::FPExt:
1193 case Instruction::PtrToInt:
1194 case Instruction::IntToPtr:
1195 case Instruction::SIToFP:
1196 case Instruction::UIToFP:
1197 case Instruction::Trunc:
1198 case Instruction::FPTrunc:
1199 case Instruction::BitCast: {
1200 Type *SrcTy = VL0->getOperand(0)->getType();
1202 // Calculate the cost of this instruction.
1203 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1204 VL0->getType(), SrcTy);
1206 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1207 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1208 return VecCost - ScalarCost;
1210 case Instruction::FCmp:
1211 case Instruction::ICmp:
1212 case Instruction::Select:
1213 case Instruction::Add:
1214 case Instruction::FAdd:
1215 case Instruction::Sub:
1216 case Instruction::FSub:
1217 case Instruction::Mul:
1218 case Instruction::FMul:
1219 case Instruction::UDiv:
1220 case Instruction::SDiv:
1221 case Instruction::FDiv:
1222 case Instruction::URem:
1223 case Instruction::SRem:
1224 case Instruction::FRem:
1225 case Instruction::Shl:
1226 case Instruction::LShr:
1227 case Instruction::AShr:
1228 case Instruction::And:
1229 case Instruction::Or:
1230 case Instruction::Xor: {
1231 // Calculate the cost of this instruction.
1234 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1235 Opcode == Instruction::Select) {
1236 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1237 ScalarCost = VecTy->getNumElements() *
1238 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1239 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1241 // Certain instructions can be cheaper to vectorize if they have a
1242 // constant second vector operand.
1243 TargetTransformInfo::OperandValueKind Op1VK =
1244 TargetTransformInfo::OK_AnyValue;
1245 TargetTransformInfo::OperandValueKind Op2VK =
1246 TargetTransformInfo::OK_UniformConstantValue;
1248 // If all operands are exactly the same ConstantInt then set the
1249 // operand kind to OK_UniformConstantValue.
1250 // If instead not all operands are constants, then set the operand kind
1251 // to OK_AnyValue. If all operands are constants but not the same,
1252 // then set the operand kind to OK_NonUniformConstantValue.
1253 ConstantInt *CInt = nullptr;
1254 for (unsigned i = 0; i < VL.size(); ++i) {
1255 const Instruction *I = cast<Instruction>(VL[i]);
1256 if (!isa<ConstantInt>(I->getOperand(1))) {
1257 Op2VK = TargetTransformInfo::OK_AnyValue;
1261 CInt = cast<ConstantInt>(I->getOperand(1));
1264 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1265 CInt != cast<ConstantInt>(I->getOperand(1)))
1266 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1270 VecTy->getNumElements() *
1271 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1272 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1274 return VecCost - ScalarCost;
1276 case Instruction::GetElementPtr: {
1277 TargetTransformInfo::OperandValueKind Op1VK =
1278 TargetTransformInfo::OK_AnyValue;
1279 TargetTransformInfo::OperandValueKind Op2VK =
1280 TargetTransformInfo::OK_UniformConstantValue;
1283 VecTy->getNumElements() *
1284 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1286 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1288 return VecCost - ScalarCost;
1290 case Instruction::Load: {
1291 // Cost of wide load - cost of scalar loads.
1292 int ScalarLdCost = VecTy->getNumElements() *
1293 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1294 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1295 return VecLdCost - ScalarLdCost;
1297 case Instruction::Store: {
1298 // We know that we can merge the stores. Calculate the cost.
1299 int ScalarStCost = VecTy->getNumElements() *
1300 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1301 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1302 return VecStCost - ScalarStCost;
1304 case Instruction::Call: {
1305 CallInst *CI = cast<CallInst>(VL0);
1306 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1308 // Calculate the cost of the scalar and vector calls.
1309 SmallVector<Type*, 4> ScalarTys, VecTys;
1310 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1311 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1312 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1313 VecTy->getNumElements()));
1316 int ScalarCallCost = VecTy->getNumElements() *
1317 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1319 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1321 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1322 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1323 << " for " << *CI << "\n");
1325 return VecCallCost - ScalarCallCost;
1327 case Instruction::ShuffleVector: {
1328 TargetTransformInfo::OperandValueKind Op1VK =
1329 TargetTransformInfo::OK_AnyValue;
1330 TargetTransformInfo::OperandValueKind Op2VK =
1331 TargetTransformInfo::OK_AnyValue;
1334 for (unsigned i = 0; i < VL.size(); ++i) {
1335 Instruction *I = cast<Instruction>(VL[i]);
1339 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1341 // VecCost is equal to sum of the cost of creating 2 vectors
1342 // and the cost of creating shuffle.
1343 Instruction *I0 = cast<Instruction>(VL[0]);
1345 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1346 Instruction *I1 = cast<Instruction>(VL[1]);
1348 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1350 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1351 return VecCost - ScalarCost;
1354 llvm_unreachable("Unknown instruction");
1358 bool BoUpSLP::isFullyVectorizableTinyTree() {
1359 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1360 VectorizableTree.size() << " is fully vectorizable .\n");
1362 // We only handle trees of height 2.
1363 if (VectorizableTree.size() != 2)
1366 // Handle splat stores.
1367 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1370 // Gathering cost would be too much for tiny trees.
1371 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1377 int BoUpSLP::getTreeCost() {
1379 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1380 VectorizableTree.size() << ".\n");
1382 // We only vectorize tiny trees if it is fully vectorizable.
1383 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1384 if (!VectorizableTree.size()) {
1385 assert(!ExternalUses.size() && "We should not have any external users");
1390 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1392 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1393 int C = getEntryCost(&VectorizableTree[i]);
1394 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1395 << *VectorizableTree[i].Scalars[0] << " .\n");
1399 SmallSet<Value *, 16> ExtractCostCalculated;
1400 int ExtractCost = 0;
1401 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1403 // We only add extract cost once for the same scalar.
1404 if (!ExtractCostCalculated.insert(I->Scalar))
1407 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1408 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1412 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1413 return Cost + ExtractCost;
1416 int BoUpSLP::getGatherCost(Type *Ty) {
1418 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1419 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1423 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1424 // Find the type of the operands in VL.
1425 Type *ScalarTy = VL[0]->getType();
1426 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1427 ScalarTy = SI->getValueOperand()->getType();
1428 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1429 // Find the cost of inserting/extracting values from the vector.
1430 return getGatherCost(VecTy);
1433 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1434 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1435 return AA->getLocation(SI);
1436 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1437 return AA->getLocation(LI);
1438 return AliasAnalysis::Location();
1441 Value *BoUpSLP::getPointerOperand(Value *I) {
1442 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1443 return LI->getPointerOperand();
1444 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1445 return SI->getPointerOperand();
1449 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1450 if (LoadInst *L = dyn_cast<LoadInst>(I))
1451 return L->getPointerAddressSpace();
1452 if (StoreInst *S = dyn_cast<StoreInst>(I))
1453 return S->getPointerAddressSpace();
1457 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1458 Value *PtrA = getPointerOperand(A);
1459 Value *PtrB = getPointerOperand(B);
1460 unsigned ASA = getAddressSpaceOperand(A);
1461 unsigned ASB = getAddressSpaceOperand(B);
1463 // Check that the address spaces match and that the pointers are valid.
1464 if (!PtrA || !PtrB || (ASA != ASB))
1467 // Make sure that A and B are different pointers of the same type.
1468 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1471 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1472 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1473 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1475 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1476 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1477 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1479 APInt OffsetDelta = OffsetB - OffsetA;
1481 // Check if they are based on the same pointer. That makes the offsets
1484 return OffsetDelta == Size;
1486 // Compute the necessary base pointer delta to have the necessary final delta
1487 // equal to the size.
1488 APInt BaseDelta = Size - OffsetDelta;
1490 // Otherwise compute the distance with SCEV between the base pointers.
1491 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1492 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1493 const SCEV *C = SE->getConstant(BaseDelta);
1494 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1495 return X == PtrSCEVB;
1498 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1499 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1500 BasicBlock::iterator I = Src, E = Dst;
1501 /// Scan all of the instruction from SRC to DST and check if
1502 /// the source may alias.
1503 for (++I; I != E; ++I) {
1504 // Ignore store instructions that are marked as 'ignore'.
1505 if (MemBarrierIgnoreList.count(I))
1507 if (Src->mayWriteToMemory()) /* Write */ {
1508 if (!I->mayReadOrWriteMemory())
1511 if (!I->mayWriteToMemory())
1514 AliasAnalysis::Location A = getLocation(&*I);
1515 AliasAnalysis::Location B = getLocation(Src);
1517 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1523 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1524 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1525 assert(BB == getSameBlock(VL) && "Invalid block");
1526 BlockNumbering &BN = getBlockNumbering(BB);
1528 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1529 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1530 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1534 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1535 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1536 assert(BB == getSameBlock(VL) && "Invalid block");
1537 BlockNumbering &BN = getBlockNumbering(BB);
1539 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1540 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1541 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1542 Instruction *I = BN.getInstruction(MaxIdx);
1543 assert(I && "bad location");
1547 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1548 Instruction *VL0 = cast<Instruction>(VL[0]);
1549 Instruction *LastInst = getLastInstruction(VL);
1550 BasicBlock::iterator NextInst = LastInst;
1552 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1553 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1556 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1557 Value *Vec = UndefValue::get(Ty);
1558 // Generate the 'InsertElement' instruction.
1559 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1560 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1561 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1562 GatherSeq.insert(Insrt);
1563 CSEBlocks.insert(Insrt->getParent());
1565 // Add to our 'need-to-extract' list.
1566 if (ScalarToTreeEntry.count(VL[i])) {
1567 int Idx = ScalarToTreeEntry[VL[i]];
1568 TreeEntry *E = &VectorizableTree[Idx];
1569 // Find which lane we need to extract.
1571 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1572 // Is this the lane of the scalar that we are looking for ?
1573 if (E->Scalars[Lane] == VL[i]) {
1578 assert(FoundLane >= 0 && "Could not find the correct lane");
1579 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1587 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1588 SmallDenseMap<Value*, int>::const_iterator Entry
1589 = ScalarToTreeEntry.find(VL[0]);
1590 if (Entry != ScalarToTreeEntry.end()) {
1591 int Idx = Entry->second;
1592 const TreeEntry *En = &VectorizableTree[Idx];
1593 if (En->isSame(VL) && En->VectorizedValue)
1594 return En->VectorizedValue;
1599 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1600 if (ScalarToTreeEntry.count(VL[0])) {
1601 int Idx = ScalarToTreeEntry[VL[0]];
1602 TreeEntry *E = &VectorizableTree[Idx];
1604 return vectorizeTree(E);
1607 Type *ScalarTy = VL[0]->getType();
1608 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1609 ScalarTy = SI->getValueOperand()->getType();
1610 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1612 return Gather(VL, VecTy);
1615 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1616 IRBuilder<>::InsertPointGuard Guard(Builder);
1618 if (E->VectorizedValue) {
1619 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1620 return E->VectorizedValue;
1623 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1624 Type *ScalarTy = VL0->getType();
1625 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1626 ScalarTy = SI->getValueOperand()->getType();
1627 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1629 if (E->NeedToGather) {
1630 setInsertPointAfterBundle(E->Scalars);
1631 return Gather(E->Scalars, VecTy);
1633 unsigned Opcode = getSameOpcode(E->Scalars);
1636 case Instruction::PHI: {
1637 PHINode *PH = dyn_cast<PHINode>(VL0);
1638 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1639 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1640 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1641 E->VectorizedValue = NewPhi;
1643 // PHINodes may have multiple entries from the same block. We want to
1644 // visit every block once.
1645 SmallSet<BasicBlock*, 4> VisitedBBs;
1647 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1649 BasicBlock *IBB = PH->getIncomingBlock(i);
1651 if (!VisitedBBs.insert(IBB)) {
1652 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1656 // Prepare the operand vector.
1657 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1658 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1659 getIncomingValueForBlock(IBB));
1661 Builder.SetInsertPoint(IBB->getTerminator());
1662 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1663 Value *Vec = vectorizeTree(Operands);
1664 NewPhi->addIncoming(Vec, IBB);
1667 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1668 "Invalid number of incoming values");
1672 case Instruction::ExtractElement: {
1673 if (CanReuseExtract(E->Scalars)) {
1674 Value *V = VL0->getOperand(0);
1675 E->VectorizedValue = V;
1678 return Gather(E->Scalars, VecTy);
1680 case Instruction::ZExt:
1681 case Instruction::SExt:
1682 case Instruction::FPToUI:
1683 case Instruction::FPToSI:
1684 case Instruction::FPExt:
1685 case Instruction::PtrToInt:
1686 case Instruction::IntToPtr:
1687 case Instruction::SIToFP:
1688 case Instruction::UIToFP:
1689 case Instruction::Trunc:
1690 case Instruction::FPTrunc:
1691 case Instruction::BitCast: {
1693 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1694 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1696 setInsertPointAfterBundle(E->Scalars);
1698 Value *InVec = vectorizeTree(INVL);
1700 if (Value *V = alreadyVectorized(E->Scalars))
1703 CastInst *CI = dyn_cast<CastInst>(VL0);
1704 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1705 E->VectorizedValue = V;
1708 case Instruction::FCmp:
1709 case Instruction::ICmp: {
1710 ValueList LHSV, RHSV;
1711 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1712 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1713 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1716 setInsertPointAfterBundle(E->Scalars);
1718 Value *L = vectorizeTree(LHSV);
1719 Value *R = vectorizeTree(RHSV);
1721 if (Value *V = alreadyVectorized(E->Scalars))
1724 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1726 if (Opcode == Instruction::FCmp)
1727 V = Builder.CreateFCmp(P0, L, R);
1729 V = Builder.CreateICmp(P0, L, R);
1731 E->VectorizedValue = V;
1734 case Instruction::Select: {
1735 ValueList TrueVec, FalseVec, CondVec;
1736 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1737 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1738 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1739 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1742 setInsertPointAfterBundle(E->Scalars);
1744 Value *Cond = vectorizeTree(CondVec);
1745 Value *True = vectorizeTree(TrueVec);
1746 Value *False = vectorizeTree(FalseVec);
1748 if (Value *V = alreadyVectorized(E->Scalars))
1751 Value *V = Builder.CreateSelect(Cond, True, False);
1752 E->VectorizedValue = V;
1755 case Instruction::Add:
1756 case Instruction::FAdd:
1757 case Instruction::Sub:
1758 case Instruction::FSub:
1759 case Instruction::Mul:
1760 case Instruction::FMul:
1761 case Instruction::UDiv:
1762 case Instruction::SDiv:
1763 case Instruction::FDiv:
1764 case Instruction::URem:
1765 case Instruction::SRem:
1766 case Instruction::FRem:
1767 case Instruction::Shl:
1768 case Instruction::LShr:
1769 case Instruction::AShr:
1770 case Instruction::And:
1771 case Instruction::Or:
1772 case Instruction::Xor: {
1773 ValueList LHSVL, RHSVL;
1774 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1775 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1777 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1778 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1779 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1782 setInsertPointAfterBundle(E->Scalars);
1784 Value *LHS = vectorizeTree(LHSVL);
1785 Value *RHS = vectorizeTree(RHSVL);
1787 if (LHS == RHS && isa<Instruction>(LHS)) {
1788 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1791 if (Value *V = alreadyVectorized(E->Scalars))
1794 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1795 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1796 E->VectorizedValue = V;
1798 if (Instruction *I = dyn_cast<Instruction>(V))
1799 return propagateMetadata(I, E->Scalars);
1803 case Instruction::Load: {
1804 // Loads are inserted at the head of the tree because we don't want to
1805 // sink them all the way down past store instructions.
1806 setInsertPointAfterBundle(E->Scalars);
1808 LoadInst *LI = cast<LoadInst>(VL0);
1809 unsigned AS = LI->getPointerAddressSpace();
1811 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1812 VecTy->getPointerTo(AS));
1813 unsigned Alignment = LI->getAlignment();
1814 LI = Builder.CreateLoad(VecPtr);
1816 Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
1817 LI->setAlignment(Alignment);
1818 E->VectorizedValue = LI;
1819 return propagateMetadata(LI, E->Scalars);
1821 case Instruction::Store: {
1822 StoreInst *SI = cast<StoreInst>(VL0);
1823 unsigned Alignment = SI->getAlignment();
1824 unsigned AS = SI->getPointerAddressSpace();
1827 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1828 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1830 setInsertPointAfterBundle(E->Scalars);
1832 Value *VecValue = vectorizeTree(ValueOp);
1833 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1834 VecTy->getPointerTo(AS));
1835 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1837 Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
1838 S->setAlignment(Alignment);
1839 E->VectorizedValue = S;
1840 return propagateMetadata(S, E->Scalars);
1842 case Instruction::GetElementPtr: {
1843 setInsertPointAfterBundle(E->Scalars);
1846 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1847 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
1849 Value *Op0 = vectorizeTree(Op0VL);
1851 std::vector<Value *> OpVecs;
1852 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
1855 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1856 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
1858 Value *OpVec = vectorizeTree(OpVL);
1859 OpVecs.push_back(OpVec);
1862 Value *V = Builder.CreateGEP(Op0, OpVecs);
1863 E->VectorizedValue = V;
1865 if (Instruction *I = dyn_cast<Instruction>(V))
1866 return propagateMetadata(I, E->Scalars);
1870 case Instruction::Call: {
1871 CallInst *CI = cast<CallInst>(VL0);
1872 setInsertPointAfterBundle(E->Scalars);
1874 Intrinsic::ID IID = Intrinsic::not_intrinsic;
1875 if (CI && (FI = CI->getCalledFunction())) {
1876 IID = (Intrinsic::ID) FI->getIntrinsicID();
1878 std::vector<Value *> OpVecs;
1879 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1881 // ctlz,cttz and powi are special intrinsics whose second argument is
1882 // a scalar. This argument should not be vectorized.
1883 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
1884 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
1885 OpVecs.push_back(CEI->getArgOperand(j));
1888 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1889 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1890 OpVL.push_back(CEI->getArgOperand(j));
1893 Value *OpVec = vectorizeTree(OpVL);
1894 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1895 OpVecs.push_back(OpVec);
1898 Module *M = F->getParent();
1899 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1900 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1901 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1902 Value *V = Builder.CreateCall(CF, OpVecs);
1903 E->VectorizedValue = V;
1906 case Instruction::ShuffleVector: {
1907 ValueList LHSVL, RHSVL;
1908 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1909 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1910 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1912 setInsertPointAfterBundle(E->Scalars);
1914 Value *LHS = vectorizeTree(LHSVL);
1915 Value *RHS = vectorizeTree(RHSVL);
1917 if (Value *V = alreadyVectorized(E->Scalars))
1920 // Create a vector of LHS op1 RHS
1921 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
1922 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
1924 // Create a vector of LHS op2 RHS
1925 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
1926 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
1927 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
1929 // Create appropriate shuffle to take alternative operations from
1931 std::vector<Constant *> Mask(E->Scalars.size());
1932 unsigned e = E->Scalars.size();
1933 for (unsigned i = 0; i < e; ++i) {
1935 Mask[i] = Builder.getInt32(e + i);
1937 Mask[i] = Builder.getInt32(i);
1940 Value *ShuffleMask = ConstantVector::get(Mask);
1942 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
1943 E->VectorizedValue = V;
1944 if (Instruction *I = dyn_cast<Instruction>(V))
1945 return propagateMetadata(I, E->Scalars);
1950 llvm_unreachable("unknown inst");
1955 Value *BoUpSLP::vectorizeTree() {
1956 Builder.SetInsertPoint(F->getEntryBlock().begin());
1957 vectorizeTree(&VectorizableTree[0]);
1959 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1961 // Extract all of the elements with the external uses.
1962 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1964 Value *Scalar = it->Scalar;
1965 llvm::User *User = it->User;
1967 // Skip users that we already RAUW. This happens when one instruction
1968 // has multiple uses of the same value.
1969 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
1972 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1974 int Idx = ScalarToTreeEntry[Scalar];
1975 TreeEntry *E = &VectorizableTree[Idx];
1976 assert(!E->NeedToGather && "Extracting from a gather list");
1978 Value *Vec = E->VectorizedValue;
1979 assert(Vec && "Can't find vectorizable value");
1981 Value *Lane = Builder.getInt32(it->Lane);
1982 // Generate extracts for out-of-tree users.
1983 // Find the insertion point for the extractelement lane.
1984 if (isa<Instruction>(Vec)){
1985 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1986 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1987 if (PH->getIncomingValue(i) == Scalar) {
1988 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1989 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1990 CSEBlocks.insert(PH->getIncomingBlock(i));
1991 PH->setOperand(i, Ex);
1995 Builder.SetInsertPoint(cast<Instruction>(User));
1996 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1997 CSEBlocks.insert(cast<Instruction>(User)->getParent());
1998 User->replaceUsesOfWith(Scalar, Ex);
2001 Builder.SetInsertPoint(F->getEntryBlock().begin());
2002 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2003 CSEBlocks.insert(&F->getEntryBlock());
2004 User->replaceUsesOfWith(Scalar, Ex);
2007 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2010 // For each vectorized value:
2011 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2012 TreeEntry *Entry = &VectorizableTree[EIdx];
2015 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2016 Value *Scalar = Entry->Scalars[Lane];
2017 // No need to handle users of gathered values.
2018 if (Entry->NeedToGather)
2021 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2023 Type *Ty = Scalar->getType();
2024 if (!Ty->isVoidTy()) {
2026 for (User *U : Scalar->users()) {
2027 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2029 assert((ScalarToTreeEntry.count(U) ||
2030 // It is legal to replace users in the ignorelist by undef.
2031 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2032 UserIgnoreList.end())) &&
2033 "Replacing out-of-tree value with undef");
2036 Value *Undef = UndefValue::get(Ty);
2037 Scalar->replaceAllUsesWith(Undef);
2039 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2040 cast<Instruction>(Scalar)->eraseFromParent();
2044 for (auto &BN : BlocksNumbers)
2047 Builder.ClearInsertionPoint();
2049 return VectorizableTree[0].VectorizedValue;
2052 void BoUpSLP::optimizeGatherSequence() {
2053 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2054 << " gather sequences instructions.\n");
2055 // LICM InsertElementInst sequences.
2056 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2057 e = GatherSeq.end(); it != e; ++it) {
2058 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2063 // Check if this block is inside a loop.
2064 Loop *L = LI->getLoopFor(Insert->getParent());
2068 // Check if it has a preheader.
2069 BasicBlock *PreHeader = L->getLoopPreheader();
2073 // If the vector or the element that we insert into it are
2074 // instructions that are defined in this basic block then we can't
2075 // hoist this instruction.
2076 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2077 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2078 if (CurrVec && L->contains(CurrVec))
2080 if (NewElem && L->contains(NewElem))
2083 // We can hoist this instruction. Move it to the pre-header.
2084 Insert->moveBefore(PreHeader->getTerminator());
2087 // Make a list of all reachable blocks in our CSE queue.
2088 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2089 CSEWorkList.reserve(CSEBlocks.size());
2090 for (BasicBlock *BB : CSEBlocks)
2091 if (DomTreeNode *N = DT->getNode(BB)) {
2092 assert(DT->isReachableFromEntry(N));
2093 CSEWorkList.push_back(N);
2096 // Sort blocks by domination. This ensures we visit a block after all blocks
2097 // dominating it are visited.
2098 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2099 [this](const DomTreeNode *A, const DomTreeNode *B) {
2100 return DT->properlyDominates(A, B);
2103 // Perform O(N^2) search over the gather sequences and merge identical
2104 // instructions. TODO: We can further optimize this scan if we split the
2105 // instructions into different buckets based on the insert lane.
2106 SmallVector<Instruction *, 16> Visited;
2107 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2108 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2109 "Worklist not sorted properly!");
2110 BasicBlock *BB = (*I)->getBlock();
2111 // For all instructions in blocks containing gather sequences:
2112 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2113 Instruction *In = it++;
2114 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2117 // Check if we can replace this instruction with any of the
2118 // visited instructions.
2119 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2122 if (In->isIdenticalTo(*v) &&
2123 DT->dominates((*v)->getParent(), In->getParent())) {
2124 In->replaceAllUsesWith(*v);
2125 In->eraseFromParent();
2131 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2132 Visited.push_back(In);
2140 /// The SLPVectorizer Pass.
2141 struct SLPVectorizer : public FunctionPass {
2142 typedef SmallVector<StoreInst *, 8> StoreList;
2143 typedef MapVector<Value *, StoreList> StoreListMap;
2145 /// Pass identification, replacement for typeid
2148 explicit SLPVectorizer() : FunctionPass(ID) {
2149 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2152 ScalarEvolution *SE;
2153 const DataLayout *DL;
2154 TargetTransformInfo *TTI;
2155 TargetLibraryInfo *TLI;
2160 bool runOnFunction(Function &F) override {
2161 if (skipOptnoneFunction(F))
2164 SE = &getAnalysis<ScalarEvolution>();
2165 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2166 DL = DLP ? &DLP->getDataLayout() : nullptr;
2167 TTI = &getAnalysis<TargetTransformInfo>();
2168 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2169 AA = &getAnalysis<AliasAnalysis>();
2170 LI = &getAnalysis<LoopInfo>();
2171 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2174 bool Changed = false;
2176 // If the target claims to have no vector registers don't attempt
2178 if (!TTI->getNumberOfRegisters(true))
2181 // Must have DataLayout. We can't require it because some tests run w/o
2186 // Don't vectorize when the attribute NoImplicitFloat is used.
2187 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2190 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2192 // Use the bottom up slp vectorizer to construct chains that start with
2193 // store instructions.
2194 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2196 // Scan the blocks in the function in post order.
2197 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2198 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2199 BasicBlock *BB = *it;
2200 // Vectorize trees that end at stores.
2201 if (unsigned count = collectStores(BB, R)) {
2203 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2204 Changed |= vectorizeStoreChains(R);
2207 // Vectorize trees that end at reductions.
2208 Changed |= vectorizeChainsInBlock(BB, R);
2212 R.optimizeGatherSequence();
2213 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2214 DEBUG(verifyFunction(F));
2219 void getAnalysisUsage(AnalysisUsage &AU) const override {
2220 FunctionPass::getAnalysisUsage(AU);
2221 AU.addRequired<ScalarEvolution>();
2222 AU.addRequired<AliasAnalysis>();
2223 AU.addRequired<TargetTransformInfo>();
2224 AU.addRequired<LoopInfo>();
2225 AU.addRequired<DominatorTreeWrapperPass>();
2226 AU.addPreserved<LoopInfo>();
2227 AU.addPreserved<DominatorTreeWrapperPass>();
2228 AU.setPreservesCFG();
2233 /// \brief Collect memory references and sort them according to their base
2234 /// object. We sort the stores to their base objects to reduce the cost of the
2235 /// quadratic search on the stores. TODO: We can further reduce this cost
2236 /// if we flush the chain creation every time we run into a memory barrier.
2237 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2239 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2240 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R,
2241 BinaryOperator *V = nullptr);
2243 /// \brief Try to vectorize a list of operands.
2244 /// \@param BuildVector A list of users to ignore for the purpose of
2245 /// scheduling and that don't need extracting.
2246 /// \returns true if a value was vectorized.
2247 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2248 ArrayRef<Value *> BuildVector = None);
2250 /// \brief Try to vectorize a chain that may start at the operands of \V;
2251 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2253 /// \brief Vectorize the stores that were collected in StoreRefs.
2254 bool vectorizeStoreChains(BoUpSLP &R);
2256 /// \brief Scan the basic block and look for patterns that are likely to start
2257 /// a vectorization chain.
2258 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2260 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2263 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2266 StoreListMap StoreRefs;
2269 /// \brief Check that the Values in the slice in VL array are still existent in
2270 /// the WeakVH array.
2271 /// Vectorization of part of the VL array may cause later values in the VL array
2272 /// to become invalid. We track when this has happened in the WeakVH array.
2273 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2274 SmallVectorImpl<WeakVH> &VH,
2275 unsigned SliceBegin,
2276 unsigned SliceSize) {
2277 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2284 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2285 int CostThreshold, BoUpSLP &R) {
2286 unsigned ChainLen = Chain.size();
2287 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2289 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2290 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2291 unsigned VF = MinVecRegSize / Sz;
2293 if (!isPowerOf2_32(Sz) || VF < 2)
2296 // Keep track of values that were deleted by vectorizing in the loop below.
2297 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2299 bool Changed = false;
2300 // Look for profitable vectorizable trees at all offsets, starting at zero.
2301 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2305 // Check that a previous iteration of this loop did not delete the Value.
2306 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2309 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2311 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2313 R.buildTree(Operands);
2315 int Cost = R.getTreeCost();
2317 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2318 if (Cost < CostThreshold) {
2319 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2322 // Move to the next bundle.
2331 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2332 int costThreshold, BoUpSLP &R) {
2333 SetVector<Value *> Heads, Tails;
2334 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2336 // We may run into multiple chains that merge into a single chain. We mark the
2337 // stores that we vectorized so that we don't visit the same store twice.
2338 BoUpSLP::ValueSet VectorizedStores;
2339 bool Changed = false;
2341 // Do a quadratic search on all of the given stores and find
2342 // all of the pairs of stores that follow each other.
2343 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2344 for (unsigned j = 0; j < e; ++j) {
2348 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2349 Tails.insert(Stores[j]);
2350 Heads.insert(Stores[i]);
2351 ConsecutiveChain[Stores[i]] = Stores[j];
2356 // For stores that start but don't end a link in the chain:
2357 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2359 if (Tails.count(*it))
2362 // We found a store instr that starts a chain. Now follow the chain and try
2364 BoUpSLP::ValueList Operands;
2366 // Collect the chain into a list.
2367 while (Tails.count(I) || Heads.count(I)) {
2368 if (VectorizedStores.count(I))
2370 Operands.push_back(I);
2371 // Move to the next value in the chain.
2372 I = ConsecutiveChain[I];
2375 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2377 // Mark the vectorized stores so that we don't vectorize them again.
2379 VectorizedStores.insert(Operands.begin(), Operands.end());
2380 Changed |= Vectorized;
2387 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2390 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2391 StoreInst *SI = dyn_cast<StoreInst>(it);
2395 // Don't touch volatile stores.
2396 if (!SI->isSimple())
2399 // Check that the pointer points to scalars.
2400 Type *Ty = SI->getValueOperand()->getType();
2401 if (Ty->isAggregateType() || Ty->isVectorTy())
2404 // Find the base pointer.
2405 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2407 // Save the store locations.
2408 StoreRefs[Ptr].push_back(SI);
2414 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R,
2415 BinaryOperator *V) {
2418 Value *VL[] = { A, B };
2420 // Canonicalize operands based on source order, so that the ordering in the
2421 // expression tree more closely matches the ordering of the source.
2422 if (V && V->isCommutative() && isa<Instruction>(A) && isa<Instruction>(B) &&
2423 cast<Instruction>(A)->getParent() == cast<Instruction>(B)->getParent()) {
2424 assert(V->getOperand(0) == A && V->getOperand(1) == B &&
2425 "Expected operands in order.");
2426 int IndexA = R.getIndex(cast<Instruction>(A));
2427 int IndexB = R.getIndex(cast<Instruction>(B));
2428 if (IndexA > IndexB)
2429 std::swap(VL[0], VL[1]);
2431 return tryToVectorizeList(VL, R);
2434 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2435 ArrayRef<Value *> BuildVector) {
2439 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2441 // Check that all of the parts are scalar instructions of the same type.
2442 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2446 unsigned Opcode0 = I0->getOpcode();
2448 Type *Ty0 = I0->getType();
2449 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2450 unsigned VF = MinVecRegSize / Sz;
2452 for (int i = 0, e = VL.size(); i < e; ++i) {
2453 Type *Ty = VL[i]->getType();
2454 if (Ty->isAggregateType() || Ty->isVectorTy())
2456 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2457 if (!Inst || Inst->getOpcode() != Opcode0)
2461 bool Changed = false;
2463 // Keep track of values that were deleted by vectorizing in the loop below.
2464 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2466 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2467 unsigned OpsWidth = 0;
2474 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2477 // Check that a previous iteration of this loop did not delete the Value.
2478 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2481 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2483 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2485 ArrayRef<Value *> BuildVectorSlice;
2486 if (!BuildVector.empty())
2487 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2489 R.buildTree(Ops, BuildVectorSlice);
2490 int Cost = R.getTreeCost();
2492 if (Cost < -SLPCostThreshold) {
2493 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2494 Value *VectorizedRoot = R.vectorizeTree();
2496 // Reconstruct the build vector by extracting the vectorized root. This
2497 // way we handle the case where some elements of the vector are undefined.
2498 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2499 if (!BuildVectorSlice.empty()) {
2500 // The insert point is the last build vector instruction. The vectorized
2501 // root will precede it. This guarantees that we get an instruction. The
2502 // vectorized tree could have been constant folded.
2503 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2504 unsigned VecIdx = 0;
2505 for (auto &V : BuildVectorSlice) {
2506 IRBuilder<true, NoFolder> Builder(
2507 ++BasicBlock::iterator(InsertAfter));
2508 InsertElementInst *IE = cast<InsertElementInst>(V);
2509 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2510 VectorizedRoot, Builder.getInt32(VecIdx++)));
2511 IE->setOperand(1, Extract);
2512 IE->removeFromParent();
2513 IE->insertAfter(Extract);
2517 // Move to the next bundle.
2526 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2530 // Try to vectorize V.
2531 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R, V))
2534 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2535 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2537 if (B && B->hasOneUse()) {
2538 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2539 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2540 if (tryToVectorizePair(A, B0, R)) {
2544 if (tryToVectorizePair(A, B1, R)) {
2551 if (A && A->hasOneUse()) {
2552 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2553 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2554 if (tryToVectorizePair(A0, B, R)) {
2558 if (tryToVectorizePair(A1, B, R)) {
2566 /// \brief Generate a shuffle mask to be used in a reduction tree.
2568 /// \param VecLen The length of the vector to be reduced.
2569 /// \param NumEltsToRdx The number of elements that should be reduced in the
2571 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2572 /// reduction. A pairwise reduction will generate a mask of
2573 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2574 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2575 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2576 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2577 bool IsPairwise, bool IsLeft,
2578 IRBuilder<> &Builder) {
2579 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2581 SmallVector<Constant *, 32> ShuffleMask(
2582 VecLen, UndefValue::get(Builder.getInt32Ty()));
2585 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2586 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2587 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2589 // Move the upper half of the vector to the lower half.
2590 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2591 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2593 return ConstantVector::get(ShuffleMask);
2597 /// Model horizontal reductions.
2599 /// A horizontal reduction is a tree of reduction operations (currently add and
2600 /// fadd) that has operations that can be put into a vector as its leaf.
2601 /// For example, this tree:
2608 /// This tree has "mul" as its reduced values and "+" as its reduction
2609 /// operations. A reduction might be feeding into a store or a binary operation
2624 class HorizontalReduction {
2625 SmallVector<Value *, 16> ReductionOps;
2626 SmallVector<Value *, 32> ReducedVals;
2628 BinaryOperator *ReductionRoot;
2629 PHINode *ReductionPHI;
2631 /// The opcode of the reduction.
2632 unsigned ReductionOpcode;
2633 /// The opcode of the values we perform a reduction on.
2634 unsigned ReducedValueOpcode;
2635 /// The width of one full horizontal reduction operation.
2636 unsigned ReduxWidth;
2637 /// Should we model this reduction as a pairwise reduction tree or a tree that
2638 /// splits the vector in halves and adds those halves.
2639 bool IsPairwiseReduction;
2642 HorizontalReduction()
2643 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
2644 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2646 /// \brief Try to find a reduction tree.
2647 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2648 const DataLayout *DL) {
2650 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2651 "Thi phi needs to use the binary operator");
2653 // We could have a initial reductions that is not an add.
2654 // r *= v1 + v2 + v3 + v4
2655 // In such a case start looking for a tree rooted in the first '+'.
2657 if (B->getOperand(0) == Phi) {
2659 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2660 } else if (B->getOperand(1) == Phi) {
2662 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2669 Type *Ty = B->getType();
2670 if (Ty->isVectorTy())
2673 ReductionOpcode = B->getOpcode();
2674 ReducedValueOpcode = 0;
2675 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2682 // We currently only support adds.
2683 if (ReductionOpcode != Instruction::Add &&
2684 ReductionOpcode != Instruction::FAdd)
2687 // Post order traverse the reduction tree starting at B. We only handle true
2688 // trees containing only binary operators.
2689 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2690 Stack.push_back(std::make_pair(B, 0));
2691 while (!Stack.empty()) {
2692 BinaryOperator *TreeN = Stack.back().first;
2693 unsigned EdgeToVist = Stack.back().second++;
2694 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2696 // Only handle trees in the current basic block.
2697 if (TreeN->getParent() != B->getParent())
2700 // Each tree node needs to have one user except for the ultimate
2702 if (!TreeN->hasOneUse() && TreeN != B)
2706 if (EdgeToVist == 2 || IsReducedValue) {
2707 if (IsReducedValue) {
2708 // Make sure that the opcodes of the operations that we are going to
2710 if (!ReducedValueOpcode)
2711 ReducedValueOpcode = TreeN->getOpcode();
2712 else if (ReducedValueOpcode != TreeN->getOpcode())
2714 ReducedVals.push_back(TreeN);
2716 // We need to be able to reassociate the adds.
2717 if (!TreeN->isAssociative())
2719 ReductionOps.push_back(TreeN);
2726 // Visit left or right.
2727 Value *NextV = TreeN->getOperand(EdgeToVist);
2728 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2730 Stack.push_back(std::make_pair(Next, 0));
2731 else if (NextV != Phi)
2737 /// \brief Attempt to vectorize the tree found by
2738 /// matchAssociativeReduction.
2739 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2740 if (ReducedVals.empty())
2743 unsigned NumReducedVals = ReducedVals.size();
2744 if (NumReducedVals < ReduxWidth)
2747 Value *VectorizedTree = nullptr;
2748 IRBuilder<> Builder(ReductionRoot);
2749 FastMathFlags Unsafe;
2750 Unsafe.setUnsafeAlgebra();
2751 Builder.SetFastMathFlags(Unsafe);
2754 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2755 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2756 V.buildTree(ValsToReduce, ReductionOps);
2759 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2760 if (Cost >= -SLPCostThreshold)
2763 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2766 // Vectorize a tree.
2767 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2768 Value *VectorizedRoot = V.vectorizeTree();
2770 // Emit a reduction.
2771 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2772 if (VectorizedTree) {
2773 Builder.SetCurrentDebugLocation(Loc);
2774 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2775 ReducedSubTree, "bin.rdx");
2777 VectorizedTree = ReducedSubTree;
2780 if (VectorizedTree) {
2781 // Finish the reduction.
2782 for (; i < NumReducedVals; ++i) {
2783 Builder.SetCurrentDebugLocation(
2784 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2785 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2790 assert(ReductionRoot && "Need a reduction operation");
2791 ReductionRoot->setOperand(0, VectorizedTree);
2792 ReductionRoot->setOperand(1, ReductionPHI);
2794 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2796 return VectorizedTree != nullptr;
2801 /// \brief Calcuate the cost of a reduction.
2802 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2803 Type *ScalarTy = FirstReducedVal->getType();
2804 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2806 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2807 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2809 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2810 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2812 int ScalarReduxCost =
2813 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2815 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2816 << " for reduction that starts with " << *FirstReducedVal
2818 << (IsPairwiseReduction ? "pairwise" : "splitting")
2819 << " reduction)\n");
2821 return VecReduxCost - ScalarReduxCost;
2824 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2825 Value *R, const Twine &Name = "") {
2826 if (Opcode == Instruction::FAdd)
2827 return Builder.CreateFAdd(L, R, Name);
2828 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2831 /// \brief Emit a horizontal reduction of the vectorized value.
2832 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2833 assert(VectorizedValue && "Need to have a vectorized tree node");
2834 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2835 assert(isPowerOf2_32(ReduxWidth) &&
2836 "We only handle power-of-two reductions for now");
2838 Value *TmpVec = ValToReduce;
2839 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2840 if (IsPairwiseReduction) {
2842 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2844 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2846 Value *LeftShuf = Builder.CreateShuffleVector(
2847 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2848 Value *RightShuf = Builder.CreateShuffleVector(
2849 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2851 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2855 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2856 Value *Shuf = Builder.CreateShuffleVector(
2857 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2858 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2862 // The result is in the first element of the vector.
2863 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2867 /// \brief Recognize construction of vectors like
2868 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2869 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2870 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2871 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2873 /// Returns true if it matches
2875 static bool findBuildVector(InsertElementInst *FirstInsertElem,
2876 SmallVectorImpl<Value *> &BuildVector,
2877 SmallVectorImpl<Value *> &BuildVectorOpds) {
2878 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
2881 InsertElementInst *IE = FirstInsertElem;
2883 BuildVector.push_back(IE);
2884 BuildVectorOpds.push_back(IE->getOperand(1));
2886 if (IE->use_empty())
2889 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2893 // If this isn't the final use, make sure the next insertelement is the only
2894 // use. It's OK if the final constructed vector is used multiple times
2895 if (!IE->hasOneUse())
2904 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2905 return V->getType() < V2->getType();
2908 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2909 bool Changed = false;
2910 SmallVector<Value *, 4> Incoming;
2911 SmallSet<Value *, 16> VisitedInstrs;
2913 bool HaveVectorizedPhiNodes = true;
2914 while (HaveVectorizedPhiNodes) {
2915 HaveVectorizedPhiNodes = false;
2917 // Collect the incoming values from the PHIs.
2919 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2921 PHINode *P = dyn_cast<PHINode>(instr);
2925 if (!VisitedInstrs.count(P))
2926 Incoming.push_back(P);
2930 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2932 // Try to vectorize elements base on their type.
2933 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2937 // Look for the next elements with the same type.
2938 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2939 while (SameTypeIt != E &&
2940 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2941 VisitedInstrs.insert(*SameTypeIt);
2945 // Try to vectorize them.
2946 unsigned NumElts = (SameTypeIt - IncIt);
2947 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2949 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2950 // Success start over because instructions might have been changed.
2951 HaveVectorizedPhiNodes = true;
2956 // Start over at the next instruction of a different type (or the end).
2961 VisitedInstrs.clear();
2963 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2964 // We may go through BB multiple times so skip the one we have checked.
2965 if (!VisitedInstrs.insert(it))
2968 if (isa<DbgInfoIntrinsic>(it))
2971 // Try to vectorize reductions that use PHINodes.
2972 if (PHINode *P = dyn_cast<PHINode>(it)) {
2973 // Check that the PHI is a reduction PHI.
2974 if (P->getNumIncomingValues() != 2)
2977 (P->getIncomingBlock(0) == BB
2978 ? (P->getIncomingValue(0))
2979 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
2981 // Check if this is a Binary Operator.
2982 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2986 // Try to match and vectorize a horizontal reduction.
2987 HorizontalReduction HorRdx;
2988 if (ShouldVectorizeHor &&
2989 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2990 HorRdx.tryToReduce(R, TTI)) {
2997 Value *Inst = BI->getOperand(0);
2999 Inst = BI->getOperand(1);
3001 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3002 // We would like to start over since some instructions are deleted
3003 // and the iterator may become invalid value.
3013 // Try to vectorize horizontal reductions feeding into a store.
3014 if (ShouldStartVectorizeHorAtStore)
3015 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3016 if (BinaryOperator *BinOp =
3017 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3018 HorizontalReduction HorRdx;
3019 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3020 HorRdx.tryToReduce(R, TTI)) ||
3021 tryToVectorize(BinOp, R))) {
3029 // Try to vectorize trees that start at compare instructions.
3030 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3031 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3033 // We would like to start over since some instructions are deleted
3034 // and the iterator may become invalid value.
3040 for (int i = 0; i < 2; ++i) {
3041 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3042 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R, BI)) {
3044 // We would like to start over since some instructions are deleted
3045 // and the iterator may become invalid value.
3054 // Try to vectorize trees that start at insertelement instructions.
3055 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3056 SmallVector<Value *, 16> BuildVector;
3057 SmallVector<Value *, 16> BuildVectorOpds;
3058 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3061 // Vectorize starting with the build vector operands ignoring the
3062 // BuildVector instructions for the purpose of scheduling and user
3064 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3077 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3078 bool Changed = false;
3079 // Attempt to sort and vectorize each of the store-groups.
3080 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3082 if (it->second.size() < 2)
3085 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3086 << it->second.size() << ".\n");
3088 // Process the stores in chunks of 16.
3089 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3090 unsigned Len = std::min<unsigned>(CE - CI, 16);
3091 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
3092 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
3098 } // end anonymous namespace
3100 char SLPVectorizer::ID = 0;
3101 static const char lv_name[] = "SLP Vectorizer";
3102 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3103 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3104 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3105 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3106 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3107 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3110 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }