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/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/NoFolder.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/Utils/VectorUtils.h"
49 #define SV_NAME "slp-vectorizer"
50 #define DEBUG_TYPE "SLP"
52 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
55 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
56 cl::desc("Only vectorize if you gain more than this "
60 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
61 cl::desc("Attempt to vectorize horizontal reductions"));
63 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
64 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
66 "Attempt to vectorize horizontal reductions feeding into a store"));
70 static const unsigned MinVecRegSize = 128;
72 static const unsigned RecursionMaxDepth = 12;
74 /// A helper class for numbering instructions in multiple blocks.
75 /// Numbers start at zero for each basic block.
76 struct BlockNumbering {
78 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
80 void numberInstructions() {
84 // Number the instructions in the block.
85 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
87 InstrVec.push_back(it);
88 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
93 int getIndex(Instruction *I) {
94 assert(I->getParent() == BB && "Invalid instruction");
97 assert(InstrIdx.count(I) && "Unknown instruction");
101 Instruction *getInstruction(unsigned loc) {
103 numberInstructions();
104 assert(InstrVec.size() > loc && "Invalid Index");
105 return InstrVec[loc];
108 void forget() { Valid = false; }
111 /// The block we are numbering.
113 /// Is the block numbered.
115 /// Maps instructions to numbers and back.
116 SmallDenseMap<Instruction *, int> InstrIdx;
117 /// Maps integers to Instructions.
118 SmallVector<Instruction *, 32> InstrVec;
121 /// \returns the parent basic block if all of the instructions in \p VL
122 /// are in the same block or null otherwise.
123 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
124 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
127 BasicBlock *BB = I0->getParent();
128 for (int i = 1, e = VL.size(); i < e; i++) {
129 Instruction *I = dyn_cast<Instruction>(VL[i]);
133 if (BB != I->getParent())
139 /// \returns True if all of the values in \p VL are constants.
140 static bool allConstant(ArrayRef<Value *> VL) {
141 for (unsigned i = 0, e = VL.size(); i < e; ++i)
142 if (!isa<Constant>(VL[i]))
147 /// \returns True if all of the values in \p VL are identical.
148 static bool isSplat(ArrayRef<Value *> VL) {
149 for (unsigned i = 1, e = VL.size(); i < e; ++i)
155 ///\returns Opcode that can be clubbed with \p Op to create an alternate
156 /// sequence which can later be merged as a ShuffleVector instruction.
157 static unsigned getAltOpcode(unsigned Op) {
159 case Instruction::FAdd:
160 return Instruction::FSub;
161 case Instruction::FSub:
162 return Instruction::FAdd;
163 case Instruction::Add:
164 return Instruction::Sub;
165 case Instruction::Sub:
166 return Instruction::Add;
172 ///\returns bool representing if Opcode \p Op can be part
173 /// of an alternate sequence which can later be merged as
174 /// a ShuffleVector instruction.
175 static bool canCombineAsAltInst(unsigned Op) {
176 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
177 Op == Instruction::Sub || Op == Instruction::Add)
182 /// \returns ShuffleVector instruction if intructions in \p VL have
183 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
184 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
185 static unsigned isAltInst(ArrayRef<Value *> VL) {
186 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
187 unsigned Opcode = I0->getOpcode();
188 unsigned AltOpcode = getAltOpcode(Opcode);
189 for (int i = 1, e = VL.size(); i < e; i++) {
190 Instruction *I = dyn_cast<Instruction>(VL[i]);
191 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
194 return Instruction::ShuffleVector;
197 /// \returns The opcode if all of the Instructions in \p VL have the same
199 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
200 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
203 unsigned Opcode = I0->getOpcode();
204 for (int i = 1, e = VL.size(); i < e; i++) {
205 Instruction *I = dyn_cast<Instruction>(VL[i]);
206 if (!I || Opcode != I->getOpcode()) {
207 if (canCombineAsAltInst(Opcode) && i == 1)
208 return isAltInst(VL);
215 /// \returns \p I after propagating metadata from \p VL.
216 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
217 Instruction *I0 = cast<Instruction>(VL[0]);
218 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
219 I0->getAllMetadataOtherThanDebugLoc(Metadata);
221 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
222 unsigned Kind = Metadata[i].first;
223 MDNode *MD = Metadata[i].second;
225 for (int i = 1, e = VL.size(); MD && i != e; i++) {
226 Instruction *I = cast<Instruction>(VL[i]);
227 MDNode *IMD = I->getMetadata(Kind);
231 MD = nullptr; // Remove unknown metadata
233 case LLVMContext::MD_tbaa:
234 MD = MDNode::getMostGenericTBAA(MD, IMD);
236 case LLVMContext::MD_alias_scope:
237 case LLVMContext::MD_noalias:
238 MD = MDNode::intersect(MD, IMD);
240 case LLVMContext::MD_fpmath:
241 MD = MDNode::getMostGenericFPMath(MD, IMD);
245 I->setMetadata(Kind, MD);
250 /// \returns The type that all of the values in \p VL have or null if there
251 /// are different types.
252 static Type* getSameType(ArrayRef<Value *> VL) {
253 Type *Ty = VL[0]->getType();
254 for (int i = 1, e = VL.size(); i < e; i++)
255 if (VL[i]->getType() != Ty)
261 /// \returns True if the ExtractElement instructions in VL can be vectorized
262 /// to use the original vector.
263 static bool CanReuseExtract(ArrayRef<Value *> VL) {
264 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
265 // Check if all of the extracts come from the same vector and from the
268 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
269 Value *Vec = E0->getOperand(0);
271 // We have to extract from the same vector type.
272 unsigned NElts = Vec->getType()->getVectorNumElements();
274 if (NElts != VL.size())
277 // Check that all of the indices extract from the correct offset.
278 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
279 if (!CI || CI->getZExtValue())
282 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
283 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
284 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
286 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
293 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
294 SmallVectorImpl<Value *> &Left,
295 SmallVectorImpl<Value *> &Right) {
297 SmallVector<Value *, 16> OrigLeft, OrigRight;
299 bool AllSameOpcodeLeft = true;
300 bool AllSameOpcodeRight = true;
301 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
302 Instruction *I = cast<Instruction>(VL[i]);
303 Value *V0 = I->getOperand(0);
304 Value *V1 = I->getOperand(1);
306 OrigLeft.push_back(V0);
307 OrigRight.push_back(V1);
309 Instruction *I0 = dyn_cast<Instruction>(V0);
310 Instruction *I1 = dyn_cast<Instruction>(V1);
312 // Check whether all operands on one side have the same opcode. In this case
313 // we want to preserve the original order and not make things worse by
315 AllSameOpcodeLeft = I0;
316 AllSameOpcodeRight = I1;
318 if (i && AllSameOpcodeLeft) {
319 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
320 if(P0->getOpcode() != I0->getOpcode())
321 AllSameOpcodeLeft = false;
323 AllSameOpcodeLeft = false;
325 if (i && AllSameOpcodeRight) {
326 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
327 if(P1->getOpcode() != I1->getOpcode())
328 AllSameOpcodeRight = false;
330 AllSameOpcodeRight = false;
333 // Sort two opcodes. In the code below we try to preserve the ability to use
334 // broadcast of values instead of individual inserts.
341 // If we just sorted according to opcode we would leave the first line in
342 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
345 // Because vr2 and vr1 are from the same load we loose the opportunity of a
346 // broadcast for the packed right side in the backend: we have [vr1, vl2]
347 // instead of [vr1, vr2=vr1].
349 if(!i && I0->getOpcode() > I1->getOpcode()) {
352 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
353 // Try not to destroy a broad cast for no apparent benefit.
356 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
357 // Try preserve broadcasts.
360 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
361 // Try preserve broadcasts.
370 // One opcode, put the instruction on the right.
380 bool LeftBroadcast = isSplat(Left);
381 bool RightBroadcast = isSplat(Right);
383 // Don't reorder if the operands where good to begin with.
384 if (!(LeftBroadcast || RightBroadcast) &&
385 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
391 /// Bottom Up SLP Vectorizer.
394 typedef SmallVector<Value *, 8> ValueList;
395 typedef SmallVector<Instruction *, 16> InstrList;
396 typedef SmallPtrSet<Value *, 16> ValueSet;
397 typedef SmallVector<StoreInst *, 8> StoreList;
399 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
400 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
401 LoopInfo *Li, DominatorTree *Dt)
402 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0),
403 F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
404 Builder(Se->getContext()) {}
406 /// \brief Vectorize the tree that starts with the elements in \p VL.
407 /// Returns the vectorized root.
408 Value *vectorizeTree();
410 /// \returns the vectorization cost of the subtree that starts at \p VL.
411 /// A negative number means that this is profitable.
414 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
415 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
416 void buildTree(ArrayRef<Value *> Roots,
417 ArrayRef<Value *> UserIgnoreLst = None);
419 /// Clear the internal data structures that are created by 'buildTree'.
421 VectorizableTree.clear();
422 ScalarToTreeEntry.clear();
424 ExternalUses.clear();
425 MemBarrierIgnoreList.clear();
426 NumLoadsWantToKeepOrder = 0;
427 NumLoadsWantToChangeOrder = 0;
430 /// \returns true if the memory operations A and B are consecutive.
431 bool isConsecutiveAccess(Value *A, Value *B);
433 /// \brief Perform LICM and CSE on the newly generated gather sequences.
434 void optimizeGatherSequence();
436 /// \returns true if it is benefitial to reverse the vector order.
437 bool shouldReorder() const {
438 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
444 /// \returns the cost of the vectorizable entry.
445 int getEntryCost(TreeEntry *E);
447 /// This is the recursive part of buildTree.
448 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
450 /// Vectorize a single entry in the tree.
451 Value *vectorizeTree(TreeEntry *E);
453 /// Vectorize a single entry in the tree, starting in \p VL.
454 Value *vectorizeTree(ArrayRef<Value *> VL);
456 /// \returns the pointer to the vectorized value if \p VL is already
457 /// vectorized, or NULL. They may happen in cycles.
458 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
460 /// \brief Take the pointer operand from the Load/Store instruction.
461 /// \returns NULL if this is not a valid Load/Store instruction.
462 static Value *getPointerOperand(Value *I);
464 /// \brief Take the address space operand from the Load/Store instruction.
465 /// \returns -1 if this is not a valid Load/Store instruction.
466 static unsigned getAddressSpaceOperand(Value *I);
468 /// \returns the scalarization cost for this type. Scalarization in this
469 /// context means the creation of vectors from a group of scalars.
470 int getGatherCost(Type *Ty);
472 /// \returns the scalarization cost for this list of values. Assuming that
473 /// this subtree gets vectorized, we may need to extract the values from the
474 /// roots. This method calculates the cost of extracting the values.
475 int getGatherCost(ArrayRef<Value *> VL);
477 /// \returns the AA location that is being access by the instruction.
478 AliasAnalysis::Location getLocation(Instruction *I);
480 /// \brief Checks if it is possible to sink an instruction from
481 /// \p Src to \p Dst.
482 /// \returns the pointer to the barrier instruction if we can't sink.
483 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
485 /// \returns the index of the last instruction in the BB from \p VL.
486 int getLastIndex(ArrayRef<Value *> VL);
488 /// \returns the Instruction in the bundle \p VL.
489 Instruction *getLastInstruction(ArrayRef<Value *> VL);
491 /// \brief Set the Builder insert point to one after the last instruction in
493 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
495 /// \returns a vector from a collection of scalars in \p VL.
496 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
498 /// \returns whether the VectorizableTree is fully vectoriable and will
499 /// be beneficial even the tree height is tiny.
500 bool isFullyVectorizableTinyTree();
503 TreeEntry() : Scalars(), VectorizedValue(nullptr), LastScalarIndex(0),
506 /// \returns true if the scalars in VL are equal to this entry.
507 bool isSame(ArrayRef<Value *> VL) const {
508 assert(VL.size() == Scalars.size() && "Invalid size");
509 return std::equal(VL.begin(), VL.end(), Scalars.begin());
512 /// A vector of scalars.
515 /// The Scalars are vectorized into this value. It is initialized to Null.
516 Value *VectorizedValue;
518 /// The index in the basic block of the last scalar.
521 /// Do we need to gather this sequence ?
525 /// Create a new VectorizableTree entry.
526 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
527 VectorizableTree.push_back(TreeEntry());
528 int idx = VectorizableTree.size() - 1;
529 TreeEntry *Last = &VectorizableTree[idx];
530 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
531 Last->NeedToGather = !Vectorized;
533 Last->LastScalarIndex = getLastIndex(VL);
534 for (int i = 0, e = VL.size(); i != e; ++i) {
535 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
536 ScalarToTreeEntry[VL[i]] = idx;
539 Last->LastScalarIndex = 0;
540 MustGather.insert(VL.begin(), VL.end());
545 /// -- Vectorization State --
546 /// Holds all of the tree entries.
547 std::vector<TreeEntry> VectorizableTree;
549 /// Maps a specific scalar to its tree entry.
550 SmallDenseMap<Value*, int> ScalarToTreeEntry;
552 /// A list of scalars that we found that we need to keep as scalars.
555 /// This POD struct describes one external user in the vectorized tree.
556 struct ExternalUser {
557 ExternalUser (Value *S, llvm::User *U, int L) :
558 Scalar(S), User(U), Lane(L){};
559 // Which scalar in our function.
561 // Which user that uses the scalar.
563 // Which lane does the scalar belong to.
566 typedef SmallVector<ExternalUser, 16> UserList;
568 /// A list of values that need to extracted out of the tree.
569 /// This list holds pairs of (Internal Scalar : External User).
570 UserList ExternalUses;
572 /// A list of instructions to ignore while sinking
573 /// memory instructions. This map must be reset between runs of getCost.
574 ValueSet MemBarrierIgnoreList;
576 /// Holds all of the instructions that we gathered.
577 SetVector<Instruction *> GatherSeq;
578 /// A list of blocks that we are going to CSE.
579 SetVector<BasicBlock *> CSEBlocks;
581 /// Numbers instructions in different blocks.
582 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
584 /// \brief Get the corresponding instruction numbering list for a given
585 /// BasicBlock. The list is allocated lazily.
586 BlockNumbering &getBlockNumbering(BasicBlock *BB) {
587 auto I = BlocksNumbers.insert(std::make_pair(BB, BlockNumbering(BB)));
588 return I.first->second;
591 /// List of users to ignore during scheduling and that don't need extracting.
592 ArrayRef<Value *> UserIgnoreList;
594 // Number of load-bundles, which contain consecutive loads.
595 int NumLoadsWantToKeepOrder;
597 // Number of load-bundles of size 2, which are consecutive loads if reversed.
598 int NumLoadsWantToChangeOrder;
600 // Analysis and block reference.
603 const DataLayout *DL;
604 TargetTransformInfo *TTI;
605 TargetLibraryInfo *TLI;
609 /// Instruction builder to construct the vectorized tree.
613 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
614 ArrayRef<Value *> UserIgnoreLst) {
616 UserIgnoreList = UserIgnoreLst;
617 if (!getSameType(Roots))
619 buildTree_rec(Roots, 0);
621 // Collect the values that we need to extract from the tree.
622 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
623 TreeEntry *Entry = &VectorizableTree[EIdx];
626 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
627 Value *Scalar = Entry->Scalars[Lane];
629 // No need to handle users of gathered values.
630 if (Entry->NeedToGather)
633 for (User *U : Scalar->users()) {
634 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
636 // Skip in-tree scalars that become vectors.
637 if (ScalarToTreeEntry.count(U)) {
638 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
640 int Idx = ScalarToTreeEntry[U]; (void) Idx;
641 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
644 Instruction *UserInst = dyn_cast<Instruction>(U);
648 // Ignore users in the user ignore list.
649 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
650 UserIgnoreList.end())
653 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
654 Lane << " from " << *Scalar << ".\n");
655 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
662 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
663 bool SameTy = getSameType(VL); (void)SameTy;
664 bool isAltShuffle = false;
665 assert(SameTy && "Invalid types!");
667 if (Depth == RecursionMaxDepth) {
668 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
669 newTreeEntry(VL, false);
673 // Don't handle vectors.
674 if (VL[0]->getType()->isVectorTy()) {
675 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
676 newTreeEntry(VL, false);
680 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
681 if (SI->getValueOperand()->getType()->isVectorTy()) {
682 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
683 newTreeEntry(VL, false);
686 unsigned Opcode = getSameOpcode(VL);
688 // Check that this shuffle vector refers to the alternate
689 // sequence of opcodes.
690 if (Opcode == Instruction::ShuffleVector) {
691 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
692 unsigned Op = I0->getOpcode();
693 if (Op != Instruction::ShuffleVector)
697 // If all of the operands are identical or constant we have a simple solution.
698 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
699 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
700 newTreeEntry(VL, false);
704 // We now know that this is a vector of instructions of the same type from
707 // Check if this is a duplicate of another entry.
708 if (ScalarToTreeEntry.count(VL[0])) {
709 int Idx = ScalarToTreeEntry[VL[0]];
710 TreeEntry *E = &VectorizableTree[Idx];
711 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
712 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
713 if (E->Scalars[i] != VL[i]) {
714 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
715 newTreeEntry(VL, false);
719 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
723 // Check that none of the instructions in the bundle are already in the tree.
724 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
725 if (ScalarToTreeEntry.count(VL[i])) {
726 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
727 ") is already in tree.\n");
728 newTreeEntry(VL, false);
733 // If any of the scalars appears in the table OR it is marked as a value that
734 // needs to stat scalar then we need to gather the scalars.
735 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
736 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
737 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
738 newTreeEntry(VL, false);
743 // Check that all of the users of the scalars that we want to vectorize are
745 Instruction *VL0 = cast<Instruction>(VL[0]);
746 int MyLastIndex = getLastIndex(VL);
747 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
749 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
750 Instruction *Scalar = cast<Instruction>(VL[i]);
751 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
752 for (User *U : Scalar->users()) {
753 DEBUG(dbgs() << "SLP: \tUser " << *U << ". \n");
754 Instruction *UI = dyn_cast<Instruction>(U);
756 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
757 newTreeEntry(VL, false);
761 // We don't care if the user is in a different basic block.
762 BasicBlock *UserBlock = UI->getParent();
763 if (UserBlock != BB) {
764 DEBUG(dbgs() << "SLP: User from a different basic block "
769 // If this is a PHINode within this basic block then we can place the
770 // extract wherever we want.
771 if (isa<PHINode>(*UI)) {
772 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *UI << ". \n");
776 // Check if this is a safe in-tree user.
777 if (ScalarToTreeEntry.count(UI)) {
778 int Idx = ScalarToTreeEntry[UI];
779 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
780 if (VecLocation <= MyLastIndex) {
781 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
782 newTreeEntry(VL, false);
785 DEBUG(dbgs() << "SLP: In-tree user (" << *UI << ") at #" <<
786 VecLocation << " vector value (" << *Scalar << ") at #"
787 << MyLastIndex << ".\n");
791 // Ignore users in the user ignore list.
792 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UI) !=
793 UserIgnoreList.end())
796 // Make sure that we can schedule this unknown user.
797 BlockNumbering &BN = getBlockNumbering(BB);
798 int UserIndex = BN.getIndex(UI);
799 if (UserIndex < MyLastIndex) {
801 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
803 newTreeEntry(VL, false);
809 // Check that every instructions appears once in this bundle.
810 for (unsigned i = 0, e = VL.size(); i < e; ++i)
811 for (unsigned j = i+1; j < e; ++j)
812 if (VL[i] == VL[j]) {
813 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
814 newTreeEntry(VL, false);
818 // Check that instructions in this bundle don't reference other instructions.
819 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
820 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
821 for (User *U : VL[i]->users()) {
822 for (unsigned j = 0; j < e; ++j) {
823 if (i != j && U == VL[j]) {
824 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << *U << ". \n");
825 newTreeEntry(VL, false);
832 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
834 // Check if it is safe to sink the loads or the stores.
835 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
836 Instruction *Last = getLastInstruction(VL);
838 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
841 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
843 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
844 << "\n because of " << *Barrier << ". Gathering.\n");
845 newTreeEntry(VL, false);
852 case Instruction::PHI: {
853 PHINode *PH = dyn_cast<PHINode>(VL0);
855 // Check for terminator values (e.g. invoke).
856 for (unsigned j = 0; j < VL.size(); ++j)
857 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
858 TerminatorInst *Term = dyn_cast<TerminatorInst>(
859 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
861 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
862 newTreeEntry(VL, false);
867 newTreeEntry(VL, true);
868 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
870 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
872 // Prepare the operand vector.
873 for (unsigned j = 0; j < VL.size(); ++j)
874 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
875 PH->getIncomingBlock(i)));
877 buildTree_rec(Operands, Depth + 1);
881 case Instruction::ExtractElement: {
882 bool Reuse = CanReuseExtract(VL);
884 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
886 newTreeEntry(VL, Reuse);
889 case Instruction::Load: {
890 // Check if the loads are consecutive or of we need to swizzle them.
891 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
892 LoadInst *L = cast<LoadInst>(VL[i]);
893 if (!L->isSimple()) {
894 newTreeEntry(VL, false);
895 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
898 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
899 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
900 ++NumLoadsWantToChangeOrder;
902 newTreeEntry(VL, false);
903 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
907 ++NumLoadsWantToKeepOrder;
908 newTreeEntry(VL, true);
909 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
912 case Instruction::ZExt:
913 case Instruction::SExt:
914 case Instruction::FPToUI:
915 case Instruction::FPToSI:
916 case Instruction::FPExt:
917 case Instruction::PtrToInt:
918 case Instruction::IntToPtr:
919 case Instruction::SIToFP:
920 case Instruction::UIToFP:
921 case Instruction::Trunc:
922 case Instruction::FPTrunc:
923 case Instruction::BitCast: {
924 Type *SrcTy = VL0->getOperand(0)->getType();
925 for (unsigned i = 0; i < VL.size(); ++i) {
926 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
927 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
928 newTreeEntry(VL, false);
929 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
933 newTreeEntry(VL, true);
934 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
936 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
938 // Prepare the operand vector.
939 for (unsigned j = 0; j < VL.size(); ++j)
940 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
942 buildTree_rec(Operands, Depth+1);
946 case Instruction::ICmp:
947 case Instruction::FCmp: {
948 // Check that all of the compares have the same predicate.
949 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
950 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
951 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
952 CmpInst *Cmp = cast<CmpInst>(VL[i]);
953 if (Cmp->getPredicate() != P0 ||
954 Cmp->getOperand(0)->getType() != ComparedTy) {
955 newTreeEntry(VL, false);
956 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
961 newTreeEntry(VL, true);
962 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
964 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
966 // Prepare the operand vector.
967 for (unsigned j = 0; j < VL.size(); ++j)
968 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
970 buildTree_rec(Operands, Depth+1);
974 case Instruction::Select:
975 case Instruction::Add:
976 case Instruction::FAdd:
977 case Instruction::Sub:
978 case Instruction::FSub:
979 case Instruction::Mul:
980 case Instruction::FMul:
981 case Instruction::UDiv:
982 case Instruction::SDiv:
983 case Instruction::FDiv:
984 case Instruction::URem:
985 case Instruction::SRem:
986 case Instruction::FRem:
987 case Instruction::Shl:
988 case Instruction::LShr:
989 case Instruction::AShr:
990 case Instruction::And:
991 case Instruction::Or:
992 case Instruction::Xor: {
993 newTreeEntry(VL, true);
994 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
996 // Sort operands of the instructions so that each side is more likely to
997 // have the same opcode.
998 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
999 ValueList Left, Right;
1000 reorderInputsAccordingToOpcode(VL, Left, Right);
1001 BasicBlock *LeftBB = getSameBlock(Left);
1002 BasicBlock *RightBB = getSameBlock(Right);
1003 // If we have common uses on separate paths in the tree make sure we
1004 // process the one with greater common depth first.
1005 // We can use block numbering to determine the subtree traversal as
1006 // earler user has to come in between the common use and the later user.
1007 if (LeftBB && RightBB && LeftBB == RightBB &&
1008 getLastIndex(Right) > getLastIndex(Left)) {
1009 buildTree_rec(Right, Depth + 1);
1010 buildTree_rec(Left, Depth + 1);
1012 buildTree_rec(Left, Depth + 1);
1013 buildTree_rec(Right, Depth + 1);
1018 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1020 // Prepare the operand vector.
1021 for (unsigned j = 0; j < VL.size(); ++j)
1022 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1024 buildTree_rec(Operands, Depth+1);
1028 case Instruction::GetElementPtr: {
1029 // We don't combine GEPs with complicated (nested) indexing.
1030 for (unsigned j = 0; j < VL.size(); ++j) {
1031 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1032 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1033 newTreeEntry(VL, false);
1038 // We can't combine several GEPs into one vector if they operate on
1040 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1041 for (unsigned j = 0; j < VL.size(); ++j) {
1042 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1044 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1045 newTreeEntry(VL, false);
1050 // We don't combine GEPs with non-constant indexes.
1051 for (unsigned j = 0; j < VL.size(); ++j) {
1052 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1053 if (!isa<ConstantInt>(Op)) {
1055 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1056 newTreeEntry(VL, false);
1061 newTreeEntry(VL, true);
1062 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1063 for (unsigned i = 0, e = 2; i < e; ++i) {
1065 // Prepare the operand vector.
1066 for (unsigned j = 0; j < VL.size(); ++j)
1067 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1069 buildTree_rec(Operands, Depth + 1);
1073 case Instruction::Store: {
1074 // Check if the stores are consecutive or of we need to swizzle them.
1075 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1076 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1077 newTreeEntry(VL, false);
1078 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1082 newTreeEntry(VL, true);
1083 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1086 for (unsigned j = 0; j < VL.size(); ++j)
1087 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1089 // We can ignore these values because we are sinking them down.
1090 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
1091 buildTree_rec(Operands, Depth + 1);
1094 case Instruction::Call: {
1095 // Check if the calls are all to the same vectorizable intrinsic.
1096 CallInst *CI = cast<CallInst>(VL[0]);
1097 // Check if this is an Intrinsic call or something that can be
1098 // represented by an intrinsic call
1099 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1100 if (!isTriviallyVectorizable(ID)) {
1101 newTreeEntry(VL, false);
1102 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1105 Function *Int = CI->getCalledFunction();
1106 Value *A1I = nullptr;
1107 if (hasVectorInstrinsicScalarOpd(ID, 1))
1108 A1I = CI->getArgOperand(1);
1109 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1110 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1111 if (!CI2 || CI2->getCalledFunction() != Int ||
1112 getIntrinsicIDForCall(CI2, TLI) != ID) {
1113 newTreeEntry(VL, false);
1114 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1118 // ctlz,cttz and powi are special intrinsics whose second argument
1119 // should be same in order for them to be vectorized.
1120 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1121 Value *A1J = CI2->getArgOperand(1);
1123 newTreeEntry(VL, false);
1124 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1125 << " argument "<< A1I<<"!=" << A1J
1132 newTreeEntry(VL, true);
1133 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1135 // Prepare the operand vector.
1136 for (unsigned j = 0; j < VL.size(); ++j) {
1137 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1138 Operands.push_back(CI2->getArgOperand(i));
1140 buildTree_rec(Operands, Depth + 1);
1144 case Instruction::ShuffleVector: {
1145 // If this is not an alternate sequence of opcode like add-sub
1146 // then do not vectorize this instruction.
1147 if (!isAltShuffle) {
1148 newTreeEntry(VL, false);
1149 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1152 newTreeEntry(VL, true);
1153 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1154 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1156 // Prepare the operand vector.
1157 for (unsigned j = 0; j < VL.size(); ++j)
1158 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1160 buildTree_rec(Operands, Depth + 1);
1165 newTreeEntry(VL, false);
1166 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1171 int BoUpSLP::getEntryCost(TreeEntry *E) {
1172 ArrayRef<Value*> VL = E->Scalars;
1174 Type *ScalarTy = VL[0]->getType();
1175 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1176 ScalarTy = SI->getValueOperand()->getType();
1177 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1179 if (E->NeedToGather) {
1180 if (allConstant(VL))
1183 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1185 return getGatherCost(E->Scalars);
1187 unsigned Opcode = getSameOpcode(VL);
1188 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1189 Instruction *VL0 = cast<Instruction>(VL[0]);
1191 case Instruction::PHI: {
1194 case Instruction::ExtractElement: {
1195 if (CanReuseExtract(VL)) {
1197 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1198 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1200 // Take credit for instruction that will become dead.
1202 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1206 return getGatherCost(VecTy);
1208 case Instruction::ZExt:
1209 case Instruction::SExt:
1210 case Instruction::FPToUI:
1211 case Instruction::FPToSI:
1212 case Instruction::FPExt:
1213 case Instruction::PtrToInt:
1214 case Instruction::IntToPtr:
1215 case Instruction::SIToFP:
1216 case Instruction::UIToFP:
1217 case Instruction::Trunc:
1218 case Instruction::FPTrunc:
1219 case Instruction::BitCast: {
1220 Type *SrcTy = VL0->getOperand(0)->getType();
1222 // Calculate the cost of this instruction.
1223 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1224 VL0->getType(), SrcTy);
1226 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1227 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1228 return VecCost - ScalarCost;
1230 case Instruction::FCmp:
1231 case Instruction::ICmp:
1232 case Instruction::Select:
1233 case Instruction::Add:
1234 case Instruction::FAdd:
1235 case Instruction::Sub:
1236 case Instruction::FSub:
1237 case Instruction::Mul:
1238 case Instruction::FMul:
1239 case Instruction::UDiv:
1240 case Instruction::SDiv:
1241 case Instruction::FDiv:
1242 case Instruction::URem:
1243 case Instruction::SRem:
1244 case Instruction::FRem:
1245 case Instruction::Shl:
1246 case Instruction::LShr:
1247 case Instruction::AShr:
1248 case Instruction::And:
1249 case Instruction::Or:
1250 case Instruction::Xor: {
1251 // Calculate the cost of this instruction.
1254 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1255 Opcode == Instruction::Select) {
1256 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1257 ScalarCost = VecTy->getNumElements() *
1258 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1259 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1261 // Certain instructions can be cheaper to vectorize if they have a
1262 // constant second vector operand.
1263 TargetTransformInfo::OperandValueKind Op1VK =
1264 TargetTransformInfo::OK_AnyValue;
1265 TargetTransformInfo::OperandValueKind Op2VK =
1266 TargetTransformInfo::OK_UniformConstantValue;
1268 // If all operands are exactly the same ConstantInt then set the
1269 // operand kind to OK_UniformConstantValue.
1270 // If instead not all operands are constants, then set the operand kind
1271 // to OK_AnyValue. If all operands are constants but not the same,
1272 // then set the operand kind to OK_NonUniformConstantValue.
1273 ConstantInt *CInt = nullptr;
1274 for (unsigned i = 0; i < VL.size(); ++i) {
1275 const Instruction *I = cast<Instruction>(VL[i]);
1276 if (!isa<ConstantInt>(I->getOperand(1))) {
1277 Op2VK = TargetTransformInfo::OK_AnyValue;
1281 CInt = cast<ConstantInt>(I->getOperand(1));
1284 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1285 CInt != cast<ConstantInt>(I->getOperand(1)))
1286 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1290 VecTy->getNumElements() *
1291 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1292 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1294 return VecCost - ScalarCost;
1296 case Instruction::GetElementPtr: {
1297 TargetTransformInfo::OperandValueKind Op1VK =
1298 TargetTransformInfo::OK_AnyValue;
1299 TargetTransformInfo::OperandValueKind Op2VK =
1300 TargetTransformInfo::OK_UniformConstantValue;
1303 VecTy->getNumElements() *
1304 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1306 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1308 return VecCost - ScalarCost;
1310 case Instruction::Load: {
1311 // Cost of wide load - cost of scalar loads.
1312 int ScalarLdCost = VecTy->getNumElements() *
1313 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1314 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1315 return VecLdCost - ScalarLdCost;
1317 case Instruction::Store: {
1318 // We know that we can merge the stores. Calculate the cost.
1319 int ScalarStCost = VecTy->getNumElements() *
1320 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1321 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1322 return VecStCost - ScalarStCost;
1324 case Instruction::Call: {
1325 CallInst *CI = cast<CallInst>(VL0);
1326 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1328 // Calculate the cost of the scalar and vector calls.
1329 SmallVector<Type*, 4> ScalarTys, VecTys;
1330 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1331 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1332 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1333 VecTy->getNumElements()));
1336 int ScalarCallCost = VecTy->getNumElements() *
1337 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1339 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1341 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1342 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1343 << " for " << *CI << "\n");
1345 return VecCallCost - ScalarCallCost;
1347 case Instruction::ShuffleVector: {
1348 TargetTransformInfo::OperandValueKind Op1VK =
1349 TargetTransformInfo::OK_AnyValue;
1350 TargetTransformInfo::OperandValueKind Op2VK =
1351 TargetTransformInfo::OK_AnyValue;
1354 for (unsigned i = 0; i < VL.size(); ++i) {
1355 Instruction *I = cast<Instruction>(VL[i]);
1359 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1361 // VecCost is equal to sum of the cost of creating 2 vectors
1362 // and the cost of creating shuffle.
1363 Instruction *I0 = cast<Instruction>(VL[0]);
1365 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1366 Instruction *I1 = cast<Instruction>(VL[1]);
1368 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1370 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1371 return VecCost - ScalarCost;
1374 llvm_unreachable("Unknown instruction");
1378 bool BoUpSLP::isFullyVectorizableTinyTree() {
1379 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1380 VectorizableTree.size() << " is fully vectorizable .\n");
1382 // We only handle trees of height 2.
1383 if (VectorizableTree.size() != 2)
1386 // Handle splat stores.
1387 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1390 // Gathering cost would be too much for tiny trees.
1391 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1397 int BoUpSLP::getTreeCost() {
1399 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1400 VectorizableTree.size() << ".\n");
1402 // We only vectorize tiny trees if it is fully vectorizable.
1403 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1404 if (!VectorizableTree.size()) {
1405 assert(!ExternalUses.size() && "We should not have any external users");
1410 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1412 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1413 int C = getEntryCost(&VectorizableTree[i]);
1414 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1415 << *VectorizableTree[i].Scalars[0] << " .\n");
1419 SmallSet<Value *, 16> ExtractCostCalculated;
1420 int ExtractCost = 0;
1421 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1423 // We only add extract cost once for the same scalar.
1424 if (!ExtractCostCalculated.insert(I->Scalar))
1427 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1428 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1432 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1433 return Cost + ExtractCost;
1436 int BoUpSLP::getGatherCost(Type *Ty) {
1438 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1439 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1443 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1444 // Find the type of the operands in VL.
1445 Type *ScalarTy = VL[0]->getType();
1446 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1447 ScalarTy = SI->getValueOperand()->getType();
1448 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1449 // Find the cost of inserting/extracting values from the vector.
1450 return getGatherCost(VecTy);
1453 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1454 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1455 return AA->getLocation(SI);
1456 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1457 return AA->getLocation(LI);
1458 return AliasAnalysis::Location();
1461 Value *BoUpSLP::getPointerOperand(Value *I) {
1462 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1463 return LI->getPointerOperand();
1464 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1465 return SI->getPointerOperand();
1469 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1470 if (LoadInst *L = dyn_cast<LoadInst>(I))
1471 return L->getPointerAddressSpace();
1472 if (StoreInst *S = dyn_cast<StoreInst>(I))
1473 return S->getPointerAddressSpace();
1477 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1478 Value *PtrA = getPointerOperand(A);
1479 Value *PtrB = getPointerOperand(B);
1480 unsigned ASA = getAddressSpaceOperand(A);
1481 unsigned ASB = getAddressSpaceOperand(B);
1483 // Check that the address spaces match and that the pointers are valid.
1484 if (!PtrA || !PtrB || (ASA != ASB))
1487 // Make sure that A and B are different pointers of the same type.
1488 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1491 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1492 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1493 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1495 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1496 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1497 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1499 APInt OffsetDelta = OffsetB - OffsetA;
1501 // Check if they are based on the same pointer. That makes the offsets
1504 return OffsetDelta == Size;
1506 // Compute the necessary base pointer delta to have the necessary final delta
1507 // equal to the size.
1508 APInt BaseDelta = Size - OffsetDelta;
1510 // Otherwise compute the distance with SCEV between the base pointers.
1511 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1512 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1513 const SCEV *C = SE->getConstant(BaseDelta);
1514 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1515 return X == PtrSCEVB;
1518 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1519 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1520 BasicBlock::iterator I = Src, E = Dst;
1521 /// Scan all of the instruction from SRC to DST and check if
1522 /// the source may alias.
1523 for (++I; I != E; ++I) {
1524 // Ignore store instructions that are marked as 'ignore'.
1525 if (MemBarrierIgnoreList.count(I))
1527 if (Src->mayWriteToMemory()) /* Write */ {
1528 if (!I->mayReadOrWriteMemory())
1531 if (!I->mayWriteToMemory())
1534 AliasAnalysis::Location A = getLocation(&*I);
1535 AliasAnalysis::Location B = getLocation(Src);
1537 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1543 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1544 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1545 assert(BB == getSameBlock(VL) && "Invalid block");
1546 BlockNumbering &BN = getBlockNumbering(BB);
1548 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1549 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1550 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1554 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1555 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1556 assert(BB == getSameBlock(VL) && "Invalid block");
1557 BlockNumbering &BN = getBlockNumbering(BB);
1559 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1560 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1561 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1562 Instruction *I = BN.getInstruction(MaxIdx);
1563 assert(I && "bad location");
1567 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1568 Instruction *VL0 = cast<Instruction>(VL[0]);
1569 Instruction *LastInst = getLastInstruction(VL);
1570 BasicBlock::iterator NextInst = LastInst;
1572 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1573 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1576 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1577 Value *Vec = UndefValue::get(Ty);
1578 // Generate the 'InsertElement' instruction.
1579 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1580 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1581 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1582 GatherSeq.insert(Insrt);
1583 CSEBlocks.insert(Insrt->getParent());
1585 // Add to our 'need-to-extract' list.
1586 if (ScalarToTreeEntry.count(VL[i])) {
1587 int Idx = ScalarToTreeEntry[VL[i]];
1588 TreeEntry *E = &VectorizableTree[Idx];
1589 // Find which lane we need to extract.
1591 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1592 // Is this the lane of the scalar that we are looking for ?
1593 if (E->Scalars[Lane] == VL[i]) {
1598 assert(FoundLane >= 0 && "Could not find the correct lane");
1599 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1607 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1608 SmallDenseMap<Value*, int>::const_iterator Entry
1609 = ScalarToTreeEntry.find(VL[0]);
1610 if (Entry != ScalarToTreeEntry.end()) {
1611 int Idx = Entry->second;
1612 const TreeEntry *En = &VectorizableTree[Idx];
1613 if (En->isSame(VL) && En->VectorizedValue)
1614 return En->VectorizedValue;
1619 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1620 if (ScalarToTreeEntry.count(VL[0])) {
1621 int Idx = ScalarToTreeEntry[VL[0]];
1622 TreeEntry *E = &VectorizableTree[Idx];
1624 return vectorizeTree(E);
1627 Type *ScalarTy = VL[0]->getType();
1628 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1629 ScalarTy = SI->getValueOperand()->getType();
1630 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1632 return Gather(VL, VecTy);
1635 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1636 IRBuilder<>::InsertPointGuard Guard(Builder);
1638 if (E->VectorizedValue) {
1639 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1640 return E->VectorizedValue;
1643 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1644 Type *ScalarTy = VL0->getType();
1645 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1646 ScalarTy = SI->getValueOperand()->getType();
1647 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1649 if (E->NeedToGather) {
1650 setInsertPointAfterBundle(E->Scalars);
1651 return Gather(E->Scalars, VecTy);
1653 unsigned Opcode = getSameOpcode(E->Scalars);
1656 case Instruction::PHI: {
1657 PHINode *PH = dyn_cast<PHINode>(VL0);
1658 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1659 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1660 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1661 E->VectorizedValue = NewPhi;
1663 // PHINodes may have multiple entries from the same block. We want to
1664 // visit every block once.
1665 SmallSet<BasicBlock*, 4> VisitedBBs;
1667 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1669 BasicBlock *IBB = PH->getIncomingBlock(i);
1671 if (!VisitedBBs.insert(IBB)) {
1672 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1676 // Prepare the operand vector.
1677 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1678 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1679 getIncomingValueForBlock(IBB));
1681 Builder.SetInsertPoint(IBB->getTerminator());
1682 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1683 Value *Vec = vectorizeTree(Operands);
1684 NewPhi->addIncoming(Vec, IBB);
1687 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1688 "Invalid number of incoming values");
1692 case Instruction::ExtractElement: {
1693 if (CanReuseExtract(E->Scalars)) {
1694 Value *V = VL0->getOperand(0);
1695 E->VectorizedValue = V;
1698 return Gather(E->Scalars, VecTy);
1700 case Instruction::ZExt:
1701 case Instruction::SExt:
1702 case Instruction::FPToUI:
1703 case Instruction::FPToSI:
1704 case Instruction::FPExt:
1705 case Instruction::PtrToInt:
1706 case Instruction::IntToPtr:
1707 case Instruction::SIToFP:
1708 case Instruction::UIToFP:
1709 case Instruction::Trunc:
1710 case Instruction::FPTrunc:
1711 case Instruction::BitCast: {
1713 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1714 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1716 setInsertPointAfterBundle(E->Scalars);
1718 Value *InVec = vectorizeTree(INVL);
1720 if (Value *V = alreadyVectorized(E->Scalars))
1723 CastInst *CI = dyn_cast<CastInst>(VL0);
1724 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1725 E->VectorizedValue = V;
1726 ++NumVectorInstructions;
1729 case Instruction::FCmp:
1730 case Instruction::ICmp: {
1731 ValueList LHSV, RHSV;
1732 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1733 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1734 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1737 setInsertPointAfterBundle(E->Scalars);
1739 Value *L = vectorizeTree(LHSV);
1740 Value *R = vectorizeTree(RHSV);
1742 if (Value *V = alreadyVectorized(E->Scalars))
1745 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1747 if (Opcode == Instruction::FCmp)
1748 V = Builder.CreateFCmp(P0, L, R);
1750 V = Builder.CreateICmp(P0, L, R);
1752 E->VectorizedValue = V;
1753 ++NumVectorInstructions;
1756 case Instruction::Select: {
1757 ValueList TrueVec, FalseVec, CondVec;
1758 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1759 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1760 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1761 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1764 setInsertPointAfterBundle(E->Scalars);
1766 Value *Cond = vectorizeTree(CondVec);
1767 Value *True = vectorizeTree(TrueVec);
1768 Value *False = vectorizeTree(FalseVec);
1770 if (Value *V = alreadyVectorized(E->Scalars))
1773 Value *V = Builder.CreateSelect(Cond, True, False);
1774 E->VectorizedValue = V;
1775 ++NumVectorInstructions;
1778 case Instruction::Add:
1779 case Instruction::FAdd:
1780 case Instruction::Sub:
1781 case Instruction::FSub:
1782 case Instruction::Mul:
1783 case Instruction::FMul:
1784 case Instruction::UDiv:
1785 case Instruction::SDiv:
1786 case Instruction::FDiv:
1787 case Instruction::URem:
1788 case Instruction::SRem:
1789 case Instruction::FRem:
1790 case Instruction::Shl:
1791 case Instruction::LShr:
1792 case Instruction::AShr:
1793 case Instruction::And:
1794 case Instruction::Or:
1795 case Instruction::Xor: {
1796 ValueList LHSVL, RHSVL;
1797 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1798 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1800 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1801 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1802 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1805 setInsertPointAfterBundle(E->Scalars);
1807 Value *LHS = vectorizeTree(LHSVL);
1808 Value *RHS = vectorizeTree(RHSVL);
1810 if (LHS == RHS && isa<Instruction>(LHS)) {
1811 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1814 if (Value *V = alreadyVectorized(E->Scalars))
1817 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1818 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1819 E->VectorizedValue = V;
1820 ++NumVectorInstructions;
1822 if (Instruction *I = dyn_cast<Instruction>(V))
1823 return propagateMetadata(I, E->Scalars);
1827 case Instruction::Load: {
1828 // Loads are inserted at the head of the tree because we don't want to
1829 // sink them all the way down past store instructions.
1830 setInsertPointAfterBundle(E->Scalars);
1832 LoadInst *LI = cast<LoadInst>(VL0);
1833 unsigned AS = LI->getPointerAddressSpace();
1835 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1836 VecTy->getPointerTo(AS));
1837 unsigned Alignment = LI->getAlignment();
1838 LI = Builder.CreateLoad(VecPtr);
1840 Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
1841 LI->setAlignment(Alignment);
1842 E->VectorizedValue = LI;
1843 ++NumVectorInstructions;
1844 return propagateMetadata(LI, E->Scalars);
1846 case Instruction::Store: {
1847 StoreInst *SI = cast<StoreInst>(VL0);
1848 unsigned Alignment = SI->getAlignment();
1849 unsigned AS = SI->getPointerAddressSpace();
1852 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1853 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1855 setInsertPointAfterBundle(E->Scalars);
1857 Value *VecValue = vectorizeTree(ValueOp);
1858 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1859 VecTy->getPointerTo(AS));
1860 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1862 Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
1863 S->setAlignment(Alignment);
1864 E->VectorizedValue = S;
1865 ++NumVectorInstructions;
1866 return propagateMetadata(S, E->Scalars);
1868 case Instruction::GetElementPtr: {
1869 setInsertPointAfterBundle(E->Scalars);
1872 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1873 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
1875 Value *Op0 = vectorizeTree(Op0VL);
1877 std::vector<Value *> OpVecs;
1878 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
1881 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1882 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
1884 Value *OpVec = vectorizeTree(OpVL);
1885 OpVecs.push_back(OpVec);
1888 Value *V = Builder.CreateGEP(Op0, OpVecs);
1889 E->VectorizedValue = V;
1890 ++NumVectorInstructions;
1892 if (Instruction *I = dyn_cast<Instruction>(V))
1893 return propagateMetadata(I, E->Scalars);
1897 case Instruction::Call: {
1898 CallInst *CI = cast<CallInst>(VL0);
1899 setInsertPointAfterBundle(E->Scalars);
1901 Intrinsic::ID IID = Intrinsic::not_intrinsic;
1902 if (CI && (FI = CI->getCalledFunction())) {
1903 IID = (Intrinsic::ID) FI->getIntrinsicID();
1905 std::vector<Value *> OpVecs;
1906 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1908 // ctlz,cttz and powi are special intrinsics whose second argument is
1909 // a scalar. This argument should not be vectorized.
1910 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
1911 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
1912 OpVecs.push_back(CEI->getArgOperand(j));
1915 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1916 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1917 OpVL.push_back(CEI->getArgOperand(j));
1920 Value *OpVec = vectorizeTree(OpVL);
1921 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1922 OpVecs.push_back(OpVec);
1925 Module *M = F->getParent();
1926 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1927 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1928 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1929 Value *V = Builder.CreateCall(CF, OpVecs);
1930 E->VectorizedValue = V;
1931 ++NumVectorInstructions;
1934 case Instruction::ShuffleVector: {
1935 ValueList LHSVL, RHSVL;
1936 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1937 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1938 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1940 setInsertPointAfterBundle(E->Scalars);
1942 Value *LHS = vectorizeTree(LHSVL);
1943 Value *RHS = vectorizeTree(RHSVL);
1945 if (Value *V = alreadyVectorized(E->Scalars))
1948 // Create a vector of LHS op1 RHS
1949 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
1950 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
1952 // Create a vector of LHS op2 RHS
1953 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
1954 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
1955 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
1957 // Create appropriate shuffle to take alternative operations from
1959 std::vector<Constant *> Mask(E->Scalars.size());
1960 unsigned e = E->Scalars.size();
1961 for (unsigned i = 0; i < e; ++i) {
1963 Mask[i] = Builder.getInt32(e + i);
1965 Mask[i] = Builder.getInt32(i);
1968 Value *ShuffleMask = ConstantVector::get(Mask);
1970 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
1971 E->VectorizedValue = V;
1972 ++NumVectorInstructions;
1973 if (Instruction *I = dyn_cast<Instruction>(V))
1974 return propagateMetadata(I, E->Scalars);
1979 llvm_unreachable("unknown inst");
1984 Value *BoUpSLP::vectorizeTree() {
1985 Builder.SetInsertPoint(F->getEntryBlock().begin());
1986 vectorizeTree(&VectorizableTree[0]);
1988 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1990 // Extract all of the elements with the external uses.
1991 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1993 Value *Scalar = it->Scalar;
1994 llvm::User *User = it->User;
1996 // Skip users that we already RAUW. This happens when one instruction
1997 // has multiple uses of the same value.
1998 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2001 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2003 int Idx = ScalarToTreeEntry[Scalar];
2004 TreeEntry *E = &VectorizableTree[Idx];
2005 assert(!E->NeedToGather && "Extracting from a gather list");
2007 Value *Vec = E->VectorizedValue;
2008 assert(Vec && "Can't find vectorizable value");
2010 Value *Lane = Builder.getInt32(it->Lane);
2011 // Generate extracts for out-of-tree users.
2012 // Find the insertion point for the extractelement lane.
2013 if (isa<Instruction>(Vec)){
2014 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2015 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2016 if (PH->getIncomingValue(i) == Scalar) {
2017 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2018 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2019 CSEBlocks.insert(PH->getIncomingBlock(i));
2020 PH->setOperand(i, Ex);
2024 Builder.SetInsertPoint(cast<Instruction>(User));
2025 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2026 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2027 User->replaceUsesOfWith(Scalar, Ex);
2030 Builder.SetInsertPoint(F->getEntryBlock().begin());
2031 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2032 CSEBlocks.insert(&F->getEntryBlock());
2033 User->replaceUsesOfWith(Scalar, Ex);
2036 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2039 // For each vectorized value:
2040 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2041 TreeEntry *Entry = &VectorizableTree[EIdx];
2044 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2045 Value *Scalar = Entry->Scalars[Lane];
2046 // No need to handle users of gathered values.
2047 if (Entry->NeedToGather)
2050 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2052 Type *Ty = Scalar->getType();
2053 if (!Ty->isVoidTy()) {
2055 for (User *U : Scalar->users()) {
2056 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2058 assert((ScalarToTreeEntry.count(U) ||
2059 // It is legal to replace users in the ignorelist by undef.
2060 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2061 UserIgnoreList.end())) &&
2062 "Replacing out-of-tree value with undef");
2065 Value *Undef = UndefValue::get(Ty);
2066 Scalar->replaceAllUsesWith(Undef);
2068 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2069 cast<Instruction>(Scalar)->eraseFromParent();
2073 for (auto &BN : BlocksNumbers)
2076 Builder.ClearInsertionPoint();
2078 return VectorizableTree[0].VectorizedValue;
2081 void BoUpSLP::optimizeGatherSequence() {
2082 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2083 << " gather sequences instructions.\n");
2084 // LICM InsertElementInst sequences.
2085 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2086 e = GatherSeq.end(); it != e; ++it) {
2087 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2092 // Check if this block is inside a loop.
2093 Loop *L = LI->getLoopFor(Insert->getParent());
2097 // Check if it has a preheader.
2098 BasicBlock *PreHeader = L->getLoopPreheader();
2102 // If the vector or the element that we insert into it are
2103 // instructions that are defined in this basic block then we can't
2104 // hoist this instruction.
2105 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2106 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2107 if (CurrVec && L->contains(CurrVec))
2109 if (NewElem && L->contains(NewElem))
2112 // We can hoist this instruction. Move it to the pre-header.
2113 Insert->moveBefore(PreHeader->getTerminator());
2116 // Make a list of all reachable blocks in our CSE queue.
2117 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2118 CSEWorkList.reserve(CSEBlocks.size());
2119 for (BasicBlock *BB : CSEBlocks)
2120 if (DomTreeNode *N = DT->getNode(BB)) {
2121 assert(DT->isReachableFromEntry(N));
2122 CSEWorkList.push_back(N);
2125 // Sort blocks by domination. This ensures we visit a block after all blocks
2126 // dominating it are visited.
2127 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2128 [this](const DomTreeNode *A, const DomTreeNode *B) {
2129 return DT->properlyDominates(A, B);
2132 // Perform O(N^2) search over the gather sequences and merge identical
2133 // instructions. TODO: We can further optimize this scan if we split the
2134 // instructions into different buckets based on the insert lane.
2135 SmallVector<Instruction *, 16> Visited;
2136 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2137 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2138 "Worklist not sorted properly!");
2139 BasicBlock *BB = (*I)->getBlock();
2140 // For all instructions in blocks containing gather sequences:
2141 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2142 Instruction *In = it++;
2143 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2146 // Check if we can replace this instruction with any of the
2147 // visited instructions.
2148 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2151 if (In->isIdenticalTo(*v) &&
2152 DT->dominates((*v)->getParent(), In->getParent())) {
2153 In->replaceAllUsesWith(*v);
2154 In->eraseFromParent();
2160 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2161 Visited.push_back(In);
2169 /// The SLPVectorizer Pass.
2170 struct SLPVectorizer : public FunctionPass {
2171 typedef SmallVector<StoreInst *, 8> StoreList;
2172 typedef MapVector<Value *, StoreList> StoreListMap;
2174 /// Pass identification, replacement for typeid
2177 explicit SLPVectorizer() : FunctionPass(ID) {
2178 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2181 ScalarEvolution *SE;
2182 const DataLayout *DL;
2183 TargetTransformInfo *TTI;
2184 TargetLibraryInfo *TLI;
2189 bool runOnFunction(Function &F) override {
2190 if (skipOptnoneFunction(F))
2193 SE = &getAnalysis<ScalarEvolution>();
2194 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2195 DL = DLP ? &DLP->getDataLayout() : nullptr;
2196 TTI = &getAnalysis<TargetTransformInfo>();
2197 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2198 AA = &getAnalysis<AliasAnalysis>();
2199 LI = &getAnalysis<LoopInfo>();
2200 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2203 bool Changed = false;
2205 // If the target claims to have no vector registers don't attempt
2207 if (!TTI->getNumberOfRegisters(true))
2210 // Must have DataLayout. We can't require it because some tests run w/o
2215 // Don't vectorize when the attribute NoImplicitFloat is used.
2216 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2219 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2221 // Use the bottom up slp vectorizer to construct chains that start with
2222 // store instructions.
2223 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2225 // Scan the blocks in the function in post order.
2226 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2227 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2228 BasicBlock *BB = *it;
2229 // Vectorize trees that end at stores.
2230 if (unsigned count = collectStores(BB, R)) {
2232 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2233 Changed |= vectorizeStoreChains(R);
2236 // Vectorize trees that end at reductions.
2237 Changed |= vectorizeChainsInBlock(BB, R);
2241 R.optimizeGatherSequence();
2242 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2243 DEBUG(verifyFunction(F));
2248 void getAnalysisUsage(AnalysisUsage &AU) const override {
2249 FunctionPass::getAnalysisUsage(AU);
2250 AU.addRequired<ScalarEvolution>();
2251 AU.addRequired<AliasAnalysis>();
2252 AU.addRequired<TargetTransformInfo>();
2253 AU.addRequired<LoopInfo>();
2254 AU.addRequired<DominatorTreeWrapperPass>();
2255 AU.addPreserved<LoopInfo>();
2256 AU.addPreserved<DominatorTreeWrapperPass>();
2257 AU.setPreservesCFG();
2262 /// \brief Collect memory references and sort them according to their base
2263 /// object. We sort the stores to their base objects to reduce the cost of the
2264 /// quadratic search on the stores. TODO: We can further reduce this cost
2265 /// if we flush the chain creation every time we run into a memory barrier.
2266 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2268 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2269 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2271 /// \brief Try to vectorize a list of operands.
2272 /// \@param BuildVector A list of users to ignore for the purpose of
2273 /// scheduling and that don't need extracting.
2274 /// \returns true if a value was vectorized.
2275 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2276 ArrayRef<Value *> BuildVector = None,
2277 bool allowReorder = false);
2279 /// \brief Try to vectorize a chain that may start at the operands of \V;
2280 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2282 /// \brief Vectorize the stores that were collected in StoreRefs.
2283 bool vectorizeStoreChains(BoUpSLP &R);
2285 /// \brief Scan the basic block and look for patterns that are likely to start
2286 /// a vectorization chain.
2287 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2289 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2292 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2295 StoreListMap StoreRefs;
2298 /// \brief Check that the Values in the slice in VL array are still existent in
2299 /// the WeakVH array.
2300 /// Vectorization of part of the VL array may cause later values in the VL array
2301 /// to become invalid. We track when this has happened in the WeakVH array.
2302 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2303 SmallVectorImpl<WeakVH> &VH,
2304 unsigned SliceBegin,
2305 unsigned SliceSize) {
2306 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2313 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2314 int CostThreshold, BoUpSLP &R) {
2315 unsigned ChainLen = Chain.size();
2316 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2318 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2319 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2320 unsigned VF = MinVecRegSize / Sz;
2322 if (!isPowerOf2_32(Sz) || VF < 2)
2325 // Keep track of values that were deleted by vectorizing in the loop below.
2326 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2328 bool Changed = false;
2329 // Look for profitable vectorizable trees at all offsets, starting at zero.
2330 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2334 // Check that a previous iteration of this loop did not delete the Value.
2335 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2338 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2340 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2342 R.buildTree(Operands);
2344 int Cost = R.getTreeCost();
2346 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2347 if (Cost < CostThreshold) {
2348 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2351 // Move to the next bundle.
2360 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2361 int costThreshold, BoUpSLP &R) {
2362 SetVector<Value *> Heads, Tails;
2363 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2365 // We may run into multiple chains that merge into a single chain. We mark the
2366 // stores that we vectorized so that we don't visit the same store twice.
2367 BoUpSLP::ValueSet VectorizedStores;
2368 bool Changed = false;
2370 // Do a quadratic search on all of the given stores and find
2371 // all of the pairs of stores that follow each other.
2372 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2373 for (unsigned j = 0; j < e; ++j) {
2377 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2378 Tails.insert(Stores[j]);
2379 Heads.insert(Stores[i]);
2380 ConsecutiveChain[Stores[i]] = Stores[j];
2385 // For stores that start but don't end a link in the chain:
2386 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2388 if (Tails.count(*it))
2391 // We found a store instr that starts a chain. Now follow the chain and try
2393 BoUpSLP::ValueList Operands;
2395 // Collect the chain into a list.
2396 while (Tails.count(I) || Heads.count(I)) {
2397 if (VectorizedStores.count(I))
2399 Operands.push_back(I);
2400 // Move to the next value in the chain.
2401 I = ConsecutiveChain[I];
2404 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2406 // Mark the vectorized stores so that we don't vectorize them again.
2408 VectorizedStores.insert(Operands.begin(), Operands.end());
2409 Changed |= Vectorized;
2416 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2419 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2420 StoreInst *SI = dyn_cast<StoreInst>(it);
2424 // Don't touch volatile stores.
2425 if (!SI->isSimple())
2428 // Check that the pointer points to scalars.
2429 Type *Ty = SI->getValueOperand()->getType();
2430 if (Ty->isAggregateType() || Ty->isVectorTy())
2433 // Find the base pointer.
2434 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2436 // Save the store locations.
2437 StoreRefs[Ptr].push_back(SI);
2443 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2446 Value *VL[] = { A, B };
2447 return tryToVectorizeList(VL, R, None, true);
2450 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2451 ArrayRef<Value *> BuildVector,
2452 bool allowReorder) {
2456 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2458 // Check that all of the parts are scalar instructions of the same type.
2459 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2463 unsigned Opcode0 = I0->getOpcode();
2465 Type *Ty0 = I0->getType();
2466 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2467 unsigned VF = MinVecRegSize / Sz;
2469 for (int i = 0, e = VL.size(); i < e; ++i) {
2470 Type *Ty = VL[i]->getType();
2471 if (Ty->isAggregateType() || Ty->isVectorTy())
2473 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2474 if (!Inst || Inst->getOpcode() != Opcode0)
2478 bool Changed = false;
2480 // Keep track of values that were deleted by vectorizing in the loop below.
2481 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2483 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2484 unsigned OpsWidth = 0;
2491 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2494 // Check that a previous iteration of this loop did not delete the Value.
2495 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2498 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2500 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2502 ArrayRef<Value *> BuildVectorSlice;
2503 if (!BuildVector.empty())
2504 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2506 R.buildTree(Ops, BuildVectorSlice);
2507 // TODO: check if we can allow reordering also for other cases than
2508 // tryToVectorizePair()
2509 if (allowReorder && R.shouldReorder()) {
2510 assert(Ops.size() == 2);
2511 assert(BuildVectorSlice.empty());
2512 Value *ReorderedOps[] = { Ops[1], Ops[0] };
2513 R.buildTree(ReorderedOps, None);
2515 int Cost = R.getTreeCost();
2517 if (Cost < -SLPCostThreshold) {
2518 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2519 Value *VectorizedRoot = R.vectorizeTree();
2521 // Reconstruct the build vector by extracting the vectorized root. This
2522 // way we handle the case where some elements of the vector are undefined.
2523 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2524 if (!BuildVectorSlice.empty()) {
2525 // The insert point is the last build vector instruction. The vectorized
2526 // root will precede it. This guarantees that we get an instruction. The
2527 // vectorized tree could have been constant folded.
2528 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2529 unsigned VecIdx = 0;
2530 for (auto &V : BuildVectorSlice) {
2531 IRBuilder<true, NoFolder> Builder(
2532 ++BasicBlock::iterator(InsertAfter));
2533 InsertElementInst *IE = cast<InsertElementInst>(V);
2534 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2535 VectorizedRoot, Builder.getInt32(VecIdx++)));
2536 IE->setOperand(1, Extract);
2537 IE->removeFromParent();
2538 IE->insertAfter(Extract);
2542 // Move to the next bundle.
2551 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2555 // Try to vectorize V.
2556 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2559 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2560 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2562 if (B && B->hasOneUse()) {
2563 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2564 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2565 if (tryToVectorizePair(A, B0, R)) {
2569 if (tryToVectorizePair(A, B1, R)) {
2576 if (A && A->hasOneUse()) {
2577 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2578 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2579 if (tryToVectorizePair(A0, B, R)) {
2583 if (tryToVectorizePair(A1, B, R)) {
2591 /// \brief Generate a shuffle mask to be used in a reduction tree.
2593 /// \param VecLen The length of the vector to be reduced.
2594 /// \param NumEltsToRdx The number of elements that should be reduced in the
2596 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2597 /// reduction. A pairwise reduction will generate a mask of
2598 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2599 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2600 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2601 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2602 bool IsPairwise, bool IsLeft,
2603 IRBuilder<> &Builder) {
2604 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2606 SmallVector<Constant *, 32> ShuffleMask(
2607 VecLen, UndefValue::get(Builder.getInt32Ty()));
2610 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2611 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2612 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2614 // Move the upper half of the vector to the lower half.
2615 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2616 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2618 return ConstantVector::get(ShuffleMask);
2622 /// Model horizontal reductions.
2624 /// A horizontal reduction is a tree of reduction operations (currently add and
2625 /// fadd) that has operations that can be put into a vector as its leaf.
2626 /// For example, this tree:
2633 /// This tree has "mul" as its reduced values and "+" as its reduction
2634 /// operations. A reduction might be feeding into a store or a binary operation
2649 class HorizontalReduction {
2650 SmallVector<Value *, 16> ReductionOps;
2651 SmallVector<Value *, 32> ReducedVals;
2653 BinaryOperator *ReductionRoot;
2654 PHINode *ReductionPHI;
2656 /// The opcode of the reduction.
2657 unsigned ReductionOpcode;
2658 /// The opcode of the values we perform a reduction on.
2659 unsigned ReducedValueOpcode;
2660 /// The width of one full horizontal reduction operation.
2661 unsigned ReduxWidth;
2662 /// Should we model this reduction as a pairwise reduction tree or a tree that
2663 /// splits the vector in halves and adds those halves.
2664 bool IsPairwiseReduction;
2667 HorizontalReduction()
2668 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
2669 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2671 /// \brief Try to find a reduction tree.
2672 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2673 const DataLayout *DL) {
2675 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2676 "Thi phi needs to use the binary operator");
2678 // We could have a initial reductions that is not an add.
2679 // r *= v1 + v2 + v3 + v4
2680 // In such a case start looking for a tree rooted in the first '+'.
2682 if (B->getOperand(0) == Phi) {
2684 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2685 } else if (B->getOperand(1) == Phi) {
2687 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2694 Type *Ty = B->getType();
2695 if (Ty->isVectorTy())
2698 ReductionOpcode = B->getOpcode();
2699 ReducedValueOpcode = 0;
2700 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2707 // We currently only support adds.
2708 if (ReductionOpcode != Instruction::Add &&
2709 ReductionOpcode != Instruction::FAdd)
2712 // Post order traverse the reduction tree starting at B. We only handle true
2713 // trees containing only binary operators.
2714 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2715 Stack.push_back(std::make_pair(B, 0));
2716 while (!Stack.empty()) {
2717 BinaryOperator *TreeN = Stack.back().first;
2718 unsigned EdgeToVist = Stack.back().second++;
2719 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2721 // Only handle trees in the current basic block.
2722 if (TreeN->getParent() != B->getParent())
2725 // Each tree node needs to have one user except for the ultimate
2727 if (!TreeN->hasOneUse() && TreeN != B)
2731 if (EdgeToVist == 2 || IsReducedValue) {
2732 if (IsReducedValue) {
2733 // Make sure that the opcodes of the operations that we are going to
2735 if (!ReducedValueOpcode)
2736 ReducedValueOpcode = TreeN->getOpcode();
2737 else if (ReducedValueOpcode != TreeN->getOpcode())
2739 ReducedVals.push_back(TreeN);
2741 // We need to be able to reassociate the adds.
2742 if (!TreeN->isAssociative())
2744 ReductionOps.push_back(TreeN);
2751 // Visit left or right.
2752 Value *NextV = TreeN->getOperand(EdgeToVist);
2753 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2755 Stack.push_back(std::make_pair(Next, 0));
2756 else if (NextV != Phi)
2762 /// \brief Attempt to vectorize the tree found by
2763 /// matchAssociativeReduction.
2764 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2765 if (ReducedVals.empty())
2768 unsigned NumReducedVals = ReducedVals.size();
2769 if (NumReducedVals < ReduxWidth)
2772 Value *VectorizedTree = nullptr;
2773 IRBuilder<> Builder(ReductionRoot);
2774 FastMathFlags Unsafe;
2775 Unsafe.setUnsafeAlgebra();
2776 Builder.SetFastMathFlags(Unsafe);
2779 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2780 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2781 V.buildTree(ValsToReduce, ReductionOps);
2784 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2785 if (Cost >= -SLPCostThreshold)
2788 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2791 // Vectorize a tree.
2792 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2793 Value *VectorizedRoot = V.vectorizeTree();
2795 // Emit a reduction.
2796 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2797 if (VectorizedTree) {
2798 Builder.SetCurrentDebugLocation(Loc);
2799 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2800 ReducedSubTree, "bin.rdx");
2802 VectorizedTree = ReducedSubTree;
2805 if (VectorizedTree) {
2806 // Finish the reduction.
2807 for (; i < NumReducedVals; ++i) {
2808 Builder.SetCurrentDebugLocation(
2809 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2810 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2815 assert(ReductionRoot && "Need a reduction operation");
2816 ReductionRoot->setOperand(0, VectorizedTree);
2817 ReductionRoot->setOperand(1, ReductionPHI);
2819 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2821 return VectorizedTree != nullptr;
2826 /// \brief Calcuate the cost of a reduction.
2827 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2828 Type *ScalarTy = FirstReducedVal->getType();
2829 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2831 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2832 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2834 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2835 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2837 int ScalarReduxCost =
2838 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2840 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2841 << " for reduction that starts with " << *FirstReducedVal
2843 << (IsPairwiseReduction ? "pairwise" : "splitting")
2844 << " reduction)\n");
2846 return VecReduxCost - ScalarReduxCost;
2849 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2850 Value *R, const Twine &Name = "") {
2851 if (Opcode == Instruction::FAdd)
2852 return Builder.CreateFAdd(L, R, Name);
2853 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2856 /// \brief Emit a horizontal reduction of the vectorized value.
2857 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2858 assert(VectorizedValue && "Need to have a vectorized tree node");
2859 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2860 assert(isPowerOf2_32(ReduxWidth) &&
2861 "We only handle power-of-two reductions for now");
2863 Value *TmpVec = ValToReduce;
2864 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2865 if (IsPairwiseReduction) {
2867 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2869 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2871 Value *LeftShuf = Builder.CreateShuffleVector(
2872 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2873 Value *RightShuf = Builder.CreateShuffleVector(
2874 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2876 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2880 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2881 Value *Shuf = Builder.CreateShuffleVector(
2882 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2883 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2887 // The result is in the first element of the vector.
2888 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2892 /// \brief Recognize construction of vectors like
2893 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2894 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2895 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2896 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2898 /// Returns true if it matches
2900 static bool findBuildVector(InsertElementInst *FirstInsertElem,
2901 SmallVectorImpl<Value *> &BuildVector,
2902 SmallVectorImpl<Value *> &BuildVectorOpds) {
2903 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
2906 InsertElementInst *IE = FirstInsertElem;
2908 BuildVector.push_back(IE);
2909 BuildVectorOpds.push_back(IE->getOperand(1));
2911 if (IE->use_empty())
2914 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2918 // If this isn't the final use, make sure the next insertelement is the only
2919 // use. It's OK if the final constructed vector is used multiple times
2920 if (!IE->hasOneUse())
2929 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2930 return V->getType() < V2->getType();
2933 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2934 bool Changed = false;
2935 SmallVector<Value *, 4> Incoming;
2936 SmallSet<Value *, 16> VisitedInstrs;
2938 bool HaveVectorizedPhiNodes = true;
2939 while (HaveVectorizedPhiNodes) {
2940 HaveVectorizedPhiNodes = false;
2942 // Collect the incoming values from the PHIs.
2944 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2946 PHINode *P = dyn_cast<PHINode>(instr);
2950 if (!VisitedInstrs.count(P))
2951 Incoming.push_back(P);
2955 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2957 // Try to vectorize elements base on their type.
2958 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2962 // Look for the next elements with the same type.
2963 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2964 while (SameTypeIt != E &&
2965 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2966 VisitedInstrs.insert(*SameTypeIt);
2970 // Try to vectorize them.
2971 unsigned NumElts = (SameTypeIt - IncIt);
2972 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2974 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2975 // Success start over because instructions might have been changed.
2976 HaveVectorizedPhiNodes = true;
2981 // Start over at the next instruction of a different type (or the end).
2986 VisitedInstrs.clear();
2988 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2989 // We may go through BB multiple times so skip the one we have checked.
2990 if (!VisitedInstrs.insert(it))
2993 if (isa<DbgInfoIntrinsic>(it))
2996 // Try to vectorize reductions that use PHINodes.
2997 if (PHINode *P = dyn_cast<PHINode>(it)) {
2998 // Check that the PHI is a reduction PHI.
2999 if (P->getNumIncomingValues() != 2)
3002 (P->getIncomingBlock(0) == BB
3003 ? (P->getIncomingValue(0))
3004 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3006 // Check if this is a Binary Operator.
3007 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3011 // Try to match and vectorize a horizontal reduction.
3012 HorizontalReduction HorRdx;
3013 if (ShouldVectorizeHor &&
3014 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3015 HorRdx.tryToReduce(R, TTI)) {
3022 Value *Inst = BI->getOperand(0);
3024 Inst = BI->getOperand(1);
3026 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3027 // We would like to start over since some instructions are deleted
3028 // and the iterator may become invalid value.
3038 // Try to vectorize horizontal reductions feeding into a store.
3039 if (ShouldStartVectorizeHorAtStore)
3040 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3041 if (BinaryOperator *BinOp =
3042 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3043 HorizontalReduction HorRdx;
3044 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3045 HorRdx.tryToReduce(R, TTI)) ||
3046 tryToVectorize(BinOp, R))) {
3054 // Try to vectorize trees that start at compare instructions.
3055 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3056 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3058 // We would like to start over since some instructions are deleted
3059 // and the iterator may become invalid value.
3065 for (int i = 0; i < 2; ++i) {
3066 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3067 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3069 // We would like to start over since some instructions are deleted
3070 // and the iterator may become invalid value.
3079 // Try to vectorize trees that start at insertelement instructions.
3080 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3081 SmallVector<Value *, 16> BuildVector;
3082 SmallVector<Value *, 16> BuildVectorOpds;
3083 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3086 // Vectorize starting with the build vector operands ignoring the
3087 // BuildVector instructions for the purpose of scheduling and user
3089 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3102 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3103 bool Changed = false;
3104 // Attempt to sort and vectorize each of the store-groups.
3105 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3107 if (it->second.size() < 2)
3110 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3111 << it->second.size() << ".\n");
3113 // Process the stores in chunks of 16.
3114 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3115 unsigned Len = std::min<unsigned>(CE - CI, 16);
3116 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
3117 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
3123 } // end anonymous namespace
3125 char SLPVectorizer::ID = 0;
3126 static const char lv_name[] = "SLP Vectorizer";
3127 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3128 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3129 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3130 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3131 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3132 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3135 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }