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 std::vector<Instruction *> 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 the Instruction at index \p Index which is in Block \p BB.
305 Instruction *getInstructionForIndex(unsigned Index, BasicBlock *BB);
307 /// \returns the index of the first User of \p VL.
308 int getFirstUserIndex(ArrayRef<Value *> VL);
310 /// \returns a vector from a collection of scalars in \p VL.
311 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
314 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
317 /// \returns true if the scalars in VL are equal to this entry.
318 bool isSame(ArrayRef<Value *> VL) {
319 assert(VL.size() == Scalars.size() && "Invalid size");
320 for (int i = 0, e = VL.size(); i != e; ++i)
321 if (VL[i] != Scalars[i])
326 /// A vector of scalars.
329 /// The Scalars are vectorized into this value. It is initialized to Null.
330 Value *VectorizedValue;
332 /// The index in the basic block of the last scalar.
335 /// Do we need to gather this sequence ?
339 /// Create a new VectorizableTree entry.
340 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
341 VectorizableTree.push_back(TreeEntry());
342 int idx = VectorizableTree.size() - 1;
343 TreeEntry *Last = &VectorizableTree[idx];
344 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
345 Last->NeedToGather = !Vectorized;
347 Last->LastScalarIndex = getLastIndex(VL);
348 for (int i = 0, e = VL.size(); i != e; ++i) {
349 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
350 ScalarToTreeEntry[VL[i]] = idx;
353 Last->LastScalarIndex = 0;
354 MustGather.insert(VL.begin(), VL.end());
359 /// -- Vectorization State --
360 /// Holds all of the tree entries.
361 std::vector<TreeEntry> VectorizableTree;
363 /// Maps a specific scalar to its tree entry.
364 SmallDenseMap<Value*, int> ScalarToTreeEntry;
366 /// A list of scalars that we found that we need to keep as scalars.
369 /// This POD struct describes one external user in the vectorized tree.
370 struct ExternalUser {
371 ExternalUser (Value *S, llvm::User *U, int L) :
372 Scalar(S), User(U), Lane(L){};
373 // Which scalar in our function.
375 // Which user that uses the scalar.
377 // Which lane does the scalar belong to.
380 typedef SmallVector<ExternalUser, 16> UserList;
382 /// A list of values that need to extracted out of the tree.
383 /// This list holds pairs of (Internal Scalar : External User).
384 UserList ExternalUses;
386 /// A list of instructions to ignore while sinking
387 /// memory instructions. This map must be reset between runs of getCost.
388 ValueSet MemBarrierIgnoreList;
390 /// Holds all of the instructions that we gathered.
391 SetVector<Instruction *> GatherSeq;
393 /// Numbers instructions in different blocks.
394 std::map<BasicBlock *, BlockNumbering> BlocksNumbers;
396 // Analysis and block reference.
400 TargetTransformInfo *TTI;
404 /// Instruction builder to construct the vectorized tree.
408 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
410 if (!getSameType(Roots))
412 buildTree_rec(Roots, 0);
414 // Collect the values that we need to extract from the tree.
415 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
416 TreeEntry *Entry = &VectorizableTree[EIdx];
419 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
420 Value *Scalar = Entry->Scalars[Lane];
422 // No need to handle users of gathered values.
423 if (Entry->NeedToGather)
426 for (Value::use_iterator User = Scalar->use_begin(),
427 UE = Scalar->use_end(); User != UE; ++User) {
428 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
430 bool Gathered = MustGather.count(*User);
432 // Skip in-tree scalars that become vectors.
433 if (ScalarToTreeEntry.count(*User) && !Gathered) {
434 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
436 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
437 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
441 if (!isa<Instruction>(*User))
444 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
445 Lane << " from " << *Scalar << ".\n");
446 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
453 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
454 bool SameTy = getSameType(VL); (void)SameTy;
455 assert(SameTy && "Invalid types!");
457 if (Depth == RecursionMaxDepth) {
458 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
459 newTreeEntry(VL, false);
463 // Don't handle vectors.
464 if (VL[0]->getType()->isVectorTy()) {
465 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
466 newTreeEntry(VL, false);
470 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
471 if (SI->getValueOperand()->getType()->isVectorTy()) {
472 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
473 newTreeEntry(VL, false);
477 // If all of the operands are identical or constant we have a simple solution.
478 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
479 !getSameOpcode(VL)) {
480 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
481 newTreeEntry(VL, false);
485 // We now know that this is a vector of instructions of the same type from
488 // Check if this is a duplicate of another entry.
489 if (ScalarToTreeEntry.count(VL[0])) {
490 int Idx = ScalarToTreeEntry[VL[0]];
491 TreeEntry *E = &VectorizableTree[Idx];
492 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
493 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
494 if (E->Scalars[i] != VL[i]) {
495 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
496 newTreeEntry(VL, false);
500 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
504 // Check that none of the instructions in the bundle are already in the tree.
505 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
506 if (ScalarToTreeEntry.count(VL[i])) {
507 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
508 ") is already in tree.\n");
509 newTreeEntry(VL, false);
514 // If any of the scalars appears in the table OR it is marked as a value that
515 // needs to stat scalar then we need to gather the scalars.
516 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
517 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
518 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
519 newTreeEntry(VL, false);
524 // Check that all of the users of the scalars that we want to vectorize are
526 Instruction *VL0 = cast<Instruction>(VL[0]);
527 int MyLastIndex = getLastIndex(VL);
528 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
530 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
531 Instruction *Scalar = cast<Instruction>(VL[i]);
532 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
533 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
535 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
536 Instruction *User = dyn_cast<Instruction>(*U);
538 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
539 newTreeEntry(VL, false);
543 // We don't care if the user is in a different basic block.
544 BasicBlock *UserBlock = User->getParent();
545 if (UserBlock != BB) {
546 DEBUG(dbgs() << "SLP: User from a different basic block "
551 // If this is a PHINode within this basic block then we can place the
552 // extract wherever we want.
553 if (isa<PHINode>(*User)) {
554 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
558 // Check if this is a safe in-tree user.
559 if (ScalarToTreeEntry.count(User)) {
560 int Idx = ScalarToTreeEntry[User];
561 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
562 if (VecLocation <= MyLastIndex) {
563 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
564 newTreeEntry(VL, false);
567 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
568 VecLocation << " vector value (" << *Scalar << ") at #"
569 << MyLastIndex << ".\n");
573 // Make sure that we can schedule this unknown user.
574 BlockNumbering &BN = BlocksNumbers[BB];
575 int UserIndex = BN.getIndex(User);
576 if (UserIndex < MyLastIndex) {
578 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
580 newTreeEntry(VL, false);
586 // Check that every instructions appears once in this bundle.
587 for (unsigned i = 0, e = VL.size(); i < e; ++i)
588 for (unsigned j = i+1; j < e; ++j)
589 if (VL[i] == VL[j]) {
590 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
591 newTreeEntry(VL, false);
595 // Check that instructions in this bundle don't reference other instructions.
596 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
597 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
598 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
600 for (unsigned j = 0; j < e; ++j) {
601 if (i != j && *U == VL[j]) {
602 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
603 newTreeEntry(VL, false);
610 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
612 unsigned Opcode = getSameOpcode(VL);
614 // Check if it is safe to sink the loads or the stores.
615 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
616 Instruction *Last = getLastInstruction(VL);
618 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
621 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
623 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
624 << "\n because of " << *Barrier << ". Gathering.\n");
625 newTreeEntry(VL, false);
632 case Instruction::PHI: {
633 PHINode *PH = dyn_cast<PHINode>(VL0);
634 newTreeEntry(VL, true);
635 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
637 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
639 // Prepare the operand vector.
640 for (unsigned j = 0; j < VL.size(); ++j)
641 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
643 buildTree_rec(Operands, Depth + 1);
647 case Instruction::ExtractElement: {
648 bool Reuse = CanReuseExtract(VL);
650 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
652 newTreeEntry(VL, Reuse);
655 case Instruction::Load: {
656 // Check if the loads are consecutive or of we need to swizzle them.
657 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
658 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
659 newTreeEntry(VL, false);
660 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
664 newTreeEntry(VL, true);
665 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
668 case Instruction::ZExt:
669 case Instruction::SExt:
670 case Instruction::FPToUI:
671 case Instruction::FPToSI:
672 case Instruction::FPExt:
673 case Instruction::PtrToInt:
674 case Instruction::IntToPtr:
675 case Instruction::SIToFP:
676 case Instruction::UIToFP:
677 case Instruction::Trunc:
678 case Instruction::FPTrunc:
679 case Instruction::BitCast: {
680 Type *SrcTy = VL0->getOperand(0)->getType();
681 for (unsigned i = 0; i < VL.size(); ++i) {
682 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
683 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
684 newTreeEntry(VL, false);
685 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
689 newTreeEntry(VL, true);
690 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
692 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
694 // Prepare the operand vector.
695 for (unsigned j = 0; j < VL.size(); ++j)
696 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
698 buildTree_rec(Operands, Depth+1);
702 case Instruction::ICmp:
703 case Instruction::FCmp: {
704 // Check that all of the compares have the same predicate.
705 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
706 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
707 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
708 CmpInst *Cmp = cast<CmpInst>(VL[i]);
709 if (Cmp->getPredicate() != P0 ||
710 Cmp->getOperand(0)->getType() != ComparedTy) {
711 newTreeEntry(VL, false);
712 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
717 newTreeEntry(VL, true);
718 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
720 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
722 // Prepare the operand vector.
723 for (unsigned j = 0; j < VL.size(); ++j)
724 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
726 buildTree_rec(Operands, Depth+1);
730 case Instruction::Select:
731 case Instruction::Add:
732 case Instruction::FAdd:
733 case Instruction::Sub:
734 case Instruction::FSub:
735 case Instruction::Mul:
736 case Instruction::FMul:
737 case Instruction::UDiv:
738 case Instruction::SDiv:
739 case Instruction::FDiv:
740 case Instruction::URem:
741 case Instruction::SRem:
742 case Instruction::FRem:
743 case Instruction::Shl:
744 case Instruction::LShr:
745 case Instruction::AShr:
746 case Instruction::And:
747 case Instruction::Or:
748 case Instruction::Xor: {
749 newTreeEntry(VL, true);
750 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
752 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
754 // Prepare the operand vector.
755 for (unsigned j = 0; j < VL.size(); ++j)
756 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
758 buildTree_rec(Operands, Depth+1);
762 case Instruction::Store: {
763 // Check if the stores are consecutive or of we need to swizzle them.
764 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
765 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
766 newTreeEntry(VL, false);
767 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
771 newTreeEntry(VL, true);
772 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
775 for (unsigned j = 0; j < VL.size(); ++j)
776 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
778 // We can ignore these values because we are sinking them down.
779 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
780 buildTree_rec(Operands, Depth + 1);
784 newTreeEntry(VL, false);
785 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
790 int BoUpSLP::getEntryCost(TreeEntry *E) {
791 ArrayRef<Value*> VL = E->Scalars;
793 Type *ScalarTy = VL[0]->getType();
794 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
795 ScalarTy = SI->getValueOperand()->getType();
796 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
798 if (E->NeedToGather) {
802 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
804 return getGatherCost(E->Scalars);
807 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
809 Instruction *VL0 = cast<Instruction>(VL[0]);
810 unsigned Opcode = VL0->getOpcode();
812 case Instruction::PHI: {
815 case Instruction::ExtractElement: {
816 if (CanReuseExtract(VL))
818 return getGatherCost(VecTy);
820 case Instruction::ZExt:
821 case Instruction::SExt:
822 case Instruction::FPToUI:
823 case Instruction::FPToSI:
824 case Instruction::FPExt:
825 case Instruction::PtrToInt:
826 case Instruction::IntToPtr:
827 case Instruction::SIToFP:
828 case Instruction::UIToFP:
829 case Instruction::Trunc:
830 case Instruction::FPTrunc:
831 case Instruction::BitCast: {
832 Type *SrcTy = VL0->getOperand(0)->getType();
834 // Calculate the cost of this instruction.
835 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
836 VL0->getType(), SrcTy);
838 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
839 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
840 return VecCost - ScalarCost;
842 case Instruction::FCmp:
843 case Instruction::ICmp:
844 case Instruction::Select:
845 case Instruction::Add:
846 case Instruction::FAdd:
847 case Instruction::Sub:
848 case Instruction::FSub:
849 case Instruction::Mul:
850 case Instruction::FMul:
851 case Instruction::UDiv:
852 case Instruction::SDiv:
853 case Instruction::FDiv:
854 case Instruction::URem:
855 case Instruction::SRem:
856 case Instruction::FRem:
857 case Instruction::Shl:
858 case Instruction::LShr:
859 case Instruction::AShr:
860 case Instruction::And:
861 case Instruction::Or:
862 case Instruction::Xor: {
863 // Calculate the cost of this instruction.
866 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
867 Opcode == Instruction::Select) {
868 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
869 ScalarCost = VecTy->getNumElements() *
870 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
871 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
873 ScalarCost = VecTy->getNumElements() *
874 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
875 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
877 return VecCost - ScalarCost;
879 case Instruction::Load: {
880 // Cost of wide load - cost of scalar loads.
881 int ScalarLdCost = VecTy->getNumElements() *
882 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
883 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
884 return VecLdCost - ScalarLdCost;
886 case Instruction::Store: {
887 // We know that we can merge the stores. Calculate the cost.
888 int ScalarStCost = VecTy->getNumElements() *
889 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
890 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
891 return VecStCost - ScalarStCost;
894 llvm_unreachable("Unknown instruction");
898 int BoUpSLP::getTreeCost() {
900 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
901 VectorizableTree.size() << ".\n");
903 if (!VectorizableTree.size()) {
904 assert(!ExternalUses.size() && "We should not have any external users");
908 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
910 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
911 int C = getEntryCost(&VectorizableTree[i]);
912 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
913 << *VectorizableTree[i].Scalars[0] << " .\n");
918 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
921 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
922 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
927 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
928 return Cost + ExtractCost;
931 int BoUpSLP::getGatherCost(Type *Ty) {
933 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
934 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
938 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
939 // Find the type of the operands in VL.
940 Type *ScalarTy = VL[0]->getType();
941 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
942 ScalarTy = SI->getValueOperand()->getType();
943 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
944 // Find the cost of inserting/extracting values from the vector.
945 return getGatherCost(VecTy);
948 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
949 if (StoreInst *SI = dyn_cast<StoreInst>(I))
950 return AA->getLocation(SI);
951 if (LoadInst *LI = dyn_cast<LoadInst>(I))
952 return AA->getLocation(LI);
953 return AliasAnalysis::Location();
956 Value *BoUpSLP::getPointerOperand(Value *I) {
957 if (LoadInst *LI = dyn_cast<LoadInst>(I))
958 return LI->getPointerOperand();
959 if (StoreInst *SI = dyn_cast<StoreInst>(I))
960 return SI->getPointerOperand();
964 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
965 if (LoadInst *L = dyn_cast<LoadInst>(I))
966 return L->getPointerAddressSpace();
967 if (StoreInst *S = dyn_cast<StoreInst>(I))
968 return S->getPointerAddressSpace();
972 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
973 Value *PtrA = getPointerOperand(A);
974 Value *PtrB = getPointerOperand(B);
975 unsigned ASA = getAddressSpaceOperand(A);
976 unsigned ASB = getAddressSpaceOperand(B);
978 // Check that the address spaces match and that the pointers are valid.
979 if (!PtrA || !PtrB || (ASA != ASB))
982 // Check that A and B are of the same type.
983 if (PtrA->getType() != PtrB->getType())
986 // Calculate a constant offset from the base pointer without using SCEV
987 // in the supported cases.
988 // TODO: Add support for the case where one of the pointers is a GEP that
989 // uses the other pointer.
990 GetElementPtrInst *GepA = dyn_cast<GetElementPtrInst>(PtrA);
991 GetElementPtrInst *GepB = dyn_cast<GetElementPtrInst>(PtrB);
992 if (GepA && GepB && GepA->getPointerOperand() == GepB->getPointerOperand()) {
993 unsigned BW = DL->getPointerSizeInBits(ASA);
994 APInt OffsetA(BW, 0) ,OffsetB(BW, 0);
996 if (GepA->accumulateConstantOffset(*DL, OffsetA) &&
997 GepB->accumulateConstantOffset(*DL, OffsetB)) {
998 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
999 int64_t Sz = DL->getTypeStoreSize(Ty);
1000 return ((OffsetB.getSExtValue() - OffsetA.getSExtValue()) == Sz);
1004 // Calculate the distance.
1005 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1006 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1007 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1008 // The instructions are consecutive if the size of the first load/store is
1009 // the same as the offset.
1010 int64_t Sz = DL->getTypeStoreSize(Ty);
1012 const SCEV *C = SE->getConstant(PtrSCEVA->getType(), Sz);
1013 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1014 return X == PtrSCEVB;
1017 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1018 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1019 BasicBlock::iterator I = Src, E = Dst;
1020 /// Scan all of the instruction from SRC to DST and check if
1021 /// the source may alias.
1022 for (++I; I != E; ++I) {
1023 // Ignore store instructions that are marked as 'ignore'.
1024 if (MemBarrierIgnoreList.count(I))
1026 if (Src->mayWriteToMemory()) /* Write */ {
1027 if (!I->mayReadOrWriteMemory())
1030 if (!I->mayWriteToMemory())
1033 AliasAnalysis::Location A = getLocation(&*I);
1034 AliasAnalysis::Location B = getLocation(Src);
1036 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1042 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1043 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1044 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1045 BlockNumbering &BN = BlocksNumbers[BB];
1047 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1048 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1049 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1053 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1054 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1055 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1056 BlockNumbering &BN = BlocksNumbers[BB];
1058 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1059 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1060 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1061 Instruction *I = BN.getInstruction(MaxIdx);
1062 assert(I && "bad location");
1066 Instruction *BoUpSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) {
1067 BlockNumbering &BN = BlocksNumbers[BB];
1068 return BN.getInstruction(Index);
1071 int BoUpSLP::getFirstUserIndex(ArrayRef<Value *> VL) {
1072 BasicBlock *BB = getSameBlock(VL);
1073 assert(BB && "All instructions must come from the same block");
1074 BlockNumbering &BN = BlocksNumbers[BB];
1076 // Find the first user of the values.
1077 int FirstUser = BN.getIndex(BB->getTerminator());
1078 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1079 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
1081 Instruction *Instr = dyn_cast<Instruction>(*U);
1083 if (!Instr || Instr->getParent() != BB)
1086 FirstUser = std::min(FirstUser, BN.getIndex(Instr));
1092 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1093 Value *Vec = UndefValue::get(Ty);
1094 // Generate the 'InsertElement' instruction.
1095 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1096 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1097 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1098 GatherSeq.insert(Insrt);
1100 // Add to our 'need-to-extract' list.
1101 if (ScalarToTreeEntry.count(VL[i])) {
1102 int Idx = ScalarToTreeEntry[VL[i]];
1103 TreeEntry *E = &VectorizableTree[Idx];
1104 // Find which lane we need to extract.
1106 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1107 // Is this the lane of the scalar that we are looking for ?
1108 if (E->Scalars[Lane] == VL[i]) {
1113 assert(FoundLane >= 0 && "Could not find the correct lane");
1114 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1122 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1123 if (ScalarToTreeEntry.count(VL[0])) {
1124 int Idx = ScalarToTreeEntry[VL[0]];
1125 TreeEntry *E = &VectorizableTree[Idx];
1127 return vectorizeTree(E);
1130 Type *ScalarTy = VL[0]->getType();
1131 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1132 ScalarTy = SI->getValueOperand()->getType();
1133 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1135 return Gather(VL, VecTy);
1138 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1139 BuilderLocGuard Guard(Builder);
1141 if (E->VectorizedValue) {
1142 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1143 return E->VectorizedValue;
1146 Type *ScalarTy = E->Scalars[0]->getType();
1147 if (StoreInst *SI = dyn_cast<StoreInst>(E->Scalars[0]))
1148 ScalarTy = SI->getValueOperand()->getType();
1149 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1151 if (E->NeedToGather) {
1152 return Gather(E->Scalars, VecTy);
1155 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1156 unsigned Opcode = VL0->getOpcode();
1157 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1160 case Instruction::PHI: {
1161 PHINode *PH = dyn_cast<PHINode>(VL0);
1162 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1163 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1164 E->VectorizedValue = NewPhi;
1166 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1168 BasicBlock *IBB = PH->getIncomingBlock(i);
1170 // Prepare the operand vector.
1171 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1172 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1173 getIncomingValueForBlock(IBB));
1175 Builder.SetInsertPoint(IBB->getTerminator());
1176 Value *Vec = vectorizeTree(Operands);
1177 NewPhi->addIncoming(Vec, IBB);
1180 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1181 "Invalid number of incoming values");
1185 case Instruction::ExtractElement: {
1186 if (CanReuseExtract(E->Scalars)) {
1187 Value *V = VL0->getOperand(0);
1188 E->VectorizedValue = V;
1191 return Gather(E->Scalars, VecTy);
1193 case Instruction::ZExt:
1194 case Instruction::SExt:
1195 case Instruction::FPToUI:
1196 case Instruction::FPToSI:
1197 case Instruction::FPExt:
1198 case Instruction::PtrToInt:
1199 case Instruction::IntToPtr:
1200 case Instruction::SIToFP:
1201 case Instruction::UIToFP:
1202 case Instruction::Trunc:
1203 case Instruction::FPTrunc:
1204 case Instruction::BitCast: {
1206 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1207 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1209 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1210 Value *InVec = vectorizeTree(INVL);
1211 CastInst *CI = dyn_cast<CastInst>(VL0);
1212 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1213 E->VectorizedValue = V;
1216 case Instruction::FCmp:
1217 case Instruction::ICmp: {
1218 ValueList LHSV, RHSV;
1219 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1220 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1221 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1224 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1225 Value *L = vectorizeTree(LHSV);
1226 Value *R = vectorizeTree(RHSV);
1229 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1230 if (Opcode == Instruction::FCmp)
1231 V = Builder.CreateFCmp(P0, L, R);
1233 V = Builder.CreateICmp(P0, L, R);
1235 E->VectorizedValue = V;
1238 case Instruction::Select: {
1239 ValueList TrueVec, FalseVec, CondVec;
1240 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1241 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1242 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1243 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1246 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1247 Value *Cond = vectorizeTree(CondVec);
1248 Value *True = vectorizeTree(TrueVec);
1249 Value *False = vectorizeTree(FalseVec);
1250 Value *V = Builder.CreateSelect(Cond, True, False);
1251 E->VectorizedValue = V;
1254 case Instruction::Add:
1255 case Instruction::FAdd:
1256 case Instruction::Sub:
1257 case Instruction::FSub:
1258 case Instruction::Mul:
1259 case Instruction::FMul:
1260 case Instruction::UDiv:
1261 case Instruction::SDiv:
1262 case Instruction::FDiv:
1263 case Instruction::URem:
1264 case Instruction::SRem:
1265 case Instruction::FRem:
1266 case Instruction::Shl:
1267 case Instruction::LShr:
1268 case Instruction::AShr:
1269 case Instruction::And:
1270 case Instruction::Or:
1271 case Instruction::Xor: {
1272 ValueList LHSVL, RHSVL;
1273 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1274 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1275 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1278 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1279 Value *LHS = vectorizeTree(LHSVL);
1280 Value *RHS = vectorizeTree(RHSVL);
1282 if (LHS == RHS && isa<Instruction>(LHS)) {
1283 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1286 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1287 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1288 E->VectorizedValue = V;
1291 case Instruction::Load: {
1292 // Loads are inserted at the head of the tree because we don't want to
1293 // sink them all the way down past store instructions.
1294 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1295 LoadInst *LI = cast<LoadInst>(VL0);
1297 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1298 unsigned Alignment = LI->getAlignment();
1299 LI = Builder.CreateLoad(VecPtr);
1300 LI->setAlignment(Alignment);
1301 E->VectorizedValue = LI;
1304 case Instruction::Store: {
1305 StoreInst *SI = cast<StoreInst>(VL0);
1306 unsigned Alignment = SI->getAlignment();
1309 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1310 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1312 Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1313 Value *VecValue = vectorizeTree(ValueOp);
1315 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1316 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1317 S->setAlignment(Alignment);
1318 E->VectorizedValue = S;
1322 llvm_unreachable("unknown inst");
1327 void BoUpSLP::vectorizeTree() {
1328 Builder.SetInsertPoint(F->getEntryBlock().begin());
1329 vectorizeTree(&VectorizableTree[0]);
1331 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1333 // Extract all of the elements with the external uses.
1334 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1336 Value *Scalar = it->Scalar;
1337 llvm::User *User = it->User;
1339 // Skip users that we already RAUW. This happens when one instruction
1340 // has multiple uses of the same value.
1341 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1344 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1346 int Idx = ScalarToTreeEntry[Scalar];
1347 TreeEntry *E = &VectorizableTree[Idx];
1348 assert(!E->NeedToGather && "Extracting from a gather list");
1350 Value *Vec = E->VectorizedValue;
1351 assert(Vec && "Can't find vectorizable value");
1353 // Generate extracts for out-of-tree users.
1354 // Find the insertion point for the extractelement lane.
1355 Instruction *Loc = 0;
1356 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1357 Loc = PN->getParent()->getFirstInsertionPt();
1358 } else if (isa<Instruction>(Vec)){
1359 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1360 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1361 if (PH->getIncomingValue(i) == Scalar) {
1362 Loc = PH->getIncomingBlock(i)->getTerminator();
1366 assert(Loc && "Unable to find incoming value for the PHI");
1368 Loc = cast<Instruction>(User);
1371 Loc = F->getEntryBlock().begin();
1374 Builder.SetInsertPoint(Loc);
1375 Value *Ex = Builder.CreateExtractElement(Vec, Builder.getInt32(it->Lane));
1376 User->replaceUsesOfWith(Scalar, Ex);
1377 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1380 // For each vectorized value:
1381 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1382 TreeEntry *Entry = &VectorizableTree[EIdx];
1385 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1386 Value *Scalar = Entry->Scalars[Lane];
1388 // No need to handle users of gathered values.
1389 if (Entry->NeedToGather)
1392 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1394 Type *Ty = Scalar->getType();
1395 if (!Ty->isVoidTy()) {
1396 for (Value::use_iterator User = Scalar->use_begin(), UE = Scalar->use_end();
1397 User != UE; ++User) {
1398 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1399 assert(!MustGather.count(*User) &&
1400 "Replacing gathered value with undef");
1401 assert(ScalarToTreeEntry.count(*User) &&
1402 "Replacing out-of-tree value with undef");
1404 Value *Undef = UndefValue::get(Ty);
1405 Scalar->replaceAllUsesWith(Undef);
1407 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1408 cast<Instruction>(Scalar)->eraseFromParent();
1412 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1413 BlocksNumbers[it].forget();
1415 Builder.ClearInsertionPoint();
1418 void BoUpSLP::optimizeGatherSequence() {
1419 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1420 << " gather sequences instructions.\n");
1421 // LICM InsertElementInst sequences.
1422 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1423 e = GatherSeq.end(); it != e; ++it) {
1424 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1429 // Check if this block is inside a loop.
1430 Loop *L = LI->getLoopFor(Insert->getParent());
1434 // Check if it has a preheader.
1435 BasicBlock *PreHeader = L->getLoopPreheader();
1439 // If the vector or the element that we insert into it are
1440 // instructions that are defined in this basic block then we can't
1441 // hoist this instruction.
1442 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1443 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1444 if (CurrVec && L->contains(CurrVec))
1446 if (NewElem && L->contains(NewElem))
1449 // We can hoist this instruction. Move it to the pre-header.
1450 Insert->moveBefore(PreHeader->getTerminator());
1453 // Perform O(N^2) search over the gather sequences and merge identical
1454 // instructions. TODO: We can further optimize this scan if we split the
1455 // instructions into different buckets based on the insert lane.
1456 SmallPtrSet<Instruction*, 16> Visited;
1457 SmallVector<Instruction*, 16> ToRemove;
1458 ReversePostOrderTraversal<Function*> RPOT(F);
1459 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1460 E = RPOT.end(); I != E; ++I) {
1461 BasicBlock *BB = *I;
1462 // For all instructions in the function:
1463 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1464 Instruction *In = it;
1465 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1466 !GatherSeq.count(In))
1469 // Check if we can replace this instruction with any of the
1470 // visited instructions.
1471 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1472 ve = Visited.end(); v != ve; ++v) {
1473 if (In->isIdenticalTo(*v) &&
1474 DT->dominates((*v)->getParent(), In->getParent())) {
1475 In->replaceAllUsesWith(*v);
1476 ToRemove.push_back(In);
1486 // Erase all of the instructions that we RAUWed.
1487 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1488 ve = ToRemove.end(); v != ve; ++v) {
1489 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1490 (*v)->eraseFromParent();
1494 /// The SLPVectorizer Pass.
1495 struct SLPVectorizer : public FunctionPass {
1496 typedef SmallVector<StoreInst *, 8> StoreList;
1497 typedef MapVector<Value *, StoreList> StoreListMap;
1499 /// Pass identification, replacement for typeid
1502 explicit SLPVectorizer() : FunctionPass(ID) {
1503 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1506 ScalarEvolution *SE;
1508 TargetTransformInfo *TTI;
1513 virtual bool runOnFunction(Function &F) {
1514 SE = &getAnalysis<ScalarEvolution>();
1515 DL = getAnalysisIfAvailable<DataLayout>();
1516 TTI = &getAnalysis<TargetTransformInfo>();
1517 AA = &getAnalysis<AliasAnalysis>();
1518 LI = &getAnalysis<LoopInfo>();
1519 DT = &getAnalysis<DominatorTree>();
1522 bool Changed = false;
1524 // Must have DataLayout. We can't require it because some tests run w/o
1529 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1531 // Use the bollom up slp vectorizer to construct chains that start with
1532 // he store instructions.
1533 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1535 // Scan the blocks in the function in post order.
1536 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1537 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1538 BasicBlock *BB = *it;
1540 // Vectorize trees that end at stores.
1541 if (unsigned count = collectStores(BB, R)) {
1543 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1544 Changed |= vectorizeStoreChains(R);
1547 // Vectorize trees that end at reductions.
1548 Changed |= vectorizeChainsInBlock(BB, R);
1552 R.optimizeGatherSequence();
1553 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1554 DEBUG(verifyFunction(F));
1559 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1560 FunctionPass::getAnalysisUsage(AU);
1561 AU.addRequired<ScalarEvolution>();
1562 AU.addRequired<AliasAnalysis>();
1563 AU.addRequired<TargetTransformInfo>();
1564 AU.addRequired<LoopInfo>();
1565 AU.addRequired<DominatorTree>();
1566 AU.addPreserved<LoopInfo>();
1567 AU.addPreserved<DominatorTree>();
1568 AU.setPreservesCFG();
1573 /// \brief Collect memory references and sort them according to their base
1574 /// object. We sort the stores to their base objects to reduce the cost of the
1575 /// quadratic search on the stores. TODO: We can further reduce this cost
1576 /// if we flush the chain creation every time we run into a memory barrier.
1577 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1579 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1580 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1582 /// \brief Try to vectorize a list of operands.
1583 /// \returns true if a value was vectorized.
1584 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1586 /// \brief Try to vectorize a chain that may start at the operands of \V;
1587 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1589 /// \brief Vectorize the stores that were collected in StoreRefs.
1590 bool vectorizeStoreChains(BoUpSLP &R);
1592 /// \brief Scan the basic block and look for patterns that are likely to start
1593 /// a vectorization chain.
1594 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1596 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1599 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1602 StoreListMap StoreRefs;
1605 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1606 int CostThreshold, BoUpSLP &R) {
1607 unsigned ChainLen = Chain.size();
1608 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1610 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1611 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1612 unsigned VF = MinVecRegSize / Sz;
1614 if (!isPowerOf2_32(Sz) || VF < 2)
1617 bool Changed = false;
1618 // Look for profitable vectorizable trees at all offsets, starting at zero.
1619 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1622 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1624 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1626 R.buildTree(Operands);
1628 int Cost = R.getTreeCost();
1630 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1631 if (Cost < CostThreshold) {
1632 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1635 // Move to the next bundle.
1641 if (Changed || ChainLen > VF)
1644 // Handle short chains. This helps us catch types such as <3 x float> that
1645 // are smaller than vector size.
1648 int Cost = R.getTreeCost();
1650 if (Cost < CostThreshold) {
1651 DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
1652 << " for size = " << ChainLen << "\n");
1660 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1661 int costThreshold, BoUpSLP &R) {
1662 SetVector<Value *> Heads, Tails;
1663 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1665 // We may run into multiple chains that merge into a single chain. We mark the
1666 // stores that we vectorized so that we don't visit the same store twice.
1667 BoUpSLP::ValueSet VectorizedStores;
1668 bool Changed = false;
1670 // Do a quadratic search on all of the given stores and find
1671 // all of the pairs of stores that follow each other.
1672 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1673 if (Heads.count(Stores[i]))
1675 for (unsigned j = 0; j < e; ++j) {
1676 if (i == j || Tails.count(Stores[j]))
1679 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1680 Tails.insert(Stores[j]);
1681 Heads.insert(Stores[i]);
1682 ConsecutiveChain[Stores[i]] = Stores[j];
1687 // For stores that start but don't end a link in the chain:
1688 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1690 if (Tails.count(*it))
1693 // We found a store instr that starts a chain. Now follow the chain and try
1695 BoUpSLP::ValueList Operands;
1697 // Collect the chain into a list.
1698 while (Tails.count(I) || Heads.count(I)) {
1699 if (VectorizedStores.count(I))
1701 Operands.push_back(I);
1702 // Move to the next value in the chain.
1703 I = ConsecutiveChain[I];
1706 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1708 // Mark the vectorized stores so that we don't vectorize them again.
1710 VectorizedStores.insert(Operands.begin(), Operands.end());
1711 Changed |= Vectorized;
1718 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1721 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1722 StoreInst *SI = dyn_cast<StoreInst>(it);
1726 // Check that the pointer points to scalars.
1727 Type *Ty = SI->getValueOperand()->getType();
1728 if (Ty->isAggregateType() || Ty->isVectorTy())
1731 // Find the base of the GEP.
1732 Value *Ptr = SI->getPointerOperand();
1733 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1734 Ptr = GEP->getPointerOperand();
1736 // Save the store locations.
1737 StoreRefs[Ptr].push_back(SI);
1743 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1746 Value *VL[] = { A, B };
1747 return tryToVectorizeList(VL, R);
1750 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1754 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1756 // Check that all of the parts are scalar instructions of the same type.
1757 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1761 unsigned Opcode0 = I0->getOpcode();
1763 for (int i = 0, e = VL.size(); i < e; ++i) {
1764 Type *Ty = VL[i]->getType();
1765 if (Ty->isAggregateType() || Ty->isVectorTy())
1767 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1768 if (!Inst || Inst->getOpcode() != Opcode0)
1773 int Cost = R.getTreeCost();
1775 if (Cost >= -SLPCostThreshold)
1778 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1783 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1787 // Try to vectorize V.
1788 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1791 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1792 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1794 if (B && B->hasOneUse()) {
1795 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1796 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1797 if (tryToVectorizePair(A, B0, R)) {
1801 if (tryToVectorizePair(A, B1, R)) {
1808 if (A && A->hasOneUse()) {
1809 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1810 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1811 if (tryToVectorizePair(A0, B, R)) {
1815 if (tryToVectorizePair(A1, B, R)) {
1823 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
1824 bool Changed = false;
1825 SmallVector<Value *, 4> Incoming;
1826 // Collect the incoming values from the PHIs.
1827 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
1829 PHINode *P = dyn_cast<PHINode>(instr);
1834 // Stop constructing the list when you reach a different type.
1835 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
1836 Changed |= tryToVectorizeList(Incoming, R);
1840 Incoming.push_back(P);
1843 if (Incoming.size() > 1)
1844 Changed |= tryToVectorizeList(Incoming, R);
1846 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1847 if (isa<DbgInfoIntrinsic>(it))
1850 // Try to vectorize reductions that use PHINodes.
1851 if (PHINode *P = dyn_cast<PHINode>(it)) {
1852 // Check that the PHI is a reduction PHI.
1853 if (P->getNumIncomingValues() != 2)
1856 (P->getIncomingBlock(0) == BB
1857 ? (P->getIncomingValue(0))
1858 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1859 // Check if this is a Binary Operator.
1860 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1864 Value *Inst = BI->getOperand(0);
1866 Inst = BI->getOperand(1);
1868 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1872 // Try to vectorize trees that start at compare instructions.
1873 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1874 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1878 for (int i = 0; i < 2; ++i)
1879 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1881 tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1889 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
1890 bool Changed = false;
1891 // Attempt to sort and vectorize each of the store-groups.
1892 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1894 if (it->second.size() < 2)
1897 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1898 << it->second.size() << ".\n");
1900 // Process the stores in chunks of 16.
1901 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
1902 unsigned Len = std::min<unsigned>(CE - CI, 16);
1903 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
1904 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
1910 } // end anonymous namespace
1912 char SLPVectorizer::ID = 0;
1913 static const char lv_name[] = "SLP Vectorizer";
1914 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1915 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1916 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1917 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1918 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1919 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1922 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }