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 trees if the gain is above this "
51 "number. (gain = -cost of vectorization)"));
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() { Builder.SetInsertPoint(Loc); }
66 BuilderLocGuard(const BuilderLocGuard &);
67 BuilderLocGuard &operator=(const BuilderLocGuard &);
69 BasicBlock::iterator 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) {
96 assert(InstrIdx.count(I) && "Unknown instruction");
100 Instruction *getInstruction(unsigned loc) {
102 numberInstructions();
103 assert(InstrVec.size() > loc && "Invalid Index");
104 return InstrVec[loc];
107 void forget() { Valid = false; }
110 /// The block we are numbering.
112 /// Is the block numbered.
114 /// Maps instructions to numbers and back.
115 SmallDenseMap<Instruction *, int> InstrIdx;
116 /// Maps integers to Instructions.
117 std::vector<Instruction *> InstrVec;
121 typedef SmallVector<Value *, 8> ValueList;
122 typedef SmallVector<Instruction *, 16> InstrList;
123 typedef SmallPtrSet<Value *, 16> ValueSet;
124 typedef SmallVector<StoreInst *, 8> StoreList;
127 static const int MAX_COST = INT_MIN;
129 FuncSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
130 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
132 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
133 Builder(Se->getContext()) {
134 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
136 BlocksNumbers[BB] = BlockNumbering(BB);
140 /// \brief Take the pointer operand from the Load/Store instruction.
141 /// \returns NULL if this is not a valid Load/Store instruction.
142 static Value *getPointerOperand(Value *I);
144 /// \brief Take the address space operand from the Load/Store instruction.
145 /// \returns -1 if this is not a valid Load/Store instruction.
146 static unsigned getAddressSpaceOperand(Value *I);
148 /// \returns true if the memory operations A and B are consecutive.
149 bool isConsecutiveAccess(Value *A, Value *B);
151 /// \brief Vectorize the tree that starts with the elements in \p VL.
152 /// \returns the vectorized value.
153 Value *vectorizeTree(ArrayRef<Value *> VL);
155 /// \returns the vectorization cost of the subtree that starts at \p VL.
156 /// A negative number means that this is profitable.
157 int getTreeCost(ArrayRef<Value *> VL);
159 /// \returns the scalarization cost for this list of values. Assuming that
160 /// this subtree gets vectorized, we may need to extract the values from the
161 /// roots. This method calculates the cost of extracting the values.
162 int getGatherCost(ArrayRef<Value *> VL);
164 /// \brief Attempts to order and vectorize a sequence of stores. This
165 /// function does a quadratic scan of the given stores.
166 /// \returns true if the basic block was modified.
167 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold);
169 /// \brief Vectorize a group of scalars into a vector tree.
170 /// \returns the vectorized value.
171 Value *vectorizeArith(ArrayRef<Value *> Operands);
173 /// \brief This method contains the recursive part of getTreeCost.
174 int getTreeCost_rec(ArrayRef<Value *> VL, unsigned Depth);
176 /// \brief This recursive method looks for vectorization hazards such as
177 /// values that are used by multiple users and checks that values are used
178 /// by only one vector lane. It updates the variables LaneMap, MultiUserVals.
179 void getTreeUses_rec(ArrayRef<Value *> VL, unsigned Depth);
181 /// \brief This method contains the recursive part of vectorizeTree.
182 Value *vectorizeTree_rec(ArrayRef<Value *> VL);
184 /// \brief Vectorize a sorted sequence of stores.
185 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold);
187 /// \returns the scalarization cost for this type. Scalarization in this
188 /// context means the creation of vectors from a group of scalars.
189 int getGatherCost(Type *Ty);
191 /// \returns the AA location that is being access by the instruction.
192 AliasAnalysis::Location getLocation(Instruction *I);
194 /// \brief Checks if it is possible to sink an instruction from
195 /// \p Src to \p Dst.
196 /// \returns the pointer to the barrier instruction if we can't sink.
197 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
199 /// \returns the index of the last instrucion in the BB from \p VL.
200 int getLastIndex(ArrayRef<Value *> VL);
202 /// \returns the Instrucion in the bundle \p VL.
203 Instruction *getLastInstruction(ArrayRef<Value *> VL);
205 /// \returns the Instruction at index \p Index which is in Block \p BB.
206 Instruction *getInstructionForIndex(unsigned Index, BasicBlock *BB);
208 /// \returns the index of the first User of \p VL.
209 int getFirstUserIndex(ArrayRef<Value *> VL);
211 /// \returns a vector from a collection of scalars in \p VL.
212 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
214 /// \brief Perform LICM and CSE on the newly generated gather sequences.
215 void optimizeGatherSequence();
217 bool needToGatherAny(ArrayRef<Value *> VL) {
218 for (int i = 0, e = VL.size(); i < e; ++i)
219 if (MustGather.count(VL[i]))
224 /// -- Vectorization State --
226 /// Maps values in the tree to the vector lanes that uses them. This map must
227 /// be reset between runs of getCost.
228 std::map<Value *, int> LaneMap;
229 /// A list of instructions to ignore while sinking
230 /// memory instructions. This map must be reset between runs of getCost.
231 ValueSet MemBarrierIgnoreList;
233 /// Maps between the first scalar to the vector. This map must be reset
235 DenseMap<Value *, Value *> VectorizedValues;
237 /// Contains values that must be gathered because they are used
238 /// by multiple lanes, or by users outside the tree.
239 /// NOTICE: The vectorization methods also use this set.
242 /// Contains a list of values that are used outside the current tree. This
243 /// set must be reset between runs.
244 SetVector<Value *> MultiUserVals;
246 /// Holds all of the instructions that we gathered.
247 SetVector<Instruction *> GatherSeq;
249 /// Numbers instructions in different blocks.
250 std::map<BasicBlock *, BlockNumbering> BlocksNumbers;
252 // Analysis and block reference.
256 TargetTransformInfo *TTI;
260 /// Instruction builder to construct the vectorized tree.
264 int FuncSLP::getGatherCost(Type *Ty) {
266 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
267 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
271 int FuncSLP::getGatherCost(ArrayRef<Value *> VL) {
272 // Find the type of the operands in VL.
273 Type *ScalarTy = VL[0]->getType();
274 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
275 ScalarTy = SI->getValueOperand()->getType();
276 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
277 // Find the cost of inserting/extracting values from the vector.
278 return getGatherCost(VecTy);
281 AliasAnalysis::Location FuncSLP::getLocation(Instruction *I) {
282 if (StoreInst *SI = dyn_cast<StoreInst>(I))
283 return AA->getLocation(SI);
284 if (LoadInst *LI = dyn_cast<LoadInst>(I))
285 return AA->getLocation(LI);
286 return AliasAnalysis::Location();
289 Value *FuncSLP::getPointerOperand(Value *I) {
290 if (LoadInst *LI = dyn_cast<LoadInst>(I))
291 return LI->getPointerOperand();
292 if (StoreInst *SI = dyn_cast<StoreInst>(I))
293 return SI->getPointerOperand();
297 unsigned FuncSLP::getAddressSpaceOperand(Value *I) {
298 if (LoadInst *L = dyn_cast<LoadInst>(I))
299 return L->getPointerAddressSpace();
300 if (StoreInst *S = dyn_cast<StoreInst>(I))
301 return S->getPointerAddressSpace();
305 bool FuncSLP::isConsecutiveAccess(Value *A, Value *B) {
306 Value *PtrA = getPointerOperand(A);
307 Value *PtrB = getPointerOperand(B);
308 unsigned ASA = getAddressSpaceOperand(A);
309 unsigned ASB = getAddressSpaceOperand(B);
311 // Check that the address spaces match and that the pointers are valid.
312 if (!PtrA || !PtrB || (ASA != ASB))
315 // Check that A and B are of the same type.
316 if (PtrA->getType() != PtrB->getType())
319 // Calculate the distance.
320 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
321 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
322 const SCEV *OffsetSCEV = SE->getMinusSCEV(PtrSCEVA, PtrSCEVB);
323 const SCEVConstant *ConstOffSCEV = dyn_cast<SCEVConstant>(OffsetSCEV);
325 // Non constant distance.
329 int64_t Offset = ConstOffSCEV->getValue()->getSExtValue();
330 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
331 // The Instructions are connsecutive if the size of the first load/store is
332 // the same as the offset.
333 int64_t Sz = DL->getTypeStoreSize(Ty);
334 return ((-Offset) == Sz);
337 Value *FuncSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
338 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
339 BasicBlock::iterator I = Src, E = Dst;
340 /// Scan all of the instruction from SRC to DST and check if
341 /// the source may alias.
342 for (++I; I != E; ++I) {
343 // Ignore store instructions that are marked as 'ignore'.
344 if (MemBarrierIgnoreList.count(I))
346 if (Src->mayWriteToMemory()) /* Write */ {
347 if (!I->mayReadOrWriteMemory())
350 if (!I->mayWriteToMemory())
353 AliasAnalysis::Location A = getLocation(&*I);
354 AliasAnalysis::Location B = getLocation(Src);
356 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
362 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
364 for (int i = 0, e = VL.size(); i < e; i++) {
365 Instruction *I = dyn_cast<Instruction>(VL[i]);
374 if (BB != I->getParent())
380 static bool allConstant(ArrayRef<Value *> VL) {
381 for (unsigned i = 0, e = VL.size(); i < e; ++i)
382 if (!isa<Constant>(VL[i]))
387 static bool isSplat(ArrayRef<Value *> VL) {
388 for (unsigned i = 1, e = VL.size(); i < e; ++i)
394 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
396 for (int i = 0, e = VL.size(); i < e; i++) {
397 if (Instruction *I = dyn_cast<Instruction>(VL[i])) {
399 Opcode = I->getOpcode();
402 if (Opcode != I->getOpcode())
409 static bool CanReuseExtract(ArrayRef<Value *> VL, unsigned VF,
411 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
412 // Check if all of the extracts come from the same vector and from the
415 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
416 Value *Vec = E0->getOperand(0);
418 // We have to extract from the same vector type.
419 if (Vec->getType() != VecTy)
422 // Check that all of the indices extract from the correct offset.
423 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
424 if (!CI || CI->getZExtValue())
427 for (unsigned i = 1, e = VF; i < e; ++i) {
428 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
429 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
431 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
438 void FuncSLP::getTreeUses_rec(ArrayRef<Value *> VL, unsigned Depth) {
439 if (Depth == RecursionMaxDepth)
440 return MustGather.insert(VL.begin(), VL.end());
442 // Don't handle vectors.
443 if (VL[0]->getType()->isVectorTy())
446 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
447 if (SI->getValueOperand()->getType()->isVectorTy())
450 // If all of the operands are identical or constant we have a simple solution.
451 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL))
452 return MustGather.insert(VL.begin(), VL.end());
454 // Stop the scan at unknown IR.
455 Instruction *VL0 = dyn_cast<Instruction>(VL[0]);
456 assert(VL0 && "Invalid instruction");
458 // Mark instructions with multiple users.
459 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
460 Instruction *I = dyn_cast<Instruction>(VL[i]);
461 // Remember to check if all of the users of this instruction are vectorized
462 // within our tree. At depth zero we have no local users, only external
463 // users that we don't care about.
464 if (Depth && I && I->getNumUses() > 1) {
465 DEBUG(dbgs() << "SLP: Adding to MultiUserVals "
466 "because it has multiple users:" << *I << " \n");
467 MultiUserVals.insert(I);
471 // Check that the instruction is only used within one lane.
472 for (int i = 0, e = VL.size(); i < e; ++i) {
473 if (LaneMap.count(VL[i]) && LaneMap[VL[i]] != i) {
474 DEBUG(dbgs() << "SLP: Value used by multiple lanes:" << *VL[i] << "\n");
475 return MustGather.insert(VL.begin(), VL.end());
477 // Make this instruction as 'seen' and remember the lane.
481 unsigned Opcode = getSameOpcode(VL);
483 return MustGather.insert(VL.begin(), VL.end());
486 case Instruction::ExtractElement: {
487 VectorType *VecTy = VectorType::get(VL[0]->getType(), VL.size());
488 // No need to follow ExtractElements that are going to be optimized away.
489 if (CanReuseExtract(VL, VL.size(), VecTy))
493 case Instruction::Load:
495 case Instruction::ZExt:
496 case Instruction::SExt:
497 case Instruction::FPToUI:
498 case Instruction::FPToSI:
499 case Instruction::FPExt:
500 case Instruction::PtrToInt:
501 case Instruction::IntToPtr:
502 case Instruction::SIToFP:
503 case Instruction::UIToFP:
504 case Instruction::Trunc:
505 case Instruction::FPTrunc:
506 case Instruction::BitCast:
507 case Instruction::Select:
508 case Instruction::ICmp:
509 case Instruction::FCmp:
510 case Instruction::Add:
511 case Instruction::FAdd:
512 case Instruction::Sub:
513 case Instruction::FSub:
514 case Instruction::Mul:
515 case Instruction::FMul:
516 case Instruction::UDiv:
517 case Instruction::SDiv:
518 case Instruction::FDiv:
519 case Instruction::URem:
520 case Instruction::SRem:
521 case Instruction::FRem:
522 case Instruction::Shl:
523 case Instruction::LShr:
524 case Instruction::AShr:
525 case Instruction::And:
526 case Instruction::Or:
527 case Instruction::Xor: {
528 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
530 // Prepare the operand vector.
531 for (unsigned j = 0; j < VL.size(); ++j)
532 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
534 getTreeUses_rec(Operands, Depth + 1);
538 case Instruction::Store: {
540 for (unsigned j = 0; j < VL.size(); ++j)
541 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
542 getTreeUses_rec(Operands, Depth + 1);
546 return MustGather.insert(VL.begin(), VL.end());
550 int FuncSLP::getLastIndex(ArrayRef<Value *> VL) {
551 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
552 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
553 BlockNumbering &BN = BlocksNumbers[BB];
555 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
556 for (unsigned i = 0, e = VL.size(); i < e; ++i)
557 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
561 Instruction *FuncSLP::getLastInstruction(ArrayRef<Value *> VL) {
562 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
563 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
564 BlockNumbering &BN = BlocksNumbers[BB];
566 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
567 for (unsigned i = 1, e = VL.size(); i < e; ++i)
568 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
569 return BN.getInstruction(MaxIdx);
572 Instruction *FuncSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) {
573 BlockNumbering &BN = BlocksNumbers[BB];
574 return BN.getInstruction(Index);
577 int FuncSLP::getFirstUserIndex(ArrayRef<Value *> VL) {
578 BasicBlock *BB = getSameBlock(VL);
579 assert(BB && "All instructions must come from the same block");
580 BlockNumbering &BN = BlocksNumbers[BB];
582 // Find the first user of the values.
583 int FirstUser = BN.getIndex(BB->getTerminator());
584 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
585 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
587 Instruction *Instr = dyn_cast<Instruction>(*U);
589 if (!Instr || Instr->getParent() != BB)
592 FirstUser = std::min(FirstUser, BN.getIndex(Instr));
598 int FuncSLP::getTreeCost_rec(ArrayRef<Value *> VL, unsigned Depth) {
599 Type *ScalarTy = VL[0]->getType();
601 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
602 ScalarTy = SI->getValueOperand()->getType();
604 /// Don't mess with vectors.
605 if (ScalarTy->isVectorTy())
606 return FuncSLP::MAX_COST;
611 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
614 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
616 int GatherCost = getGatherCost(VecTy);
617 if (Depth == RecursionMaxDepth || needToGatherAny(VL))
620 BasicBlock *BB = getSameBlock(VL);
621 unsigned Opcode = getSameOpcode(VL);
622 assert(Opcode && BB && "Invalid Instruction Value");
624 // Check if it is safe to sink the loads or the stores.
625 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
626 int MaxIdx = getLastIndex(VL);
627 Instruction *Last = getInstructionForIndex(MaxIdx, BB);
629 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
632 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
634 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
635 << "\n because of " << *Barrier << "\n");
641 Instruction *VL0 = cast<Instruction>(VL[0]);
643 case Instruction::ExtractElement: {
644 if (CanReuseExtract(VL, VL.size(), VecTy))
646 return getGatherCost(VecTy);
648 case Instruction::ZExt:
649 case Instruction::SExt:
650 case Instruction::FPToUI:
651 case Instruction::FPToSI:
652 case Instruction::FPExt:
653 case Instruction::PtrToInt:
654 case Instruction::IntToPtr:
655 case Instruction::SIToFP:
656 case Instruction::UIToFP:
657 case Instruction::Trunc:
658 case Instruction::FPTrunc:
659 case Instruction::BitCast: {
661 Type *SrcTy = VL0->getOperand(0)->getType();
662 // Prepare the operand vector.
663 for (unsigned j = 0; j < VL.size(); ++j) {
664 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
665 // Check that the casted type is the same for all users.
666 if (cast<Instruction>(VL[j])->getOperand(0)->getType() != SrcTy)
667 return getGatherCost(VecTy);
670 int Cost = getTreeCost_rec(Operands, Depth + 1);
671 if (Cost == FuncSLP::MAX_COST)
674 // Calculate the cost of this instruction.
675 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
676 VL0->getType(), SrcTy);
678 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
679 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
680 Cost += (VecCost - ScalarCost);
682 if (Cost > GatherCost) {
683 MustGather.insert(VL.begin(), VL.end());
689 case Instruction::FCmp:
690 case Instruction::ICmp: {
691 // Check that all of the compares have the same predicate.
692 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
693 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
694 CmpInst *Cmp = cast<CmpInst>(VL[i]);
695 if (Cmp->getPredicate() != P0)
696 return getGatherCost(VecTy);
700 case Instruction::Select:
701 case Instruction::Add:
702 case Instruction::FAdd:
703 case Instruction::Sub:
704 case Instruction::FSub:
705 case Instruction::Mul:
706 case Instruction::FMul:
707 case Instruction::UDiv:
708 case Instruction::SDiv:
709 case Instruction::FDiv:
710 case Instruction::URem:
711 case Instruction::SRem:
712 case Instruction::FRem:
713 case Instruction::Shl:
714 case Instruction::LShr:
715 case Instruction::AShr:
716 case Instruction::And:
717 case Instruction::Or:
718 case Instruction::Xor: {
720 // Calculate the cost of all of the operands.
721 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
723 // Prepare the operand vector.
724 for (unsigned j = 0; j < VL.size(); ++j)
725 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
727 int Cost = getTreeCost_rec(Operands, Depth + 1);
728 if (Cost == MAX_COST)
733 // Calculate the cost of this instruction.
736 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
737 Opcode == Instruction::Select) {
738 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
740 VecTy->getNumElements() *
741 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
742 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
744 ScalarCost = VecTy->getNumElements() *
745 TTI->getArithmeticInstrCost(Opcode, ScalarTy);
746 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
748 TotalCost += (VecCost - ScalarCost);
750 if (TotalCost > GatherCost) {
751 MustGather.insert(VL.begin(), VL.end());
757 case Instruction::Load: {
758 // If we are scalarize the loads, add the cost of forming the vector.
759 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
760 if (!isConsecutiveAccess(VL[i], VL[i + 1]))
761 return getGatherCost(VecTy);
763 // Cost of wide load - cost of scalar loads.
764 int ScalarLdCost = VecTy->getNumElements() *
765 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
766 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
767 int TotalCost = VecLdCost - ScalarLdCost;
769 if (TotalCost > GatherCost) {
770 MustGather.insert(VL.begin(), VL.end());
776 case Instruction::Store: {
777 // We know that we can merge the stores. Calculate the cost.
778 int ScalarStCost = VecTy->getNumElements() *
779 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
780 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
781 int StoreCost = VecStCost - ScalarStCost;
784 for (unsigned j = 0; j < VL.size(); ++j) {
785 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
786 MemBarrierIgnoreList.insert(VL[j]);
789 int Cost = getTreeCost_rec(Operands, Depth + 1);
790 if (Cost == MAX_COST)
793 int TotalCost = StoreCost + Cost;
797 // Unable to vectorize unknown instructions.
798 return getGatherCost(VecTy);
802 int FuncSLP::getTreeCost(ArrayRef<Value *> VL) {
803 // Get rid of the list of stores that were removed, and from the
804 // lists of instructions with multiple users.
805 MemBarrierIgnoreList.clear();
807 MultiUserVals.clear();
810 if (!getSameBlock(VL))
813 // Find the location of the last root.
814 int LastRootIndex = getLastIndex(VL);
815 int FirstUserIndex = getFirstUserIndex(VL);
817 // Don't vectorize if there are users of the tree roots inside the tree
819 if (LastRootIndex > FirstUserIndex)
822 // Scan the tree and find which value is used by which lane, and which values
823 // must be scalarized.
824 getTreeUses_rec(VL, 0);
826 // Check that instructions with multiple users can be vectorized. Mark unsafe
828 for (SetVector<Value *>::iterator it = MultiUserVals.begin(),
829 e = MultiUserVals.end();
831 // Check that all of the users of this instr are within the tree.
832 for (Value::use_iterator I = (*it)->use_begin(), E = (*it)->use_end();
834 if (LaneMap.find(*I) == LaneMap.end()) {
835 DEBUG(dbgs() << "SLP: Adding to MustExtract "
836 "because of an out of tree usage.\n");
837 MustGather.insert(*it);
843 // Now calculate the cost of vectorizing the tree.
844 return getTreeCost_rec(VL, 0);
846 bool FuncSLP::vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold) {
847 unsigned ChainLen = Chain.size();
848 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
850 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
851 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
852 unsigned VF = MinVecRegSize / Sz;
854 if (!isPowerOf2_32(Sz) || VF < 2)
857 bool Changed = false;
858 // Look for profitable vectorizable trees at all offsets, starting at zero.
859 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
862 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
864 ArrayRef<Value *> Operands = Chain.slice(i, VF);
866 int Cost = getTreeCost(Operands);
867 if (Cost == FuncSLP::MAX_COST)
869 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
870 if (Cost < CostThreshold) {
871 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
872 vectorizeTree(Operands);
874 // Remove the scalar stores.
875 for (int j = 0, e = VF; j < e; ++j)
876 cast<Instruction>(Operands[j])->eraseFromParent();
878 // Move to the next bundle.
884 if (Changed || ChainLen > VF)
887 // Handle short chains. This helps us catch types such as <3 x float> that
888 // are smaller than vector size.
889 int Cost = getTreeCost(Chain);
890 if (Cost == FuncSLP::MAX_COST)
892 if (Cost < CostThreshold) {
893 DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
894 << " for size = " << ChainLen << "\n");
895 vectorizeTree(Chain);
897 // Remove all of the scalar stores.
898 for (int i = 0, e = Chain.size(); i < e; ++i)
899 cast<Instruction>(Chain[i])->eraseFromParent();
907 bool FuncSLP::vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold) {
908 SetVector<Value *> Heads, Tails;
909 SmallDenseMap<Value *, Value *> ConsecutiveChain;
911 // We may run into multiple chains that merge into a single chain. We mark the
912 // stores that we vectorized so that we don't visit the same store twice.
913 ValueSet VectorizedStores;
914 bool Changed = false;
916 // Do a quadratic search on all of the given stores and find
917 // all of the pairs of loads that follow each other.
918 for (unsigned i = 0, e = Stores.size(); i < e; ++i)
919 for (unsigned j = 0; j < e; ++j) {
923 if (isConsecutiveAccess(Stores[i], Stores[j])) {
924 Tails.insert(Stores[j]);
925 Heads.insert(Stores[i]);
926 ConsecutiveChain[Stores[i]] = Stores[j];
930 // For stores that start but don't end a link in the chain:
931 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
933 if (Tails.count(*it))
936 // We found a store instr that starts a chain. Now follow the chain and try
940 // Collect the chain into a list.
941 while (Tails.count(I) || Heads.count(I)) {
942 if (VectorizedStores.count(I))
944 Operands.push_back(I);
945 // Move to the next value in the chain.
946 I = ConsecutiveChain[I];
949 bool Vectorized = vectorizeStoreChain(Operands, costThreshold);
951 // Mark the vectorized stores so that we don't vectorize them again.
953 VectorizedStores.insert(Operands.begin(), Operands.end());
954 Changed |= Vectorized;
960 Value *FuncSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
961 Value *Vec = UndefValue::get(Ty);
962 // Generate the 'InsertElement' instruction.
963 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
964 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
965 if (Instruction *I = dyn_cast<Instruction>(Vec))
972 Value *FuncSLP::vectorizeTree_rec(ArrayRef<Value *> VL) {
973 BuilderLocGuard Guard(Builder);
975 Type *ScalarTy = VL[0]->getType();
976 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
977 ScalarTy = SI->getValueOperand()->getType();
978 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
980 if (needToGatherAny(VL))
981 return Gather(VL, VecTy);
983 if (VectorizedValues.count(VL[0])) {
984 DEBUG(dbgs() << "SLP: Diamond merged at depth.\n");
985 return VectorizedValues[VL[0]];
988 Instruction *VL0 = cast<Instruction>(VL[0]);
989 unsigned Opcode = VL0->getOpcode();
990 assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
993 case Instruction::ExtractElement: {
994 if (CanReuseExtract(VL, VL.size(), VecTy))
995 return VL0->getOperand(0);
996 return Gather(VL, VecTy);
998 case Instruction::ZExt:
999 case Instruction::SExt:
1000 case Instruction::FPToUI:
1001 case Instruction::FPToSI:
1002 case Instruction::FPExt:
1003 case Instruction::PtrToInt:
1004 case Instruction::IntToPtr:
1005 case Instruction::SIToFP:
1006 case Instruction::UIToFP:
1007 case Instruction::Trunc:
1008 case Instruction::FPTrunc:
1009 case Instruction::BitCast: {
1011 for (int i = 0, e = VL.size(); i < e; ++i)
1012 INVL.push_back(cast<Instruction>(VL[i])->getOperand(0));
1014 Builder.SetInsertPoint(getLastInstruction(VL));
1015 Value *InVec = vectorizeTree_rec(INVL);
1016 CastInst *CI = dyn_cast<CastInst>(VL0);
1017 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1018 VectorizedValues[VL0] = V;
1021 case Instruction::FCmp:
1022 case Instruction::ICmp: {
1023 // Check that all of the compares have the same predicate.
1024 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1025 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1026 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1027 if (Cmp->getPredicate() != P0)
1028 return Gather(VL, VecTy);
1031 ValueList LHSV, RHSV;
1032 for (int i = 0, e = VL.size(); i < e; ++i) {
1033 LHSV.push_back(cast<Instruction>(VL[i])->getOperand(0));
1034 RHSV.push_back(cast<Instruction>(VL[i])->getOperand(1));
1037 Builder.SetInsertPoint(getLastInstruction(VL));
1038 Value *L = vectorizeTree_rec(LHSV);
1039 Value *R = vectorizeTree_rec(RHSV);
1042 if (Opcode == Instruction::FCmp)
1043 V = Builder.CreateFCmp(P0, L, R);
1045 V = Builder.CreateICmp(P0, L, R);
1047 VectorizedValues[VL0] = V;
1050 case Instruction::Select: {
1051 ValueList TrueVec, FalseVec, CondVec;
1052 for (int i = 0, e = VL.size(); i < e; ++i) {
1053 CondVec.push_back(cast<Instruction>(VL[i])->getOperand(0));
1054 TrueVec.push_back(cast<Instruction>(VL[i])->getOperand(1));
1055 FalseVec.push_back(cast<Instruction>(VL[i])->getOperand(2));
1058 Builder.SetInsertPoint(getLastInstruction(VL));
1059 Value *True = vectorizeTree_rec(TrueVec);
1060 Value *False = vectorizeTree_rec(FalseVec);
1061 Value *Cond = vectorizeTree_rec(CondVec);
1062 Value *V = Builder.CreateSelect(Cond, True, False);
1063 VectorizedValues[VL0] = V;
1066 case Instruction::Add:
1067 case Instruction::FAdd:
1068 case Instruction::Sub:
1069 case Instruction::FSub:
1070 case Instruction::Mul:
1071 case Instruction::FMul:
1072 case Instruction::UDiv:
1073 case Instruction::SDiv:
1074 case Instruction::FDiv:
1075 case Instruction::URem:
1076 case Instruction::SRem:
1077 case Instruction::FRem:
1078 case Instruction::Shl:
1079 case Instruction::LShr:
1080 case Instruction::AShr:
1081 case Instruction::And:
1082 case Instruction::Or:
1083 case Instruction::Xor: {
1084 ValueList LHSVL, RHSVL;
1085 for (int i = 0, e = VL.size(); i < e; ++i) {
1086 LHSVL.push_back(cast<Instruction>(VL[i])->getOperand(0));
1087 RHSVL.push_back(cast<Instruction>(VL[i])->getOperand(1));
1090 Builder.SetInsertPoint(getLastInstruction(VL));
1091 Value *LHS = vectorizeTree_rec(LHSVL);
1092 Value *RHS = vectorizeTree_rec(RHSVL);
1095 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1098 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1099 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1100 VectorizedValues[VL0] = V;
1103 case Instruction::Load: {
1104 // Check if all of the loads are consecutive.
1105 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1106 if (!isConsecutiveAccess(VL[i - 1], VL[i]))
1107 return Gather(VL, VecTy);
1109 // Loads are inserted at the head of the tree because we don't want to
1110 // sink them all the way down past store instructions.
1111 Builder.SetInsertPoint(getLastInstruction(VL));
1112 LoadInst *LI = cast<LoadInst>(VL0);
1114 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1115 unsigned Alignment = LI->getAlignment();
1116 LI = Builder.CreateLoad(VecPtr);
1117 LI->setAlignment(Alignment);
1119 VectorizedValues[VL0] = LI;
1122 case Instruction::Store: {
1123 StoreInst *SI = cast<StoreInst>(VL0);
1124 unsigned Alignment = SI->getAlignment();
1127 for (int i = 0, e = VL.size(); i < e; ++i)
1128 ValueOp.push_back(cast<StoreInst>(VL[i])->getValueOperand());
1130 Value *VecValue = vectorizeTree_rec(ValueOp);
1132 Builder.SetInsertPoint(getLastInstruction(VL));
1134 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1135 Builder.CreateStore(VecValue, VecPtr)->setAlignment(Alignment);
1139 return Gather(VL, VecTy);
1143 Value *FuncSLP::vectorizeTree(ArrayRef<Value *> VL) {
1144 Builder.SetInsertPoint(getLastInstruction(VL));
1145 Value *V = vectorizeTree_rec(VL);
1147 // We moved some instructions around. We have to number them again
1148 // before we can do any analysis.
1149 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it)
1150 BlocksNumbers[it].forget();
1153 VectorizedValues.clear();
1154 MemBarrierIgnoreList.clear();
1158 Value *FuncSLP::vectorizeArith(ArrayRef<Value *> Operands) {
1159 Value *Vec = vectorizeTree(Operands);
1160 // After vectorizing the operands we need to generate extractelement
1161 // instructions and replace all of the uses of the scalar values with
1162 // the values that we extracted from the vectorized tree.
1163 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1164 Value *S = Builder.CreateExtractElement(Vec, Builder.getInt32(i));
1165 Operands[i]->replaceAllUsesWith(S);
1171 void FuncSLP::optimizeGatherSequence() {
1172 // LICM InsertElementInst sequences.
1173 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1174 e = GatherSeq.end(); it != e; ++it) {
1175 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1180 // Check if this block is inside a loop.
1181 Loop *L = LI->getLoopFor(Insert->getParent());
1185 // Check if it has a preheader.
1186 BasicBlock *PreHeader = L->getLoopPreheader();
1190 // If the vector or the element that we insert into it are
1191 // instructions that are defined in this basic block then we can't
1192 // hoist this instruction.
1193 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1194 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1195 if (CurrVec && L->contains(CurrVec))
1197 if (NewElem && L->contains(NewElem))
1200 // We can hoist this instruction. Move it to the pre-header.
1201 Insert->moveBefore(PreHeader->getTerminator());
1204 // Perform O(N^2) search over the gather sequences and merge identical
1205 // instructions. TODO: We can further optimize this scan if we split the
1206 // instructions into different buckets based on the insert lane.
1207 SmallPtrSet<Instruction*, 16> Visited;
1208 ReversePostOrderTraversal<Function*> RPOT(F);
1209 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1210 E = RPOT.end(); I != E; ++I) {
1211 BasicBlock *BB = *I;
1212 // For all instructions in the function:
1213 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1214 InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
1215 if (!Insert || !GatherSeq.count(Insert))
1218 // Check if we can replace this instruction with any of the
1219 // visited instructions.
1220 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1221 ve = Visited.end(); v != ve; ++v) {
1222 if (Insert->isIdenticalTo(*v) &&
1223 DT->dominates((*v)->getParent(), Insert->getParent())) {
1224 Insert->replaceAllUsesWith(*v);
1228 Visited.insert(Insert);
1233 /// The SLPVectorizer Pass.
1234 struct SLPVectorizer : public FunctionPass {
1235 typedef SmallVector<StoreInst *, 8> StoreList;
1236 typedef MapVector<Value *, StoreList> StoreListMap;
1238 /// Pass identification, replacement for typeid
1241 explicit SLPVectorizer() : FunctionPass(ID) {
1242 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1245 ScalarEvolution *SE;
1247 TargetTransformInfo *TTI;
1252 virtual bool runOnFunction(Function &F) {
1253 SE = &getAnalysis<ScalarEvolution>();
1254 DL = getAnalysisIfAvailable<DataLayout>();
1255 TTI = &getAnalysis<TargetTransformInfo>();
1256 AA = &getAnalysis<AliasAnalysis>();
1257 LI = &getAnalysis<LoopInfo>();
1258 DT = &getAnalysis<DominatorTree>();
1261 bool Changed = false;
1263 // Must have DataLayout. We can't require it because some tests run w/o
1268 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1270 // Use the bollom up slp vectorizer to construct chains that start with
1271 // he store instructions.
1272 FuncSLP R(&F, SE, DL, TTI, AA, LI, DT);
1274 for (Function::iterator it = F.begin(), e = F.end(); it != e; ++it) {
1275 BasicBlock *BB = it;
1277 // Vectorize trees that end at reductions.
1278 Changed |= vectorizeChainsInBlock(BB, R);
1280 // Vectorize trees that end at stores.
1281 if (unsigned count = collectStores(BB, R)) {
1283 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1284 Changed |= vectorizeStoreChains(R);
1289 R.optimizeGatherSequence();
1290 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1291 DEBUG(verifyFunction(F));
1296 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1297 FunctionPass::getAnalysisUsage(AU);
1298 AU.addRequired<ScalarEvolution>();
1299 AU.addRequired<AliasAnalysis>();
1300 AU.addRequired<TargetTransformInfo>();
1301 AU.addRequired<LoopInfo>();
1302 AU.addRequired<DominatorTree>();
1307 /// \brief Collect memory references and sort them according to their base
1308 /// object. We sort the stores to their base objects to reduce the cost of the
1309 /// quadratic search on the stores. TODO: We can further reduce this cost
1310 /// if we flush the chain creation every time we run into a memory barrier.
1311 unsigned collectStores(BasicBlock *BB, FuncSLP &R);
1313 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1314 bool tryToVectorizePair(Value *A, Value *B, FuncSLP &R);
1316 /// \brief Try to vectorize a list of operands. If \p NeedExtracts is true
1317 /// then we calculate the cost of extracting the scalars from the vector.
1318 /// \returns true if a value was vectorized.
1319 bool tryToVectorizeList(ArrayRef<Value *> VL, FuncSLP &R, bool NeedExtracts);
1321 /// \brief Try to vectorize a chain that may start at the operands of \V;
1322 bool tryToVectorize(BinaryOperator *V, FuncSLP &R);
1324 /// \brief Vectorize the stores that were collected in StoreRefs.
1325 bool vectorizeStoreChains(FuncSLP &R);
1327 /// \brief Scan the basic block and look for patterns that are likely to start
1328 /// a vectorization chain.
1329 bool vectorizeChainsInBlock(BasicBlock *BB, FuncSLP &R);
1332 StoreListMap StoreRefs;
1335 unsigned SLPVectorizer::collectStores(BasicBlock *BB, FuncSLP &R) {
1338 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1339 StoreInst *SI = dyn_cast<StoreInst>(it);
1343 // Check that the pointer points to scalars.
1344 Type *Ty = SI->getValueOperand()->getType();
1345 if (Ty->isAggregateType() || Ty->isVectorTy())
1348 // Find the base of the GEP.
1349 Value *Ptr = SI->getPointerOperand();
1350 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1351 Ptr = GEP->getPointerOperand();
1353 // Save the store locations.
1354 StoreRefs[Ptr].push_back(SI);
1360 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, FuncSLP &R) {
1363 Value *VL[] = { A, B };
1364 return tryToVectorizeList(VL, R, true);
1367 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, FuncSLP &R,
1368 bool NeedExtracts) {
1372 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1374 // Check that all of the parts are scalar instructions of the same type.
1375 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1379 unsigned Opcode0 = I0->getOpcode();
1381 for (int i = 0, e = VL.size(); i < e; ++i) {
1382 Type *Ty = VL[i]->getType();
1383 if (Ty->isAggregateType() || Ty->isVectorTy())
1385 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1386 if (!Inst || Inst->getOpcode() != Opcode0)
1390 int Cost = R.getTreeCost(VL);
1391 if (Cost == FuncSLP::MAX_COST)
1394 int ExtrCost = NeedExtracts ? R.getGatherCost(VL) : 0;
1395 DEBUG(dbgs() << "SLP: Cost of pair:" << Cost
1396 << " Cost of extract:" << ExtrCost << ".\n");
1397 if ((Cost + ExtrCost) >= -SLPCostThreshold)
1399 DEBUG(dbgs() << "SLP: Vectorizing pair.\n");
1400 R.vectorizeArith(VL);
1404 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, FuncSLP &R) {
1408 // Try to vectorize V.
1409 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1412 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1413 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1415 if (B && B->hasOneUse()) {
1416 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1417 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1418 if (tryToVectorizePair(A, B0, R)) {
1422 if (tryToVectorizePair(A, B1, R)) {
1429 if (A && A->hasOneUse()) {
1430 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1431 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1432 if (tryToVectorizePair(A0, B, R)) {
1436 if (tryToVectorizePair(A1, B, R)) {
1444 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, FuncSLP &R) {
1445 bool Changed = false;
1446 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1447 if (isa<DbgInfoIntrinsic>(it))
1450 // Try to vectorize reductions that use PHINodes.
1451 if (PHINode *P = dyn_cast<PHINode>(it)) {
1452 // Check that the PHI is a reduction PHI.
1453 if (P->getNumIncomingValues() != 2)
1456 (P->getIncomingBlock(0) == BB
1457 ? (P->getIncomingValue(0))
1458 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1459 // Check if this is a Binary Operator.
1460 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1464 Value *Inst = BI->getOperand(0);
1466 Inst = BI->getOperand(1);
1468 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1472 // Try to vectorize trees that start at compare instructions.
1473 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1474 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1478 for (int i = 0; i < 2; ++i)
1479 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1481 tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1486 // Scan the PHINodes in our successors in search for pairing hints.
1487 for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
1488 BasicBlock *Succ = *it;
1489 SmallVector<Value *, 4> Incoming;
1491 // Collect the incoming values from the PHIs.
1492 for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
1493 instr != ie; ++instr) {
1494 PHINode *P = dyn_cast<PHINode>(instr);
1499 Value *V = P->getIncomingValueForBlock(BB);
1500 if (Instruction *I = dyn_cast<Instruction>(V))
1501 if (I->getParent() == BB)
1502 Incoming.push_back(I);
1505 if (Incoming.size() > 1)
1506 Changed |= tryToVectorizeList(Incoming, R, true);
1512 bool SLPVectorizer::vectorizeStoreChains(FuncSLP &R) {
1513 bool Changed = false;
1514 // Attempt to sort and vectorize each of the store-groups.
1515 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1517 if (it->second.size() < 2)
1520 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1521 << it->second.size() << ".\n");
1523 Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
1528 } // end anonymous namespace
1530 char SLPVectorizer::ID = 0;
1531 static const char lv_name[] = "SLP Vectorizer";
1532 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1533 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1534 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1535 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1536 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1537 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1540 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }