fix a miscompilation of tramp3d-v4: when forming a memcpy, we have to make
[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     DominatorTree *DT;
62     ScalarEvolution *SE;
63   public:
64     static char ID;
65     explicit LoopIdiomRecognize() : LoopPass(ID) {
66       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
67     }
68
69     bool runOnLoop(Loop *L, LPPassManager &LPM);
70     bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
71                         SmallVectorImpl<BasicBlock*> &ExitBlocks);
72
73     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
74     
75     bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
76                                       Value *SplatValue,
77                                       const SCEVAddRecExpr *Ev,
78                                       const SCEV *BECount);
79     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
80                                     const SCEVAddRecExpr *StoreEv,
81                                     const SCEVAddRecExpr *LoadEv,
82                                     const SCEV *BECount);
83       
84     /// This transformation requires natural loop information & requires that
85     /// loop preheaders be inserted into the CFG.
86     ///
87     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88       AU.addRequired<LoopInfo>();
89       AU.addPreserved<LoopInfo>();
90       AU.addRequiredID(LoopSimplifyID);
91       AU.addPreservedID(LoopSimplifyID);
92       AU.addRequiredID(LCSSAID);
93       AU.addPreservedID(LCSSAID);
94       AU.addRequired<AliasAnalysis>();
95       AU.addPreserved<AliasAnalysis>();
96       AU.addRequired<ScalarEvolution>();
97       AU.addPreserved<ScalarEvolution>();
98       AU.addPreserved<DominatorTree>();
99       AU.addRequired<DominatorTree>();
100     }
101   };
102 }
103
104 char LoopIdiomRecognize::ID = 0;
105 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
106                       false, false)
107 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
108 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
109 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
110 INITIALIZE_PASS_DEPENDENCY(LCSSA)
111 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
112 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
113 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
114                     false, false)
115
116 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
117
118 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
119 /// and zero out all the operands of this instruction.  If any of them become
120 /// dead, delete them and the computation tree that feeds them.
121 ///
122 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
123   SmallVector<Instruction*, 32> NowDeadInsts;
124   
125   NowDeadInsts.push_back(I);
126   
127   // Before we touch this instruction, remove it from SE!
128   do {
129     Instruction *DeadInst = NowDeadInsts.pop_back_val();
130     
131     // This instruction is dead, zap it, in stages.  Start by removing it from
132     // SCEV.
133     SE.forgetValue(DeadInst);
134     
135     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
136       Value *Op = DeadInst->getOperand(op);
137       DeadInst->setOperand(op, 0);
138       
139       // If this operand just became dead, add it to the NowDeadInsts list.
140       if (!Op->use_empty()) continue;
141       
142       if (Instruction *OpI = dyn_cast<Instruction>(Op))
143         if (isInstructionTriviallyDead(OpI))
144           NowDeadInsts.push_back(OpI);
145     }
146     
147     DeadInst->eraseFromParent();
148     
149   } while (!NowDeadInsts.empty());
150 }
151
152 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
153   CurLoop = L;
154   
155   // The trip count of the loop must be analyzable.
156   SE = &getAnalysis<ScalarEvolution>();
157   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
158     return false;
159   const SCEV *BECount = SE->getBackedgeTakenCount(L);
160   if (isa<SCEVCouldNotCompute>(BECount)) return false;
161   
162   // If this loop executes exactly one time, then it should be peeled, not
163   // optimized by this pass.
164   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
165     if (BECst->getValue()->getValue() == 0)
166       return false;
167   
168   // We require target data for now.
169   TD = getAnalysisIfAvailable<TargetData>();
170   if (TD == 0) return false;
171
172   DT = &getAnalysis<DominatorTree>();
173   LoopInfo &LI = getAnalysis<LoopInfo>();
174   
175   SmallVector<BasicBlock*, 8> ExitBlocks;
176   CurLoop->getUniqueExitBlocks(ExitBlocks);
177
178   DEBUG(dbgs() << "loop-idiom Scanning: F["
179                << L->getHeader()->getParent()->getName()
180                << "] Loop %" << L->getHeader()->getName() << "\n");
181   
182   bool MadeChange = false;
183   // Scan all the blocks in the loop that are not in subloops.
184   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
185        ++BI) {
186     // Ignore blocks in subloops.
187     if (LI.getLoopFor(*BI) != CurLoop)
188       continue;
189     
190     MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
191   }
192   return MadeChange;
193 }
194
195 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
196 /// with the specified backedge count.  This block is known to be in the current
197 /// loop and not in any subloops.
198 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
199                                      SmallVectorImpl<BasicBlock*> &ExitBlocks) {
200   // We can only promote stores in this block if they are unconditionally
201   // executed in the loop.  For a block to be unconditionally executed, it has
202   // to dominate all the exit blocks of the loop.  Verify this now.
203   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
204     if (!DT->dominates(BB, ExitBlocks[i]))
205       return false;
206   
207   bool MadeChange = false;
208   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
209     // Look for store instructions, which may be memsets.
210     StoreInst *SI = dyn_cast<StoreInst>(I++);
211     if (SI == 0 || SI->isVolatile()) continue;
212     
213     WeakVH InstPtr(SI);
214     if (!processLoopStore(SI, BECount)) continue;
215     
216     MadeChange = true;
217     
218     // If processing the store invalidated our iterator, start over from the
219     // head of the loop.
220     if (InstPtr == 0)
221       I = BB->begin();
222   }
223   
224   return MadeChange;
225 }
226
227
228 /// scanBlock - Look over a block to see if we can promote anything out of it.
229 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
230   Value *StoredVal = SI->getValueOperand();
231   Value *StorePtr = SI->getPointerOperand();
232   
233   // Reject stores that are so large that they overflow an unsigned.
234   uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
235   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
236     return false;
237   
238   // See if the pointer expression is an AddRec like {base,+,1} on the current
239   // loop, which indicates a strided store.  If we have something else, it's a
240   // random store we can't handle.
241   const SCEVAddRecExpr *StoreEv =
242     dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
243   if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
244     return false;
245
246   // Check to see if the stride matches the size of the store.  If so, then we
247   // know that every byte is touched in the loop.
248   unsigned StoreSize = (unsigned)SizeInBits >> 3; 
249   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
250   
251   // TODO: Could also handle negative stride here someday, that will require the
252   // validity check in mayLoopModRefLocation to be updated though.
253   if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
254     return false;
255   
256   // If the stored value is a byte-wise value (like i32 -1), then it may be
257   // turned into a memset of i8 -1, assuming that all the consequtive bytes
258   // are stored.  A store of i32 0x01020304 can never be turned into a memset.
259   if (Value *SplatValue = isBytewiseValue(StoredVal))
260     if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
261                                      BECount))
262       return true;
263
264   // If the stored value is a strided load in the same loop with the same stride
265   // this this may be transformable into a memcpy.  This kicks in for stuff like
266   //   for (i) A[i] = B[i];
267   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
268     const SCEVAddRecExpr *LoadEv =
269       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
270     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
271         StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
272       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
273         return true;
274   }
275   //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
276
277   return false;
278 }
279
280 /// mayLoopAccessLocation - Return true if the specified loop might access the
281 /// specified pointer location, which is a loop-strided access.  The 'Access'
282 /// argument specifies what the verboten forms of access are (read or write).
283 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
284                                   Loop *L, const SCEV *BECount,
285                                   unsigned StoreSize, AliasAnalysis &AA,
286                                   StoreInst *IgnoredStore) {
287   // Get the location that may be stored across the loop.  Since the access is
288   // strided positively through memory, we say that the modified location starts
289   // at the pointer and has infinite size.
290   uint64_t AccessSize = AliasAnalysis::UnknownSize;
291
292   // If the loop iterates a fixed number of times, we can refine the access size
293   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
294   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
295     AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
296   
297   // TODO: For this to be really effective, we have to dive into the pointer
298   // operand in the store.  Store to &A[i] of 100 will always return may alias
299   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
300   // which will then no-alias a store to &A[100].
301   AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
302
303   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
304        ++BI)
305     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
306       if (&*I != IgnoredStore &&
307           (AA.getModRefInfo(I, StoreLoc) & Access))
308         return true;
309
310   return false;
311 }
312
313 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
314 /// If we can transform this into a memset in the loop preheader, do so.
315 bool LoopIdiomRecognize::
316 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
317                              Value *SplatValue,
318                              const SCEVAddRecExpr *Ev, const SCEV *BECount) {
319   // Verify that the stored value is loop invariant.  If not, we can't promote
320   // the memset.
321   if (!CurLoop->isLoopInvariant(SplatValue))
322     return false;
323   
324   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
325   // this into a memset 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.  Check for an alias.
328   if (mayLoopAccessLocation(SI->getPointerOperand(), AliasAnalysis::ModRef,
329                             CurLoop, BECount,
330                             StoreSize, getAnalysis<AliasAnalysis>(), SI))
331     return false;
332   
333   // Okay, everything looks good, insert the memset.
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   unsigned AddrSpace = SI->getPointerAddressSpace();
344   Value *BasePtr = 
345     Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
346                            Preheader->getTerminator());
347   
348   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
349   // pointer size if it isn't already.
350   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
351   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
352   if (BESize < TD->getPointerSizeInBits())
353     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
354   else if (BESize > TD->getPointerSizeInBits())
355     BECount = SE->getTruncateExpr(BECount, IntPtr);
356   
357   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
358                                          true, true /*nooverflow*/);
359   if (StoreSize != 1)
360     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
361                                true, true /*nooverflow*/);
362   
363   Value *NumBytes = 
364     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
365   
366   Value *NewCall =
367     Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
368   
369   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
370                << "    from store to: " << *Ev << " at: " << *SI << "\n");
371   (void)NewCall;
372   
373   // Okay, the memset has been formed.  Zap the original store and anything that
374   // feeds into it.
375   DeleteDeadInstruction(SI, *SE);
376   ++NumMemSet;
377   return true;
378 }
379
380 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
381 /// same-strided load.
382 bool LoopIdiomRecognize::
383 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
384                            const SCEVAddRecExpr *StoreEv,
385                            const SCEVAddRecExpr *LoadEv,
386                            const SCEV *BECount) {
387   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
388   
389   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
390   // this into a memcpy in the loop preheader now if we want.  However, this
391   // would be unsafe to do if there is anything else in the loop that may read
392   // or write to the stored location (including the load feeding the stores).
393   // Check for an alias.
394   if (mayLoopAccessLocation(SI->getPointerOperand(), AliasAnalysis::ModRef,
395                             CurLoop, BECount, StoreSize,
396                             getAnalysis<AliasAnalysis>(), SI))
397     return false;
398
399   // For a memcpy, we have to make sure that the input array is not being
400   // mutated by the loop.
401   if (mayLoopAccessLocation(LI->getPointerOperand(), AliasAnalysis::Mod,
402                             CurLoop, BECount, StoreSize,
403                             getAnalysis<AliasAnalysis>(), SI))
404     return false;
405   
406   // Okay, everything looks good, insert the memcpy.
407   BasicBlock *Preheader = CurLoop->getLoopPreheader();
408   
409   IRBuilder<> Builder(Preheader->getTerminator());
410   
411   // The trip count of the loop and the base pointer of the addrec SCEV is
412   // guaranteed to be loop invariant, which means that it should dominate the
413   // header.  Just insert code for it in the preheader.
414   SCEVExpander Expander(*SE);
415
416   Value *LoadBasePtr = 
417     Expander.expandCodeFor(LoadEv->getStart(),
418                            Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
419                            Preheader->getTerminator());
420   Value *StoreBasePtr = 
421     Expander.expandCodeFor(StoreEv->getStart(),
422                            Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
423                            Preheader->getTerminator());
424   
425   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
426   // pointer size if it isn't already.
427   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
428   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
429   if (BESize < TD->getPointerSizeInBits())
430     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
431   else if (BESize > TD->getPointerSizeInBits())
432     BECount = SE->getTruncateExpr(BECount, IntPtr);
433   
434   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
435                                          true, true /*nooverflow*/);
436   if (StoreSize != 1)
437     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
438                                true, true /*nooverflow*/);
439   
440   Value *NumBytes =
441     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
442   
443   Value *NewCall =
444     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
445                          std::min(SI->getAlignment(), LI->getAlignment()));
446   
447   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
448                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
449                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
450   (void)NewCall;
451   
452   // Okay, the memset has been formed.  Zap the original store and anything that
453   // feeds into it.
454   DeleteDeadInstruction(SI, *SE);
455   ++NumMemCpy;
456   return true;
457 }