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"
22 #include "llvm/Transforms/Vectorize.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/Verifier.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
44 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
45 cl::desc("Only vectorize trees if the gain is above this "
46 "number. (gain = -cost of vectorization)"));
49 /// The SLPVectorizer Pass.
50 struct SLPVectorizer : public FunctionPass {
51 typedef MapVector<Value*, BoUpSLP::StoreList> StoreListMap;
53 /// Pass identification, replacement for typeid
56 explicit SLPVectorizer() : FunctionPass(ID) {
57 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
62 TargetTransformInfo *TTI;
66 virtual bool runOnFunction(Function &F) {
67 SE = &getAnalysis<ScalarEvolution>();
68 DL = getAnalysisIfAvailable<DataLayout>();
69 TTI = &getAnalysis<TargetTransformInfo>();
70 AA = &getAnalysis<AliasAnalysis>();
71 LI = &getAnalysis<LoopInfo>();
76 // Must have DataLayout. We can't require it because some tests run w/o
81 DEBUG(dbgs()<<"SLP: Analyzing blocks in " << F.getName() << ".\n");
83 for (Function::iterator it = F.begin(), e = F.end(); it != e; ++it) {
85 bool BBChanged = false;
87 // Use the bollom up slp vectorizer to construct chains that start with
88 // he store instructions.
89 BoUpSLP R(BB, SE, DL, TTI, AA, LI->getLoopFor(BB));
91 // Vectorize trees that end at reductions.
92 BBChanged |= vectorizeChainsInBlock(BB, R);
94 // Vectorize trees that end at stores.
95 if (unsigned count = collectStores(BB, R)) {
97 DEBUG(dbgs()<<"SLP: Found " << count << " stores to vectorize.\n");
98 BBChanged |= vectorizeStoreChains(R);
101 // Try to hoist some of the scalarization code to the preheader.
102 if (BBChanged) hoistGatherSequence(LI, BB, R);
104 Changed |= BBChanged;
108 DEBUG(dbgs()<<"SLP: vectorized \""<<F.getName()<<"\"\n");
109 DEBUG(verifyFunction(F));
114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115 FunctionPass::getAnalysisUsage(AU);
116 AU.addRequired<ScalarEvolution>();
117 AU.addRequired<AliasAnalysis>();
118 AU.addRequired<TargetTransformInfo>();
119 AU.addRequired<LoopInfo>();
124 /// \brief Collect memory references and sort them according to their base
125 /// object. We sort the stores to their base objects to reduce the cost of the
126 /// quadratic search on the stores. TODO: We can further reduce this cost
127 /// if we flush the chain creation every time we run into a memory barrier.
128 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
130 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
131 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
133 /// \brief Try to vectorize a list of operands.
134 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
136 /// \brief Try to vectorize a chain that may start at the operands of \V;
137 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
139 /// \brief Vectorize the stores that were collected in StoreRefs.
140 bool vectorizeStoreChains(BoUpSLP &R);
142 /// \brief Try to hoist gather sequences outside of the loop in cases where
143 /// all of the sources are loop invariant.
144 void hoistGatherSequence(LoopInfo *LI, BasicBlock *BB, BoUpSLP &R);
146 /// \brief Scan the basic block and look for patterns that are likely to start
147 /// a vectorization chain.
148 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
151 StoreListMap StoreRefs;
154 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
157 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
158 StoreInst *SI = dyn_cast<StoreInst>(it);
162 // Check that the pointer points to scalars.
163 Type *Ty = SI->getValueOperand()->getType();
164 if (Ty->isAggregateType() || Ty->isVectorTy())
167 // Find the base of the GEP.
168 Value *Ptr = SI->getPointerOperand();
169 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
170 Ptr = GEP->getPointerOperand();
172 // Save the store locations.
173 StoreRefs[Ptr].push_back(SI);
179 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
180 if (!A || !B) return false;
181 Value *VL[] = { A, B };
182 return tryToVectorizeList(VL, R);
185 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
189 DEBUG(dbgs()<<"SLP: Vectorizing a list of length = " << VL.size() << ".\n");
191 // Check that all of the parts are scalar instructions of the same type.
192 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
195 unsigned Opcode0 = I0->getOpcode();
197 for (int i = 0, e = VL.size(); i < e; ++i) {
198 Type *Ty = VL[i]->getType();
199 if (Ty->isAggregateType() || Ty->isVectorTy())
201 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
202 if (!Inst || Inst->getOpcode() != Opcode0)
206 int Cost = R.getTreeCost(VL);
207 int ExtrCost = R.getScalarizationCost(VL);
208 DEBUG(dbgs()<<"SLP: Cost of pair:" << Cost <<
209 " Cost of extract:" << ExtrCost << ".\n");
210 if ((Cost+ExtrCost) >= -SLPCostThreshold) return false;
211 DEBUG(dbgs()<<"SLP: Vectorizing pair.\n");
212 R.vectorizeArith(VL);
216 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
217 if (!V) return false;
218 // Try to vectorize V.
219 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
222 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
223 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
225 if (B && B->hasOneUse()) {
226 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
227 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
228 if (tryToVectorizePair(A, B0, R)) {
232 if (tryToVectorizePair(A, B1, R)) {
239 if (A && A->hasOneUse()) {
240 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
241 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
242 if (tryToVectorizePair(A0, B, R)) {
246 if (tryToVectorizePair(A1, B, R)) {
254 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
255 bool Changed = false;
256 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
257 if (isa<DbgInfoIntrinsic>(it)) continue;
259 // Try to vectorize reductions that use PHINodes.
260 if (PHINode *P = dyn_cast<PHINode>(it)) {
261 // Check that the PHI is a reduction PHI.
262 if (P->getNumIncomingValues() != 2) return Changed;
263 Value *Rdx = (P->getIncomingBlock(0) == BB ? P->getIncomingValue(0) :
264 (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) :
266 // Check if this is a Binary Operator.
267 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
271 Value *Inst = BI->getOperand(0);
272 if (Inst == P) Inst = BI->getOperand(1);
273 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
277 // Try to vectorize trees that start at compare instructions.
278 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
279 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
283 for (int i = 0; i < 2; ++i)
284 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
285 Changed |= tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
290 // Scan the PHINodes in our successors in search for pairing hints.
291 for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
292 BasicBlock *Succ = *it;
293 SmallVector<Value*, 4> Incoming;
295 // Collect the incoming values from the PHIs.
296 for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
297 instr != ie; ++instr) {
298 PHINode *P = dyn_cast<PHINode>(instr);
303 Value *V = P->getIncomingValueForBlock(BB);
304 if (Instruction *I = dyn_cast<Instruction>(V))
305 if (I->getParent() == BB)
306 Incoming.push_back(I);
309 if (Incoming.size() > 1)
310 Changed |= tryToVectorizeList(Incoming, R);
316 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
317 bool Changed = false;
318 // Attempt to sort and vectorize each of the store-groups.
319 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
321 if (it->second.size() < 2)
324 DEBUG(dbgs()<<"SLP: Analyzing a store chain of length " <<
325 it->second.size() << ".\n");
327 Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
332 void SLPVectorizer::hoistGatherSequence(LoopInfo *LI, BasicBlock *BB,
334 // Check if this block is inside a loop.
335 Loop *L = LI->getLoopFor(BB);
339 // Check if it has a preheader.
340 BasicBlock *PreHeader = L->getLoopPreheader();
344 // Mark the insertion point for the block.
345 Instruction *Location = PreHeader->getTerminator();
347 BoUpSLP::ValueList &Gathers = R.getGatherSeqInstructions();
348 for (BoUpSLP::ValueList::iterator it = Gathers.begin(), e = Gathers.end();
350 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
352 // The InsertElement sequence can be simplified into a constant.
356 // If the vector or the element that we insert into it are
357 // instructions that are defined in this basic block then we can't
358 // hoist this instruction.
359 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
360 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
361 if (CurrVec && L->contains(CurrVec)) continue;
362 if (NewElem && L->contains(NewElem)) continue;
364 // We can hoist this instruction. Move it to the pre-header.
365 Insert->moveBefore(Location);
369 } // end anonymous namespace
371 char SLPVectorizer::ID = 0;
372 static const char lv_name[] = "SLP Vectorizer";
373 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
374 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
375 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
376 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
377 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
378 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
381 Pass *createSLPVectorizerPass() {
382 return new SLPVectorizer();