1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
18 #define SV_NAME "slp-vectorizer"
19 #define DEBUG_TYPE "SLP"
21 #include "llvm/Transforms/Vectorize.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.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"
49 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
50 cl::desc("Only vectorize if you gain more than this "
54 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
55 cl::desc("Attempt to vectorize horizontal reductions"));
59 static const unsigned MinVecRegSize = 128;
61 static const unsigned RecursionMaxDepth = 12;
63 /// RAII pattern to save the insertion point of the IR builder.
64 class BuilderLocGuard {
66 BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()),
67 DbgLoc(B.getCurrentDebugLocation()) {}
69 Builder.SetCurrentDebugLocation(DbgLoc);
71 Builder.SetInsertPoint(Loc);
76 BuilderLocGuard(const BuilderLocGuard &);
77 BuilderLocGuard &operator=(const BuilderLocGuard &);
79 AssertingVH<Instruction> Loc;
83 /// A helper class for numbering instructions in multiple blocks.
84 /// Numbers start at zero for each basic block.
85 struct BlockNumbering {
87 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
89 BlockNumbering() : BB(0), Valid(false) {}
91 void numberInstructions() {
95 // Number the instructions in the block.
96 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
98 InstrVec.push_back(it);
99 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
104 int getIndex(Instruction *I) {
105 assert(I->getParent() == BB && "Invalid instruction");
107 numberInstructions();
108 assert(InstrIdx.count(I) && "Unknown instruction");
112 Instruction *getInstruction(unsigned loc) {
114 numberInstructions();
115 assert(InstrVec.size() > loc && "Invalid Index");
116 return InstrVec[loc];
119 void forget() { Valid = false; }
122 /// The block we are numbering.
124 /// Is the block numbered.
126 /// Maps instructions to numbers and back.
127 SmallDenseMap<Instruction *, int> InstrIdx;
128 /// Maps integers to Instructions.
129 SmallVector<Instruction *, 32> InstrVec;
132 /// \returns the parent basic block if all of the instructions in \p VL
133 /// are in the same block or null otherwise.
134 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
135 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
138 BasicBlock *BB = I0->getParent();
139 for (int i = 1, e = VL.size(); i < e; i++) {
140 Instruction *I = dyn_cast<Instruction>(VL[i]);
144 if (BB != I->getParent())
150 /// \returns True if all of the values in \p VL are constants.
151 static bool allConstant(ArrayRef<Value *> VL) {
152 for (unsigned i = 0, e = VL.size(); i < e; ++i)
153 if (!isa<Constant>(VL[i]))
158 /// \returns True if all of the values in \p VL are identical.
159 static bool isSplat(ArrayRef<Value *> VL) {
160 for (unsigned i = 1, e = VL.size(); i < e; ++i)
166 /// \returns The opcode if all of the Instructions in \p VL have the same
168 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
169 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
172 unsigned Opcode = I0->getOpcode();
173 for (int i = 1, e = VL.size(); i < e; i++) {
174 Instruction *I = dyn_cast<Instruction>(VL[i]);
175 if (!I || Opcode != I->getOpcode())
181 /// \returns The type that all of the values in \p VL have or null if there
182 /// are different types.
183 static Type* getSameType(ArrayRef<Value *> VL) {
184 Type *Ty = VL[0]->getType();
185 for (int i = 1, e = VL.size(); i < e; i++)
186 if (VL[i]->getType() != Ty)
192 /// \returns True if the ExtractElement instructions in VL can be vectorized
193 /// to use the original vector.
194 static bool CanReuseExtract(ArrayRef<Value *> VL) {
195 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
196 // Check if all of the extracts come from the same vector and from the
199 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
200 Value *Vec = E0->getOperand(0);
202 // We have to extract from the same vector type.
203 unsigned NElts = Vec->getType()->getVectorNumElements();
205 if (NElts != VL.size())
208 // Check that all of the indices extract from the correct offset.
209 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
210 if (!CI || CI->getZExtValue())
213 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
214 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
215 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
217 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
224 /// Bottom Up SLP Vectorizer.
227 typedef SmallVector<Value *, 8> ValueList;
228 typedef SmallVector<Instruction *, 16> InstrList;
229 typedef SmallPtrSet<Value *, 16> ValueSet;
230 typedef SmallVector<StoreInst *, 8> StoreList;
232 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
233 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
235 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
236 Builder(Se->getContext()) {
237 // Setup the block numbering utility for all of the blocks in the
239 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
241 BlocksNumbers[BB] = BlockNumbering(BB);
245 /// \brief Vectorize the tree that starts with the elements in \p VL.
246 /// Returns the vectorized root.
247 Value *vectorizeTree();
249 /// \returns the vectorization cost of the subtree that starts at \p VL.
250 /// A negative number means that this is profitable.
253 /// Construct a vectorizable tree that starts at \p Roots and is possibly
254 /// used by a reduction of \p RdxOps.
255 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
257 /// Clear the internal data structures that are created by 'buildTree'.
260 VectorizableTree.clear();
261 ScalarToTreeEntry.clear();
263 ExternalUses.clear();
264 MemBarrierIgnoreList.clear();
267 /// \returns true if the memory operations A and B are consecutive.
268 bool isConsecutiveAccess(Value *A, Value *B);
270 /// \brief Perform LICM and CSE on the newly generated gather sequences.
271 void optimizeGatherSequence();
275 /// \returns the cost of the vectorizable entry.
276 int getEntryCost(TreeEntry *E);
278 /// This is the recursive part of buildTree.
279 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
281 /// Vectorize a single entry in the tree.
282 Value *vectorizeTree(TreeEntry *E);
284 /// Vectorize a single entry in the tree, starting in \p VL.
285 Value *vectorizeTree(ArrayRef<Value *> VL);
287 /// \returns the pointer to the vectorized value if \p VL is already
288 /// vectorized, or NULL. They may happen in cycles.
289 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
291 /// \brief Take the pointer operand from the Load/Store instruction.
292 /// \returns NULL if this is not a valid Load/Store instruction.
293 static Value *getPointerOperand(Value *I);
295 /// \brief Take the address space operand from the Load/Store instruction.
296 /// \returns -1 if this is not a valid Load/Store instruction.
297 static unsigned getAddressSpaceOperand(Value *I);
299 /// \returns the scalarization cost for this type. Scalarization in this
300 /// context means the creation of vectors from a group of scalars.
301 int getGatherCost(Type *Ty);
303 /// \returns the scalarization cost for this list of values. Assuming that
304 /// this subtree gets vectorized, we may need to extract the values from the
305 /// roots. This method calculates the cost of extracting the values.
306 int getGatherCost(ArrayRef<Value *> VL);
308 /// \returns the AA location that is being access by the instruction.
309 AliasAnalysis::Location getLocation(Instruction *I);
311 /// \brief Checks if it is possible to sink an instruction from
312 /// \p Src to \p Dst.
313 /// \returns the pointer to the barrier instruction if we can't sink.
314 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
316 /// \returns the index of the last instrucion in the BB from \p VL.
317 int getLastIndex(ArrayRef<Value *> VL);
319 /// \returns the Instruction in the bundle \p VL.
320 Instruction *getLastInstruction(ArrayRef<Value *> VL);
322 /// \brief Set the Builder insert point to one after the last instruction in
324 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
326 /// \returns a vector from a collection of scalars in \p VL.
327 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
330 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
333 /// \returns true if the scalars in VL are equal to this entry.
334 bool isSame(ArrayRef<Value *> VL) const {
335 assert(VL.size() == Scalars.size() && "Invalid size");
336 for (int i = 0, e = VL.size(); i != e; ++i)
337 if (VL[i] != Scalars[i])
342 /// A vector of scalars.
345 /// The Scalars are vectorized into this value. It is initialized to Null.
346 Value *VectorizedValue;
348 /// The index in the basic block of the last scalar.
351 /// Do we need to gather this sequence ?
355 /// Create a new VectorizableTree entry.
356 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
357 VectorizableTree.push_back(TreeEntry());
358 int idx = VectorizableTree.size() - 1;
359 TreeEntry *Last = &VectorizableTree[idx];
360 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
361 Last->NeedToGather = !Vectorized;
363 Last->LastScalarIndex = getLastIndex(VL);
364 for (int i = 0, e = VL.size(); i != e; ++i) {
365 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
366 ScalarToTreeEntry[VL[i]] = idx;
369 Last->LastScalarIndex = 0;
370 MustGather.insert(VL.begin(), VL.end());
375 /// -- Vectorization State --
376 /// Holds all of the tree entries.
377 std::vector<TreeEntry> VectorizableTree;
379 /// Maps a specific scalar to its tree entry.
380 SmallDenseMap<Value*, int> ScalarToTreeEntry;
382 /// A list of scalars that we found that we need to keep as scalars.
385 /// This POD struct describes one external user in the vectorized tree.
386 struct ExternalUser {
387 ExternalUser (Value *S, llvm::User *U, int L) :
388 Scalar(S), User(U), Lane(L){};
389 // Which scalar in our function.
391 // Which user that uses the scalar.
393 // Which lane does the scalar belong to.
396 typedef SmallVector<ExternalUser, 16> UserList;
398 /// A list of values that need to extracted out of the tree.
399 /// This list holds pairs of (Internal Scalar : External User).
400 UserList ExternalUses;
402 /// A list of instructions to ignore while sinking
403 /// memory instructions. This map must be reset between runs of getCost.
404 ValueSet MemBarrierIgnoreList;
406 /// Holds all of the instructions that we gathered.
407 SetVector<Instruction *> GatherSeq;
409 /// Numbers instructions in different blocks.
410 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
412 /// Reduction operators.
415 // Analysis and block reference.
419 TargetTransformInfo *TTI;
423 /// Instruction builder to construct the vectorized tree.
427 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
430 if (!getSameType(Roots))
432 buildTree_rec(Roots, 0);
434 // Collect the values that we need to extract from the tree.
435 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
436 TreeEntry *Entry = &VectorizableTree[EIdx];
439 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
440 Value *Scalar = Entry->Scalars[Lane];
442 // No need to handle users of gathered values.
443 if (Entry->NeedToGather)
446 for (Value::use_iterator User = Scalar->use_begin(),
447 UE = Scalar->use_end(); User != UE; ++User) {
448 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
450 bool Gathered = MustGather.count(*User);
452 // Skip in-tree scalars that become vectors.
453 if (ScalarToTreeEntry.count(*User) && !Gathered) {
454 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
456 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
457 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
460 Instruction *UserInst = dyn_cast<Instruction>(*User);
464 // Ignore uses that are part of the reduction.
465 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
468 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
469 Lane << " from " << *Scalar << ".\n");
470 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
477 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
478 bool SameTy = getSameType(VL); (void)SameTy;
479 assert(SameTy && "Invalid types!");
481 if (Depth == RecursionMaxDepth) {
482 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
483 newTreeEntry(VL, false);
487 // Don't handle vectors.
488 if (VL[0]->getType()->isVectorTy()) {
489 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
490 newTreeEntry(VL, false);
494 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
495 if (SI->getValueOperand()->getType()->isVectorTy()) {
496 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
497 newTreeEntry(VL, false);
501 // If all of the operands are identical or constant we have a simple solution.
502 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
503 !getSameOpcode(VL)) {
504 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
505 newTreeEntry(VL, false);
509 // We now know that this is a vector of instructions of the same type from
512 // Check if this is a duplicate of another entry.
513 if (ScalarToTreeEntry.count(VL[0])) {
514 int Idx = ScalarToTreeEntry[VL[0]];
515 TreeEntry *E = &VectorizableTree[Idx];
516 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
517 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
518 if (E->Scalars[i] != VL[i]) {
519 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
520 newTreeEntry(VL, false);
524 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
528 // Check that none of the instructions in the bundle are already in the tree.
529 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
530 if (ScalarToTreeEntry.count(VL[i])) {
531 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
532 ") is already in tree.\n");
533 newTreeEntry(VL, false);
538 // If any of the scalars appears in the table OR it is marked as a value that
539 // needs to stat scalar then we need to gather the scalars.
540 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
541 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
542 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
543 newTreeEntry(VL, false);
548 // Check that all of the users of the scalars that we want to vectorize are
550 Instruction *VL0 = cast<Instruction>(VL[0]);
551 int MyLastIndex = getLastIndex(VL);
552 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
554 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
555 Instruction *Scalar = cast<Instruction>(VL[i]);
556 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
557 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
559 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
560 Instruction *User = dyn_cast<Instruction>(*U);
562 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
563 newTreeEntry(VL, false);
567 // We don't care if the user is in a different basic block.
568 BasicBlock *UserBlock = User->getParent();
569 if (UserBlock != BB) {
570 DEBUG(dbgs() << "SLP: User from a different basic block "
575 // If this is a PHINode within this basic block then we can place the
576 // extract wherever we want.
577 if (isa<PHINode>(*User)) {
578 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
582 // Check if this is a safe in-tree user.
583 if (ScalarToTreeEntry.count(User)) {
584 int Idx = ScalarToTreeEntry[User];
585 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
586 if (VecLocation <= MyLastIndex) {
587 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
588 newTreeEntry(VL, false);
591 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
592 VecLocation << " vector value (" << *Scalar << ") at #"
593 << MyLastIndex << ".\n");
597 // This user is part of the reduction.
598 if (RdxOps && RdxOps->count(User))
601 // Make sure that we can schedule this unknown user.
602 BlockNumbering &BN = BlocksNumbers[BB];
603 int UserIndex = BN.getIndex(User);
604 if (UserIndex < MyLastIndex) {
606 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
608 newTreeEntry(VL, false);
614 // Check that every instructions appears once in this bundle.
615 for (unsigned i = 0, e = VL.size(); i < e; ++i)
616 for (unsigned j = i+1; j < e; ++j)
617 if (VL[i] == VL[j]) {
618 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
619 newTreeEntry(VL, false);
623 // Check that instructions in this bundle don't reference other instructions.
624 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
625 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
626 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
628 for (unsigned j = 0; j < e; ++j) {
629 if (i != j && *U == VL[j]) {
630 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
631 newTreeEntry(VL, false);
638 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
640 unsigned Opcode = getSameOpcode(VL);
642 // Check if it is safe to sink the loads or the stores.
643 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
644 Instruction *Last = getLastInstruction(VL);
646 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
649 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
651 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
652 << "\n because of " << *Barrier << ". Gathering.\n");
653 newTreeEntry(VL, false);
660 case Instruction::PHI: {
661 PHINode *PH = dyn_cast<PHINode>(VL0);
663 // Check for terminator values (e.g. invoke).
664 for (unsigned j = 0; j < VL.size(); ++j)
665 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
666 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
668 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
669 newTreeEntry(VL, false);
674 newTreeEntry(VL, true);
675 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
677 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
679 // Prepare the operand vector.
680 for (unsigned j = 0; j < VL.size(); ++j)
681 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
683 buildTree_rec(Operands, Depth + 1);
687 case Instruction::ExtractElement: {
688 bool Reuse = CanReuseExtract(VL);
690 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
692 newTreeEntry(VL, Reuse);
695 case Instruction::Load: {
696 // Check if the loads are consecutive or of we need to swizzle them.
697 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
698 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
699 newTreeEntry(VL, false);
700 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
704 newTreeEntry(VL, true);
705 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
708 case Instruction::ZExt:
709 case Instruction::SExt:
710 case Instruction::FPToUI:
711 case Instruction::FPToSI:
712 case Instruction::FPExt:
713 case Instruction::PtrToInt:
714 case Instruction::IntToPtr:
715 case Instruction::SIToFP:
716 case Instruction::UIToFP:
717 case Instruction::Trunc:
718 case Instruction::FPTrunc:
719 case Instruction::BitCast: {
720 Type *SrcTy = VL0->getOperand(0)->getType();
721 for (unsigned i = 0; i < VL.size(); ++i) {
722 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
723 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
724 newTreeEntry(VL, false);
725 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
729 newTreeEntry(VL, true);
730 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
732 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
734 // Prepare the operand vector.
735 for (unsigned j = 0; j < VL.size(); ++j)
736 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
738 buildTree_rec(Operands, Depth+1);
742 case Instruction::ICmp:
743 case Instruction::FCmp: {
744 // Check that all of the compares have the same predicate.
745 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
746 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
747 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
748 CmpInst *Cmp = cast<CmpInst>(VL[i]);
749 if (Cmp->getPredicate() != P0 ||
750 Cmp->getOperand(0)->getType() != ComparedTy) {
751 newTreeEntry(VL, false);
752 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
757 newTreeEntry(VL, true);
758 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
760 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
762 // Prepare the operand vector.
763 for (unsigned j = 0; j < VL.size(); ++j)
764 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
766 buildTree_rec(Operands, Depth+1);
770 case Instruction::Select:
771 case Instruction::Add:
772 case Instruction::FAdd:
773 case Instruction::Sub:
774 case Instruction::FSub:
775 case Instruction::Mul:
776 case Instruction::FMul:
777 case Instruction::UDiv:
778 case Instruction::SDiv:
779 case Instruction::FDiv:
780 case Instruction::URem:
781 case Instruction::SRem:
782 case Instruction::FRem:
783 case Instruction::Shl:
784 case Instruction::LShr:
785 case Instruction::AShr:
786 case Instruction::And:
787 case Instruction::Or:
788 case Instruction::Xor: {
789 newTreeEntry(VL, true);
790 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
792 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
794 // Prepare the operand vector.
795 for (unsigned j = 0; j < VL.size(); ++j)
796 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
798 buildTree_rec(Operands, Depth+1);
802 case Instruction::Store: {
803 // Check if the stores are consecutive or of we need to swizzle them.
804 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
805 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
806 newTreeEntry(VL, false);
807 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
811 newTreeEntry(VL, true);
812 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
815 for (unsigned j = 0; j < VL.size(); ++j)
816 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
818 // We can ignore these values because we are sinking them down.
819 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
820 buildTree_rec(Operands, Depth + 1);
824 newTreeEntry(VL, false);
825 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
830 int BoUpSLP::getEntryCost(TreeEntry *E) {
831 ArrayRef<Value*> VL = E->Scalars;
833 Type *ScalarTy = VL[0]->getType();
834 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
835 ScalarTy = SI->getValueOperand()->getType();
836 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
838 if (E->NeedToGather) {
842 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
844 return getGatherCost(E->Scalars);
847 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
849 Instruction *VL0 = cast<Instruction>(VL[0]);
850 unsigned Opcode = VL0->getOpcode();
852 case Instruction::PHI: {
855 case Instruction::ExtractElement: {
856 if (CanReuseExtract(VL))
858 return getGatherCost(VecTy);
860 case Instruction::ZExt:
861 case Instruction::SExt:
862 case Instruction::FPToUI:
863 case Instruction::FPToSI:
864 case Instruction::FPExt:
865 case Instruction::PtrToInt:
866 case Instruction::IntToPtr:
867 case Instruction::SIToFP:
868 case Instruction::UIToFP:
869 case Instruction::Trunc:
870 case Instruction::FPTrunc:
871 case Instruction::BitCast: {
872 Type *SrcTy = VL0->getOperand(0)->getType();
874 // Calculate the cost of this instruction.
875 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
876 VL0->getType(), SrcTy);
878 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
879 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
880 return VecCost - ScalarCost;
882 case Instruction::FCmp:
883 case Instruction::ICmp:
884 case Instruction::Select:
885 case Instruction::Add:
886 case Instruction::FAdd:
887 case Instruction::Sub:
888 case Instruction::FSub:
889 case Instruction::Mul:
890 case Instruction::FMul:
891 case Instruction::UDiv:
892 case Instruction::SDiv:
893 case Instruction::FDiv:
894 case Instruction::URem:
895 case Instruction::SRem:
896 case Instruction::FRem:
897 case Instruction::Shl:
898 case Instruction::LShr:
899 case Instruction::AShr:
900 case Instruction::And:
901 case Instruction::Or:
902 case Instruction::Xor: {
903 // Calculate the cost of this instruction.
906 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
907 Opcode == Instruction::Select) {
908 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
909 ScalarCost = VecTy->getNumElements() *
910 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
911 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
913 ScalarCost = VecTy->getNumElements() *
914 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
915 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
917 return VecCost - ScalarCost;
919 case Instruction::Load: {
920 // Cost of wide load - cost of scalar loads.
921 int ScalarLdCost = VecTy->getNumElements() *
922 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
923 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
924 return VecLdCost - ScalarLdCost;
926 case Instruction::Store: {
927 // We know that we can merge the stores. Calculate the cost.
928 int ScalarStCost = VecTy->getNumElements() *
929 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
930 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
931 return VecStCost - ScalarStCost;
934 llvm_unreachable("Unknown instruction");
938 int BoUpSLP::getTreeCost() {
940 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
941 VectorizableTree.size() << ".\n");
943 // Don't vectorize tiny trees. Small load/store chains or consecutive stores
944 // of constants will be vectoried in SelectionDAG in MergeConsecutiveStores.
945 // The SelectionDAG vectorizer can only handle pairs (trees of height = 2).
946 if (VectorizableTree.size() < 3) {
947 if (!VectorizableTree.size()) {
948 assert(!ExternalUses.size() && "We should not have any external users");
953 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
955 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
956 int C = getEntryCost(&VectorizableTree[i]);
957 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
958 << *VectorizableTree[i].Scalars[0] << " .\n");
963 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
966 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
967 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
972 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
973 return Cost + ExtractCost;
976 int BoUpSLP::getGatherCost(Type *Ty) {
978 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
979 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
983 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
984 // Find the type of the operands in VL.
985 Type *ScalarTy = VL[0]->getType();
986 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
987 ScalarTy = SI->getValueOperand()->getType();
988 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
989 // Find the cost of inserting/extracting values from the vector.
990 return getGatherCost(VecTy);
993 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
994 if (StoreInst *SI = dyn_cast<StoreInst>(I))
995 return AA->getLocation(SI);
996 if (LoadInst *LI = dyn_cast<LoadInst>(I))
997 return AA->getLocation(LI);
998 return AliasAnalysis::Location();
1001 Value *BoUpSLP::getPointerOperand(Value *I) {
1002 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1003 return LI->getPointerOperand();
1004 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1005 return SI->getPointerOperand();
1009 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1010 if (LoadInst *L = dyn_cast<LoadInst>(I))
1011 return L->getPointerAddressSpace();
1012 if (StoreInst *S = dyn_cast<StoreInst>(I))
1013 return S->getPointerAddressSpace();
1017 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1018 Value *PtrA = getPointerOperand(A);
1019 Value *PtrB = getPointerOperand(B);
1020 unsigned ASA = getAddressSpaceOperand(A);
1021 unsigned ASB = getAddressSpaceOperand(B);
1023 // Check that the address spaces match and that the pointers are valid.
1024 if (!PtrA || !PtrB || (ASA != ASB))
1027 // Make sure that A and B are different pointers of the same type.
1028 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1031 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1032 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1033 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1035 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1036 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1037 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1039 APInt OffsetDelta = OffsetB - OffsetA;
1041 // Check if they are based on the same pointer. That makes the offsets
1044 return OffsetDelta == Size;
1046 // Compute the necessary base pointer delta to have the necessary final delta
1047 // equal to the size.
1048 APInt BaseDelta = Size - OffsetDelta;
1050 // Otherwise compute the distance with SCEV between the base pointers.
1051 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1052 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1053 const SCEV *C = SE->getConstant(BaseDelta);
1054 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1055 return X == PtrSCEVB;
1058 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1059 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1060 BasicBlock::iterator I = Src, E = Dst;
1061 /// Scan all of the instruction from SRC to DST and check if
1062 /// the source may alias.
1063 for (++I; I != E; ++I) {
1064 // Ignore store instructions that are marked as 'ignore'.
1065 if (MemBarrierIgnoreList.count(I))
1067 if (Src->mayWriteToMemory()) /* Write */ {
1068 if (!I->mayReadOrWriteMemory())
1071 if (!I->mayWriteToMemory())
1074 AliasAnalysis::Location A = getLocation(&*I);
1075 AliasAnalysis::Location B = getLocation(Src);
1077 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1083 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1084 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1085 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1086 BlockNumbering &BN = BlocksNumbers[BB];
1088 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1089 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1090 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1094 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1095 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1096 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1097 BlockNumbering &BN = BlocksNumbers[BB];
1099 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1100 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1101 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1102 Instruction *I = BN.getInstruction(MaxIdx);
1103 assert(I && "bad location");
1107 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1108 Instruction *VL0 = cast<Instruction>(VL[0]);
1109 Instruction *LastInst = getLastInstruction(VL);
1110 BasicBlock::iterator NextInst = LastInst;
1112 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1113 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1116 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1117 Value *Vec = UndefValue::get(Ty);
1118 // Generate the 'InsertElement' instruction.
1119 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1120 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1121 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1122 GatherSeq.insert(Insrt);
1124 // Add to our 'need-to-extract' list.
1125 if (ScalarToTreeEntry.count(VL[i])) {
1126 int Idx = ScalarToTreeEntry[VL[i]];
1127 TreeEntry *E = &VectorizableTree[Idx];
1128 // Find which lane we need to extract.
1130 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1131 // Is this the lane of the scalar that we are looking for ?
1132 if (E->Scalars[Lane] == VL[i]) {
1137 assert(FoundLane >= 0 && "Could not find the correct lane");
1138 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1146 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1147 SmallDenseMap<Value*, int>::const_iterator Entry
1148 = ScalarToTreeEntry.find(VL[0]);
1149 if (Entry != ScalarToTreeEntry.end()) {
1150 int Idx = Entry->second;
1151 const TreeEntry *En = &VectorizableTree[Idx];
1152 if (En->isSame(VL) && En->VectorizedValue)
1153 return En->VectorizedValue;
1158 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1159 if (ScalarToTreeEntry.count(VL[0])) {
1160 int Idx = ScalarToTreeEntry[VL[0]];
1161 TreeEntry *E = &VectorizableTree[Idx];
1163 return vectorizeTree(E);
1166 Type *ScalarTy = VL[0]->getType();
1167 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1168 ScalarTy = SI->getValueOperand()->getType();
1169 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1171 return Gather(VL, VecTy);
1174 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1175 BuilderLocGuard Guard(Builder);
1177 if (E->VectorizedValue) {
1178 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1179 return E->VectorizedValue;
1182 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1183 Type *ScalarTy = VL0->getType();
1184 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1185 ScalarTy = SI->getValueOperand()->getType();
1186 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1188 if (E->NeedToGather) {
1189 setInsertPointAfterBundle(E->Scalars);
1190 return Gather(E->Scalars, VecTy);
1193 unsigned Opcode = VL0->getOpcode();
1194 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1197 case Instruction::PHI: {
1198 PHINode *PH = dyn_cast<PHINode>(VL0);
1199 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1200 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1201 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1202 E->VectorizedValue = NewPhi;
1204 // PHINodes may have multiple entries from the same block. We want to
1205 // visit every block once.
1206 SmallSet<BasicBlock*, 4> VisitedBBs;
1208 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1210 BasicBlock *IBB = PH->getIncomingBlock(i);
1212 if (!VisitedBBs.insert(IBB)) {
1213 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1217 // Prepare the operand vector.
1218 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1219 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1220 getIncomingValueForBlock(IBB));
1222 Builder.SetInsertPoint(IBB->getTerminator());
1223 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1224 Value *Vec = vectorizeTree(Operands);
1225 NewPhi->addIncoming(Vec, IBB);
1228 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1229 "Invalid number of incoming values");
1233 case Instruction::ExtractElement: {
1234 if (CanReuseExtract(E->Scalars)) {
1235 Value *V = VL0->getOperand(0);
1236 E->VectorizedValue = V;
1239 return Gather(E->Scalars, VecTy);
1241 case Instruction::ZExt:
1242 case Instruction::SExt:
1243 case Instruction::FPToUI:
1244 case Instruction::FPToSI:
1245 case Instruction::FPExt:
1246 case Instruction::PtrToInt:
1247 case Instruction::IntToPtr:
1248 case Instruction::SIToFP:
1249 case Instruction::UIToFP:
1250 case Instruction::Trunc:
1251 case Instruction::FPTrunc:
1252 case Instruction::BitCast: {
1254 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1255 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1257 setInsertPointAfterBundle(E->Scalars);
1259 Value *InVec = vectorizeTree(INVL);
1261 if (Value *V = alreadyVectorized(E->Scalars))
1264 CastInst *CI = dyn_cast<CastInst>(VL0);
1265 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1266 E->VectorizedValue = V;
1269 case Instruction::FCmp:
1270 case Instruction::ICmp: {
1271 ValueList LHSV, RHSV;
1272 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1273 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1274 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1277 setInsertPointAfterBundle(E->Scalars);
1279 Value *L = vectorizeTree(LHSV);
1280 Value *R = vectorizeTree(RHSV);
1282 if (Value *V = alreadyVectorized(E->Scalars))
1285 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1287 if (Opcode == Instruction::FCmp)
1288 V = Builder.CreateFCmp(P0, L, R);
1290 V = Builder.CreateICmp(P0, L, R);
1292 E->VectorizedValue = V;
1295 case Instruction::Select: {
1296 ValueList TrueVec, FalseVec, CondVec;
1297 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1298 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1299 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1300 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1303 setInsertPointAfterBundle(E->Scalars);
1305 Value *Cond = vectorizeTree(CondVec);
1306 Value *True = vectorizeTree(TrueVec);
1307 Value *False = vectorizeTree(FalseVec);
1309 if (Value *V = alreadyVectorized(E->Scalars))
1312 Value *V = Builder.CreateSelect(Cond, True, False);
1313 E->VectorizedValue = V;
1316 case Instruction::Add:
1317 case Instruction::FAdd:
1318 case Instruction::Sub:
1319 case Instruction::FSub:
1320 case Instruction::Mul:
1321 case Instruction::FMul:
1322 case Instruction::UDiv:
1323 case Instruction::SDiv:
1324 case Instruction::FDiv:
1325 case Instruction::URem:
1326 case Instruction::SRem:
1327 case Instruction::FRem:
1328 case Instruction::Shl:
1329 case Instruction::LShr:
1330 case Instruction::AShr:
1331 case Instruction::And:
1332 case Instruction::Or:
1333 case Instruction::Xor: {
1334 ValueList LHSVL, RHSVL;
1335 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1336 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1337 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1340 setInsertPointAfterBundle(E->Scalars);
1342 Value *LHS = vectorizeTree(LHSVL);
1343 Value *RHS = vectorizeTree(RHSVL);
1345 if (LHS == RHS && isa<Instruction>(LHS)) {
1346 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1349 if (Value *V = alreadyVectorized(E->Scalars))
1352 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1353 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1354 E->VectorizedValue = V;
1357 case Instruction::Load: {
1358 // Loads are inserted at the head of the tree because we don't want to
1359 // sink them all the way down past store instructions.
1360 setInsertPointAfterBundle(E->Scalars);
1362 LoadInst *LI = cast<LoadInst>(VL0);
1364 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1365 unsigned Alignment = LI->getAlignment();
1366 LI = Builder.CreateLoad(VecPtr);
1367 LI->setAlignment(Alignment);
1368 E->VectorizedValue = LI;
1371 case Instruction::Store: {
1372 StoreInst *SI = cast<StoreInst>(VL0);
1373 unsigned Alignment = SI->getAlignment();
1376 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1377 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1379 setInsertPointAfterBundle(E->Scalars);
1381 Value *VecValue = vectorizeTree(ValueOp);
1383 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1384 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1385 S->setAlignment(Alignment);
1386 E->VectorizedValue = S;
1390 llvm_unreachable("unknown inst");
1395 Value *BoUpSLP::vectorizeTree() {
1396 Builder.SetInsertPoint(F->getEntryBlock().begin());
1397 vectorizeTree(&VectorizableTree[0]);
1399 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1401 // Extract all of the elements with the external uses.
1402 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1404 Value *Scalar = it->Scalar;
1405 llvm::User *User = it->User;
1407 // Skip users that we already RAUW. This happens when one instruction
1408 // has multiple uses of the same value.
1409 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1412 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1414 int Idx = ScalarToTreeEntry[Scalar];
1415 TreeEntry *E = &VectorizableTree[Idx];
1416 assert(!E->NeedToGather && "Extracting from a gather list");
1418 Value *Vec = E->VectorizedValue;
1419 assert(Vec && "Can't find vectorizable value");
1421 Value *Lane = Builder.getInt32(it->Lane);
1422 // Generate extracts for out-of-tree users.
1423 // Find the insertion point for the extractelement lane.
1424 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1425 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1426 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1427 User->replaceUsesOfWith(Scalar, Ex);
1428 } else if (isa<Instruction>(Vec)){
1429 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1430 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1431 if (PH->getIncomingValue(i) == Scalar) {
1432 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1433 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1434 PH->setOperand(i, Ex);
1438 Builder.SetInsertPoint(cast<Instruction>(User));
1439 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1440 User->replaceUsesOfWith(Scalar, Ex);
1443 Builder.SetInsertPoint(F->getEntryBlock().begin());
1444 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1445 User->replaceUsesOfWith(Scalar, Ex);
1448 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1451 // For each vectorized value:
1452 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1453 TreeEntry *Entry = &VectorizableTree[EIdx];
1456 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1457 Value *Scalar = Entry->Scalars[Lane];
1459 // No need to handle users of gathered values.
1460 if (Entry->NeedToGather)
1463 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1465 Type *Ty = Scalar->getType();
1466 if (!Ty->isVoidTy()) {
1467 for (Value::use_iterator User = Scalar->use_begin(),
1468 UE = Scalar->use_end(); User != UE; ++User) {
1469 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1470 assert(!MustGather.count(*User) &&
1471 "Replacing gathered value with undef");
1473 assert((ScalarToTreeEntry.count(*User) ||
1474 // It is legal to replace the reduction users by undef.
1475 (RdxOps && RdxOps->count(*User))) &&
1476 "Replacing out-of-tree value with undef");
1478 Value *Undef = UndefValue::get(Ty);
1479 Scalar->replaceAllUsesWith(Undef);
1481 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1482 cast<Instruction>(Scalar)->eraseFromParent();
1486 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1487 BlocksNumbers[it].forget();
1489 Builder.ClearInsertionPoint();
1491 return VectorizableTree[0].VectorizedValue;
1494 void BoUpSLP::optimizeGatherSequence() {
1495 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1496 << " gather sequences instructions.\n");
1497 // LICM InsertElementInst sequences.
1498 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1499 e = GatherSeq.end(); it != e; ++it) {
1500 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1505 // Check if this block is inside a loop.
1506 Loop *L = LI->getLoopFor(Insert->getParent());
1510 // Check if it has a preheader.
1511 BasicBlock *PreHeader = L->getLoopPreheader();
1515 // If the vector or the element that we insert into it are
1516 // instructions that are defined in this basic block then we can't
1517 // hoist this instruction.
1518 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1519 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1520 if (CurrVec && L->contains(CurrVec))
1522 if (NewElem && L->contains(NewElem))
1525 // We can hoist this instruction. Move it to the pre-header.
1526 Insert->moveBefore(PreHeader->getTerminator());
1529 // Perform O(N^2) search over the gather sequences and merge identical
1530 // instructions. TODO: We can further optimize this scan if we split the
1531 // instructions into different buckets based on the insert lane.
1532 SmallPtrSet<Instruction*, 16> Visited;
1533 SmallVector<Instruction*, 16> ToRemove;
1534 ReversePostOrderTraversal<Function*> RPOT(F);
1535 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1536 E = RPOT.end(); I != E; ++I) {
1537 BasicBlock *BB = *I;
1538 // For all instructions in the function:
1539 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1540 Instruction *In = it;
1541 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1542 !GatherSeq.count(In))
1545 // Check if we can replace this instruction with any of the
1546 // visited instructions.
1547 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1548 ve = Visited.end(); v != ve; ++v) {
1549 if (In->isIdenticalTo(*v) &&
1550 DT->dominates((*v)->getParent(), In->getParent())) {
1551 In->replaceAllUsesWith(*v);
1552 ToRemove.push_back(In);
1562 // Erase all of the instructions that we RAUWed.
1563 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1564 ve = ToRemove.end(); v != ve; ++v) {
1565 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1566 (*v)->eraseFromParent();
1570 /// The SLPVectorizer Pass.
1571 struct SLPVectorizer : public FunctionPass {
1572 typedef SmallVector<StoreInst *, 8> StoreList;
1573 typedef MapVector<Value *, StoreList> StoreListMap;
1575 /// Pass identification, replacement for typeid
1578 explicit SLPVectorizer() : FunctionPass(ID) {
1579 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1582 ScalarEvolution *SE;
1584 TargetTransformInfo *TTI;
1589 virtual bool runOnFunction(Function &F) {
1590 SE = &getAnalysis<ScalarEvolution>();
1591 DL = getAnalysisIfAvailable<DataLayout>();
1592 TTI = &getAnalysis<TargetTransformInfo>();
1593 AA = &getAnalysis<AliasAnalysis>();
1594 LI = &getAnalysis<LoopInfo>();
1595 DT = &getAnalysis<DominatorTree>();
1598 bool Changed = false;
1600 // If the target claims to have no vector registers don't attempt
1602 if (!TTI->getNumberOfRegisters(true))
1605 // Must have DataLayout. We can't require it because some tests run w/o
1610 // Don't vectorize when the attribute NoImplicitFloat is used.
1611 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1614 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1616 // Use the bollom up slp vectorizer to construct chains that start with
1617 // he store instructions.
1618 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1620 // Scan the blocks in the function in post order.
1621 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1622 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1623 BasicBlock *BB = *it;
1625 // Vectorize trees that end at stores.
1626 if (unsigned count = collectStores(BB, R)) {
1628 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1629 Changed |= vectorizeStoreChains(R);
1632 // Vectorize trees that end at reductions.
1633 Changed |= vectorizeChainsInBlock(BB, R);
1637 R.optimizeGatherSequence();
1638 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1639 DEBUG(verifyFunction(F));
1644 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1645 FunctionPass::getAnalysisUsage(AU);
1646 AU.addRequired<ScalarEvolution>();
1647 AU.addRequired<AliasAnalysis>();
1648 AU.addRequired<TargetTransformInfo>();
1649 AU.addRequired<LoopInfo>();
1650 AU.addRequired<DominatorTree>();
1651 AU.addPreserved<LoopInfo>();
1652 AU.addPreserved<DominatorTree>();
1653 AU.setPreservesCFG();
1658 /// \brief Collect memory references and sort them according to their base
1659 /// object. We sort the stores to their base objects to reduce the cost of the
1660 /// quadratic search on the stores. TODO: We can further reduce this cost
1661 /// if we flush the chain creation every time we run into a memory barrier.
1662 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1664 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1665 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1667 /// \brief Try to vectorize a list of operands.
1668 /// \returns true if a value was vectorized.
1669 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1671 /// \brief Try to vectorize a chain that may start at the operands of \V;
1672 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1674 /// \brief Vectorize the stores that were collected in StoreRefs.
1675 bool vectorizeStoreChains(BoUpSLP &R);
1677 /// \brief Scan the basic block and look for patterns that are likely to start
1678 /// a vectorization chain.
1679 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1681 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1684 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1687 StoreListMap StoreRefs;
1690 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1691 int CostThreshold, BoUpSLP &R) {
1692 unsigned ChainLen = Chain.size();
1693 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1695 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1696 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1697 unsigned VF = MinVecRegSize / Sz;
1699 if (!isPowerOf2_32(Sz) || VF < 2)
1702 bool Changed = false;
1703 // Look for profitable vectorizable trees at all offsets, starting at zero.
1704 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1707 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1709 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1711 R.buildTree(Operands);
1713 int Cost = R.getTreeCost();
1715 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1716 if (Cost < CostThreshold) {
1717 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1720 // Move to the next bundle.
1729 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1730 int costThreshold, BoUpSLP &R) {
1731 SetVector<Value *> Heads, Tails;
1732 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1734 // We may run into multiple chains that merge into a single chain. We mark the
1735 // stores that we vectorized so that we don't visit the same store twice.
1736 BoUpSLP::ValueSet VectorizedStores;
1737 bool Changed = false;
1739 // Do a quadratic search on all of the given stores and find
1740 // all of the pairs of stores that follow each other.
1741 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1742 for (unsigned j = 0; j < e; ++j) {
1746 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1747 Tails.insert(Stores[j]);
1748 Heads.insert(Stores[i]);
1749 ConsecutiveChain[Stores[i]] = Stores[j];
1754 // For stores that start but don't end a link in the chain:
1755 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1757 if (Tails.count(*it))
1760 // We found a store instr that starts a chain. Now follow the chain and try
1762 BoUpSLP::ValueList Operands;
1764 // Collect the chain into a list.
1765 while (Tails.count(I) || Heads.count(I)) {
1766 if (VectorizedStores.count(I))
1768 Operands.push_back(I);
1769 // Move to the next value in the chain.
1770 I = ConsecutiveChain[I];
1773 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1775 // Mark the vectorized stores so that we don't vectorize them again.
1777 VectorizedStores.insert(Operands.begin(), Operands.end());
1778 Changed |= Vectorized;
1785 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1788 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1789 StoreInst *SI = dyn_cast<StoreInst>(it);
1793 // Check that the pointer points to scalars.
1794 Type *Ty = SI->getValueOperand()->getType();
1795 if (Ty->isAggregateType() || Ty->isVectorTy())
1798 // Find the base of the GEP.
1799 Value *Ptr = SI->getPointerOperand();
1800 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1801 Ptr = GEP->getPointerOperand();
1803 // Save the store locations.
1804 StoreRefs[Ptr].push_back(SI);
1810 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1813 Value *VL[] = { A, B };
1814 return tryToVectorizeList(VL, R);
1817 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1821 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1823 // Check that all of the parts are scalar instructions of the same type.
1824 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1828 unsigned Opcode0 = I0->getOpcode();
1830 Type *Ty0 = I0->getType();
1831 unsigned Sz = DL->getTypeSizeInBits(Ty0);
1832 unsigned VF = MinVecRegSize / Sz;
1834 for (int i = 0, e = VL.size(); i < e; ++i) {
1835 Type *Ty = VL[i]->getType();
1836 if (Ty->isAggregateType() || Ty->isVectorTy())
1838 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1839 if (!Inst || Inst->getOpcode() != Opcode0)
1843 bool Changed = false;
1845 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1846 unsigned OpsWidth = 0;
1853 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
1856 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
1857 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
1860 int Cost = R.getTreeCost();
1862 if (Cost < -SLPCostThreshold) {
1863 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1866 // Move to the next bundle.
1875 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1879 // Try to vectorize V.
1880 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1883 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1884 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1886 if (B && B->hasOneUse()) {
1887 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1888 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1889 if (tryToVectorizePair(A, B0, R)) {
1893 if (tryToVectorizePair(A, B1, R)) {
1900 if (A && A->hasOneUse()) {
1901 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1902 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1903 if (tryToVectorizePair(A0, B, R)) {
1907 if (tryToVectorizePair(A1, B, R)) {
1915 /// \brief Generate a shuffle mask to be used in a reduction tree.
1917 /// \param VecLen The length of the vector to be reduced.
1918 /// \param NumEltsToRdx The number of elements that should be reduced in the
1920 /// \param IsPairwise Whether the reduction is a pairwise or splitting
1921 /// reduction. A pairwise reduction will generate a mask of
1922 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
1923 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
1924 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
1925 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
1926 bool IsPairwise, bool IsLeft,
1927 IRBuilder<> &Builder) {
1928 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
1930 SmallVector<Constant *, 32> ShuffleMask(
1931 VecLen, UndefValue::get(Builder.getInt32Ty()));
1934 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
1935 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1936 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
1938 // Move the upper half of the vector to the lower half.
1939 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1940 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
1942 return ConstantVector::get(ShuffleMask);
1946 /// Model horizontal reductions.
1948 /// A horizontal reduction is a tree of reduction operations (currently add and
1949 /// fadd) that has operations that can be put into a vector as its leaf.
1950 /// For example, this tree:
1957 /// This tree has "mul" as its reduced values and "+" as its reduction
1958 /// operations. A reduction might be feeding into a store or a binary operation
1973 class HorizontalReduction {
1974 SmallPtrSet<Value *, 16> ReductionOps;
1975 SmallVector<Value *, 32> ReducedVals;
1977 BinaryOperator *ReductionRoot;
1978 PHINode *ReductionPHI;
1980 /// The opcode of the reduction.
1981 unsigned ReductionOpcode;
1982 /// The opcode of the values we perform a reduction on.
1983 unsigned ReducedValueOpcode;
1984 /// The width of one full horizontal reduction operation.
1985 unsigned ReduxWidth;
1986 /// Should we model this reduction as a pairwise reduction tree or a tree that
1987 /// splits the vector in halves and adds those halves.
1988 bool IsPairwiseReduction;
1991 HorizontalReduction()
1992 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
1993 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
1995 /// \brief Try to find a reduction tree.
1996 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
1999 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2000 "Thi phi needs to use the binary operator");
2002 // We could have a initial reductions that is not an add.
2003 // r *= v1 + v2 + v3 + v4
2004 // In such a case start looking for a tree rooted in the first '+'.
2006 if (B->getOperand(0) == Phi) {
2008 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2009 } else if (B->getOperand(1) == Phi) {
2011 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2018 Type *Ty = B->getType();
2019 if (Ty->isVectorTy())
2022 ReductionOpcode = B->getOpcode();
2023 ReducedValueOpcode = 0;
2024 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2031 // We currently only support adds.
2032 if (ReductionOpcode != Instruction::Add &&
2033 ReductionOpcode != Instruction::FAdd)
2036 // Post order traverse the reduction tree starting at B. We only handle true
2037 // trees containing only binary operators.
2038 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2039 Stack.push_back(std::make_pair(B, 0));
2040 while (!Stack.empty()) {
2041 BinaryOperator *TreeN = Stack.back().first;
2042 unsigned EdgeToVist = Stack.back().second++;
2043 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2045 // Only handle trees in the current basic block.
2046 if (TreeN->getParent() != B->getParent())
2049 // Each tree node needs to have one user except for the ultimate
2051 if (!TreeN->hasOneUse() && TreeN != B)
2055 if (EdgeToVist == 2 || IsReducedValue) {
2056 if (IsReducedValue) {
2057 // Make sure that the opcodes of the operations that we are going to
2059 if (!ReducedValueOpcode)
2060 ReducedValueOpcode = TreeN->getOpcode();
2061 else if (ReducedValueOpcode != TreeN->getOpcode())
2063 ReducedVals.push_back(TreeN);
2065 // We need to be able to reassociate the adds.
2066 if (!TreeN->isAssociative())
2068 ReductionOps.insert(TreeN);
2075 // Visit left or right.
2076 Value *NextV = TreeN->getOperand(EdgeToVist);
2077 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2079 Stack.push_back(std::make_pair(Next, 0));
2080 else if (NextV != Phi)
2086 /// \brief Attempt to vectorize the tree found by
2087 /// matchAssociativeReduction.
2088 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2089 if (ReducedVals.empty())
2092 unsigned NumReducedVals = ReducedVals.size();
2093 if (NumReducedVals < ReduxWidth)
2096 Value *VectorizedTree = 0;
2097 IRBuilder<> Builder(ReductionRoot);
2098 FastMathFlags Unsafe;
2099 Unsafe.setUnsafeAlgebra();
2100 Builder.SetFastMathFlags(Unsafe);
2103 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2104 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2105 V.buildTree(ValsToReduce, &ReductionOps);
2108 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2109 if (Cost >= -SLPCostThreshold)
2112 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2115 // Vectorize a tree.
2116 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2117 Value *VectorizedRoot = V.vectorizeTree();
2119 // Emit a reduction.
2120 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2121 if (VectorizedTree) {
2122 Builder.SetCurrentDebugLocation(Loc);
2123 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2124 ReducedSubTree, "bin.rdx");
2126 VectorizedTree = ReducedSubTree;
2129 if (VectorizedTree) {
2130 // Finish the reduction.
2131 for (; i < NumReducedVals; ++i) {
2132 Builder.SetCurrentDebugLocation(
2133 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2134 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2139 assert(ReductionRoot != NULL && "Need a reduction operation");
2140 ReductionRoot->setOperand(0, VectorizedTree);
2141 ReductionRoot->setOperand(1, ReductionPHI);
2143 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2145 return VectorizedTree != 0;
2150 /// \brief Calcuate the cost of a reduction.
2151 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2152 Type *ScalarTy = FirstReducedVal->getType();
2153 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2155 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2156 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2158 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2159 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2161 int ScalarReduxCost =
2162 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2164 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2165 << " for reduction that starts with " << *FirstReducedVal
2167 << (IsPairwiseReduction ? "pairwise" : "splitting")
2168 << " reduction)\n");
2170 return VecReduxCost - ScalarReduxCost;
2173 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2174 Value *R, const Twine &Name = "") {
2175 if (Opcode == Instruction::FAdd)
2176 return Builder.CreateFAdd(L, R, Name);
2177 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2180 /// \brief Emit a horizontal reduction of the vectorized value.
2181 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2182 assert(VectorizedValue && "Need to have a vectorized tree node");
2183 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2184 assert(isPowerOf2_32(ReduxWidth) &&
2185 "We only handle power-of-two reductions for now");
2187 SmallVector<Constant *, 32> ShuffleMask(ReduxWidth, 0);
2188 Value *TmpVec = ValToReduce;
2189 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2190 if (IsPairwiseReduction) {
2192 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2194 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2196 Value *LeftShuf = Builder.CreateShuffleVector(
2197 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2198 Value *RightShuf = Builder.CreateShuffleVector(
2199 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2201 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2205 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2206 Value *Shuf = Builder.CreateShuffleVector(
2207 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2208 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2212 // The result is in the first element of the vector.
2213 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2217 /// \brief Recognize construction of vectors like
2218 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2219 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2220 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2221 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2223 /// Returns true if it matches
2225 static bool findBuildVector(InsertElementInst *IE,
2226 SmallVectorImpl<Value *> &Ops) {
2227 if (!isa<UndefValue>(IE->getOperand(0)))
2231 Ops.push_back(IE->getOperand(1));
2233 if (IE->use_empty())
2236 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2240 // If this isn't the final use, make sure the next insertelement is the only
2241 // use. It's OK if the final constructed vector is used multiple times
2242 if (!IE->hasOneUse())
2251 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2252 bool Changed = false;
2253 SmallVector<Value *, 4> Incoming;
2254 SmallSet<Instruction *, 16> VisitedInstrs;
2256 // Collect the incoming values from the PHIs.
2257 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2259 PHINode *P = dyn_cast<PHINode>(instr);
2264 // We may go through BB multiple times so skip the one we have checked.
2265 if (!VisitedInstrs.insert(instr))
2268 // Stop constructing the list when you reach a different type.
2269 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
2270 if (tryToVectorizeList(Incoming, R)) {
2271 // We would like to start over since some instructions are deleted
2272 // and the iterator may become invalid value.
2274 instr = BB->begin();
2281 Incoming.push_back(P);
2284 if (Incoming.size() > 1)
2285 Changed |= tryToVectorizeList(Incoming, R);
2287 VisitedInstrs.clear();
2289 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2290 // We may go through BB multiple times so skip the one we have checked.
2291 if (!VisitedInstrs.insert(it))
2294 if (isa<DbgInfoIntrinsic>(it))
2297 // Try to vectorize reductions that use PHINodes.
2298 if (PHINode *P = dyn_cast<PHINode>(it)) {
2299 // Check that the PHI is a reduction PHI.
2300 if (P->getNumIncomingValues() != 2)
2303 (P->getIncomingBlock(0) == BB
2304 ? (P->getIncomingValue(0))
2305 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2306 // Check if this is a Binary Operator.
2307 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2311 // Try to match and vectorize a horizontal reduction.
2312 HorizontalReduction HorRdx;
2313 if (ShouldVectorizeHor &&
2314 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2315 HorRdx.tryToReduce(R, TTI)) {
2322 Value *Inst = BI->getOperand(0);
2324 Inst = BI->getOperand(1);
2326 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2327 // We would like to start over since some instructions are deleted
2328 // and the iterator may become invalid value.
2338 // Try to vectorize horizontal reductions feeding into a store.
2339 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2340 if (BinaryOperator *BinOp =
2341 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2342 HorizontalReduction HorRdx;
2343 if (ShouldVectorizeHor &&
2344 ((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2345 HorRdx.tryToReduce(R, TTI)) ||
2346 tryToVectorize(BinOp, R))) {
2354 // Try to vectorize trees that start at compare instructions.
2355 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2356 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2358 // We would like to start over since some instructions are deleted
2359 // and the iterator may become invalid value.
2365 for (int i = 0; i < 2; ++i) {
2366 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2367 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2369 // We would like to start over since some instructions are deleted
2370 // and the iterator may become invalid value.
2379 // Try to vectorize trees that start at insertelement instructions.
2380 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2381 SmallVector<Value *, 8> Ops;
2382 if (!findBuildVector(IE, Ops))
2385 if (tryToVectorizeList(Ops, R)) {
2398 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2399 bool Changed = false;
2400 // Attempt to sort and vectorize each of the store-groups.
2401 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2403 if (it->second.size() < 2)
2406 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2407 << it->second.size() << ".\n");
2409 // Process the stores in chunks of 16.
2410 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2411 unsigned Len = std::min<unsigned>(CE - CI, 16);
2412 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2413 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2419 } // end anonymous namespace
2421 char SLPVectorizer::ID = 0;
2422 static const char lv_name[] = "SLP Vectorizer";
2423 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2424 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2425 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2426 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2427 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2428 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2431 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }