blob: f8748efeceaa2114188771659411355aee5106f8 [file] [log] [blame]
Chris Lattnere6bb6492010-12-26 19:39:38 +00001//===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements an idiom recognizer that transforms simple loops into a
11// non-loop form. In cases that this kicks in, it can be a significant
12// performance win.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "loop-idiom"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000020#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000021#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/Target/TargetData.h"
Chris Lattner9f391882010-12-27 00:03:23 +000023#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000024#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000025#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000026#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
29// TODO: Recognize "N" size array multiplies: replace with call to blas or
30// something.
31
32namespace {
33 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000034 Loop *CurLoop;
35 const TargetData *TD;
36 ScalarEvolution *SE;
Chris Lattnere6bb6492010-12-26 19:39:38 +000037 public:
38 static char ID;
39 explicit LoopIdiomRecognize() : LoopPass(ID) {
40 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
41 }
42
43 bool runOnLoop(Loop *L, LPPassManager &LPM);
44
Chris Lattner22920b52010-12-26 20:45:45 +000045 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000046
Chris Lattnera92ff912010-12-26 23:42:51 +000047 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
48 Value *SplatValue,
49 const SCEVAddRecExpr *Ev,
50 const SCEV *BECount);
51
Chris Lattnere6bb6492010-12-26 19:39:38 +000052 /// This transformation requires natural loop information & requires that
53 /// loop preheaders be inserted into the CFG.
54 ///
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<LoopInfo>();
57 AU.addPreserved<LoopInfo>();
58 AU.addRequiredID(LoopSimplifyID);
59 AU.addPreservedID(LoopSimplifyID);
60 AU.addRequiredID(LCSSAID);
61 AU.addPreservedID(LCSSAID);
62 AU.addRequired<ScalarEvolution>();
63 AU.addPreserved<ScalarEvolution>();
64 AU.addPreserved<DominatorTree>();
65 }
66 };
67}
68
69char LoopIdiomRecognize::ID = 0;
70INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
71 false, false)
72INITIALIZE_PASS_DEPENDENCY(LoopInfo)
73INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
74INITIALIZE_PASS_DEPENDENCY(LCSSA)
75INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
76INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
77 false, false)
78
79Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
80
Chris Lattner9f391882010-12-27 00:03:23 +000081/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
82/// and zero out all the operands of this instruction. If any of them become
83/// dead, delete them and the computation tree that feeds them.
84///
85static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
86 SmallVector<Instruction*, 32> NowDeadInsts;
87
88 NowDeadInsts.push_back(I);
89
90 // Before we touch this instruction, remove it from SE!
91 do {
92 Instruction *DeadInst = NowDeadInsts.pop_back_val();
93
94 // This instruction is dead, zap it, in stages. Start by removing it from
95 // SCEV.
96 SE.forgetValue(DeadInst);
97
98 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
99 Value *Op = DeadInst->getOperand(op);
100 DeadInst->setOperand(op, 0);
101
102 // If this operand just became dead, add it to the NowDeadInsts list.
103 if (!Op->use_empty()) continue;
104
105 if (Instruction *OpI = dyn_cast<Instruction>(Op))
106 if (isInstructionTriviallyDead(OpI))
107 NowDeadInsts.push_back(OpI);
108 }
109
110 DeadInst->eraseFromParent();
111
112 } while (!NowDeadInsts.empty());
113}
114
Chris Lattnere6bb6492010-12-26 19:39:38 +0000115bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000116 CurLoop = L;
117
Chris Lattnere6bb6492010-12-26 19:39:38 +0000118 // We only look at trivial single basic block loops.
119 // TODO: eventually support more complex loops, scanning the header.
120 if (L->getBlocks().size() != 1)
121 return false;
122
Chris Lattner22920b52010-12-26 20:45:45 +0000123 // The trip count of the loop must be analyzable.
124 SE = &getAnalysis<ScalarEvolution>();
125 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
126 return false;
127 const SCEV *BECount = SE->getBackedgeTakenCount(L);
128 if (isa<SCEVCouldNotCompute>(BECount)) return false;
129
130 // We require target data for now.
131 TD = getAnalysisIfAvailable<TargetData>();
132 if (TD == 0) return false;
133
Chris Lattnere6bb6492010-12-26 19:39:38 +0000134 BasicBlock *BB = L->getHeader();
Chris Lattner22920b52010-12-26 20:45:45 +0000135 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
Chris Lattnere6bb6492010-12-26 19:39:38 +0000136 << "] Loop %" << BB->getName() << "\n");
137
Chris Lattner22920b52010-12-26 20:45:45 +0000138 bool MadeChange = false;
139 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
140 // Look for store instructions, which may be memsets.
Chris Lattnera92ff912010-12-26 23:42:51 +0000141 StoreInst *SI = dyn_cast<StoreInst>(I++);
142 if (SI == 0 || SI->isVolatile()) continue;
143
Chris Lattner9f391882010-12-27 00:03:23 +0000144 WeakVH InstPtr;
145 if (processLoopStore(SI, BECount)) {
146 // If processing the store invalidated our iterator, start over from the
147 // head of the loop.
148 if (InstPtr == 0)
149 I = BB->begin();
150 }
Chris Lattner22920b52010-12-26 20:45:45 +0000151 }
152
153 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000154}
155
156/// scanBlock - Look over a block to see if we can promote anything out of it.
Chris Lattner22920b52010-12-26 20:45:45 +0000157bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
158 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000159 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000160
Chris Lattner22920b52010-12-26 20:45:45 +0000161 // Check to see if the store updates all bits in memory. We don't want to
162 // process things like a store of i3. We also require that the store be a
163 // multiple of a byte.
164 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
165 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0 ||
166 SizeInBits != TD->getTypeStoreSizeInBits(StoredVal->getType()))
167 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000168
Chris Lattner22920b52010-12-26 20:45:45 +0000169 // See if the pointer expression is an AddRec like {base,+,1} on the current
170 // loop, which indicates a strided store. If we have something else, it's a
171 // random store we can't handle.
Chris Lattnera92ff912010-12-26 23:42:51 +0000172 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chris Lattner22920b52010-12-26 20:45:45 +0000173 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
174 return false;
175
176 // Check to see if the stride matches the size of the store. If so, then we
177 // know that every byte is touched in the loop.
178 unsigned StoreSize = (unsigned)SizeInBits >> 3;
179 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
180 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
181 return false;
182
Chris Lattner22920b52010-12-26 20:45:45 +0000183 // If the stored value is a byte-wise value (like i32 -1), then it may be
184 // turned into a memset of i8 -1, assuming that all the consequtive bytes
185 // are stored. A store of i32 0x01020304 can never be turned into a memset.
Chris Lattnera92ff912010-12-26 23:42:51 +0000186 if (Value *SplatValue = isBytewiseValue(StoredVal))
187 return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
188
189 // Handle the memcpy case here.
190 errs() << "Found strided store: " << *Ev << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000191
192
Chris Lattnere6bb6492010-12-26 19:39:38 +0000193 return false;
194}
195
Chris Lattnera92ff912010-12-26 23:42:51 +0000196/// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
197/// If we can transform this into a memset in the loop preheader, do so.
198bool LoopIdiomRecognize::
199processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
200 Value *SplatValue,
201 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
202 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
203 // this into a memset in the loop preheader now if we want. However, this
204 // would be unsafe to do if there is anything else in the loop that may read
205 // or write to the aliased location. Check for an alias.
206
207 // FIXME: TODO safety check.
208
209 // Okay, everything looks good, insert the memset.
210 BasicBlock *Preheader = CurLoop->getLoopPreheader();
211
212 IRBuilder<> Builder(Preheader->getTerminator());
213
214 // The trip count of the loop and the base pointer of the addrec SCEV is
215 // guaranteed to be loop invariant, which means that it should dominate the
216 // header. Just insert code for it in the preheader.
217 SCEVExpander Expander(*SE);
218
219 unsigned AddrSpace = SI->getPointerAddressSpace();
220 Value *BasePtr =
221 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
222 Preheader->getTerminator());
223
224 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
225 // pointer size if it isn't already.
226 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
227 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
228 if (BESize < TD->getPointerSizeInBits())
229 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
230 else if (BESize > TD->getPointerSizeInBits())
231 BECount = SE->getTruncateExpr(BECount, IntPtr);
232
233 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
234 true, true /*nooverflow*/);
235 if (StoreSize != 1)
236 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
237 true, true /*nooverflow*/);
238
239 Value *NumBytes =
240 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
241
242 Value *NewCall =
243 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
244
245 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
246 << " from store to: " << *Ev << " at: " << *SI << "\n");
247
Chris Lattner9f391882010-12-27 00:03:23 +0000248 // Okay, the memset has been formed. Zap the original store and anything that
249 // feeds into it.
250 DeleteDeadInstruction(SI, *SE);
Chris Lattnera92ff912010-12-26 23:42:51 +0000251 return true;
252}
253