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 static const unsigned MinVecRegSize = 128;
56 static const unsigned RecursionMaxDepth = 12;
58 /// RAII pattern to save the insertion point of the IR builder.
59 class BuilderLocGuard {
61 BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()) {}
62 ~BuilderLocGuard() { if (Loc) Builder.SetInsertPoint(Loc); }
66 BuilderLocGuard(const BuilderLocGuard &);
67 BuilderLocGuard &operator=(const BuilderLocGuard &);
69 AssertingVH<Instruction> Loc;
72 /// A helper class for numbering instructions in multible blocks.
73 /// Numbers starts at zero for each basic block.
74 struct BlockNumbering {
76 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
78 BlockNumbering() : BB(0), 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 The opcode if all of the Instructions in \p VL have the same
157 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
158 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
161 unsigned Opcode = I0->getOpcode();
162 for (int i = 1, e = VL.size(); i < e; i++) {
163 Instruction *I = dyn_cast<Instruction>(VL[i]);
164 if (!I || Opcode != I->getOpcode())
170 /// \returns The type that all of the values in \p VL have or null if there
171 /// are different types.
172 static Type* getSameType(ArrayRef<Value *> VL) {
173 Type *Ty = VL[0]->getType();
174 for (int i = 1, e = VL.size(); i < e; i++)
175 if (VL[i]->getType() != Ty)
181 /// \returns True if the ExtractElement instructions in VL can be vectorized
182 /// to use the original vector.
183 static bool CanReuseExtract(ArrayRef<Value *> VL) {
184 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
185 // Check if all of the extracts come from the same vector and from the
188 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
189 Value *Vec = E0->getOperand(0);
191 // We have to extract from the same vector type.
192 unsigned NElts = Vec->getType()->getVectorNumElements();
194 if (NElts != VL.size())
197 // Check that all of the indices extract from the correct offset.
198 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
199 if (!CI || CI->getZExtValue())
202 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
203 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
204 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
206 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
213 /// Bottom Up SLP Vectorizer.
216 typedef SmallVector<Value *, 8> ValueList;
217 typedef SmallVector<Instruction *, 16> InstrList;
218 typedef SmallPtrSet<Value *, 16> ValueSet;
219 typedef SmallVector<StoreInst *, 8> StoreList;
221 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
222 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
224 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
225 Builder(Se->getContext()) {
226 // Setup the block numbering utility for all of the blocks in the
228 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
230 BlocksNumbers[BB] = BlockNumbering(BB);
234 /// \brief Vectorize the tree that starts with the elements in \p VL.
235 void vectorizeTree();
237 /// \returns the vectorization cost of the subtree that starts at \p VL.
238 /// A negative number means that this is profitable.
241 /// Construct a vectorizable tree that starts at \p Roots.
242 void buildTree(ArrayRef<Value *> Roots);
244 /// Clear the internal data structures that are created by 'buildTree'.
246 VectorizableTree.clear();
247 ScalarToTreeEntry.clear();
249 ExternalUses.clear();
250 MemBarrierIgnoreList.clear();
253 /// \returns true if the memory operations A and B are consecutive.
254 bool isConsecutiveAccess(Value *A, Value *B);
256 /// \brief Perform LICM and CSE on the newly generated gather sequences.
257 void optimizeGatherSequence();
261 /// \returns the cost of the vectorizable entry.
262 int getEntryCost(TreeEntry *E);
264 /// This is the recursive part of buildTree.
265 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
267 /// Vectorizer a single entry in the tree.
268 Value *vectorizeTree(TreeEntry *E);
270 /// Vectorizer a single entry in the tree, starting in \p VL.
271 Value *vectorizeTree(ArrayRef<Value *> VL);
273 /// \brief Take the pointer operand from the Load/Store instruction.
274 /// \returns NULL if this is not a valid Load/Store instruction.
275 static Value *getPointerOperand(Value *I);
277 /// \brief Take the address space operand from the Load/Store instruction.
278 /// \returns -1 if this is not a valid Load/Store instruction.
279 static unsigned getAddressSpaceOperand(Value *I);
281 /// \returns the scalarization cost for this type. Scalarization in this
282 /// context means the creation of vectors from a group of scalars.
283 int getGatherCost(Type *Ty);
285 /// \returns the scalarization cost for this list of values. Assuming that
286 /// this subtree gets vectorized, we may need to extract the values from the
287 /// roots. This method calculates the cost of extracting the values.
288 int getGatherCost(ArrayRef<Value *> VL);
290 /// \returns the AA location that is being access by the instruction.
291 AliasAnalysis::Location getLocation(Instruction *I);
293 /// \brief Checks if it is possible to sink an instruction from
294 /// \p Src to \p Dst.
295 /// \returns the pointer to the barrier instruction if we can't sink.
296 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
298 /// \returns the index of the last instrucion in the BB from \p VL.
299 int getLastIndex(ArrayRef<Value *> VL);
301 /// \returns the Instrucion in the bundle \p VL.
302 Instruction *getLastInstruction(ArrayRef<Value *> VL);
304 /// \returns a vector from a collection of scalars in \p VL.
305 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
308 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
311 /// \returns true if the scalars in VL are equal to this entry.
312 bool isSame(ArrayRef<Value *> VL) {
313 assert(VL.size() == Scalars.size() && "Invalid size");
314 for (int i = 0, e = VL.size(); i != e; ++i)
315 if (VL[i] != Scalars[i])
320 /// A vector of scalars.
323 /// The Scalars are vectorized into this value. It is initialized to Null.
324 Value *VectorizedValue;
326 /// The index in the basic block of the last scalar.
329 /// Do we need to gather this sequence ?
333 /// Create a new VectorizableTree entry.
334 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
335 VectorizableTree.push_back(TreeEntry());
336 int idx = VectorizableTree.size() - 1;
337 TreeEntry *Last = &VectorizableTree[idx];
338 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
339 Last->NeedToGather = !Vectorized;
341 Last->LastScalarIndex = getLastIndex(VL);
342 for (int i = 0, e = VL.size(); i != e; ++i) {
343 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
344 ScalarToTreeEntry[VL[i]] = idx;
347 Last->LastScalarIndex = 0;
348 MustGather.insert(VL.begin(), VL.end());
353 /// -- Vectorization State --
354 /// Holds all of the tree entries.
355 std::vector<TreeEntry> VectorizableTree;
357 /// Maps a specific scalar to its tree entry.
358 SmallDenseMap<Value*, int> ScalarToTreeEntry;
360 /// A list of scalars that we found that we need to keep as scalars.
363 /// This POD struct describes one external user in the vectorized tree.
364 struct ExternalUser {
365 ExternalUser (Value *S, llvm::User *U, int L) :
366 Scalar(S), User(U), Lane(L){};
367 // Which scalar in our function.
369 // Which user that uses the scalar.
371 // Which lane does the scalar belong to.
374 typedef SmallVector<ExternalUser, 16> UserList;
376 /// A list of values that need to extracted out of the tree.
377 /// This list holds pairs of (Internal Scalar : External User).
378 UserList ExternalUses;
380 /// A list of instructions to ignore while sinking
381 /// memory instructions. This map must be reset between runs of getCost.
382 ValueSet MemBarrierIgnoreList;
384 /// Holds all of the instructions that we gathered.
385 SetVector<Instruction *> GatherSeq;
387 /// Numbers instructions in different blocks.
388 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
390 // Analysis and block reference.
394 TargetTransformInfo *TTI;
398 /// Instruction builder to construct the vectorized tree.
402 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
404 if (!getSameType(Roots))
406 buildTree_rec(Roots, 0);
408 // Collect the values that we need to extract from the tree.
409 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
410 TreeEntry *Entry = &VectorizableTree[EIdx];
413 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
414 Value *Scalar = Entry->Scalars[Lane];
416 // No need to handle users of gathered values.
417 if (Entry->NeedToGather)
420 for (Value::use_iterator User = Scalar->use_begin(),
421 UE = Scalar->use_end(); User != UE; ++User) {
422 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
424 bool Gathered = MustGather.count(*User);
426 // Skip in-tree scalars that become vectors.
427 if (ScalarToTreeEntry.count(*User) && !Gathered) {
428 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
430 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
431 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
435 if (!isa<Instruction>(*User))
438 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
439 Lane << " from " << *Scalar << ".\n");
440 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
447 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
448 bool SameTy = getSameType(VL); (void)SameTy;
449 assert(SameTy && "Invalid types!");
451 if (Depth == RecursionMaxDepth) {
452 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
453 newTreeEntry(VL, false);
457 // Don't handle vectors.
458 if (VL[0]->getType()->isVectorTy()) {
459 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
460 newTreeEntry(VL, false);
464 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
465 if (SI->getValueOperand()->getType()->isVectorTy()) {
466 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
467 newTreeEntry(VL, false);
471 // If all of the operands are identical or constant we have a simple solution.
472 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
473 !getSameOpcode(VL)) {
474 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
475 newTreeEntry(VL, false);
479 // We now know that this is a vector of instructions of the same type from
482 // Check if this is a duplicate of another entry.
483 if (ScalarToTreeEntry.count(VL[0])) {
484 int Idx = ScalarToTreeEntry[VL[0]];
485 TreeEntry *E = &VectorizableTree[Idx];
486 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
487 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
488 if (E->Scalars[i] != VL[i]) {
489 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
490 newTreeEntry(VL, false);
494 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
498 // Check that none of the instructions in the bundle are already in the tree.
499 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
500 if (ScalarToTreeEntry.count(VL[i])) {
501 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
502 ") is already in tree.\n");
503 newTreeEntry(VL, false);
508 // If any of the scalars appears in the table OR it is marked as a value that
509 // needs to stat scalar then we need to gather the scalars.
510 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
511 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
512 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
513 newTreeEntry(VL, false);
518 // Check that all of the users of the scalars that we want to vectorize are
520 Instruction *VL0 = cast<Instruction>(VL[0]);
521 int MyLastIndex = getLastIndex(VL);
522 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
524 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
525 Instruction *Scalar = cast<Instruction>(VL[i]);
526 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
527 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
529 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
530 Instruction *User = dyn_cast<Instruction>(*U);
532 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
533 newTreeEntry(VL, false);
537 // We don't care if the user is in a different basic block.
538 BasicBlock *UserBlock = User->getParent();
539 if (UserBlock != BB) {
540 DEBUG(dbgs() << "SLP: User from a different basic block "
545 // If this is a PHINode within this basic block then we can place the
546 // extract wherever we want.
547 if (isa<PHINode>(*User)) {
548 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
552 // Check if this is a safe in-tree user.
553 if (ScalarToTreeEntry.count(User)) {
554 int Idx = ScalarToTreeEntry[User];
555 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
556 if (VecLocation <= MyLastIndex) {
557 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
558 newTreeEntry(VL, false);
561 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
562 VecLocation << " vector value (" << *Scalar << ") at #"
563 << MyLastIndex << ".\n");
567 // Make sure that we can schedule this unknown user.
568 BlockNumbering &BN = BlocksNumbers[BB];
569 int UserIndex = BN.getIndex(User);
570 if (UserIndex < MyLastIndex) {
572 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
574 newTreeEntry(VL, false);
580 // Check that every instructions appears once in this bundle.
581 for (unsigned i = 0, e = VL.size(); i < e; ++i)
582 for (unsigned j = i+1; j < e; ++j)
583 if (VL[i] == VL[j]) {
584 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
585 newTreeEntry(VL, false);
589 // Check that instructions in this bundle don't reference other instructions.
590 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
591 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
592 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
594 for (unsigned j = 0; j < e; ++j) {
595 if (i != j && *U == VL[j]) {
596 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
597 newTreeEntry(VL, false);
604 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
606 unsigned Opcode = getSameOpcode(VL);
608 // Check if it is safe to sink the loads or the stores.
609 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
610 Instruction *Last = getLastInstruction(VL);
612 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
615 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
617 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
618 << "\n because of " << *Barrier << ". Gathering.\n");
619 newTreeEntry(VL, false);
626 case Instruction::PHI: {
627 PHINode *PH = dyn_cast<PHINode>(VL0);
628 newTreeEntry(VL, true);
629 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
631 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
633 // Prepare the operand vector.
634 for (unsigned j = 0; j < VL.size(); ++j)
635 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
637 buildTree_rec(Operands, Depth + 1);
641 case Instruction::ExtractElement: {
642 bool Reuse = CanReuseExtract(VL);
644 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
646 newTreeEntry(VL, Reuse);
649 case Instruction::Load: {
650 // Check if the loads are consecutive or of we need to swizzle them.
651 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
652 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
653 newTreeEntry(VL, false);
654 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
658 newTreeEntry(VL, true);
659 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
662 case Instruction::ZExt:
663 case Instruction::SExt:
664 case Instruction::FPToUI:
665 case Instruction::FPToSI:
666 case Instruction::FPExt:
667 case Instruction::PtrToInt:
668 case Instruction::IntToPtr:
669 case Instruction::SIToFP:
670 case Instruction::UIToFP:
671 case Instruction::Trunc:
672 case Instruction::FPTrunc:
673 case Instruction::BitCast: {
674 Type *SrcTy = VL0->getOperand(0)->getType();
675 for (unsigned i = 0; i < VL.size(); ++i) {
676 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
677 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
678 newTreeEntry(VL, false);
679 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
683 newTreeEntry(VL, true);
684 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
686 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
688 // Prepare the operand vector.
689 for (unsigned j = 0; j < VL.size(); ++j)
690 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
692 buildTree_rec(Operands, Depth+1);
696 case Instruction::ICmp:
697 case Instruction::FCmp: {
698 // Check that all of the compares have the same predicate.
699 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
700 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
701 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
702 CmpInst *Cmp = cast<CmpInst>(VL[i]);
703 if (Cmp->getPredicate() != P0 ||
704 Cmp->getOperand(0)->getType() != ComparedTy) {
705 newTreeEntry(VL, false);
706 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
711 newTreeEntry(VL, true);
712 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
714 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
716 // Prepare the operand vector.
717 for (unsigned j = 0; j < VL.size(); ++j)
718 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
720 buildTree_rec(Operands, Depth+1);
724 case Instruction::Select:
725 case Instruction::Add:
726 case Instruction::FAdd:
727 case Instruction::Sub:
728 case Instruction::FSub:
729 case Instruction::Mul:
730 case Instruction::FMul:
731 case Instruction::UDiv:
732 case Instruction::SDiv:
733 case Instruction::FDiv:
734 case Instruction::URem:
735 case Instruction::SRem:
736 case Instruction::FRem:
737 case Instruction::Shl:
738 case Instruction::LShr:
739 case Instruction::AShr:
740 case Instruction::And:
741 case Instruction::Or:
742 case Instruction::Xor: {
743 newTreeEntry(VL, true);
744 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
746 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
748 // Prepare the operand vector.
749 for (unsigned j = 0; j < VL.size(); ++j)
750 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
752 buildTree_rec(Operands, Depth+1);
756 case Instruction::Store: {
757 // Check if the stores are consecutive or of we need to swizzle them.
758 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
759 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
760 newTreeEntry(VL, false);
761 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
765 newTreeEntry(VL, true);
766 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
769 for (unsigned j = 0; j < VL.size(); ++j)
770 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
772 // We can ignore these values because we are sinking them down.
773 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
774 buildTree_rec(Operands, Depth + 1);
778 newTreeEntry(VL, false);
779 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
784 int BoUpSLP::getEntryCost(TreeEntry *E) {
785 ArrayRef<Value*> VL = E->Scalars;
787 Type *ScalarTy = VL[0]->getType();
788 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
789 ScalarTy = SI->getValueOperand()->getType();
790 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
792 if (E->NeedToGather) {
796 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
798 return getGatherCost(E->Scalars);
801 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
803 Instruction *VL0 = cast<Instruction>(VL[0]);
804 unsigned Opcode = VL0->getOpcode();
806 case Instruction::PHI: {
809 case Instruction::ExtractElement: {
810 if (CanReuseExtract(VL))
812 return getGatherCost(VecTy);
814 case Instruction::ZExt:
815 case Instruction::SExt:
816 case Instruction::FPToUI:
817 case Instruction::FPToSI:
818 case Instruction::FPExt:
819 case Instruction::PtrToInt:
820 case Instruction::IntToPtr:
821 case Instruction::SIToFP:
822 case Instruction::UIToFP:
823 case Instruction::Trunc:
824 case Instruction::FPTrunc:
825 case Instruction::BitCast: {
826 Type *SrcTy = VL0->getOperand(0)->getType();
828 // Calculate the cost of this instruction.
829 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
830 VL0->getType(), SrcTy);
832 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
833 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
834 return VecCost - ScalarCost;
836 case Instruction::FCmp:
837 case Instruction::ICmp:
838 case Instruction::Select:
839 case Instruction::Add:
840 case Instruction::FAdd:
841 case Instruction::Sub:
842 case Instruction::FSub:
843 case Instruction::Mul:
844 case Instruction::FMul:
845 case Instruction::UDiv:
846 case Instruction::SDiv:
847 case Instruction::FDiv:
848 case Instruction::URem:
849 case Instruction::SRem:
850 case Instruction::FRem:
851 case Instruction::Shl:
852 case Instruction::LShr:
853 case Instruction::AShr:
854 case Instruction::And:
855 case Instruction::Or:
856 case Instruction::Xor: {
857 // Calculate the cost of this instruction.
860 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
861 Opcode == Instruction::Select) {
862 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
863 ScalarCost = VecTy->getNumElements() *
864 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
865 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
867 ScalarCost = VecTy->getNumElements() *
868 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
869 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
871 return VecCost - ScalarCost;
873 case Instruction::Load: {
874 // Cost of wide load - cost of scalar loads.
875 int ScalarLdCost = VecTy->getNumElements() *
876 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
877 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
878 return VecLdCost - ScalarLdCost;
880 case Instruction::Store: {
881 // We know that we can merge the stores. Calculate the cost.
882 int ScalarStCost = VecTy->getNumElements() *
883 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
884 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
885 return VecStCost - ScalarStCost;
888 llvm_unreachable("Unknown instruction");
892 int BoUpSLP::getTreeCost() {
894 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
895 VectorizableTree.size() << ".\n");
897 if (!VectorizableTree.size()) {
898 assert(!ExternalUses.size() && "We should not have any external users");
902 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
904 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
905 int C = getEntryCost(&VectorizableTree[i]);
906 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
907 << *VectorizableTree[i].Scalars[0] << " .\n");
912 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
915 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
916 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
921 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
922 return Cost + ExtractCost;
925 int BoUpSLP::getGatherCost(Type *Ty) {
927 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
928 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
932 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
933 // Find the type of the operands in VL.
934 Type *ScalarTy = VL[0]->getType();
935 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
936 ScalarTy = SI->getValueOperand()->getType();
937 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
938 // Find the cost of inserting/extracting values from the vector.
939 return getGatherCost(VecTy);
942 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
943 if (StoreInst *SI = dyn_cast<StoreInst>(I))
944 return AA->getLocation(SI);
945 if (LoadInst *LI = dyn_cast<LoadInst>(I))
946 return AA->getLocation(LI);
947 return AliasAnalysis::Location();
950 Value *BoUpSLP::getPointerOperand(Value *I) {
951 if (LoadInst *LI = dyn_cast<LoadInst>(I))
952 return LI->getPointerOperand();
953 if (StoreInst *SI = dyn_cast<StoreInst>(I))
954 return SI->getPointerOperand();
958 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
959 if (LoadInst *L = dyn_cast<LoadInst>(I))
960 return L->getPointerAddressSpace();
961 if (StoreInst *S = dyn_cast<StoreInst>(I))
962 return S->getPointerAddressSpace();
966 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
967 Value *PtrA = getPointerOperand(A);
968 Value *PtrB = getPointerOperand(B);
969 unsigned ASA = getAddressSpaceOperand(A);
970 unsigned ASB = getAddressSpaceOperand(B);
972 // Check that the address spaces match and that the pointers are valid.
973 if (!PtrA || !PtrB || (ASA != ASB))
976 // Make sure that A and B are different pointers of the same type.
977 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
980 // Calculate a constant offset from the base pointer without using SCEV
981 // in the supported cases.
982 // TODO: Add support for the case where one of the pointers is a GEP that
983 // uses the other pointer.
984 GetElementPtrInst *GepA = dyn_cast<GetElementPtrInst>(PtrA);
985 GetElementPtrInst *GepB = dyn_cast<GetElementPtrInst>(PtrB);
987 unsigned BW = DL->getPointerSizeInBits(ASA);
988 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
989 int64_t Sz = DL->getTypeStoreSize(Ty);
991 // Check if PtrA is the base and PtrB is a constant offset.
992 if (GepB && GepB->getPointerOperand() == PtrA) {
994 if (GepB->accumulateConstantOffset(*DL, Offset))
995 return Offset.getSExtValue() == Sz;
999 // Check if PtrB is the base and PtrA is a constant offset.
1000 if (GepA && GepA->getPointerOperand() == PtrB) {
1001 APInt Offset(BW, 0);
1002 if (GepA->accumulateConstantOffset(*DL, Offset))
1003 return Offset.getSExtValue() == -Sz;
1007 // If both pointers are GEPs:
1009 // Check that they have the same base pointer and number of indices.
1010 if (GepA->getPointerOperand() != GepB->getPointerOperand() ||
1011 GepA->getNumIndices() != GepB->getNumIndices())
1014 // Try to strip the geps. This makes SCEV faster.
1015 // Make sure that all of the indices except for the last are identical.
1016 int LastIdx = GepA->getNumIndices();
1017 for (int i = 0; i < LastIdx - 1; i++) {
1018 if (GepA->getOperand(i+1) != GepB->getOperand(i+1))
1022 PtrA = GepA->getOperand(LastIdx);
1023 PtrB = GepB->getOperand(LastIdx);
1027 ConstantInt *CA = dyn_cast<ConstantInt>(PtrA);
1028 ConstantInt *CB = dyn_cast<ConstantInt>(PtrB);
1030 return (CA->getSExtValue() + Sz == CB->getSExtValue());
1033 // Calculate the distance.
1034 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1035 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1036 const SCEV *C = SE->getConstant(PtrSCEVA->getType(), Sz);
1037 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1038 return X == PtrSCEVB;
1041 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1042 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1043 BasicBlock::iterator I = Src, E = Dst;
1044 /// Scan all of the instruction from SRC to DST and check if
1045 /// the source may alias.
1046 for (++I; I != E; ++I) {
1047 // Ignore store instructions that are marked as 'ignore'.
1048 if (MemBarrierIgnoreList.count(I))
1050 if (Src->mayWriteToMemory()) /* Write */ {
1051 if (!I->mayReadOrWriteMemory())
1054 if (!I->mayWriteToMemory())
1057 AliasAnalysis::Location A = getLocation(&*I);
1058 AliasAnalysis::Location B = getLocation(Src);
1060 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1066 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1067 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1068 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1069 BlockNumbering &BN = BlocksNumbers[BB];
1071 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1072 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1073 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1077 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1078 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1079 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1080 BlockNumbering &BN = BlocksNumbers[BB];
1082 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1083 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1084 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1085 Instruction *I = BN.getInstruction(MaxIdx);
1086 assert(I && "bad location");
1090 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1091 Value *Vec = UndefValue::get(Ty);
1092 // Generate the 'InsertElement' instruction.
1093 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1094 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1095 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1096 GatherSeq.insert(Insrt);
1098 // Add to our 'need-to-extract' list.
1099 if (ScalarToTreeEntry.count(VL[i])) {
1100 int Idx = ScalarToTreeEntry[VL[i]];
1101 TreeEntry *E = &VectorizableTree[Idx];
1102 // Find which lane we need to extract.
1104 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1105 // Is this the lane of the scalar that we are looking for ?
1106 if (E->Scalars[Lane] == VL[i]) {
1111 assert(FoundLane >= 0 && "Could not find the correct lane");
1112 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1120 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1121 if (ScalarToTreeEntry.count(VL[0])) {
1122 int Idx = ScalarToTreeEntry[VL[0]];
1123 TreeEntry *E = &VectorizableTree[Idx];
1125 return vectorizeTree(E);
1128 Type *ScalarTy = VL[0]->getType();
1129 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1130 ScalarTy = SI->getValueOperand()->getType();
1131 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1133 return Gather(VL, VecTy);
1136 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1137 BuilderLocGuard Guard(Builder);
1139 if (E->VectorizedValue) {
1140 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1141 return E->VectorizedValue;
1144 Type *ScalarTy = E->Scalars[0]->getType();
1145 if (StoreInst *SI = dyn_cast<StoreInst>(E->Scalars[0]))
1146 ScalarTy = SI->getValueOperand()->getType();
1147 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1149 if (E->NeedToGather) {
1150 return Gather(E->Scalars, VecTy);
1153 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1154 unsigned Opcode = VL0->getOpcode();
1155 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1158 case Instruction::PHI: {
1159 PHINode *PH = dyn_cast<PHINode>(VL0);
1160 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1161 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1162 E->VectorizedValue = NewPhi;
1164 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1166 BasicBlock *IBB = PH->getIncomingBlock(i);
1168 // Prepare the operand vector.
1169 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1170 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1171 getIncomingValueForBlock(IBB));
1173 Builder.SetInsertPoint(IBB->getTerminator());
1174 Value *Vec = vectorizeTree(Operands);
1175 NewPhi->addIncoming(Vec, IBB);
1178 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1179 "Invalid number of incoming values");
1183 case Instruction::ExtractElement: {
1184 if (CanReuseExtract(E->Scalars)) {
1185 Value *V = VL0->getOperand(0);
1186 E->VectorizedValue = V;
1189 return Gather(E->Scalars, VecTy);
1191 case Instruction::ZExt:
1192 case Instruction::SExt:
1193 case Instruction::FPToUI:
1194 case Instruction::FPToSI:
1195 case Instruction::FPExt:
1196 case Instruction::PtrToInt:
1197 case Instruction::IntToPtr:
1198 case Instruction::SIToFP:
1199 case Instruction::UIToFP:
1200 case Instruction::Trunc:
1201 case Instruction::FPTrunc:
1202 case Instruction::BitCast: {
1204 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1205 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1207 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1208 Value *InVec = vectorizeTree(INVL);
1209 CastInst *CI = dyn_cast<CastInst>(VL0);
1210 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1211 E->VectorizedValue = V;
1214 case Instruction::FCmp:
1215 case Instruction::ICmp: {
1216 ValueList LHSV, RHSV;
1217 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1218 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1219 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1222 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1223 Value *L = vectorizeTree(LHSV);
1224 Value *R = vectorizeTree(RHSV);
1227 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1228 if (Opcode == Instruction::FCmp)
1229 V = Builder.CreateFCmp(P0, L, R);
1231 V = Builder.CreateICmp(P0, L, R);
1233 E->VectorizedValue = V;
1236 case Instruction::Select: {
1237 ValueList TrueVec, FalseVec, CondVec;
1238 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1239 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1240 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1241 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1244 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1245 Value *Cond = vectorizeTree(CondVec);
1246 Value *True = vectorizeTree(TrueVec);
1247 Value *False = vectorizeTree(FalseVec);
1248 Value *V = Builder.CreateSelect(Cond, True, False);
1249 E->VectorizedValue = V;
1252 case Instruction::Add:
1253 case Instruction::FAdd:
1254 case Instruction::Sub:
1255 case Instruction::FSub:
1256 case Instruction::Mul:
1257 case Instruction::FMul:
1258 case Instruction::UDiv:
1259 case Instruction::SDiv:
1260 case Instruction::FDiv:
1261 case Instruction::URem:
1262 case Instruction::SRem:
1263 case Instruction::FRem:
1264 case Instruction::Shl:
1265 case Instruction::LShr:
1266 case Instruction::AShr:
1267 case Instruction::And:
1268 case Instruction::Or:
1269 case Instruction::Xor: {
1270 ValueList LHSVL, RHSVL;
1271 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1272 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1273 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1276 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1277 Value *LHS = vectorizeTree(LHSVL);
1278 Value *RHS = vectorizeTree(RHSVL);
1280 if (LHS == RHS && isa<Instruction>(LHS)) {
1281 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1284 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1285 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1286 E->VectorizedValue = V;
1289 case Instruction::Load: {
1290 // Loads are inserted at the head of the tree because we don't want to
1291 // sink them all the way down past store instructions.
1292 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1293 LoadInst *LI = cast<LoadInst>(VL0);
1295 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1296 unsigned Alignment = LI->getAlignment();
1297 LI = Builder.CreateLoad(VecPtr);
1298 LI->setAlignment(Alignment);
1299 E->VectorizedValue = LI;
1302 case Instruction::Store: {
1303 StoreInst *SI = cast<StoreInst>(VL0);
1304 unsigned Alignment = SI->getAlignment();
1307 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1308 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1310 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1311 Value *VecValue = vectorizeTree(ValueOp);
1313 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1314 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1315 S->setAlignment(Alignment);
1316 E->VectorizedValue = S;
1320 llvm_unreachable("unknown inst");
1325 void BoUpSLP::vectorizeTree() {
1326 Builder.SetInsertPoint(F->getEntryBlock().begin());
1327 vectorizeTree(&VectorizableTree[0]);
1329 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1331 // Extract all of the elements with the external uses.
1332 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1334 Value *Scalar = it->Scalar;
1335 llvm::User *User = it->User;
1337 // Skip users that we already RAUW. This happens when one instruction
1338 // has multiple uses of the same value.
1339 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1342 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1344 int Idx = ScalarToTreeEntry[Scalar];
1345 TreeEntry *E = &VectorizableTree[Idx];
1346 assert(!E->NeedToGather && "Extracting from a gather list");
1348 Value *Vec = E->VectorizedValue;
1349 assert(Vec && "Can't find vectorizable value");
1351 // Generate extracts for out-of-tree users.
1352 // Find the insertion point for the extractelement lane.
1353 Instruction *Loc = 0;
1354 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1355 Loc = PN->getParent()->getFirstInsertionPt();
1356 } else if (isa<Instruction>(Vec)){
1357 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1358 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1359 if (PH->getIncomingValue(i) == Scalar) {
1360 Loc = PH->getIncomingBlock(i)->getTerminator();
1364 assert(Loc && "Unable to find incoming value for the PHI");
1366 Loc = cast<Instruction>(User);
1369 Loc = F->getEntryBlock().begin();
1372 Builder.SetInsertPoint(Loc);
1373 Value *Ex = Builder.CreateExtractElement(Vec, Builder.getInt32(it->Lane));
1374 User->replaceUsesOfWith(Scalar, Ex);
1375 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1378 // For each vectorized value:
1379 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1380 TreeEntry *Entry = &VectorizableTree[EIdx];
1383 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1384 Value *Scalar = Entry->Scalars[Lane];
1386 // No need to handle users of gathered values.
1387 if (Entry->NeedToGather)
1390 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1392 Type *Ty = Scalar->getType();
1393 if (!Ty->isVoidTy()) {
1394 for (Value::use_iterator User = Scalar->use_begin(),
1395 UE = Scalar->use_end(); User != UE; ++User) {
1396 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1397 assert(!MustGather.count(*User) &&
1398 "Replacing gathered value with undef");
1399 assert(ScalarToTreeEntry.count(*User) &&
1400 "Replacing out-of-tree value with undef");
1402 Value *Undef = UndefValue::get(Ty);
1403 Scalar->replaceAllUsesWith(Undef);
1405 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1406 cast<Instruction>(Scalar)->eraseFromParent();
1410 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1411 BlocksNumbers[it].forget();
1413 Builder.ClearInsertionPoint();
1416 void BoUpSLP::optimizeGatherSequence() {
1417 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1418 << " gather sequences instructions.\n");
1419 // LICM InsertElementInst sequences.
1420 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1421 e = GatherSeq.end(); it != e; ++it) {
1422 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1427 // Check if this block is inside a loop.
1428 Loop *L = LI->getLoopFor(Insert->getParent());
1432 // Check if it has a preheader.
1433 BasicBlock *PreHeader = L->getLoopPreheader();
1437 // If the vector or the element that we insert into it are
1438 // instructions that are defined in this basic block then we can't
1439 // hoist this instruction.
1440 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1441 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1442 if (CurrVec && L->contains(CurrVec))
1444 if (NewElem && L->contains(NewElem))
1447 // We can hoist this instruction. Move it to the pre-header.
1448 Insert->moveBefore(PreHeader->getTerminator());
1451 // Perform O(N^2) search over the gather sequences and merge identical
1452 // instructions. TODO: We can further optimize this scan if we split the
1453 // instructions into different buckets based on the insert lane.
1454 SmallPtrSet<Instruction*, 16> Visited;
1455 SmallVector<Instruction*, 16> ToRemove;
1456 ReversePostOrderTraversal<Function*> RPOT(F);
1457 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1458 E = RPOT.end(); I != E; ++I) {
1459 BasicBlock *BB = *I;
1460 // For all instructions in the function:
1461 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1462 Instruction *In = it;
1463 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1464 !GatherSeq.count(In))
1467 // Check if we can replace this instruction with any of the
1468 // visited instructions.
1469 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1470 ve = Visited.end(); v != ve; ++v) {
1471 if (In->isIdenticalTo(*v) &&
1472 DT->dominates((*v)->getParent(), In->getParent())) {
1473 In->replaceAllUsesWith(*v);
1474 ToRemove.push_back(In);
1484 // Erase all of the instructions that we RAUWed.
1485 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1486 ve = ToRemove.end(); v != ve; ++v) {
1487 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1488 (*v)->eraseFromParent();
1492 /// The SLPVectorizer Pass.
1493 struct SLPVectorizer : public FunctionPass {
1494 typedef SmallVector<StoreInst *, 8> StoreList;
1495 typedef MapVector<Value *, StoreList> StoreListMap;
1497 /// Pass identification, replacement for typeid
1500 explicit SLPVectorizer() : FunctionPass(ID) {
1501 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1504 ScalarEvolution *SE;
1506 TargetTransformInfo *TTI;
1511 virtual bool runOnFunction(Function &F) {
1512 SE = &getAnalysis<ScalarEvolution>();
1513 DL = getAnalysisIfAvailable<DataLayout>();
1514 TTI = &getAnalysis<TargetTransformInfo>();
1515 AA = &getAnalysis<AliasAnalysis>();
1516 LI = &getAnalysis<LoopInfo>();
1517 DT = &getAnalysis<DominatorTree>();
1520 bool Changed = false;
1522 // Must have DataLayout. We can't require it because some tests run w/o
1527 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1529 // Use the bollom up slp vectorizer to construct chains that start with
1530 // he store instructions.
1531 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1533 // Scan the blocks in the function in post order.
1534 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1535 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1536 BasicBlock *BB = *it;
1538 // Vectorize trees that end at stores.
1539 if (unsigned count = collectStores(BB, R)) {
1541 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1542 Changed |= vectorizeStoreChains(R);
1545 // Vectorize trees that end at reductions.
1546 Changed |= vectorizeChainsInBlock(BB, R);
1550 R.optimizeGatherSequence();
1551 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1552 DEBUG(verifyFunction(F));
1557 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1558 FunctionPass::getAnalysisUsage(AU);
1559 AU.addRequired<ScalarEvolution>();
1560 AU.addRequired<AliasAnalysis>();
1561 AU.addRequired<TargetTransformInfo>();
1562 AU.addRequired<LoopInfo>();
1563 AU.addRequired<DominatorTree>();
1564 AU.addPreserved<LoopInfo>();
1565 AU.addPreserved<DominatorTree>();
1566 AU.setPreservesCFG();
1571 /// \brief Collect memory references and sort them according to their base
1572 /// object. We sort the stores to their base objects to reduce the cost of the
1573 /// quadratic search on the stores. TODO: We can further reduce this cost
1574 /// if we flush the chain creation every time we run into a memory barrier.
1575 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1577 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1578 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1580 /// \brief Try to vectorize a list of operands.
1581 /// \returns true if a value was vectorized.
1582 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1584 /// \brief Try to vectorize a chain that may start at the operands of \V;
1585 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1587 /// \brief Vectorize the stores that were collected in StoreRefs.
1588 bool vectorizeStoreChains(BoUpSLP &R);
1590 /// \brief Scan the basic block and look for patterns that are likely to start
1591 /// a vectorization chain.
1592 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1594 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1597 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1600 StoreListMap StoreRefs;
1603 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1604 int CostThreshold, BoUpSLP &R) {
1605 unsigned ChainLen = Chain.size();
1606 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1608 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1609 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1610 unsigned VF = MinVecRegSize / Sz;
1612 if (!isPowerOf2_32(Sz) || VF < 2)
1615 bool Changed = false;
1616 // Look for profitable vectorizable trees at all offsets, starting at zero.
1617 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1620 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1622 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1624 R.buildTree(Operands);
1626 int Cost = R.getTreeCost();
1628 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1629 if (Cost < CostThreshold) {
1630 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1633 // Move to the next bundle.
1639 if (Changed || ChainLen > VF)
1642 // Handle short chains. This helps us catch types such as <3 x float> that
1643 // are smaller than vector size.
1646 int Cost = R.getTreeCost();
1648 if (Cost < CostThreshold) {
1649 DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
1650 << " for size = " << ChainLen << "\n");
1658 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1659 int costThreshold, BoUpSLP &R) {
1660 SetVector<Value *> Heads, Tails;
1661 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1663 // We may run into multiple chains that merge into a single chain. We mark the
1664 // stores that we vectorized so that we don't visit the same store twice.
1665 BoUpSLP::ValueSet VectorizedStores;
1666 bool Changed = false;
1668 // Do a quadratic search on all of the given stores and find
1669 // all of the pairs of stores that follow each other.
1670 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1671 for (unsigned j = 0; j < e; ++j) {
1675 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1676 Tails.insert(Stores[j]);
1677 Heads.insert(Stores[i]);
1678 ConsecutiveChain[Stores[i]] = Stores[j];
1683 // For stores that start but don't end a link in the chain:
1684 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1686 if (Tails.count(*it))
1689 // We found a store instr that starts a chain. Now follow the chain and try
1691 BoUpSLP::ValueList Operands;
1693 // Collect the chain into a list.
1694 while (Tails.count(I) || Heads.count(I)) {
1695 if (VectorizedStores.count(I))
1697 Operands.push_back(I);
1698 // Move to the next value in the chain.
1699 I = ConsecutiveChain[I];
1702 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1704 // Mark the vectorized stores so that we don't vectorize them again.
1706 VectorizedStores.insert(Operands.begin(), Operands.end());
1707 Changed |= Vectorized;
1714 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1717 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1718 StoreInst *SI = dyn_cast<StoreInst>(it);
1722 // Check that the pointer points to scalars.
1723 Type *Ty = SI->getValueOperand()->getType();
1724 if (Ty->isAggregateType() || Ty->isVectorTy())
1727 // Find the base of the GEP.
1728 Value *Ptr = SI->getPointerOperand();
1729 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1730 Ptr = GEP->getPointerOperand();
1732 // Save the store locations.
1733 StoreRefs[Ptr].push_back(SI);
1739 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1742 Value *VL[] = { A, B };
1743 return tryToVectorizeList(VL, R);
1746 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1750 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1752 // Check that all of the parts are scalar instructions of the same type.
1753 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1757 unsigned Opcode0 = I0->getOpcode();
1759 for (int i = 0, e = VL.size(); i < e; ++i) {
1760 Type *Ty = VL[i]->getType();
1761 if (Ty->isAggregateType() || Ty->isVectorTy())
1763 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1764 if (!Inst || Inst->getOpcode() != Opcode0)
1769 int Cost = R.getTreeCost();
1771 if (Cost >= -SLPCostThreshold)
1774 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1779 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1783 // Try to vectorize V.
1784 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1787 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1788 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1790 if (B && B->hasOneUse()) {
1791 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1792 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1793 if (tryToVectorizePair(A, B0, R)) {
1797 if (tryToVectorizePair(A, B1, R)) {
1804 if (A && A->hasOneUse()) {
1805 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1806 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1807 if (tryToVectorizePair(A0, B, R)) {
1811 if (tryToVectorizePair(A1, B, R)) {
1819 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
1820 bool Changed = false;
1821 SmallVector<Value *, 4> Incoming;
1822 // Collect the incoming values from the PHIs.
1823 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
1825 PHINode *P = dyn_cast<PHINode>(instr);
1830 // Stop constructing the list when you reach a different type.
1831 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
1832 Changed |= tryToVectorizeList(Incoming, R);
1836 Incoming.push_back(P);
1839 if (Incoming.size() > 1)
1840 Changed |= tryToVectorizeList(Incoming, R);
1842 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1843 if (isa<DbgInfoIntrinsic>(it))
1846 // Try to vectorize reductions that use PHINodes.
1847 if (PHINode *P = dyn_cast<PHINode>(it)) {
1848 // Check that the PHI is a reduction PHI.
1849 if (P->getNumIncomingValues() != 2)
1852 (P->getIncomingBlock(0) == BB
1853 ? (P->getIncomingValue(0))
1854 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1855 // Check if this is a Binary Operator.
1856 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1860 Value *Inst = BI->getOperand(0);
1862 Inst = BI->getOperand(1);
1864 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1868 // Try to vectorize trees that start at compare instructions.
1869 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1870 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1874 for (int i = 0; i < 2; ++i)
1875 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1877 tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1885 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
1886 bool Changed = false;
1887 // Attempt to sort and vectorize each of the store-groups.
1888 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1890 if (it->second.size() < 2)
1893 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1894 << it->second.size() << ".\n");
1896 // Process the stores in chunks of 16.
1897 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
1898 unsigned Len = std::min<unsigned>(CE - CI, 16);
1899 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
1900 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
1906 } // end anonymous namespace
1908 char SLPVectorizer::ID = 0;
1909 static const char lv_name[] = "SLP Vectorizer";
1910 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1911 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1912 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1913 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1914 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1915 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1918 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }