add a list of opportunities for future improvement.
[oota-llvm.git] / lib / Transforms / Scalar / LoopIdiomRecognize.cpp
1 //===-- 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 // TODO List:
17 //
18 // Future loop memory idioms to recognize:
19 //   memcmp, memmove, strlen, etc.
20 // Future floating point idioms to recognize in -ffast-math mode:
21 //   fpowi
22 // Future integer operation idioms to recognize:
23 //   ctpop, ctlz, cttz
24 //
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.
28 //
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
34 //  
35 //===----------------------------------------------------------------------===//
36
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"
50 using namespace llvm;
51
52 // TODO: Recognize "N" size array multiplies: replace with call to blas or
53 // something.
54 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
55 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
56
57 namespace {
58   class LoopIdiomRecognize : public LoopPass {
59     Loop *CurLoop;
60     const TargetData *TD;
61     ScalarEvolution *SE;
62   public:
63     static char ID;
64     explicit LoopIdiomRecognize() : LoopPass(ID) {
65       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
66     }
67
68     bool runOnLoop(Loop *L, LPPassManager &LPM);
69
70     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
71     
72     bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
73                                       Value *SplatValue,
74                                       const SCEVAddRecExpr *Ev,
75                                       const SCEV *BECount);
76     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
77                                     const SCEVAddRecExpr *StoreEv,
78                                     const SCEVAddRecExpr *LoadEv,
79                                     const SCEV *BECount);
80       
81     /// This transformation requires natural loop information & requires that
82     /// loop preheaders be inserted into the CFG.
83     ///
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>();
96     }
97   };
98 }
99
100 char LoopIdiomRecognize::ID = 0;
101 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
102                       false, false)
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",
109                     false, false)
110
111 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
112
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.
116 ///
117 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
118   SmallVector<Instruction*, 32> NowDeadInsts;
119   
120   NowDeadInsts.push_back(I);
121   
122   // Before we touch this instruction, remove it from SE!
123   do {
124     Instruction *DeadInst = NowDeadInsts.pop_back_val();
125     
126     // This instruction is dead, zap it, in stages.  Start by removing it from
127     // SCEV.
128     SE.forgetValue(DeadInst);
129     
130     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
131       Value *Op = DeadInst->getOperand(op);
132       DeadInst->setOperand(op, 0);
133       
134       // If this operand just became dead, add it to the NowDeadInsts list.
135       if (!Op->use_empty()) continue;
136       
137       if (Instruction *OpI = dyn_cast<Instruction>(Op))
138         if (isInstructionTriviallyDead(OpI))
139           NowDeadInsts.push_back(OpI);
140     }
141     
142     DeadInst->eraseFromParent();
143     
144   } while (!NowDeadInsts.empty());
145 }
146
147 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
148   CurLoop = L;
149   
150   // The trip count of the loop must be analyzable.
151   SE = &getAnalysis<ScalarEvolution>();
152   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
153     return false;
154   const SCEV *BECount = SE->getBackedgeTakenCount(L);
155   if (isa<SCEVCouldNotCompute>(BECount)) return false;
156   
157   // We require target data for now.
158   TD = getAnalysisIfAvailable<TargetData>();
159   if (TD == 0) return false;
160   
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");
169
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;
175     
176     WeakVH InstPtr(SI);
177     if (!processLoopStore(SI, BECount)) continue;
178     
179     MadeChange = true;
180     
181     // If processing the store invalidated our iterator, start over from the
182     // head of the loop.
183     if (InstPtr == 0)
184       I = BB->begin();
185   }
186   
187   return MadeChange;
188 }
189
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();
194   
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)
198     return false;
199   
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())
206     return false;
207
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));
212   
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())
216     return false;
217   
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,
223                                      BECount))
224       return true;
225
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))
235         return true;
236   }
237   //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
238
239   return false;
240 }
241
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;
252
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;
257   
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);
263
264   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
265        ++BI)
266     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
267       if (&*I != IgnoredStore &&
268           AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
269         return true;
270
271   return false;
272 }
273
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,
278                              Value *SplatValue,
279                              const SCEVAddRecExpr *Ev, const SCEV *BECount) {
280   // Verify that the stored value is loop invariant.  If not, we can't promote
281   // the memset.
282   if (!CurLoop->isLoopInvariant(SplatValue))
283     return false;
284   
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))
291     return false;
292   
293   // Okay, everything looks good, insert the memset.
294   BasicBlock *Preheader = CurLoop->getLoopPreheader();
295   
296   IRBuilder<> Builder(Preheader->getTerminator());
297   
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);
302   
303   unsigned AddrSpace = SI->getPointerAddressSpace();
304   Value *BasePtr = 
305     Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
306                            Preheader->getTerminator());
307   
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);
316   
317   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
318                                          true, true /*nooverflow*/);
319   if (StoreSize != 1)
320     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
321                                true, true /*nooverflow*/);
322   
323   Value *NumBytes = 
324     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
325   
326   Value *NewCall =
327     Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
328   
329   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
330                << "    from store to: " << *Ev << " at: " << *SI << "\n");
331   (void)NewCall;
332   
333   // Okay, the memset has been formed.  Zap the original store and anything that
334   // feeds into it.
335   DeleteDeadInstruction(SI, *SE);
336   ++NumMemSet;
337   return true;
338 }
339
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());
348   
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))
356     return false;
357   
358   // Okay, everything looks good, insert the memcpy.
359   BasicBlock *Preheader = CurLoop->getLoopPreheader();
360   
361   IRBuilder<> Builder(Preheader->getTerminator());
362   
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);
367
368   Value *LoadBasePtr = 
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());
376   
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);
385   
386   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
387                                          true, true /*nooverflow*/);
388   if (StoreSize != 1)
389     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
390                                true, true /*nooverflow*/);
391   
392   Value *NumBytes =
393     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
394   
395   Value *NewCall =
396     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
397                          std::min(SI->getAlignment(), LI->getAlignment()));
398   
399   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
400                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
401                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
402   (void)NewCall;
403   
404   // Okay, the memset has been formed.  Zap the original store and anything that
405   // feeds into it.
406   DeleteDeadInstruction(SI, *SE);
407   ++NumMemCpy;
408   return true;
409 }