d4d4b57692425321e1d54c462e995a61b7e9c7c5
[oota-llvm.git] / lib / Transforms / Scalar / MemCpyOptimizer.cpp
1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
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 performs various transformations related to eliminating memcpy
11 // calls, or transforming sets of stores into memset's.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "memcpyopt"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetData.h"
29 #include <list>
30 using namespace llvm;
31
32 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
33 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
34 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
35
36 /// isBytewiseValue - If the specified value can be set by repeating the same
37 /// byte in memory, return the i8 value that it is represented with.  This is
38 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
39 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
40 /// byte store (e.g. i16 0x1234), return null.
41 static Value *isBytewiseValue(Value *V) {
42   LLVMContext &Context = V->getContext();
43   
44   // All byte-wide stores are splatable, even of arbitrary variables.
45   if (V->getType()->isIntegerTy(8)) return V;
46   
47   // Constant float and double values can be handled as integer values if the
48   // corresponding integer value is "byteable".  An important case is 0.0. 
49   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
50     if (CFP->getType()->isFloatTy())
51       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(Context));
52     if (CFP->getType()->isDoubleTy())
53       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(Context));
54     // Don't handle long double formats, which have strange constraints.
55   }
56   
57   // We can handle constant integers that are power of two in size and a 
58   // multiple of 8 bits.
59   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
60     unsigned Width = CI->getBitWidth();
61     if (isPowerOf2_32(Width) && Width > 8) {
62       // We can handle this value if the recursive binary decomposition is the
63       // same at all levels.
64       APInt Val = CI->getValue();
65       APInt Val2;
66       while (Val.getBitWidth() != 8) {
67         unsigned NextWidth = Val.getBitWidth()/2;
68         Val2  = Val.lshr(NextWidth);
69         Val2.trunc(Val.getBitWidth()/2);
70         Val.trunc(Val.getBitWidth()/2);
71
72         // If the top/bottom halves aren't the same, reject it.
73         if (Val != Val2)
74           return 0;
75       }
76       return ConstantInt::get(Context, Val);
77     }
78   }
79   
80   // Conceptually, we could handle things like:
81   //   %a = zext i8 %X to i16
82   //   %b = shl i16 %a, 8
83   //   %c = or i16 %a, %b
84   // but until there is an example that actually needs this, it doesn't seem
85   // worth worrying about.
86   return 0;
87 }
88
89 static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
90                                   bool &VariableIdxFound, TargetData &TD) {
91   // Skip over the first indices.
92   gep_type_iterator GTI = gep_type_begin(GEP);
93   for (unsigned i = 1; i != Idx; ++i, ++GTI)
94     /*skip along*/;
95   
96   // Compute the offset implied by the rest of the indices.
97   int64_t Offset = 0;
98   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
99     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
100     if (OpC == 0)
101       return VariableIdxFound = true;
102     if (OpC->isZero()) continue;  // No offset.
103
104     // Handle struct indices, which add their field offset to the pointer.
105     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
106       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
107       continue;
108     }
109     
110     // Otherwise, we have a sequential type like an array or vector.  Multiply
111     // the index by the ElementSize.
112     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
113     Offset += Size*OpC->getSExtValue();
114   }
115
116   return Offset;
117 }
118
119 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
120 /// constant offset, and return that constant offset.  For example, Ptr1 might
121 /// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
122 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
123                             TargetData &TD) {
124   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
125   // base.  After that base, they may have some number of common (and
126   // potentially variable) indices.  After that they handle some constant
127   // offset, which determines their offset from each other.  At this point, we
128   // handle no other case.
129   GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
130   GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
131   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
132     return false;
133   
134   // Skip any common indices and track the GEP types.
135   unsigned Idx = 1;
136   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
137     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
138       break;
139
140   bool VariableIdxFound = false;
141   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
142   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
143   if (VariableIdxFound) return false;
144   
145   Offset = Offset2-Offset1;
146   return true;
147 }
148
149
150 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
151 /// This allows us to analyze stores like:
152 ///   store 0 -> P+1
153 ///   store 0 -> P+0
154 ///   store 0 -> P+3
155 ///   store 0 -> P+2
156 /// which sometimes happens with stores to arrays of structs etc.  When we see
157 /// the first store, we make a range [1, 2).  The second store extends the range
158 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
159 /// two ranges into [0, 3) which is memset'able.
160 namespace {
161 struct MemsetRange {
162   // Start/End - A semi range that describes the span that this range covers.
163   // The range is closed at the start and open at the end: [Start, End).  
164   int64_t Start, End;
165
166   /// StartPtr - The getelementptr instruction that points to the start of the
167   /// range.
168   Value *StartPtr;
169   
170   /// Alignment - The known alignment of the first store.
171   unsigned Alignment;
172   
173   /// TheStores - The actual stores that make up this range.
174   SmallVector<StoreInst*, 16> TheStores;
175   
176   bool isProfitableToUseMemset(const TargetData &TD) const;
177
178 };
179 } // end anon namespace
180
181 bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
182   // If we found more than 8 stores to merge or 64 bytes, use memset.
183   if (TheStores.size() >= 8 || End-Start >= 64) return true;
184   
185   // Assume that the code generator is capable of merging pairs of stores
186   // together if it wants to.
187   if (TheStores.size() <= 2) return false;
188   
189   // If we have fewer than 8 stores, it can still be worthwhile to do this.
190   // For example, merging 4 i8 stores into an i32 store is useful almost always.
191   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
192   // memset will be split into 2 32-bit stores anyway) and doing so can
193   // pessimize the llvm optimizer.
194   //
195   // Since we don't have perfect knowledge here, make some assumptions: assume
196   // the maximum GPR width is the same size as the pointer size and assume that
197   // this width can be stored.  If so, check to see whether we will end up
198   // actually reducing the number of stores used.
199   unsigned Bytes = unsigned(End-Start);
200   unsigned NumPointerStores = Bytes/TD.getPointerSize();
201   
202   // Assume the remaining bytes if any are done a byte at a time.
203   unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
204   
205   // If we will reduce the # stores (according to this heuristic), do the
206   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
207   // etc.
208   return TheStores.size() > NumPointerStores+NumByteStores;
209 }    
210
211
212 namespace {
213 class MemsetRanges {
214   /// Ranges - A sorted list of the memset ranges.  We use std::list here
215   /// because each element is relatively large and expensive to copy.
216   std::list<MemsetRange> Ranges;
217   typedef std::list<MemsetRange>::iterator range_iterator;
218   TargetData &TD;
219 public:
220   MemsetRanges(TargetData &td) : TD(td) {}
221   
222   typedef std::list<MemsetRange>::const_iterator const_iterator;
223   const_iterator begin() const { return Ranges.begin(); }
224   const_iterator end() const { return Ranges.end(); }
225   bool empty() const { return Ranges.empty(); }
226   
227   void addStore(int64_t OffsetFromFirst, StoreInst *SI);
228 };
229   
230 } // end anon namespace
231
232
233 /// addStore - Add a new store to the MemsetRanges data structure.  This adds a
234 /// new range for the specified store at the specified offset, merging into
235 /// existing ranges as appropriate.
236 void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
237   int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
238   
239   // Do a linear search of the ranges to see if this can be joined and/or to
240   // find the insertion point in the list.  We keep the ranges sorted for
241   // simplicity here.  This is a linear search of a linked list, which is ugly,
242   // however the number of ranges is limited, so this won't get crazy slow.
243   range_iterator I = Ranges.begin(), E = Ranges.end();
244   
245   while (I != E && Start > I->End)
246     ++I;
247   
248   // We now know that I == E, in which case we didn't find anything to merge
249   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
250   // to insert a new range.  Handle this now.
251   if (I == E || End < I->Start) {
252     MemsetRange &R = *Ranges.insert(I, MemsetRange());
253     R.Start        = Start;
254     R.End          = End;
255     R.StartPtr     = SI->getPointerOperand();
256     R.Alignment    = SI->getAlignment();
257     R.TheStores.push_back(SI);
258     return;
259   }
260
261   // This store overlaps with I, add it.
262   I->TheStores.push_back(SI);
263   
264   // At this point, we may have an interval that completely contains our store.
265   // If so, just add it to the interval and return.
266   if (I->Start <= Start && I->End >= End)
267     return;
268   
269   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
270   // but is not entirely contained within the range.
271   
272   // See if the range extends the start of the range.  In this case, it couldn't
273   // possibly cause it to join the prior range, because otherwise we would have
274   // stopped on *it*.
275   if (Start < I->Start) {
276     I->Start = Start;
277     I->StartPtr = SI->getPointerOperand();
278     I->Alignment = SI->getAlignment();
279   }
280     
281   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
282   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
283   // End.
284   if (End > I->End) {
285     I->End = End;
286     range_iterator NextI = I;
287     while (++NextI != E && End >= NextI->Start) {
288       // Merge the range in.
289       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
290       if (NextI->End > I->End)
291         I->End = NextI->End;
292       Ranges.erase(NextI);
293       NextI = I;
294     }
295   }
296 }
297
298 //===----------------------------------------------------------------------===//
299 //                         MemCpyOpt Pass
300 //===----------------------------------------------------------------------===//
301
302 namespace {
303   class MemCpyOpt : public FunctionPass {
304     bool runOnFunction(Function &F);
305   public:
306     static char ID; // Pass identification, replacement for typeid
307     MemCpyOpt() : FunctionPass(ID) {}
308
309   private:
310     // This transformation requires dominator postdominator info
311     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
312       AU.setPreservesCFG();
313       AU.addRequired<DominatorTree>();
314       AU.addRequired<MemoryDependenceAnalysis>();
315       AU.addRequired<AliasAnalysis>();
316       AU.addPreserved<AliasAnalysis>();
317       AU.addPreserved<MemoryDependenceAnalysis>();
318     }
319   
320     // Helper fuctions
321     bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
322     bool processMemCpy(MemCpyInst *M);
323     bool processMemMove(MemMoveInst *M);
324     bool performCallSlotOptzn(MemCpyInst *cpy, CallInst *C);
325     bool iterateOnFunction(Function &F);
326   };
327   
328   char MemCpyOpt::ID = 0;
329 }
330
331 // createMemCpyOptPass - The public interface to this file...
332 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
333
334 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
335                       false, false)
336 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
337 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
338 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
339 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
340                     false, false)
341
342
343 /// processStore - When GVN is scanning forward over instructions, we look for
344 /// some other patterns to fold away.  In particular, this looks for stores to
345 /// neighboring locations of memory.  If it sees enough consequtive ones
346 /// (currently 4) it attempts to merge them together into a memcpy/memset.
347 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
348   if (SI->isVolatile()) return false;
349   
350   LLVMContext &Context = SI->getContext();
351
352   // There are two cases that are interesting for this code to handle: memcpy
353   // and memset.  Right now we only handle memset.
354   
355   // Ensure that the value being stored is something that can be memset'able a
356   // byte at a time like "0" or "-1" or any width, as well as things like
357   // 0xA0A0A0A0 and 0.0.
358   Value *ByteVal = isBytewiseValue(SI->getOperand(0));
359   if (!ByteVal)
360     return false;
361
362   TargetData *TD = getAnalysisIfAvailable<TargetData>();
363   if (!TD) return false;
364   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
365   Module *M = SI->getParent()->getParent()->getParent();
366
367   // Okay, so we now have a single store that can be splatable.  Scan to find
368   // all subsequent stores of the same value to offset from the same pointer.
369   // Join these together into ranges, so we can decide whether contiguous blocks
370   // are stored.
371   MemsetRanges Ranges(*TD);
372   
373   Value *StartPtr = SI->getPointerOperand();
374   
375   BasicBlock::iterator BI = SI;
376   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
377     if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) { 
378       // If the call is readnone, ignore it, otherwise bail out.  We don't even
379       // allow readonly here because we don't want something like:
380       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
381       if (AA.getModRefBehavior(CallSite(BI)) ==
382             AliasAnalysis::DoesNotAccessMemory)
383         continue;
384       
385       // TODO: If this is a memset, try to join it in.
386       
387       break;
388     } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
389       break;
390
391     // If this is a non-store instruction it is fine, ignore it.
392     StoreInst *NextStore = dyn_cast<StoreInst>(BI);
393     if (NextStore == 0) continue;
394     
395     // If this is a store, see if we can merge it in.
396     if (NextStore->isVolatile()) break;
397     
398     // Check to see if this stored value is of the same byte-splattable value.
399     if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
400       break;
401
402     // Check to see if this store is to a constant offset from the start ptr.
403     int64_t Offset;
404     if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
405       break;
406
407     Ranges.addStore(Offset, NextStore);
408   }
409
410   // If we have no ranges, then we just had a single store with nothing that
411   // could be merged in.  This is a very common case of course.
412   if (Ranges.empty())
413     return false;
414   
415   // If we had at least one store that could be merged in, add the starting
416   // store as well.  We try to avoid this unless there is at least something
417   // interesting as a small compile-time optimization.
418   Ranges.addStore(0, SI);
419   
420   
421   // Now that we have full information about ranges, loop over the ranges and
422   // emit memset's for anything big enough to be worthwhile.
423   bool MadeChange = false;
424   for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
425        I != E; ++I) {
426     const MemsetRange &Range = *I;
427
428     if (Range.TheStores.size() == 1) continue;
429     
430     // If it is profitable to lower this range to memset, do so now.
431     if (!Range.isProfitableToUseMemset(*TD))
432       continue;
433     
434     // Otherwise, we do want to transform this!  Create a new memset.  We put
435     // the memset right before the first instruction that isn't part of this
436     // memset block.  This ensure that the memset is dominated by any addressing
437     // instruction needed by the start of the block.
438     BasicBlock::iterator InsertPt = BI;
439
440     // Get the starting pointer of the block.
441     StartPtr = Range.StartPtr;
442
443     // Determine alignment
444     unsigned Alignment = Range.Alignment;
445     if (Alignment == 0) {
446       const Type *EltType = 
447          cast<PointerType>(StartPtr->getType())->getElementType();
448       Alignment = TD->getABITypeAlignment(EltType);
449     }
450
451     // Cast the start ptr to be i8* as memset requires.
452     const PointerType* StartPTy = cast<PointerType>(StartPtr->getType());
453     const PointerType *i8Ptr = Type::getInt8PtrTy(Context,
454                                                   StartPTy->getAddressSpace());
455     if (StartPTy!= i8Ptr)
456       StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getName(),
457                                  InsertPt);
458
459     Value *Ops[] = {
460       StartPtr, ByteVal,   // Start, value
461       // size
462       ConstantInt::get(Type::getInt64Ty(Context), Range.End-Range.Start),
463       // align
464       ConstantInt::get(Type::getInt32Ty(Context), Alignment),
465       // volatile
466       ConstantInt::get(Type::getInt1Ty(Context), 0),
467     };
468     const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
469
470     Function *MemSetF = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
471
472     Value *C = CallInst::Create(MemSetF, Ops, Ops+5, "", InsertPt);
473     DEBUG(dbgs() << "Replace stores:\n";
474           for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
475             dbgs() << *Range.TheStores[i];
476           dbgs() << "With: " << *C); C=C;
477   
478     // Don't invalidate the iterator
479     BBI = BI;
480   
481     // Zap all the stores.
482     for (SmallVector<StoreInst*, 16>::const_iterator
483          SI = Range.TheStores.begin(),
484          SE = Range.TheStores.end(); SI != SE; ++SI)
485       (*SI)->eraseFromParent();
486     ++NumMemSetInfer;
487     MadeChange = true;
488   }
489   
490   return MadeChange;
491 }
492
493
494 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
495 /// and checks for the possibility of a call slot optimization by having
496 /// the call write its result directly into the destination of the memcpy.
497 bool MemCpyOpt::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C) {
498   // The general transformation to keep in mind is
499   //
500   //   call @func(..., src, ...)
501   //   memcpy(dest, src, ...)
502   //
503   // ->
504   //
505   //   memcpy(dest, src, ...)
506   //   call @func(..., dest, ...)
507   //
508   // Since moving the memcpy is technically awkward, we additionally check that
509   // src only holds uninitialized values at the moment of the call, meaning that
510   // the memcpy can be discarded rather than moved.
511
512   // Deliberately get the source and destination with bitcasts stripped away,
513   // because we'll need to do type comparisons based on the underlying type.
514   Value *cpyDest = cpy->getDest();
515   Value *cpySrc = cpy->getSource();
516   CallSite CS(C);
517
518   // We need to be able to reason about the size of the memcpy, so we require
519   // that it be a constant.
520   ConstantInt *cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
521   if (!cpyLength)
522     return false;
523
524   // Require that src be an alloca.  This simplifies the reasoning considerably.
525   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
526   if (!srcAlloca)
527     return false;
528
529   // Check that all of src is copied to dest.
530   TargetData *TD = getAnalysisIfAvailable<TargetData>();
531   if (!TD) return false;
532
533   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
534   if (!srcArraySize)
535     return false;
536
537   uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
538     srcArraySize->getZExtValue();
539
540   if (cpyLength->getZExtValue() < srcSize)
541     return false;
542
543   // Check that accessing the first srcSize bytes of dest will not cause a
544   // trap.  Otherwise the transform is invalid since it might cause a trap
545   // to occur earlier than it otherwise would.
546   if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
547     // The destination is an alloca.  Check it is larger than srcSize.
548     ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
549     if (!destArraySize)
550       return false;
551
552     uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
553       destArraySize->getZExtValue();
554
555     if (destSize < srcSize)
556       return false;
557   } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
558     // If the destination is an sret parameter then only accesses that are
559     // outside of the returned struct type can trap.
560     if (!A->hasStructRetAttr())
561       return false;
562
563     const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
564     uint64_t destSize = TD->getTypeAllocSize(StructTy);
565
566     if (destSize < srcSize)
567       return false;
568   } else {
569     return false;
570   }
571
572   // Check that src is not accessed except via the call and the memcpy.  This
573   // guarantees that it holds only undefined values when passed in (so the final
574   // memcpy can be dropped), that it is not read or written between the call and
575   // the memcpy, and that writing beyond the end of it is undefined.
576   SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
577                                    srcAlloca->use_end());
578   while (!srcUseList.empty()) {
579     User *UI = srcUseList.pop_back_val();
580
581     if (isa<BitCastInst>(UI)) {
582       for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
583            I != E; ++I)
584         srcUseList.push_back(*I);
585     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
586       if (G->hasAllZeroIndices())
587         for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
588              I != E; ++I)
589           srcUseList.push_back(*I);
590       else
591         return false;
592     } else if (UI != C && UI != cpy) {
593       return false;
594     }
595   }
596
597   // Since we're changing the parameter to the callsite, we need to make sure
598   // that what would be the new parameter dominates the callsite.
599   DominatorTree &DT = getAnalysis<DominatorTree>();
600   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
601     if (!DT.dominates(cpyDestInst, C))
602       return false;
603
604   // In addition to knowing that the call does not access src in some
605   // unexpected manner, for example via a global, which we deduce from
606   // the use analysis, we also need to know that it does not sneakily
607   // access dest.  We rely on AA to figure this out for us.
608   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
609   if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
610       AliasAnalysis::NoModRef)
611     return false;
612
613   // All the checks have passed, so do the transformation.
614   bool changedArgument = false;
615   for (unsigned i = 0; i < CS.arg_size(); ++i)
616     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
617       if (cpySrc->getType() != cpyDest->getType())
618         cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
619                                               cpyDest->getName(), C);
620       changedArgument = true;
621       if (CS.getArgument(i)->getType() == cpyDest->getType())
622         CS.setArgument(i, cpyDest);
623       else
624         CS.setArgument(i, CastInst::CreatePointerCast(cpyDest, 
625                           CS.getArgument(i)->getType(), cpyDest->getName(), C));
626     }
627
628   if (!changedArgument)
629     return false;
630
631   // Drop any cached information about the call, because we may have changed
632   // its dependence information by changing its parameter.
633   MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
634   MD.removeInstruction(C);
635
636   // Remove the memcpy
637   MD.removeInstruction(cpy);
638   cpy->eraseFromParent();
639   ++NumMemCpyInstr;
640
641   return true;
642 }
643
644 /// processMemCpy - perform simplification of memcpy's.  If we have memcpy A
645 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
646 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
647 /// circumstances). This allows later passes to remove the first memcpy
648 /// altogether.
649 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
650   MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
651
652   // The are two possible optimizations we can do for memcpy:
653   //   a) memcpy-memcpy xform which exposes redundance for DSE.
654   //   b) call-memcpy xform for return slot optimization.
655   MemDepResult dep = MD.getDependency(M);
656   if (!dep.isClobber())
657     return false;
658   if (!isa<MemCpyInst>(dep.getInst())) {
659     if (CallInst *C = dyn_cast<CallInst>(dep.getInst()))
660       return performCallSlotOptzn(M, C);
661     return false;
662   }
663   
664   MemCpyInst *MDep = cast<MemCpyInst>(dep.getInst());
665   
666   // We can only transforms memcpy's where the dest of one is the source of the
667   // other
668   if (M->getSource() != MDep->getDest())
669     return false;
670   
671   // Second, the length of the memcpy's must be the same, or the preceeding one
672   // must be larger than the following one.
673   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
674   ConstantInt *C2 = dyn_cast<ConstantInt>(M->getLength());
675   if (!C1 || !C2)
676     return false;
677   
678   uint64_t DepSize = C1->getValue().getZExtValue();
679   uint64_t CpySize = C2->getValue().getZExtValue();
680   
681   if (DepSize < CpySize)
682     return false;
683   
684   // Finally, we have to make sure that the dest of the second does not
685   // alias the source of the first
686   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
687   if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
688       AliasAnalysis::NoAlias)
689     return false;
690   else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
691            AliasAnalysis::NoAlias)
692     return false;
693   else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
694            != AliasAnalysis::NoAlias)
695     return false;
696   
697   // If all checks passed, then we can transform these memcpy's
698   const Type *ArgTys[3] = { M->getRawDest()->getType(),
699                             MDep->getRawSource()->getType(),
700                             M->getLength()->getType() };
701   Function *MemCpyFun = Intrinsic::getDeclaration(
702                                  M->getParent()->getParent()->getParent(),
703                                  M->getIntrinsicID(), ArgTys, 3);
704     
705   // Make sure to use the lesser of the alignment of the source and the dest
706   // since we're changing where we're reading from, but don't want to increase
707   // the alignment past what can be read from or written to.
708   // TODO: Is this worth it if we're creating a less aligned memcpy? For
709   // example we could be moving from movaps -> movq on x86.
710   unsigned Align = std::min(MDep->getAlignmentCst()->getZExtValue(),
711                             M->getAlignmentCst()->getZExtValue());
712   LLVMContext &Context = M->getContext();
713   ConstantInt *AlignCI = ConstantInt::get(Type::getInt32Ty(Context), Align);
714   Value *Args[5] = {
715     M->getRawDest(), MDep->getRawSource(), M->getLength(),
716     AlignCI, M->getVolatileCst()
717   };
718   CallInst *C = CallInst::Create(MemCpyFun, Args, Args+5, "", M);
719   
720   // If C and M don't interfere, then this is a valid transformation.  If they
721   // did, this would mean that the two sources overlap, which would be bad.
722   if (MD.getDependency(C) == dep) {
723     MD.removeInstruction(M);
724     M->eraseFromParent();
725     ++NumMemCpyInstr;
726     return true;
727   }
728   
729   // Otherwise, there was no point in doing this, so we remove the call we
730   // inserted and act like nothing happened.
731   MD.removeInstruction(C);
732   C->eraseFromParent();
733   return false;
734 }
735
736 /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
737 /// are guaranteed not to alias.
738 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
739   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
740
741   // If the memmove is a constant size, use it for the alias query, this allows
742   // us to optimize things like: memmove(P, P+64, 64);
743   uint64_t MemMoveSize = ~0ULL;
744   if (ConstantInt *Len = dyn_cast<ConstantInt>(M->getLength()))
745     MemMoveSize = Len->getZExtValue();
746   
747   // See if the pointers alias.
748   if (AA.alias(M->getRawDest(), MemMoveSize, M->getRawSource(), MemMoveSize) !=
749       AliasAnalysis::NoAlias)
750     return false;
751   
752   DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
753   
754   // If not, then we know we can transform this.
755   Module *Mod = M->getParent()->getParent()->getParent();
756   const Type *ArgTys[3] = { M->getRawDest()->getType(),
757                             M->getRawSource()->getType(),
758                             M->getLength()->getType() };
759   M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
760                                                  ArgTys, 3));
761
762   // MemDep may have over conservative information about this instruction, just
763   // conservatively flush it from the cache.
764   getAnalysis<MemoryDependenceAnalysis>().removeInstruction(M);
765
766   ++NumMoveToCpy;
767   return true;
768 }
769   
770
771 // MemCpyOpt::iterateOnFunction - Executes one iteration of GVN.
772 bool MemCpyOpt::iterateOnFunction(Function &F) {
773   bool MadeChange = false;
774
775   // Walk all instruction in the function.
776   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
777     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
778          BI != BE;) {
779       // Avoid invalidating the iterator.
780       Instruction *I = BI++;
781       
782       if (StoreInst *SI = dyn_cast<StoreInst>(I))
783         MadeChange |= processStore(SI, BI);
784       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
785         MadeChange |= processMemCpy(M);
786       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) {
787         if (processMemMove(M)) {
788           --BI;         // Reprocess the new memcpy.
789           MadeChange = true;
790         }
791       }
792     }
793   }
794   
795   return MadeChange;
796 }
797
798 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
799 // function.
800 //
801 bool MemCpyOpt::runOnFunction(Function &F) {
802   bool MadeChange = false;
803   while (1) {
804     if (!iterateOnFunction(F))
805       break;
806     MadeChange = true;
807   }
808   
809   return MadeChange;
810 }
811
812
813