1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
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 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
18 // Future loop memory idioms to recognize:
19 // memcmp, memmove, strlen, etc.
20 // Future floating point idioms to recognize in -ffast-math mode:
22 // Future integer operation idioms to recognize:
25 // Beware that isel's default lowering for ctpop is highly inefficient for
26 // i64 and larger types when i64 is legal and the value has few bits set. It
27 // would be good to enhance isel to emit a loop for ctpop in this case.
29 // We should enhance the memset/memcpy recognition to handle multiple stores in
30 // the loop. This would handle things like:
31 // void foo(_Complex float *P)
32 // for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
33 // this is also "Example 2" from http://blog.regehr.org/archives/320
35 //===----------------------------------------------------------------------===//
37 #define DEBUG_TYPE "loop-idiom"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Analysis/AliasAnalysis.h"
40 #include "llvm/Analysis/LoopPass.h"
41 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
42 #include "llvm/Analysis/ScalarEvolutionExpander.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/IRBuilder.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/ADT/Statistic.h"
52 // TODO: Recognize "N" size array multiplies: replace with call to blas or
54 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
55 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
58 class LoopIdiomRecognize : public LoopPass {
64 explicit LoopIdiomRecognize() : LoopPass(ID) {
65 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
68 bool runOnLoop(Loop *L, LPPassManager &LPM);
70 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
72 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
74 const SCEVAddRecExpr *Ev,
76 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
77 const SCEVAddRecExpr *StoreEv,
78 const SCEVAddRecExpr *LoadEv,
81 /// This transformation requires natural loop information & requires that
82 /// loop preheaders be inserted into the CFG.
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
86 AU.addPreserved<LoopInfo>();
87 AU.addRequiredID(LoopSimplifyID);
88 AU.addPreservedID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addPreservedID(LCSSAID);
91 AU.addRequired<AliasAnalysis>();
92 AU.addPreserved<AliasAnalysis>();
93 AU.addRequired<ScalarEvolution>();
94 AU.addPreserved<ScalarEvolution>();
95 AU.addPreserved<DominatorTree>();
100 char LoopIdiomRecognize::ID = 0;
101 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
103 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
104 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
105 INITIALIZE_PASS_DEPENDENCY(LCSSA)
106 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
107 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
108 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
111 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
113 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
114 /// and zero out all the operands of this instruction. If any of them become
115 /// dead, delete them and the computation tree that feeds them.
117 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
118 SmallVector<Instruction*, 32> NowDeadInsts;
120 NowDeadInsts.push_back(I);
122 // Before we touch this instruction, remove it from SE!
124 Instruction *DeadInst = NowDeadInsts.pop_back_val();
126 // This instruction is dead, zap it, in stages. Start by removing it from
128 SE.forgetValue(DeadInst);
130 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
131 Value *Op = DeadInst->getOperand(op);
132 DeadInst->setOperand(op, 0);
134 // If this operand just became dead, add it to the NowDeadInsts list.
135 if (!Op->use_empty()) continue;
137 if (Instruction *OpI = dyn_cast<Instruction>(Op))
138 if (isInstructionTriviallyDead(OpI))
139 NowDeadInsts.push_back(OpI);
142 DeadInst->eraseFromParent();
144 } while (!NowDeadInsts.empty());
147 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
150 // The trip count of the loop must be analyzable.
151 SE = &getAnalysis<ScalarEvolution>();
152 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
154 const SCEV *BECount = SE->getBackedgeTakenCount(L);
155 if (isa<SCEVCouldNotCompute>(BECount)) return false;
157 // We require target data for now.
158 TD = getAnalysisIfAvailable<TargetData>();
159 if (TD == 0) return false;
161 // TODO: We currently only scan the header of the loop, because it is the only
162 // part that is known to execute and we don't want to make a conditional store
163 // into an unconditional one in the preheader. However, there can be diamonds
164 // and other things in the loop that would make other blocks "always executed"
165 // we should get the full set and scan each block.
166 BasicBlock *BB = L->getHeader();
167 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
168 << "] Loop %" << BB->getName() << "\n");
170 bool MadeChange = false;
171 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
172 // Look for store instructions, which may be memsets.
173 StoreInst *SI = dyn_cast<StoreInst>(I++);
174 if (SI == 0 || SI->isVolatile()) continue;
177 if (!processLoopStore(SI, BECount)) continue;
181 // If processing the store invalidated our iterator, start over from the
190 /// scanBlock - Look over a block to see if we can promote anything out of it.
191 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
192 Value *StoredVal = SI->getValueOperand();
193 Value *StorePtr = SI->getPointerOperand();
195 // Reject stores that are so large that they overflow an unsigned.
196 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
197 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
200 // See if the pointer expression is an AddRec like {base,+,1} on the current
201 // loop, which indicates a strided store. If we have something else, it's a
202 // random store we can't handle.
203 const SCEVAddRecExpr *StoreEv =
204 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
205 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
208 // Check to see if the stride matches the size of the store. If so, then we
209 // know that every byte is touched in the loop.
210 unsigned StoreSize = (unsigned)SizeInBits >> 3;
211 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
213 // TODO: Could also handle negative stride here someday, that will require the
214 // validity check in mayLoopModRefLocation to be updated though.
215 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
218 // If the stored value is a byte-wise value (like i32 -1), then it may be
219 // turned into a memset of i8 -1, assuming that all the consequtive bytes
220 // are stored. A store of i32 0x01020304 can never be turned into a memset.
221 if (Value *SplatValue = isBytewiseValue(StoredVal))
222 if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
226 // If the stored value is a strided load in the same loop with the same stride
227 // this this may be transformable into a memcpy. This kicks in for stuff like
228 // for (i) A[i] = B[i];
229 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
230 const SCEVAddRecExpr *LoadEv =
231 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
232 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
233 StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
234 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
237 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
242 /// mayLoopModRefLocation - Return true if the specified loop might do a load or
243 /// store to the same location that the specified store could store to, which is
244 /// a loop-strided access.
245 static bool mayLoopModRefLocation(Value *Ptr, Loop *L, const SCEV *BECount,
246 unsigned StoreSize, AliasAnalysis &AA,
247 StoreInst *IgnoredStore) {
248 // Get the location that may be stored across the loop. Since the access is
249 // strided positively through memory, we say that the modified location starts
250 // at the pointer and has infinite size.
251 uint64_t AccessSize = AliasAnalysis::UnknownSize;
253 // If the loop iterates a fixed number of times, we can refine the access size
254 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
255 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
256 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
258 // TODO: For this to be really effective, we have to dive into the pointer
259 // operand in the store. Store to &A[i] of 100 will always return may alias
260 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
261 // which will then no-alias a store to &A[100].
262 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
264 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
266 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
267 if (&*I != IgnoredStore &&
268 AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
274 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
275 /// If we can transform this into a memset in the loop preheader, do so.
276 bool LoopIdiomRecognize::
277 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
279 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
280 // Verify that the stored value is loop invariant. If not, we can't promote
282 if (!CurLoop->isLoopInvariant(SplatValue))
285 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
286 // this into a memset in the loop preheader now if we want. However, this
287 // would be unsafe to do if there is anything else in the loop that may read
288 // or write to the aliased location. Check for an alias.
289 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
290 StoreSize, getAnalysis<AliasAnalysis>(), SI))
293 // Okay, everything looks good, insert the memset.
294 BasicBlock *Preheader = CurLoop->getLoopPreheader();
296 IRBuilder<> Builder(Preheader->getTerminator());
298 // The trip count of the loop and the base pointer of the addrec SCEV is
299 // guaranteed to be loop invariant, which means that it should dominate the
300 // header. Just insert code for it in the preheader.
301 SCEVExpander Expander(*SE);
303 unsigned AddrSpace = SI->getPointerAddressSpace();
305 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
306 Preheader->getTerminator());
308 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
309 // pointer size if it isn't already.
310 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
311 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
312 if (BESize < TD->getPointerSizeInBits())
313 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
314 else if (BESize > TD->getPointerSizeInBits())
315 BECount = SE->getTruncateExpr(BECount, IntPtr);
317 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
318 true, true /*nooverflow*/);
320 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
321 true, true /*nooverflow*/);
324 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
327 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
329 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
330 << " from store to: " << *Ev << " at: " << *SI << "\n");
333 // Okay, the memset has been formed. Zap the original store and anything that
335 DeleteDeadInstruction(SI, *SE);
340 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
341 /// same-strided load.
342 bool LoopIdiomRecognize::
343 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
344 const SCEVAddRecExpr *StoreEv,
345 const SCEVAddRecExpr *LoadEv,
346 const SCEV *BECount) {
347 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
349 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
350 // this into a memcpy in the loop preheader now if we want. However, this
351 // would be unsafe to do if there is anything else in the loop that may read
352 // or write to the aliased location (including the load feeding the stores).
353 // Check for an alias.
354 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
355 StoreSize, getAnalysis<AliasAnalysis>(), SI))
358 // Okay, everything looks good, insert the memcpy.
359 BasicBlock *Preheader = CurLoop->getLoopPreheader();
361 IRBuilder<> Builder(Preheader->getTerminator());
363 // The trip count of the loop and the base pointer of the addrec SCEV is
364 // guaranteed to be loop invariant, which means that it should dominate the
365 // header. Just insert code for it in the preheader.
366 SCEVExpander Expander(*SE);
369 Expander.expandCodeFor(LoadEv->getStart(),
370 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
371 Preheader->getTerminator());
372 Value *StoreBasePtr =
373 Expander.expandCodeFor(StoreEv->getStart(),
374 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
375 Preheader->getTerminator());
377 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
378 // pointer size if it isn't already.
379 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
380 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
381 if (BESize < TD->getPointerSizeInBits())
382 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
383 else if (BESize > TD->getPointerSizeInBits())
384 BECount = SE->getTruncateExpr(BECount, IntPtr);
386 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
387 true, true /*nooverflow*/);
389 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
390 true, true /*nooverflow*/);
393 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
396 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
397 std::min(SI->getAlignment(), LI->getAlignment()));
399 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
400 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
401 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
404 // Okay, the memset has been formed. Zap the original store and anything that
406 DeleteDeadInstruction(SI, *SE);