teach loop idiom recognition to form memcpy's from simple loops.
[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 #define DEBUG_TYPE "loop-idiom"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/ScalarEvolutionExpander.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/IRBuilder.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 // TODO: Recognize "N" size array multiplies: replace with call to blas or
31 // something.
32
33 namespace {
34   class LoopIdiomRecognize : public LoopPass {
35     Loop *CurLoop;
36     const TargetData *TD;
37     ScalarEvolution *SE;
38   public:
39     static char ID;
40     explicit LoopIdiomRecognize() : LoopPass(ID) {
41       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
42     }
43
44     bool runOnLoop(Loop *L, LPPassManager &LPM);
45
46     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
47     
48     bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
49                                       Value *SplatValue,
50                                       const SCEVAddRecExpr *Ev,
51                                       const SCEV *BECount);
52     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
53                                     const SCEVAddRecExpr *StoreEv,
54                                     const SCEVAddRecExpr *LoadEv,
55                                     const SCEV *BECount);
56       
57     /// This transformation requires natural loop information & requires that
58     /// loop preheaders be inserted into the CFG.
59     ///
60     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61       AU.addRequired<LoopInfo>();
62       AU.addPreserved<LoopInfo>();
63       AU.addRequiredID(LoopSimplifyID);
64       AU.addPreservedID(LoopSimplifyID);
65       AU.addRequiredID(LCSSAID);
66       AU.addPreservedID(LCSSAID);
67       AU.addRequired<AliasAnalysis>();
68       AU.addPreserved<AliasAnalysis>();
69       AU.addRequired<ScalarEvolution>();
70       AU.addPreserved<ScalarEvolution>();
71       AU.addPreserved<DominatorTree>();
72     }
73   };
74 }
75
76 char LoopIdiomRecognize::ID = 0;
77 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
78                       false, false)
79 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
81 INITIALIZE_PASS_DEPENDENCY(LCSSA)
82 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
83 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
84 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
85                     false, false)
86
87 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
88
89 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
90 /// and zero out all the operands of this instruction.  If any of them become
91 /// dead, delete them and the computation tree that feeds them.
92 ///
93 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
94   SmallVector<Instruction*, 32> NowDeadInsts;
95   
96   NowDeadInsts.push_back(I);
97   
98   // Before we touch this instruction, remove it from SE!
99   do {
100     Instruction *DeadInst = NowDeadInsts.pop_back_val();
101     
102     // This instruction is dead, zap it, in stages.  Start by removing it from
103     // SCEV.
104     SE.forgetValue(DeadInst);
105     
106     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
107       Value *Op = DeadInst->getOperand(op);
108       DeadInst->setOperand(op, 0);
109       
110       // If this operand just became dead, add it to the NowDeadInsts list.
111       if (!Op->use_empty()) continue;
112       
113       if (Instruction *OpI = dyn_cast<Instruction>(Op))
114         if (isInstructionTriviallyDead(OpI))
115           NowDeadInsts.push_back(OpI);
116     }
117     
118     DeadInst->eraseFromParent();
119     
120   } while (!NowDeadInsts.empty());
121 }
122
123 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
124   CurLoop = L;
125   
126   // We only look at trivial single basic block loops.
127   // TODO: eventually support more complex loops, scanning the header.
128   if (L->getBlocks().size() != 1)
129     return false;
130   
131   // The trip count of the loop must be analyzable.
132   SE = &getAnalysis<ScalarEvolution>();
133   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
134     return false;
135   const SCEV *BECount = SE->getBackedgeTakenCount(L);
136   if (isa<SCEVCouldNotCompute>(BECount)) return false;
137   
138   // We require target data for now.
139   TD = getAnalysisIfAvailable<TargetData>();
140   if (TD == 0) return false;
141   
142   BasicBlock *BB = L->getHeader();
143   DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
144                << "] Loop %" << BB->getName() << "\n");
145
146   bool MadeChange = false;
147   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
148     // Look for store instructions, which may be memsets.
149     StoreInst *SI = dyn_cast<StoreInst>(I++);
150     if (SI == 0 || SI->isVolatile()) continue;
151     
152     WeakVH InstPtr(SI);
153     if (!processLoopStore(SI, BECount)) continue;
154     
155     MadeChange = true;
156     
157     // If processing the store invalidated our iterator, start over from the
158     // head of the loop.
159     if (InstPtr == 0)
160       I = BB->begin();
161   }
162   
163   return MadeChange;
164 }
165
166 /// scanBlock - Look over a block to see if we can promote anything out of it.
167 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
168   Value *StoredVal = SI->getValueOperand();
169   Value *StorePtr = SI->getPointerOperand();
170   
171   // Reject stores that are so large that they overflow an unsigned.
172   uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
173   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
174     return false;
175   
176   // See if the pointer expression is an AddRec like {base,+,1} on the current
177   // loop, which indicates a strided store.  If we have something else, it's a
178   // random store we can't handle.
179   const SCEVAddRecExpr *StoreEv =
180     dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
181   if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
182     return false;
183
184   // Check to see if the stride matches the size of the store.  If so, then we
185   // know that every byte is touched in the loop.
186   unsigned StoreSize = (unsigned)SizeInBits >> 3; 
187   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
188   
189   // TODO: Could also handle negative stride here someday, that will require the
190   // validity check in mayLoopModRefLocation to be updated though.
191   if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
192     return false;
193   
194   // If the stored value is a byte-wise value (like i32 -1), then it may be
195   // turned into a memset of i8 -1, assuming that all the consequtive bytes
196   // are stored.  A store of i32 0x01020304 can never be turned into a memset.
197   if (Value *SplatValue = isBytewiseValue(StoredVal))
198     if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
199                                      BECount))
200       return true;
201
202   // If the stored value is a strided load in the same loop with the same stride
203   // this this may be transformable into a memcpy.  This kicks in for stuff like
204   //   for (i) A[i] = B[i];
205   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
206     const SCEVAddRecExpr *LoadEv =
207       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
208     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
209         StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
210       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
211         return true;
212   }
213  // errs() << "UNHANDLED strided store: " << *Ev << " - " << *SI << "\n";
214
215   return false;
216 }
217
218 /// mayLoopModRefLocation - Return true if the specified loop might do a load or
219 /// store to the same location that the specified store could store to, which is
220 /// a loop-strided access. 
221 static bool mayLoopModRefLocation(Value *Ptr, Loop *L, const SCEV *BECount,
222                                   unsigned StoreSize, AliasAnalysis &AA,
223                                   StoreInst *IgnoredStore) {
224   // Get the location that may be stored across the loop.  Since the access is
225   // strided positively through memory, we say that the modified location starts
226   // at the pointer and has infinite size.
227   uint64_t AccessSize = AliasAnalysis::UnknownSize;
228
229   // If the loop iterates a fixed number of times, we can refine the access size
230   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
231   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
232     AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
233   
234   // TODO: For this to be really effective, we have to dive into the pointer
235   // operand in the store.  Store to &A[i] of 100 will always return may alias
236   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
237   // which will then no-alias a store to &A[100].
238   AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
239
240   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
241        ++BI)
242     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
243       if (&*I != IgnoredStore &&
244           AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
245         return true;
246
247   return false;
248 }
249
250 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
251 /// If we can transform this into a memset in the loop preheader, do so.
252 bool LoopIdiomRecognize::
253 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
254                              Value *SplatValue,
255                              const SCEVAddRecExpr *Ev, const SCEV *BECount) {
256   // Verify that the stored value is loop invariant.  If not, we can't promote
257   // the memset.
258   if (!CurLoop->isLoopInvariant(SplatValue))
259     return false;
260   
261   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
262   // this into a memset in the loop preheader now if we want.  However, this
263   // would be unsafe to do if there is anything else in the loop that may read
264   // or write to the aliased location.  Check for an alias.
265   if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
266                             StoreSize, getAnalysis<AliasAnalysis>(), SI))
267     return false;
268   
269   // Okay, everything looks good, insert the memset.
270   BasicBlock *Preheader = CurLoop->getLoopPreheader();
271   
272   IRBuilder<> Builder(Preheader->getTerminator());
273   
274   // The trip count of the loop and the base pointer of the addrec SCEV is
275   // guaranteed to be loop invariant, which means that it should dominate the
276   // header.  Just insert code for it in the preheader.
277   SCEVExpander Expander(*SE);
278   
279   unsigned AddrSpace = SI->getPointerAddressSpace();
280   Value *BasePtr = 
281     Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
282                            Preheader->getTerminator());
283   
284   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
285   // pointer size if it isn't already.
286   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
287   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
288   if (BESize < TD->getPointerSizeInBits())
289     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
290   else if (BESize > TD->getPointerSizeInBits())
291     BECount = SE->getTruncateExpr(BECount, IntPtr);
292   
293   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
294                                          true, true /*nooverflow*/);
295   if (StoreSize != 1)
296     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
297                                true, true /*nooverflow*/);
298   
299   Value *NumBytes = 
300     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
301   
302   Value *NewCall =
303     Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
304   
305   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
306                << "    from store to: " << *Ev << " at: " << *SI << "\n");
307   (void)NewCall;
308   
309   // Okay, the memset has been formed.  Zap the original store and anything that
310   // feeds into it.
311   DeleteDeadInstruction(SI, *SE);
312   return true;
313 }
314
315 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
316 /// same-strided load.
317 bool LoopIdiomRecognize::
318 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
319                            const SCEVAddRecExpr *StoreEv,
320                            const SCEVAddRecExpr *LoadEv,
321                            const SCEV *BECount) {
322   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
323   
324   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
325   // this into a memcmp in the loop preheader now if we want.  However, this
326   // would be unsafe to do if there is anything else in the loop that may read
327   // or write to the aliased location (including the load feeding the stores).
328   // Check for an alias.
329   if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
330                             StoreSize, getAnalysis<AliasAnalysis>(), SI))
331     return false;
332   
333   // Okay, everything looks good, insert the memcpy.
334   BasicBlock *Preheader = CurLoop->getLoopPreheader();
335   
336   IRBuilder<> Builder(Preheader->getTerminator());
337   
338   // The trip count of the loop and the base pointer of the addrec SCEV is
339   // guaranteed to be loop invariant, which means that it should dominate the
340   // header.  Just insert code for it in the preheader.
341   SCEVExpander Expander(*SE);
342
343   Value *LoadBasePtr = 
344     Expander.expandCodeFor(LoadEv->getStart(),
345                            Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
346                            Preheader->getTerminator());
347   Value *StoreBasePtr = 
348     Expander.expandCodeFor(StoreEv->getStart(),
349                            Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
350                            Preheader->getTerminator());
351   
352   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
353   // pointer size if it isn't already.
354   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
355   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
356   if (BESize < TD->getPointerSizeInBits())
357     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
358   else if (BESize > TD->getPointerSizeInBits())
359     BECount = SE->getTruncateExpr(BECount, IntPtr);
360   
361   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
362                                          true, true /*nooverflow*/);
363   if (StoreSize != 1)
364     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
365                                true, true /*nooverflow*/);
366   
367   Value *NumBytes =
368     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
369   
370   Value *NewCall =
371     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
372                          std::min(SI->getAlignment(), LI->getAlignment()));
373   
374   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
375                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
376                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
377   (void)NewCall;
378   
379   // Okay, the memset has been formed.  Zap the original store and anything that
380   // feeds into it.
381   DeleteDeadInstruction(SI, *SE);
382   return true;
383 }