1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
18 #define SV_NAME "slp-vectorizer"
19 #define DEBUG_TYPE "SLP"
21 #include "llvm/Transforms/Vectorize.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
49 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
50 cl::desc("Only vectorize if you gain more than this "
54 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
55 cl::desc("Attempt to vectorize horizontal reductions"));
57 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
58 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
60 "Attempt to vectorize horizontal reductions feeding into a store"));
64 static const unsigned MinVecRegSize = 128;
66 static const unsigned RecursionMaxDepth = 12;
68 /// RAII pattern to save the insertion point of the IR builder.
69 class BuilderLocGuard {
71 BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()),
72 DbgLoc(B.getCurrentDebugLocation()) {}
74 Builder.SetCurrentDebugLocation(DbgLoc);
76 Builder.SetInsertPoint(Loc);
81 BuilderLocGuard(const BuilderLocGuard &);
82 BuilderLocGuard &operator=(const BuilderLocGuard &);
84 AssertingVH<Instruction> Loc;
88 /// A helper class for numbering instructions in multiple blocks.
89 /// Numbers start at zero for each basic block.
90 struct BlockNumbering {
92 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
94 BlockNumbering() : BB(0), Valid(false) {}
96 void numberInstructions() {
100 // Number the instructions in the block.
101 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
102 InstrIdx[it] = Loc++;
103 InstrVec.push_back(it);
104 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
109 int getIndex(Instruction *I) {
110 assert(I->getParent() == BB && "Invalid instruction");
112 numberInstructions();
113 assert(InstrIdx.count(I) && "Unknown instruction");
117 Instruction *getInstruction(unsigned loc) {
119 numberInstructions();
120 assert(InstrVec.size() > loc && "Invalid Index");
121 return InstrVec[loc];
124 void forget() { Valid = false; }
127 /// The block we are numbering.
129 /// Is the block numbered.
131 /// Maps instructions to numbers and back.
132 SmallDenseMap<Instruction *, int> InstrIdx;
133 /// Maps integers to Instructions.
134 SmallVector<Instruction *, 32> InstrVec;
137 /// \returns the parent basic block if all of the instructions in \p VL
138 /// are in the same block or null otherwise.
139 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
140 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
143 BasicBlock *BB = I0->getParent();
144 for (int i = 1, e = VL.size(); i < e; i++) {
145 Instruction *I = dyn_cast<Instruction>(VL[i]);
149 if (BB != I->getParent())
155 /// \returns True if all of the values in \p VL are constants.
156 static bool allConstant(ArrayRef<Value *> VL) {
157 for (unsigned i = 0, e = VL.size(); i < e; ++i)
158 if (!isa<Constant>(VL[i]))
163 /// \returns True if all of the values in \p VL are identical.
164 static bool isSplat(ArrayRef<Value *> VL) {
165 for (unsigned i = 1, e = VL.size(); i < e; ++i)
171 /// \returns The opcode if all of the Instructions in \p VL have the same
173 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
174 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
177 unsigned Opcode = I0->getOpcode();
178 for (int i = 1, e = VL.size(); i < e; i++) {
179 Instruction *I = dyn_cast<Instruction>(VL[i]);
180 if (!I || Opcode != I->getOpcode())
186 /// \returns The type that all of the values in \p VL have or null if there
187 /// are different types.
188 static Type* getSameType(ArrayRef<Value *> VL) {
189 Type *Ty = VL[0]->getType();
190 for (int i = 1, e = VL.size(); i < e; i++)
191 if (VL[i]->getType() != Ty)
197 /// \returns True if the ExtractElement instructions in VL can be vectorized
198 /// to use the original vector.
199 static bool CanReuseExtract(ArrayRef<Value *> VL) {
200 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
201 // Check if all of the extracts come from the same vector and from the
204 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
205 Value *Vec = E0->getOperand(0);
207 // We have to extract from the same vector type.
208 unsigned NElts = Vec->getType()->getVectorNumElements();
210 if (NElts != VL.size())
213 // Check that all of the indices extract from the correct offset.
214 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
215 if (!CI || CI->getZExtValue())
218 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
219 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
220 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
222 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
229 /// Bottom Up SLP Vectorizer.
232 typedef SmallVector<Value *, 8> ValueList;
233 typedef SmallVector<Instruction *, 16> InstrList;
234 typedef SmallPtrSet<Value *, 16> ValueSet;
235 typedef SmallVector<StoreInst *, 8> StoreList;
237 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
238 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
240 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
241 Builder(Se->getContext()) {
242 // Setup the block numbering utility for all of the blocks in the
244 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
246 BlocksNumbers[BB] = BlockNumbering(BB);
250 /// \brief Vectorize the tree that starts with the elements in \p VL.
251 /// Returns the vectorized root.
252 Value *vectorizeTree();
254 /// \returns the vectorization cost of the subtree that starts at \p VL.
255 /// A negative number means that this is profitable.
258 /// Construct a vectorizable tree that starts at \p Roots and is possibly
259 /// used by a reduction of \p RdxOps.
260 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
262 /// Clear the internal data structures that are created by 'buildTree'.
265 VectorizableTree.clear();
266 ScalarToTreeEntry.clear();
268 ExternalUses.clear();
269 MemBarrierIgnoreList.clear();
272 /// \returns true if the memory operations A and B are consecutive.
273 bool isConsecutiveAccess(Value *A, Value *B);
275 /// \brief Perform LICM and CSE on the newly generated gather sequences.
276 void optimizeGatherSequence();
280 /// \returns the cost of the vectorizable entry.
281 int getEntryCost(TreeEntry *E);
283 /// This is the recursive part of buildTree.
284 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
286 /// Vectorize a single entry in the tree.
287 Value *vectorizeTree(TreeEntry *E);
289 /// Vectorize a single entry in the tree, starting in \p VL.
290 Value *vectorizeTree(ArrayRef<Value *> VL);
292 /// \returns the pointer to the vectorized value if \p VL is already
293 /// vectorized, or NULL. They may happen in cycles.
294 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
296 /// \brief Take the pointer operand from the Load/Store instruction.
297 /// \returns NULL if this is not a valid Load/Store instruction.
298 static Value *getPointerOperand(Value *I);
300 /// \brief Take the address space operand from the Load/Store instruction.
301 /// \returns -1 if this is not a valid Load/Store instruction.
302 static unsigned getAddressSpaceOperand(Value *I);
304 /// \returns the scalarization cost for this type. Scalarization in this
305 /// context means the creation of vectors from a group of scalars.
306 int getGatherCost(Type *Ty);
308 /// \returns the scalarization cost for this list of values. Assuming that
309 /// this subtree gets vectorized, we may need to extract the values from the
310 /// roots. This method calculates the cost of extracting the values.
311 int getGatherCost(ArrayRef<Value *> VL);
313 /// \returns the AA location that is being access by the instruction.
314 AliasAnalysis::Location getLocation(Instruction *I);
316 /// \brief Checks if it is possible to sink an instruction from
317 /// \p Src to \p Dst.
318 /// \returns the pointer to the barrier instruction if we can't sink.
319 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
321 /// \returns the index of the last instrucion in the BB from \p VL.
322 int getLastIndex(ArrayRef<Value *> VL);
324 /// \returns the Instruction in the bundle \p VL.
325 Instruction *getLastInstruction(ArrayRef<Value *> VL);
327 /// \brief Set the Builder insert point to one after the last instruction in
329 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
331 /// \returns a vector from a collection of scalars in \p VL.
332 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
335 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
338 /// \returns true if the scalars in VL are equal to this entry.
339 bool isSame(ArrayRef<Value *> VL) const {
340 assert(VL.size() == Scalars.size() && "Invalid size");
341 for (int i = 0, e = VL.size(); i != e; ++i)
342 if (VL[i] != Scalars[i])
347 /// A vector of scalars.
350 /// The Scalars are vectorized into this value. It is initialized to Null.
351 Value *VectorizedValue;
353 /// The index in the basic block of the last scalar.
356 /// Do we need to gather this sequence ?
360 /// Create a new VectorizableTree entry.
361 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
362 VectorizableTree.push_back(TreeEntry());
363 int idx = VectorizableTree.size() - 1;
364 TreeEntry *Last = &VectorizableTree[idx];
365 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
366 Last->NeedToGather = !Vectorized;
368 Last->LastScalarIndex = getLastIndex(VL);
369 for (int i = 0, e = VL.size(); i != e; ++i) {
370 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
371 ScalarToTreeEntry[VL[i]] = idx;
374 Last->LastScalarIndex = 0;
375 MustGather.insert(VL.begin(), VL.end());
380 /// -- Vectorization State --
381 /// Holds all of the tree entries.
382 std::vector<TreeEntry> VectorizableTree;
384 /// Maps a specific scalar to its tree entry.
385 SmallDenseMap<Value*, int> ScalarToTreeEntry;
387 /// A list of scalars that we found that we need to keep as scalars.
390 /// This POD struct describes one external user in the vectorized tree.
391 struct ExternalUser {
392 ExternalUser (Value *S, llvm::User *U, int L) :
393 Scalar(S), User(U), Lane(L){};
394 // Which scalar in our function.
396 // Which user that uses the scalar.
398 // Which lane does the scalar belong to.
401 typedef SmallVector<ExternalUser, 16> UserList;
403 /// A list of values that need to extracted out of the tree.
404 /// This list holds pairs of (Internal Scalar : External User).
405 UserList ExternalUses;
407 /// A list of instructions to ignore while sinking
408 /// memory instructions. This map must be reset between runs of getCost.
409 ValueSet MemBarrierIgnoreList;
411 /// Holds all of the instructions that we gathered.
412 SetVector<Instruction *> GatherSeq;
414 /// Numbers instructions in different blocks.
415 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
417 /// Reduction operators.
420 // Analysis and block reference.
424 TargetTransformInfo *TTI;
428 /// Instruction builder to construct the vectorized tree.
432 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
435 if (!getSameType(Roots))
437 buildTree_rec(Roots, 0);
439 // Collect the values that we need to extract from the tree.
440 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
441 TreeEntry *Entry = &VectorizableTree[EIdx];
444 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
445 Value *Scalar = Entry->Scalars[Lane];
447 // No need to handle users of gathered values.
448 if (Entry->NeedToGather)
451 for (Value::use_iterator User = Scalar->use_begin(),
452 UE = Scalar->use_end(); User != UE; ++User) {
453 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
455 bool Gathered = MustGather.count(*User);
457 // Skip in-tree scalars that become vectors.
458 if (ScalarToTreeEntry.count(*User) && !Gathered) {
459 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
461 int Idx = ScalarToTreeEntry[*User]; (void) Idx;
462 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
465 Instruction *UserInst = dyn_cast<Instruction>(*User);
469 // Ignore uses that are part of the reduction.
470 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
473 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
474 Lane << " from " << *Scalar << ".\n");
475 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
482 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
483 bool SameTy = getSameType(VL); (void)SameTy;
484 assert(SameTy && "Invalid types!");
486 if (Depth == RecursionMaxDepth) {
487 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
488 newTreeEntry(VL, false);
492 // Don't handle vectors.
493 if (VL[0]->getType()->isVectorTy()) {
494 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
495 newTreeEntry(VL, false);
499 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
500 if (SI->getValueOperand()->getType()->isVectorTy()) {
501 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
502 newTreeEntry(VL, false);
506 // If all of the operands are identical or constant we have a simple solution.
507 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
508 !getSameOpcode(VL)) {
509 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
510 newTreeEntry(VL, false);
514 // We now know that this is a vector of instructions of the same type from
517 // Check if this is a duplicate of another entry.
518 if (ScalarToTreeEntry.count(VL[0])) {
519 int Idx = ScalarToTreeEntry[VL[0]];
520 TreeEntry *E = &VectorizableTree[Idx];
521 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
522 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
523 if (E->Scalars[i] != VL[i]) {
524 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
525 newTreeEntry(VL, false);
529 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
533 // Check that none of the instructions in the bundle are already in the tree.
534 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
535 if (ScalarToTreeEntry.count(VL[i])) {
536 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
537 ") is already in tree.\n");
538 newTreeEntry(VL, false);
543 // If any of the scalars appears in the table OR it is marked as a value that
544 // needs to stat scalar then we need to gather the scalars.
545 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
546 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
547 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
548 newTreeEntry(VL, false);
553 // Check that all of the users of the scalars that we want to vectorize are
555 Instruction *VL0 = cast<Instruction>(VL[0]);
556 int MyLastIndex = getLastIndex(VL);
557 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
559 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
560 Instruction *Scalar = cast<Instruction>(VL[i]);
561 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
562 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
564 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
565 Instruction *User = dyn_cast<Instruction>(*U);
567 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
568 newTreeEntry(VL, false);
572 // We don't care if the user is in a different basic block.
573 BasicBlock *UserBlock = User->getParent();
574 if (UserBlock != BB) {
575 DEBUG(dbgs() << "SLP: User from a different basic block "
580 // If this is a PHINode within this basic block then we can place the
581 // extract wherever we want.
582 if (isa<PHINode>(*User)) {
583 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
587 // Check if this is a safe in-tree user.
588 if (ScalarToTreeEntry.count(User)) {
589 int Idx = ScalarToTreeEntry[User];
590 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
591 if (VecLocation <= MyLastIndex) {
592 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
593 newTreeEntry(VL, false);
596 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
597 VecLocation << " vector value (" << *Scalar << ") at #"
598 << MyLastIndex << ".\n");
602 // This user is part of the reduction.
603 if (RdxOps && RdxOps->count(User))
606 // Make sure that we can schedule this unknown user.
607 BlockNumbering &BN = BlocksNumbers[BB];
608 int UserIndex = BN.getIndex(User);
609 if (UserIndex < MyLastIndex) {
611 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
613 newTreeEntry(VL, false);
619 // Check that every instructions appears once in this bundle.
620 for (unsigned i = 0, e = VL.size(); i < e; ++i)
621 for (unsigned j = i+1; j < e; ++j)
622 if (VL[i] == VL[j]) {
623 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
624 newTreeEntry(VL, false);
628 // Check that instructions in this bundle don't reference other instructions.
629 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
630 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
631 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
633 for (unsigned j = 0; j < e; ++j) {
634 if (i != j && *U == VL[j]) {
635 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
636 newTreeEntry(VL, false);
643 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
645 unsigned Opcode = getSameOpcode(VL);
647 // Check if it is safe to sink the loads or the stores.
648 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
649 Instruction *Last = getLastInstruction(VL);
651 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
654 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
656 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
657 << "\n because of " << *Barrier << ". Gathering.\n");
658 newTreeEntry(VL, false);
665 case Instruction::PHI: {
666 PHINode *PH = dyn_cast<PHINode>(VL0);
668 // Check for terminator values (e.g. invoke).
669 for (unsigned j = 0; j < VL.size(); ++j)
670 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
671 TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
673 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
674 newTreeEntry(VL, false);
679 newTreeEntry(VL, true);
680 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
682 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
684 // Prepare the operand vector.
685 for (unsigned j = 0; j < VL.size(); ++j)
686 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
688 buildTree_rec(Operands, Depth + 1);
692 case Instruction::ExtractElement: {
693 bool Reuse = CanReuseExtract(VL);
695 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
697 newTreeEntry(VL, Reuse);
700 case Instruction::Load: {
701 // Check if the loads are consecutive or of we need to swizzle them.
702 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
703 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
704 newTreeEntry(VL, false);
705 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
709 newTreeEntry(VL, true);
710 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
713 case Instruction::ZExt:
714 case Instruction::SExt:
715 case Instruction::FPToUI:
716 case Instruction::FPToSI:
717 case Instruction::FPExt:
718 case Instruction::PtrToInt:
719 case Instruction::IntToPtr:
720 case Instruction::SIToFP:
721 case Instruction::UIToFP:
722 case Instruction::Trunc:
723 case Instruction::FPTrunc:
724 case Instruction::BitCast: {
725 Type *SrcTy = VL0->getOperand(0)->getType();
726 for (unsigned i = 0; i < VL.size(); ++i) {
727 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
728 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
729 newTreeEntry(VL, false);
730 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
734 newTreeEntry(VL, true);
735 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
737 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
739 // Prepare the operand vector.
740 for (unsigned j = 0; j < VL.size(); ++j)
741 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
743 buildTree_rec(Operands, Depth+1);
747 case Instruction::ICmp:
748 case Instruction::FCmp: {
749 // Check that all of the compares have the same predicate.
750 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
751 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
752 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
753 CmpInst *Cmp = cast<CmpInst>(VL[i]);
754 if (Cmp->getPredicate() != P0 ||
755 Cmp->getOperand(0)->getType() != ComparedTy) {
756 newTreeEntry(VL, false);
757 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
762 newTreeEntry(VL, true);
763 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
765 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
767 // Prepare the operand vector.
768 for (unsigned j = 0; j < VL.size(); ++j)
769 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
771 buildTree_rec(Operands, Depth+1);
775 case Instruction::Select:
776 case Instruction::Add:
777 case Instruction::FAdd:
778 case Instruction::Sub:
779 case Instruction::FSub:
780 case Instruction::Mul:
781 case Instruction::FMul:
782 case Instruction::UDiv:
783 case Instruction::SDiv:
784 case Instruction::FDiv:
785 case Instruction::URem:
786 case Instruction::SRem:
787 case Instruction::FRem:
788 case Instruction::Shl:
789 case Instruction::LShr:
790 case Instruction::AShr:
791 case Instruction::And:
792 case Instruction::Or:
793 case Instruction::Xor: {
794 newTreeEntry(VL, true);
795 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
797 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
799 // Prepare the operand vector.
800 for (unsigned j = 0; j < VL.size(); ++j)
801 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
803 buildTree_rec(Operands, Depth+1);
807 case Instruction::Store: {
808 // Check if the stores are consecutive or of we need to swizzle them.
809 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
810 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
811 newTreeEntry(VL, false);
812 DEBUG(dbgs() << "SLP: Non consecutive store.\n");
816 newTreeEntry(VL, true);
817 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
820 for (unsigned j = 0; j < VL.size(); ++j)
821 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
823 // We can ignore these values because we are sinking them down.
824 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
825 buildTree_rec(Operands, Depth + 1);
829 newTreeEntry(VL, false);
830 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
835 int BoUpSLP::getEntryCost(TreeEntry *E) {
836 ArrayRef<Value*> VL = E->Scalars;
838 Type *ScalarTy = VL[0]->getType();
839 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
840 ScalarTy = SI->getValueOperand()->getType();
841 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
843 if (E->NeedToGather) {
847 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
849 return getGatherCost(E->Scalars);
852 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
854 Instruction *VL0 = cast<Instruction>(VL[0]);
855 unsigned Opcode = VL0->getOpcode();
857 case Instruction::PHI: {
860 case Instruction::ExtractElement: {
861 if (CanReuseExtract(VL))
863 return getGatherCost(VecTy);
865 case Instruction::ZExt:
866 case Instruction::SExt:
867 case Instruction::FPToUI:
868 case Instruction::FPToSI:
869 case Instruction::FPExt:
870 case Instruction::PtrToInt:
871 case Instruction::IntToPtr:
872 case Instruction::SIToFP:
873 case Instruction::UIToFP:
874 case Instruction::Trunc:
875 case Instruction::FPTrunc:
876 case Instruction::BitCast: {
877 Type *SrcTy = VL0->getOperand(0)->getType();
879 // Calculate the cost of this instruction.
880 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
881 VL0->getType(), SrcTy);
883 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
884 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
885 return VecCost - ScalarCost;
887 case Instruction::FCmp:
888 case Instruction::ICmp:
889 case Instruction::Select:
890 case Instruction::Add:
891 case Instruction::FAdd:
892 case Instruction::Sub:
893 case Instruction::FSub:
894 case Instruction::Mul:
895 case Instruction::FMul:
896 case Instruction::UDiv:
897 case Instruction::SDiv:
898 case Instruction::FDiv:
899 case Instruction::URem:
900 case Instruction::SRem:
901 case Instruction::FRem:
902 case Instruction::Shl:
903 case Instruction::LShr:
904 case Instruction::AShr:
905 case Instruction::And:
906 case Instruction::Or:
907 case Instruction::Xor: {
908 // Calculate the cost of this instruction.
911 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
912 Opcode == Instruction::Select) {
913 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
914 ScalarCost = VecTy->getNumElements() *
915 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
916 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
918 ScalarCost = VecTy->getNumElements() *
919 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
920 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
922 return VecCost - ScalarCost;
924 case Instruction::Load: {
925 // Cost of wide load - cost of scalar loads.
926 int ScalarLdCost = VecTy->getNumElements() *
927 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
928 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
929 return VecLdCost - ScalarLdCost;
931 case Instruction::Store: {
932 // We know that we can merge the stores. Calculate the cost.
933 int ScalarStCost = VecTy->getNumElements() *
934 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
935 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
936 return VecStCost - ScalarStCost;
939 llvm_unreachable("Unknown instruction");
943 int BoUpSLP::getTreeCost() {
945 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
946 VectorizableTree.size() << ".\n");
948 // Don't vectorize tiny trees. Small load/store chains or consecutive stores
949 // of constants will be vectoried in SelectionDAG in MergeConsecutiveStores.
950 // The SelectionDAG vectorizer can only handle pairs (trees of height = 2).
951 if (VectorizableTree.size() < 3) {
952 if (!VectorizableTree.size()) {
953 assert(!ExternalUses.size() && "We should not have any external users");
958 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
960 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
961 int C = getEntryCost(&VectorizableTree[i]);
962 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
963 << *VectorizableTree[i].Scalars[0] << " .\n");
968 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
971 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
972 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
977 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
978 return Cost + ExtractCost;
981 int BoUpSLP::getGatherCost(Type *Ty) {
983 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
984 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
988 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
989 // Find the type of the operands in VL.
990 Type *ScalarTy = VL[0]->getType();
991 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
992 ScalarTy = SI->getValueOperand()->getType();
993 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
994 // Find the cost of inserting/extracting values from the vector.
995 return getGatherCost(VecTy);
998 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
999 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1000 return AA->getLocation(SI);
1001 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1002 return AA->getLocation(LI);
1003 return AliasAnalysis::Location();
1006 Value *BoUpSLP::getPointerOperand(Value *I) {
1007 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1008 return LI->getPointerOperand();
1009 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1010 return SI->getPointerOperand();
1014 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1015 if (LoadInst *L = dyn_cast<LoadInst>(I))
1016 return L->getPointerAddressSpace();
1017 if (StoreInst *S = dyn_cast<StoreInst>(I))
1018 return S->getPointerAddressSpace();
1022 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1023 Value *PtrA = getPointerOperand(A);
1024 Value *PtrB = getPointerOperand(B);
1025 unsigned ASA = getAddressSpaceOperand(A);
1026 unsigned ASB = getAddressSpaceOperand(B);
1028 // Check that the address spaces match and that the pointers are valid.
1029 if (!PtrA || !PtrB || (ASA != ASB))
1032 // Make sure that A and B are different pointers of the same type.
1033 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1036 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1037 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1038 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1040 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1041 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1042 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1044 APInt OffsetDelta = OffsetB - OffsetA;
1046 // Check if they are based on the same pointer. That makes the offsets
1049 return OffsetDelta == Size;
1051 // Compute the necessary base pointer delta to have the necessary final delta
1052 // equal to the size.
1053 APInt BaseDelta = Size - OffsetDelta;
1055 // Otherwise compute the distance with SCEV between the base pointers.
1056 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1057 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1058 const SCEV *C = SE->getConstant(BaseDelta);
1059 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1060 return X == PtrSCEVB;
1063 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1064 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1065 BasicBlock::iterator I = Src, E = Dst;
1066 /// Scan all of the instruction from SRC to DST and check if
1067 /// the source may alias.
1068 for (++I; I != E; ++I) {
1069 // Ignore store instructions that are marked as 'ignore'.
1070 if (MemBarrierIgnoreList.count(I))
1072 if (Src->mayWriteToMemory()) /* Write */ {
1073 if (!I->mayReadOrWriteMemory())
1076 if (!I->mayWriteToMemory())
1079 AliasAnalysis::Location A = getLocation(&*I);
1080 AliasAnalysis::Location B = getLocation(Src);
1082 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1088 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1089 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1090 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1091 BlockNumbering &BN = BlocksNumbers[BB];
1093 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1094 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1095 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1099 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1100 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1101 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1102 BlockNumbering &BN = BlocksNumbers[BB];
1104 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1105 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1106 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1107 Instruction *I = BN.getInstruction(MaxIdx);
1108 assert(I && "bad location");
1112 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1113 Instruction *VL0 = cast<Instruction>(VL[0]);
1114 Instruction *LastInst = getLastInstruction(VL);
1115 BasicBlock::iterator NextInst = LastInst;
1117 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1118 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1121 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1122 Value *Vec = UndefValue::get(Ty);
1123 // Generate the 'InsertElement' instruction.
1124 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1125 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1126 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1127 GatherSeq.insert(Insrt);
1129 // Add to our 'need-to-extract' list.
1130 if (ScalarToTreeEntry.count(VL[i])) {
1131 int Idx = ScalarToTreeEntry[VL[i]];
1132 TreeEntry *E = &VectorizableTree[Idx];
1133 // Find which lane we need to extract.
1135 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1136 // Is this the lane of the scalar that we are looking for ?
1137 if (E->Scalars[Lane] == VL[i]) {
1142 assert(FoundLane >= 0 && "Could not find the correct lane");
1143 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1151 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1152 SmallDenseMap<Value*, int>::const_iterator Entry
1153 = ScalarToTreeEntry.find(VL[0]);
1154 if (Entry != ScalarToTreeEntry.end()) {
1155 int Idx = Entry->second;
1156 const TreeEntry *En = &VectorizableTree[Idx];
1157 if (En->isSame(VL) && En->VectorizedValue)
1158 return En->VectorizedValue;
1163 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1164 if (ScalarToTreeEntry.count(VL[0])) {
1165 int Idx = ScalarToTreeEntry[VL[0]];
1166 TreeEntry *E = &VectorizableTree[Idx];
1168 return vectorizeTree(E);
1171 Type *ScalarTy = VL[0]->getType();
1172 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1173 ScalarTy = SI->getValueOperand()->getType();
1174 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1176 return Gather(VL, VecTy);
1179 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1180 BuilderLocGuard Guard(Builder);
1182 if (E->VectorizedValue) {
1183 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1184 return E->VectorizedValue;
1187 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1188 Type *ScalarTy = VL0->getType();
1189 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1190 ScalarTy = SI->getValueOperand()->getType();
1191 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1193 if (E->NeedToGather) {
1194 setInsertPointAfterBundle(E->Scalars);
1195 return Gather(E->Scalars, VecTy);
1198 unsigned Opcode = VL0->getOpcode();
1199 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1202 case Instruction::PHI: {
1203 PHINode *PH = dyn_cast<PHINode>(VL0);
1204 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1205 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1206 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1207 E->VectorizedValue = NewPhi;
1209 // PHINodes may have multiple entries from the same block. We want to
1210 // visit every block once.
1211 SmallSet<BasicBlock*, 4> VisitedBBs;
1213 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1215 BasicBlock *IBB = PH->getIncomingBlock(i);
1217 if (!VisitedBBs.insert(IBB)) {
1218 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1222 // Prepare the operand vector.
1223 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1224 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1225 getIncomingValueForBlock(IBB));
1227 Builder.SetInsertPoint(IBB->getTerminator());
1228 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1229 Value *Vec = vectorizeTree(Operands);
1230 NewPhi->addIncoming(Vec, IBB);
1233 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1234 "Invalid number of incoming values");
1238 case Instruction::ExtractElement: {
1239 if (CanReuseExtract(E->Scalars)) {
1240 Value *V = VL0->getOperand(0);
1241 E->VectorizedValue = V;
1244 return Gather(E->Scalars, VecTy);
1246 case Instruction::ZExt:
1247 case Instruction::SExt:
1248 case Instruction::FPToUI:
1249 case Instruction::FPToSI:
1250 case Instruction::FPExt:
1251 case Instruction::PtrToInt:
1252 case Instruction::IntToPtr:
1253 case Instruction::SIToFP:
1254 case Instruction::UIToFP:
1255 case Instruction::Trunc:
1256 case Instruction::FPTrunc:
1257 case Instruction::BitCast: {
1259 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1260 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1262 setInsertPointAfterBundle(E->Scalars);
1264 Value *InVec = vectorizeTree(INVL);
1266 if (Value *V = alreadyVectorized(E->Scalars))
1269 CastInst *CI = dyn_cast<CastInst>(VL0);
1270 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1271 E->VectorizedValue = V;
1274 case Instruction::FCmp:
1275 case Instruction::ICmp: {
1276 ValueList LHSV, RHSV;
1277 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1278 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1279 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1282 setInsertPointAfterBundle(E->Scalars);
1284 Value *L = vectorizeTree(LHSV);
1285 Value *R = vectorizeTree(RHSV);
1287 if (Value *V = alreadyVectorized(E->Scalars))
1290 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1292 if (Opcode == Instruction::FCmp)
1293 V = Builder.CreateFCmp(P0, L, R);
1295 V = Builder.CreateICmp(P0, L, R);
1297 E->VectorizedValue = V;
1300 case Instruction::Select: {
1301 ValueList TrueVec, FalseVec, CondVec;
1302 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1303 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1304 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1305 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1308 setInsertPointAfterBundle(E->Scalars);
1310 Value *Cond = vectorizeTree(CondVec);
1311 Value *True = vectorizeTree(TrueVec);
1312 Value *False = vectorizeTree(FalseVec);
1314 if (Value *V = alreadyVectorized(E->Scalars))
1317 Value *V = Builder.CreateSelect(Cond, True, False);
1318 E->VectorizedValue = V;
1321 case Instruction::Add:
1322 case Instruction::FAdd:
1323 case Instruction::Sub:
1324 case Instruction::FSub:
1325 case Instruction::Mul:
1326 case Instruction::FMul:
1327 case Instruction::UDiv:
1328 case Instruction::SDiv:
1329 case Instruction::FDiv:
1330 case Instruction::URem:
1331 case Instruction::SRem:
1332 case Instruction::FRem:
1333 case Instruction::Shl:
1334 case Instruction::LShr:
1335 case Instruction::AShr:
1336 case Instruction::And:
1337 case Instruction::Or:
1338 case Instruction::Xor: {
1339 ValueList LHSVL, RHSVL;
1340 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1341 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1342 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1345 setInsertPointAfterBundle(E->Scalars);
1347 Value *LHS = vectorizeTree(LHSVL);
1348 Value *RHS = vectorizeTree(RHSVL);
1350 if (LHS == RHS && isa<Instruction>(LHS)) {
1351 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1354 if (Value *V = alreadyVectorized(E->Scalars))
1357 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1358 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1359 E->VectorizedValue = V;
1362 case Instruction::Load: {
1363 // Loads are inserted at the head of the tree because we don't want to
1364 // sink them all the way down past store instructions.
1365 setInsertPointAfterBundle(E->Scalars);
1367 LoadInst *LI = cast<LoadInst>(VL0);
1369 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1370 unsigned Alignment = LI->getAlignment();
1371 LI = Builder.CreateLoad(VecPtr);
1372 LI->setAlignment(Alignment);
1373 E->VectorizedValue = LI;
1376 case Instruction::Store: {
1377 StoreInst *SI = cast<StoreInst>(VL0);
1378 unsigned Alignment = SI->getAlignment();
1381 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1382 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1384 setInsertPointAfterBundle(E->Scalars);
1386 Value *VecValue = vectorizeTree(ValueOp);
1388 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1389 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1390 S->setAlignment(Alignment);
1391 E->VectorizedValue = S;
1395 llvm_unreachable("unknown inst");
1400 Value *BoUpSLP::vectorizeTree() {
1401 Builder.SetInsertPoint(F->getEntryBlock().begin());
1402 vectorizeTree(&VectorizableTree[0]);
1404 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1406 // Extract all of the elements with the external uses.
1407 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1409 Value *Scalar = it->Scalar;
1410 llvm::User *User = it->User;
1412 // Skip users that we already RAUW. This happens when one instruction
1413 // has multiple uses of the same value.
1414 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1417 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1419 int Idx = ScalarToTreeEntry[Scalar];
1420 TreeEntry *E = &VectorizableTree[Idx];
1421 assert(!E->NeedToGather && "Extracting from a gather list");
1423 Value *Vec = E->VectorizedValue;
1424 assert(Vec && "Can't find vectorizable value");
1426 Value *Lane = Builder.getInt32(it->Lane);
1427 // Generate extracts for out-of-tree users.
1428 // Find the insertion point for the extractelement lane.
1429 if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1430 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1431 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1432 User->replaceUsesOfWith(Scalar, Ex);
1433 } else if (isa<Instruction>(Vec)){
1434 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1435 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1436 if (PH->getIncomingValue(i) == Scalar) {
1437 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1438 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1439 PH->setOperand(i, Ex);
1443 Builder.SetInsertPoint(cast<Instruction>(User));
1444 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1445 User->replaceUsesOfWith(Scalar, Ex);
1448 Builder.SetInsertPoint(F->getEntryBlock().begin());
1449 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1450 User->replaceUsesOfWith(Scalar, Ex);
1453 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1456 // For each vectorized value:
1457 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1458 TreeEntry *Entry = &VectorizableTree[EIdx];
1461 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1462 Value *Scalar = Entry->Scalars[Lane];
1464 // No need to handle users of gathered values.
1465 if (Entry->NeedToGather)
1468 assert(Entry->VectorizedValue && "Can't find vectorizable value");
1470 Type *Ty = Scalar->getType();
1471 if (!Ty->isVoidTy()) {
1472 for (Value::use_iterator User = Scalar->use_begin(),
1473 UE = Scalar->use_end(); User != UE; ++User) {
1474 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1475 assert(!MustGather.count(*User) &&
1476 "Replacing gathered value with undef");
1478 assert((ScalarToTreeEntry.count(*User) ||
1479 // It is legal to replace the reduction users by undef.
1480 (RdxOps && RdxOps->count(*User))) &&
1481 "Replacing out-of-tree value with undef");
1483 Value *Undef = UndefValue::get(Ty);
1484 Scalar->replaceAllUsesWith(Undef);
1486 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1487 cast<Instruction>(Scalar)->eraseFromParent();
1491 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1492 BlocksNumbers[it].forget();
1494 Builder.ClearInsertionPoint();
1496 return VectorizableTree[0].VectorizedValue;
1499 void BoUpSLP::optimizeGatherSequence() {
1500 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1501 << " gather sequences instructions.\n");
1502 // LICM InsertElementInst sequences.
1503 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1504 e = GatherSeq.end(); it != e; ++it) {
1505 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1510 // Check if this block is inside a loop.
1511 Loop *L = LI->getLoopFor(Insert->getParent());
1515 // Check if it has a preheader.
1516 BasicBlock *PreHeader = L->getLoopPreheader();
1520 // If the vector or the element that we insert into it are
1521 // instructions that are defined in this basic block then we can't
1522 // hoist this instruction.
1523 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1524 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1525 if (CurrVec && L->contains(CurrVec))
1527 if (NewElem && L->contains(NewElem))
1530 // We can hoist this instruction. Move it to the pre-header.
1531 Insert->moveBefore(PreHeader->getTerminator());
1534 // Perform O(N^2) search over the gather sequences and merge identical
1535 // instructions. TODO: We can further optimize this scan if we split the
1536 // instructions into different buckets based on the insert lane.
1537 SmallPtrSet<Instruction*, 16> Visited;
1538 SmallVector<Instruction*, 16> ToRemove;
1539 ReversePostOrderTraversal<Function*> RPOT(F);
1540 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1541 E = RPOT.end(); I != E; ++I) {
1542 BasicBlock *BB = *I;
1543 // For all instructions in the function:
1544 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1545 Instruction *In = it;
1546 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1547 !GatherSeq.count(In))
1550 // Check if we can replace this instruction with any of the
1551 // visited instructions.
1552 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1553 ve = Visited.end(); v != ve; ++v) {
1554 if (In->isIdenticalTo(*v) &&
1555 DT->dominates((*v)->getParent(), In->getParent())) {
1556 In->replaceAllUsesWith(*v);
1557 ToRemove.push_back(In);
1567 // Erase all of the instructions that we RAUWed.
1568 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1569 ve = ToRemove.end(); v != ve; ++v) {
1570 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1571 (*v)->eraseFromParent();
1575 /// The SLPVectorizer Pass.
1576 struct SLPVectorizer : public FunctionPass {
1577 typedef SmallVector<StoreInst *, 8> StoreList;
1578 typedef MapVector<Value *, StoreList> StoreListMap;
1580 /// Pass identification, replacement for typeid
1583 explicit SLPVectorizer() : FunctionPass(ID) {
1584 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1587 ScalarEvolution *SE;
1589 TargetTransformInfo *TTI;
1594 virtual bool runOnFunction(Function &F) {
1595 SE = &getAnalysis<ScalarEvolution>();
1596 DL = getAnalysisIfAvailable<DataLayout>();
1597 TTI = &getAnalysis<TargetTransformInfo>();
1598 AA = &getAnalysis<AliasAnalysis>();
1599 LI = &getAnalysis<LoopInfo>();
1600 DT = &getAnalysis<DominatorTree>();
1603 bool Changed = false;
1605 // If the target claims to have no vector registers don't attempt
1607 if (!TTI->getNumberOfRegisters(true))
1610 // Must have DataLayout. We can't require it because some tests run w/o
1615 // Don't vectorize when the attribute NoImplicitFloat is used.
1616 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1619 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1621 // Use the bollom up slp vectorizer to construct chains that start with
1622 // he store instructions.
1623 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1625 // Scan the blocks in the function in post order.
1626 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1627 e = po_end(&F.getEntryBlock()); it != e; ++it) {
1628 BasicBlock *BB = *it;
1630 // Vectorize trees that end at stores.
1631 if (unsigned count = collectStores(BB, R)) {
1633 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1634 Changed |= vectorizeStoreChains(R);
1637 // Vectorize trees that end at reductions.
1638 Changed |= vectorizeChainsInBlock(BB, R);
1642 R.optimizeGatherSequence();
1643 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1644 DEBUG(verifyFunction(F));
1649 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1650 FunctionPass::getAnalysisUsage(AU);
1651 AU.addRequired<ScalarEvolution>();
1652 AU.addRequired<AliasAnalysis>();
1653 AU.addRequired<TargetTransformInfo>();
1654 AU.addRequired<LoopInfo>();
1655 AU.addRequired<DominatorTree>();
1656 AU.addPreserved<LoopInfo>();
1657 AU.addPreserved<DominatorTree>();
1658 AU.setPreservesCFG();
1663 /// \brief Collect memory references and sort them according to their base
1664 /// object. We sort the stores to their base objects to reduce the cost of the
1665 /// quadratic search on the stores. TODO: We can further reduce this cost
1666 /// if we flush the chain creation every time we run into a memory barrier.
1667 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1669 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1670 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1672 /// \brief Try to vectorize a list of operands.
1673 /// \returns true if a value was vectorized.
1674 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1676 /// \brief Try to vectorize a chain that may start at the operands of \V;
1677 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1679 /// \brief Vectorize the stores that were collected in StoreRefs.
1680 bool vectorizeStoreChains(BoUpSLP &R);
1682 /// \brief Scan the basic block and look for patterns that are likely to start
1683 /// a vectorization chain.
1684 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1686 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1689 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1692 StoreListMap StoreRefs;
1695 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1696 int CostThreshold, BoUpSLP &R) {
1697 unsigned ChainLen = Chain.size();
1698 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1700 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1701 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1702 unsigned VF = MinVecRegSize / Sz;
1704 if (!isPowerOf2_32(Sz) || VF < 2)
1707 bool Changed = false;
1708 // Look for profitable vectorizable trees at all offsets, starting at zero.
1709 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1712 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1714 ArrayRef<Value *> Operands = Chain.slice(i, VF);
1716 R.buildTree(Operands);
1718 int Cost = R.getTreeCost();
1720 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1721 if (Cost < CostThreshold) {
1722 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1725 // Move to the next bundle.
1734 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1735 int costThreshold, BoUpSLP &R) {
1736 SetVector<Value *> Heads, Tails;
1737 SmallDenseMap<Value *, Value *> ConsecutiveChain;
1739 // We may run into multiple chains that merge into a single chain. We mark the
1740 // stores that we vectorized so that we don't visit the same store twice.
1741 BoUpSLP::ValueSet VectorizedStores;
1742 bool Changed = false;
1744 // Do a quadratic search on all of the given stores and find
1745 // all of the pairs of stores that follow each other.
1746 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1747 for (unsigned j = 0; j < e; ++j) {
1751 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1752 Tails.insert(Stores[j]);
1753 Heads.insert(Stores[i]);
1754 ConsecutiveChain[Stores[i]] = Stores[j];
1759 // For stores that start but don't end a link in the chain:
1760 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1762 if (Tails.count(*it))
1765 // We found a store instr that starts a chain. Now follow the chain and try
1767 BoUpSLP::ValueList Operands;
1769 // Collect the chain into a list.
1770 while (Tails.count(I) || Heads.count(I)) {
1771 if (VectorizedStores.count(I))
1773 Operands.push_back(I);
1774 // Move to the next value in the chain.
1775 I = ConsecutiveChain[I];
1778 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1780 // Mark the vectorized stores so that we don't vectorize them again.
1782 VectorizedStores.insert(Operands.begin(), Operands.end());
1783 Changed |= Vectorized;
1790 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1793 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1794 StoreInst *SI = dyn_cast<StoreInst>(it);
1798 // Check that the pointer points to scalars.
1799 Type *Ty = SI->getValueOperand()->getType();
1800 if (Ty->isAggregateType() || Ty->isVectorTy())
1803 // Find the base of the GEP.
1804 Value *Ptr = SI->getPointerOperand();
1805 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1806 Ptr = GEP->getPointerOperand();
1808 // Save the store locations.
1809 StoreRefs[Ptr].push_back(SI);
1815 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1818 Value *VL[] = { A, B };
1819 return tryToVectorizeList(VL, R);
1822 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1826 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1828 // Check that all of the parts are scalar instructions of the same type.
1829 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1833 unsigned Opcode0 = I0->getOpcode();
1835 Type *Ty0 = I0->getType();
1836 unsigned Sz = DL->getTypeSizeInBits(Ty0);
1837 unsigned VF = MinVecRegSize / Sz;
1839 for (int i = 0, e = VL.size(); i < e; ++i) {
1840 Type *Ty = VL[i]->getType();
1841 if (Ty->isAggregateType() || Ty->isVectorTy())
1843 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1844 if (!Inst || Inst->getOpcode() != Opcode0)
1848 bool Changed = false;
1850 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1851 unsigned OpsWidth = 0;
1858 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
1861 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
1862 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
1865 int Cost = R.getTreeCost();
1867 if (Cost < -SLPCostThreshold) {
1868 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1871 // Move to the next bundle.
1880 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1884 // Try to vectorize V.
1885 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1888 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1889 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1891 if (B && B->hasOneUse()) {
1892 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1893 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1894 if (tryToVectorizePair(A, B0, R)) {
1898 if (tryToVectorizePair(A, B1, R)) {
1905 if (A && A->hasOneUse()) {
1906 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1907 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1908 if (tryToVectorizePair(A0, B, R)) {
1912 if (tryToVectorizePair(A1, B, R)) {
1920 /// \brief Generate a shuffle mask to be used in a reduction tree.
1922 /// \param VecLen The length of the vector to be reduced.
1923 /// \param NumEltsToRdx The number of elements that should be reduced in the
1925 /// \param IsPairwise Whether the reduction is a pairwise or splitting
1926 /// reduction. A pairwise reduction will generate a mask of
1927 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
1928 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
1929 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
1930 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
1931 bool IsPairwise, bool IsLeft,
1932 IRBuilder<> &Builder) {
1933 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
1935 SmallVector<Constant *, 32> ShuffleMask(
1936 VecLen, UndefValue::get(Builder.getInt32Ty()));
1939 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
1940 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1941 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
1943 // Move the upper half of the vector to the lower half.
1944 for (unsigned i = 0; i != NumEltsToRdx; ++i)
1945 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
1947 return ConstantVector::get(ShuffleMask);
1951 /// Model horizontal reductions.
1953 /// A horizontal reduction is a tree of reduction operations (currently add and
1954 /// fadd) that has operations that can be put into a vector as its leaf.
1955 /// For example, this tree:
1962 /// This tree has "mul" as its reduced values and "+" as its reduction
1963 /// operations. A reduction might be feeding into a store or a binary operation
1978 class HorizontalReduction {
1979 SmallPtrSet<Value *, 16> ReductionOps;
1980 SmallVector<Value *, 32> ReducedVals;
1982 BinaryOperator *ReductionRoot;
1983 PHINode *ReductionPHI;
1985 /// The opcode of the reduction.
1986 unsigned ReductionOpcode;
1987 /// The opcode of the values we perform a reduction on.
1988 unsigned ReducedValueOpcode;
1989 /// The width of one full horizontal reduction operation.
1990 unsigned ReduxWidth;
1991 /// Should we model this reduction as a pairwise reduction tree or a tree that
1992 /// splits the vector in halves and adds those halves.
1993 bool IsPairwiseReduction;
1996 HorizontalReduction()
1997 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
1998 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2000 /// \brief Try to find a reduction tree.
2001 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2004 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2005 "Thi phi needs to use the binary operator");
2007 // We could have a initial reductions that is not an add.
2008 // r *= v1 + v2 + v3 + v4
2009 // In such a case start looking for a tree rooted in the first '+'.
2011 if (B->getOperand(0) == Phi) {
2013 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2014 } else if (B->getOperand(1) == Phi) {
2016 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2023 Type *Ty = B->getType();
2024 if (Ty->isVectorTy())
2027 ReductionOpcode = B->getOpcode();
2028 ReducedValueOpcode = 0;
2029 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2036 // We currently only support adds.
2037 if (ReductionOpcode != Instruction::Add &&
2038 ReductionOpcode != Instruction::FAdd)
2041 // Post order traverse the reduction tree starting at B. We only handle true
2042 // trees containing only binary operators.
2043 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2044 Stack.push_back(std::make_pair(B, 0));
2045 while (!Stack.empty()) {
2046 BinaryOperator *TreeN = Stack.back().first;
2047 unsigned EdgeToVist = Stack.back().second++;
2048 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2050 // Only handle trees in the current basic block.
2051 if (TreeN->getParent() != B->getParent())
2054 // Each tree node needs to have one user except for the ultimate
2056 if (!TreeN->hasOneUse() && TreeN != B)
2060 if (EdgeToVist == 2 || IsReducedValue) {
2061 if (IsReducedValue) {
2062 // Make sure that the opcodes of the operations that we are going to
2064 if (!ReducedValueOpcode)
2065 ReducedValueOpcode = TreeN->getOpcode();
2066 else if (ReducedValueOpcode != TreeN->getOpcode())
2068 ReducedVals.push_back(TreeN);
2070 // We need to be able to reassociate the adds.
2071 if (!TreeN->isAssociative())
2073 ReductionOps.insert(TreeN);
2080 // Visit left or right.
2081 Value *NextV = TreeN->getOperand(EdgeToVist);
2082 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2084 Stack.push_back(std::make_pair(Next, 0));
2085 else if (NextV != Phi)
2091 /// \brief Attempt to vectorize the tree found by
2092 /// matchAssociativeReduction.
2093 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2094 if (ReducedVals.empty())
2097 unsigned NumReducedVals = ReducedVals.size();
2098 if (NumReducedVals < ReduxWidth)
2101 Value *VectorizedTree = 0;
2102 IRBuilder<> Builder(ReductionRoot);
2103 FastMathFlags Unsafe;
2104 Unsafe.setUnsafeAlgebra();
2105 Builder.SetFastMathFlags(Unsafe);
2108 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2109 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2110 V.buildTree(ValsToReduce, &ReductionOps);
2113 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2114 if (Cost >= -SLPCostThreshold)
2117 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2120 // Vectorize a tree.
2121 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2122 Value *VectorizedRoot = V.vectorizeTree();
2124 // Emit a reduction.
2125 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2126 if (VectorizedTree) {
2127 Builder.SetCurrentDebugLocation(Loc);
2128 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2129 ReducedSubTree, "bin.rdx");
2131 VectorizedTree = ReducedSubTree;
2134 if (VectorizedTree) {
2135 // Finish the reduction.
2136 for (; i < NumReducedVals; ++i) {
2137 Builder.SetCurrentDebugLocation(
2138 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2139 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2144 assert(ReductionRoot != NULL && "Need a reduction operation");
2145 ReductionRoot->setOperand(0, VectorizedTree);
2146 ReductionRoot->setOperand(1, ReductionPHI);
2148 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2150 return VectorizedTree != 0;
2155 /// \brief Calcuate the cost of a reduction.
2156 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2157 Type *ScalarTy = FirstReducedVal->getType();
2158 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2160 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2161 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2163 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2164 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2166 int ScalarReduxCost =
2167 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2169 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2170 << " for reduction that starts with " << *FirstReducedVal
2172 << (IsPairwiseReduction ? "pairwise" : "splitting")
2173 << " reduction)\n");
2175 return VecReduxCost - ScalarReduxCost;
2178 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2179 Value *R, const Twine &Name = "") {
2180 if (Opcode == Instruction::FAdd)
2181 return Builder.CreateFAdd(L, R, Name);
2182 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2185 /// \brief Emit a horizontal reduction of the vectorized value.
2186 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2187 assert(VectorizedValue && "Need to have a vectorized tree node");
2188 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2189 assert(isPowerOf2_32(ReduxWidth) &&
2190 "We only handle power-of-two reductions for now");
2192 SmallVector<Constant *, 32> ShuffleMask(ReduxWidth, 0);
2193 Value *TmpVec = ValToReduce;
2194 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2195 if (IsPairwiseReduction) {
2197 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2199 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2201 Value *LeftShuf = Builder.CreateShuffleVector(
2202 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2203 Value *RightShuf = Builder.CreateShuffleVector(
2204 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2206 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2210 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2211 Value *Shuf = Builder.CreateShuffleVector(
2212 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2213 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2217 // The result is in the first element of the vector.
2218 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2222 /// \brief Recognize construction of vectors like
2223 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2224 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2225 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2226 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2228 /// Returns true if it matches
2230 static bool findBuildVector(InsertElementInst *IE,
2231 SmallVectorImpl<Value *> &Ops) {
2232 if (!isa<UndefValue>(IE->getOperand(0)))
2236 Ops.push_back(IE->getOperand(1));
2238 if (IE->use_empty())
2241 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2245 // If this isn't the final use, make sure the next insertelement is the only
2246 // use. It's OK if the final constructed vector is used multiple times
2247 if (!IE->hasOneUse())
2256 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2257 bool Changed = false;
2258 SmallVector<Value *, 4> Incoming;
2259 SmallSet<Instruction *, 16> VisitedInstrs;
2261 // Collect the incoming values from the PHIs.
2262 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2264 PHINode *P = dyn_cast<PHINode>(instr);
2269 // We may go through BB multiple times so skip the one we have checked.
2270 if (!VisitedInstrs.insert(instr))
2273 // Stop constructing the list when you reach a different type.
2274 if (Incoming.size() && P->getType() != Incoming[0]->getType()) {
2275 if (tryToVectorizeList(Incoming, R)) {
2276 // We would like to start over since some instructions are deleted
2277 // and the iterator may become invalid value.
2279 instr = BB->begin();
2286 Incoming.push_back(P);
2289 if (Incoming.size() > 1)
2290 Changed |= tryToVectorizeList(Incoming, R);
2292 VisitedInstrs.clear();
2294 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2295 // We may go through BB multiple times so skip the one we have checked.
2296 if (!VisitedInstrs.insert(it))
2299 if (isa<DbgInfoIntrinsic>(it))
2302 // Try to vectorize reductions that use PHINodes.
2303 if (PHINode *P = dyn_cast<PHINode>(it)) {
2304 // Check that the PHI is a reduction PHI.
2305 if (P->getNumIncomingValues() != 2)
2308 (P->getIncomingBlock(0) == BB
2309 ? (P->getIncomingValue(0))
2310 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2311 // Check if this is a Binary Operator.
2312 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2316 // Try to match and vectorize a horizontal reduction.
2317 HorizontalReduction HorRdx;
2318 if (ShouldVectorizeHor &&
2319 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2320 HorRdx.tryToReduce(R, TTI)) {
2327 Value *Inst = BI->getOperand(0);
2329 Inst = BI->getOperand(1);
2331 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2332 // We would like to start over since some instructions are deleted
2333 // and the iterator may become invalid value.
2343 // Try to vectorize horizontal reductions feeding into a store.
2344 if (ShouldStartVectorizeHorAtStore)
2345 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2346 if (BinaryOperator *BinOp =
2347 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2348 HorizontalReduction HorRdx;
2349 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2350 HorRdx.tryToReduce(R, TTI)) ||
2351 tryToVectorize(BinOp, R))) {
2359 // Try to vectorize trees that start at compare instructions.
2360 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2361 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2363 // We would like to start over since some instructions are deleted
2364 // and the iterator may become invalid value.
2370 for (int i = 0; i < 2; ++i) {
2371 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2372 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2374 // We would like to start over since some instructions are deleted
2375 // and the iterator may become invalid value.
2384 // Try to vectorize trees that start at insertelement instructions.
2385 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2386 SmallVector<Value *, 8> Ops;
2387 if (!findBuildVector(IE, Ops))
2390 if (tryToVectorizeList(Ops, R)) {
2403 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2404 bool Changed = false;
2405 // Attempt to sort and vectorize each of the store-groups.
2406 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2408 if (it->second.size() < 2)
2411 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2412 << it->second.size() << ".\n");
2414 // Process the stores in chunks of 16.
2415 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2416 unsigned Len = std::min<unsigned>(CE - CI, 16);
2417 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2418 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2424 } // end anonymous namespace
2426 char SLPVectorizer::ID = 0;
2427 static const char lv_name[] = "SLP Vectorizer";
2428 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2429 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2430 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2431 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2432 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2433 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2436 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }