LLVM API Documentation

MemCpyOptimizer.cpp

Go to the documentation of this file.
00001 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs various transformations related to eliminating memcpy
00011 // calls, or transforming sets of stores into memset's.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "memcpyopt"
00016 #include "llvm/Transforms/Scalar.h"
00017 #include "llvm/IntrinsicInst.h"
00018 #include "llvm/Instructions.h"
00019 #include "llvm/LLVMContext.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/Dominators.h"
00023 #include "llvm/Analysis/AliasAnalysis.h"
00024 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/Support/GetElementPtrTypeIterator.h"
00027 #include "llvm/Target/TargetData.h"
00028 #include <list>
00029 using namespace llvm;
00030 
00031 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
00032 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
00033 
00034 /// isBytewiseValue - If the specified value can be set by repeating the same
00035 /// byte in memory, return the i8 value that it is represented with.  This is
00036 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
00037 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
00038 /// byte store (e.g. i16 0x1234), return null.
00039 static Value *isBytewiseValue(Value *V, LLVMContext& Context) {
00040   // All byte-wide stores are splatable, even of arbitrary variables.
00041   if (V->getType() == Type::getInt8Ty(Context)) return V;
00042   
00043   // Constant float and double values can be handled as integer values if the
00044   // corresponding integer value is "byteable".  An important case is 0.0. 
00045   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
00046     if (CFP->getType() == Type::getFloatTy(Context))
00047       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(Context));
00048     if (CFP->getType() == Type::getDoubleTy(Context))
00049       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(Context));
00050     // Don't handle long double formats, which have strange constraints.
00051   }
00052   
00053   // We can handle constant integers that are power of two in size and a 
00054   // multiple of 8 bits.
00055   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00056     unsigned Width = CI->getBitWidth();
00057     if (isPowerOf2_32(Width) && Width > 8) {
00058       // We can handle this value if the recursive binary decomposition is the
00059       // same at all levels.
00060       APInt Val = CI->getValue();
00061       APInt Val2;
00062       while (Val.getBitWidth() != 8) {
00063         unsigned NextWidth = Val.getBitWidth()/2;
00064         Val2  = Val.lshr(NextWidth);
00065         Val2.trunc(Val.getBitWidth()/2);
00066         Val.trunc(Val.getBitWidth()/2);
00067 
00068         // If the top/bottom halves aren't the same, reject it.
00069         if (Val != Val2)
00070           return 0;
00071       }
00072       return ConstantInt::get(Context, Val);
00073     }
00074   }
00075   
00076   // Conceptually, we could handle things like:
00077   //   %a = zext i8 %X to i16
00078   //   %b = shl i16 %a, 8
00079   //   %c = or i16 %a, %b
00080   // but until there is an example that actually needs this, it doesn't seem
00081   // worth worrying about.
00082   return 0;
00083 }
00084 
00085 static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
00086                                   bool &VariableIdxFound, TargetData &TD) {
00087   // Skip over the first indices.
00088   gep_type_iterator GTI = gep_type_begin(GEP);
00089   for (unsigned i = 1; i != Idx; ++i, ++GTI)
00090     /*skip along*/;
00091   
00092   // Compute the offset implied by the rest of the indices.
00093   int64_t Offset = 0;
00094   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
00095     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
00096     if (OpC == 0)
00097       return VariableIdxFound = true;
00098     if (OpC->isZero()) continue;  // No offset.
00099 
00100     // Handle struct indices, which add their field offset to the pointer.
00101     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
00102       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
00103       continue;
00104     }
00105     
00106     // Otherwise, we have a sequential type like an array or vector.  Multiply
00107     // the index by the ElementSize.
00108     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
00109     Offset += Size*OpC->getSExtValue();
00110   }
00111 
00112   return Offset;
00113 }
00114 
00115 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
00116 /// constant offset, and return that constant offset.  For example, Ptr1 might
00117 /// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
00118 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
00119                             TargetData &TD) {
00120   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
00121   // base.  After that base, they may have some number of common (and
00122   // potentially variable) indices.  After that they handle some constant
00123   // offset, which determines their offset from each other.  At this point, we
00124   // handle no other case.
00125   GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
00126   GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
00127   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
00128     return false;
00129   
00130   // Skip any common indices and track the GEP types.
00131   unsigned Idx = 1;
00132   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
00133     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
00134       break;
00135 
00136   bool VariableIdxFound = false;
00137   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
00138   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
00139   if (VariableIdxFound) return false;
00140   
00141   Offset = Offset2-Offset1;
00142   return true;
00143 }
00144 
00145 
00146 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
00147 /// This allows us to analyze stores like:
00148 ///   store 0 -> P+1
00149 ///   store 0 -> P+0
00150 ///   store 0 -> P+3
00151 ///   store 0 -> P+2
00152 /// which sometimes happens with stores to arrays of structs etc.  When we see
00153 /// the first store, we make a range [1, 2).  The second store extends the range
00154 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
00155 /// two ranges into [0, 3) which is memset'able.
00156 namespace {
00157 struct MemsetRange {
00158   // Start/End - A semi range that describes the span that this range covers.
00159   // The range is closed at the start and open at the end: [Start, End).  
00160   int64_t Start, End;
00161 
00162   /// StartPtr - The getelementptr instruction that points to the start of the
00163   /// range.
00164   Value *StartPtr;
00165   
00166   /// Alignment - The known alignment of the first store.
00167   unsigned Alignment;
00168   
00169   /// TheStores - The actual stores that make up this range.
00170   SmallVector<StoreInst*, 16> TheStores;
00171   
00172   bool isProfitableToUseMemset(const TargetData &TD) const;
00173 
00174 };
00175 } // end anon namespace
00176 
00177 bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
00178   // If we found more than 8 stores to merge or 64 bytes, use memset.
00179   if (TheStores.size() >= 8 || End-Start >= 64) return true;
00180   
00181   // Assume that the code generator is capable of merging pairs of stores
00182   // together if it wants to.
00183   if (TheStores.size() <= 2) return false;
00184   
00185   // If we have fewer than 8 stores, it can still be worthwhile to do this.
00186   // For example, merging 4 i8 stores into an i32 store is useful almost always.
00187   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
00188   // memset will be split into 2 32-bit stores anyway) and doing so can
00189   // pessimize the llvm optimizer.
00190   //
00191   // Since we don't have perfect knowledge here, make some assumptions: assume
00192   // the maximum GPR width is the same size as the pointer size and assume that
00193   // this width can be stored.  If so, check to see whether we will end up
00194   // actually reducing the number of stores used.
00195   unsigned Bytes = unsigned(End-Start);
00196   unsigned NumPointerStores = Bytes/TD.getPointerSize();
00197   
00198   // Assume the remaining bytes if any are done a byte at a time.
00199   unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
00200   
00201   // If we will reduce the # stores (according to this heuristic), do the
00202   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
00203   // etc.
00204   return TheStores.size() > NumPointerStores+NumByteStores;
00205 }    
00206 
00207 
00208 namespace {
00209 class MemsetRanges {
00210   /// Ranges - A sorted list of the memset ranges.  We use std::list here
00211   /// because each element is relatively large and expensive to copy.
00212   std::list<MemsetRange> Ranges;
00213   typedef std::list<MemsetRange>::iterator range_iterator;
00214   TargetData &TD;
00215 public:
00216   MemsetRanges(TargetData &td) : TD(td) {}
00217   
00218   typedef std::list<MemsetRange>::const_iterator const_iterator;
00219   const_iterator begin() const { return Ranges.begin(); }
00220   const_iterator end() const { return Ranges.end(); }
00221   bool empty() const { return Ranges.empty(); }
00222   
00223   void addStore(int64_t OffsetFromFirst, StoreInst *SI);
00224 };
00225   
00226 } // end anon namespace
00227 
00228 
00229 /// addStore - Add a new store to the MemsetRanges data structure.  This adds a
00230 /// new range for the specified store at the specified offset, merging into
00231 /// existing ranges as appropriate.
00232 void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
00233   int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
00234   
00235   // Do a linear search of the ranges to see if this can be joined and/or to
00236   // find the insertion point in the list.  We keep the ranges sorted for
00237   // simplicity here.  This is a linear search of a linked list, which is ugly,
00238   // however the number of ranges is limited, so this won't get crazy slow.
00239   range_iterator I = Ranges.begin(), E = Ranges.end();
00240   
00241   while (I != E && Start > I->End)
00242     ++I;
00243   
00244   // We now know that I == E, in which case we didn't find anything to merge
00245   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
00246   // to insert a new range.  Handle this now.
00247   if (I == E || End < I->Start) {
00248     MemsetRange &R = *Ranges.insert(I, MemsetRange());
00249     R.Start        = Start;
00250     R.End          = End;
00251     R.StartPtr     = SI->getPointerOperand();
00252     R.Alignment    = SI->getAlignment();
00253     R.TheStores.push_back(SI);
00254     return;
00255   }
00256 
00257   // This store overlaps with I, add it.
00258   I->TheStores.push_back(SI);
00259   
00260   // At this point, we may have an interval that completely contains our store.
00261   // If so, just add it to the interval and return.
00262   if (I->Start <= Start && I->End >= End)
00263     return;
00264   
00265   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
00266   // but is not entirely contained within the range.
00267   
00268   // See if the range extends the start of the range.  In this case, it couldn't
00269   // possibly cause it to join the prior range, because otherwise we would have
00270   // stopped on *it*.
00271   if (Start < I->Start) {
00272     I->Start = Start;
00273     I->StartPtr = SI->getPointerOperand();
00274     I->Alignment = SI->getAlignment();
00275   }
00276     
00277   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
00278   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
00279   // End.
00280   if (End > I->End) {
00281     I->End = End;
00282     range_iterator NextI = I;
00283     while (++NextI != E && End >= NextI->Start) {
00284       // Merge the range in.
00285       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
00286       if (NextI->End > I->End)
00287         I->End = NextI->End;
00288       Ranges.erase(NextI);
00289       NextI = I;
00290     }
00291   }
00292 }
00293 
00294 //===----------------------------------------------------------------------===//
00295 //                         MemCpyOpt Pass
00296 //===----------------------------------------------------------------------===//
00297 
00298 namespace {
00299 
00300   class VISIBILITY_HIDDEN MemCpyOpt : public FunctionPass {
00301     bool runOnFunction(Function &F);
00302   public:
00303     static char ID; // Pass identification, replacement for typeid
00304     MemCpyOpt() : FunctionPass(&ID) {}
00305 
00306   private:
00307     // This transformation requires dominator postdominator info
00308     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00309       AU.setPreservesCFG();
00310       AU.addRequired<DominatorTree>();
00311       AU.addRequired<MemoryDependenceAnalysis>();
00312       AU.addRequired<AliasAnalysis>();
00313       AU.addPreserved<AliasAnalysis>();
00314       AU.addPreserved<MemoryDependenceAnalysis>();
00315     }
00316   
00317     // Helper fuctions
00318     bool processStore(StoreInst *SI, BasicBlock::iterator& BBI);
00319     bool processMemCpy(MemCpyInst* M);
00320     bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C);
00321     bool iterateOnFunction(Function &F);
00322   };
00323   
00324   char MemCpyOpt::ID = 0;
00325 }
00326 
00327 // createMemCpyOptPass - The public interface to this file...
00328 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
00329 
00330 static RegisterPass<MemCpyOpt> X("memcpyopt",
00331                                  "MemCpy Optimization");
00332 
00333 
00334 
00335 /// processStore - When GVN is scanning forward over instructions, we look for
00336 /// some other patterns to fold away.  In particular, this looks for stores to
00337 /// neighboring locations of memory.  If it sees enough consequtive ones
00338 /// (currently 4) it attempts to merge them together into a memcpy/memset.
00339 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator& BBI) {
00340   if (SI->isVolatile()) return false;
00341   
00342   LLVMContext &Context = SI->getContext();
00343 
00344   // There are two cases that are interesting for this code to handle: memcpy
00345   // and memset.  Right now we only handle memset.
00346   
00347   // Ensure that the value being stored is something that can be memset'able a
00348   // byte at a time like "0" or "-1" or any width, as well as things like
00349   // 0xA0A0A0A0 and 0.0.
00350   Value *ByteVal = isBytewiseValue(SI->getOperand(0), Context);
00351   if (!ByteVal)
00352     return false;
00353 
00354   TargetData *TD = getAnalysisIfAvailable<TargetData>();
00355   if (!TD) return false;
00356   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00357   Module *M = SI->getParent()->getParent()->getParent();
00358 
00359   // Okay, so we now have a single store that can be splatable.  Scan to find
00360   // all subsequent stores of the same value to offset from the same pointer.
00361   // Join these together into ranges, so we can decide whether contiguous blocks
00362   // are stored.
00363   MemsetRanges Ranges(*TD);
00364   
00365   Value *StartPtr = SI->getPointerOperand();
00366   
00367   BasicBlock::iterator BI = SI;
00368   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
00369     if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) { 
00370       // If the call is readnone, ignore it, otherwise bail out.  We don't even
00371       // allow readonly here because we don't want something like:
00372       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
00373       if (AA.getModRefBehavior(CallSite::get(BI)) ==
00374             AliasAnalysis::DoesNotAccessMemory)
00375         continue;
00376       
00377       // TODO: If this is a memset, try to join it in.
00378       
00379       break;
00380     } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
00381       break;
00382 
00383     // If this is a non-store instruction it is fine, ignore it.
00384     StoreInst *NextStore = dyn_cast<StoreInst>(BI);
00385     if (NextStore == 0) continue;
00386     
00387     // If this is a store, see if we can merge it in.
00388     if (NextStore->isVolatile()) break;
00389     
00390     // Check to see if this stored value is of the same byte-splattable value.
00391     if (ByteVal != isBytewiseValue(NextStore->getOperand(0), Context))
00392       break;
00393 
00394     // Check to see if this store is to a constant offset from the start ptr.
00395     int64_t Offset;
00396     if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
00397       break;
00398 
00399     Ranges.addStore(Offset, NextStore);
00400   }
00401 
00402   // If we have no ranges, then we just had a single store with nothing that
00403   // could be merged in.  This is a very common case of course.
00404   if (Ranges.empty())
00405     return false;
00406   
00407   // If we had at least one store that could be merged in, add the starting
00408   // store as well.  We try to avoid this unless there is at least something
00409   // interesting as a small compile-time optimization.
00410   Ranges.addStore(0, SI);
00411   
00412   Function *MemSetF = 0;
00413   
00414   // Now that we have full information about ranges, loop over the ranges and
00415   // emit memset's for anything big enough to be worthwhile.
00416   bool MadeChange = false;
00417   for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
00418        I != E; ++I) {
00419     const MemsetRange &Range = *I;
00420 
00421     if (Range.TheStores.size() == 1) continue;
00422     
00423     // If it is profitable to lower this range to memset, do so now.
00424     if (!Range.isProfitableToUseMemset(*TD))
00425       continue;
00426     
00427     // Otherwise, we do want to transform this!  Create a new memset.  We put
00428     // the memset right before the first instruction that isn't part of this
00429     // memset block.  This ensure that the memset is dominated by any addressing
00430     // instruction needed by the start of the block.
00431     BasicBlock::iterator InsertPt = BI;
00432   
00433     if (MemSetF == 0) {
00434       const Type *Ty = Type::getInt64Ty(Context);
00435       MemSetF = Intrinsic::getDeclaration(M, Intrinsic::memset, &Ty, 1);
00436     }
00437     
00438     // Get the starting pointer of the block.
00439     StartPtr = Range.StartPtr;
00440   
00441     // Cast the start ptr to be i8* as memset requires.
00442     const Type *i8Ptr = PointerType::getUnqual(Type::getInt8Ty(Context));
00443     if (StartPtr->getType() != i8Ptr)
00444       StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getName(),
00445                                  InsertPt);
00446   
00447     Value *Ops[] = {
00448       StartPtr, ByteVal,   // Start, value
00449       // size
00450       ConstantInt::get(Type::getInt64Ty(Context), Range.End-Range.Start),
00451       // align
00452       ConstantInt::get(Type::getInt32Ty(Context), Range.Alignment)
00453     };
00454     Value *C = CallInst::Create(MemSetF, Ops, Ops+4, "", InsertPt);
00455     DEBUG(cerr << "Replace stores:\n";
00456           for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
00457             cerr << *Range.TheStores[i];
00458           cerr << "With: " << *C); C=C;
00459   
00460     // Don't invalidate the iterator
00461     BBI = BI;
00462   
00463     // Zap all the stores.
00464     for (SmallVector<StoreInst*, 16>::const_iterator
00465          SI = Range.TheStores.begin(),
00466          SE = Range.TheStores.end(); SI != SE; ++SI)
00467       (*SI)->eraseFromParent();
00468     ++NumMemSetInfer;
00469     MadeChange = true;
00470   }
00471   
00472   return MadeChange;
00473 }
00474 
00475 
00476 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
00477 /// and checks for the possibility of a call slot optimization by having
00478 /// the call write its result directly into the destination of the memcpy.
00479 bool MemCpyOpt::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C) {
00480   // The general transformation to keep in mind is
00481   //
00482   //   call @func(..., src, ...)
00483   //   memcpy(dest, src, ...)
00484   //
00485   // ->
00486   //
00487   //   memcpy(dest, src, ...)
00488   //   call @func(..., dest, ...)
00489   //
00490   // Since moving the memcpy is technically awkward, we additionally check that
00491   // src only holds uninitialized values at the moment of the call, meaning that
00492   // the memcpy can be discarded rather than moved.
00493 
00494   // Deliberately get the source and destination with bitcasts stripped away,
00495   // because we'll need to do type comparisons based on the underlying type.
00496   Value* cpyDest = cpy->getDest();
00497   Value* cpySrc = cpy->getSource();
00498   CallSite CS = CallSite::get(C);
00499 
00500   // We need to be able to reason about the size of the memcpy, so we require
00501   // that it be a constant.
00502   ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
00503   if (!cpyLength)
00504     return false;
00505 
00506   // Require that src be an alloca.  This simplifies the reasoning considerably.
00507   AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
00508   if (!srcAlloca)
00509     return false;
00510 
00511   // Check that all of src is copied to dest.
00512   TargetData* TD = getAnalysisIfAvailable<TargetData>();
00513   if (!TD) return false;
00514 
00515   ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
00516   if (!srcArraySize)
00517     return false;
00518 
00519   uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
00520     srcArraySize->getZExtValue();
00521 
00522   if (cpyLength->getZExtValue() < srcSize)
00523     return false;
00524 
00525   // Check that accessing the first srcSize bytes of dest will not cause a
00526   // trap.  Otherwise the transform is invalid since it might cause a trap
00527   // to occur earlier than it otherwise would.
00528   if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
00529     // The destination is an alloca.  Check it is larger than srcSize.
00530     ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
00531     if (!destArraySize)
00532       return false;
00533 
00534     uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
00535       destArraySize->getZExtValue();
00536 
00537     if (destSize < srcSize)
00538       return false;
00539   } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
00540     // If the destination is an sret parameter then only accesses that are
00541     // outside of the returned struct type can trap.
00542     if (!A->hasStructRetAttr())
00543       return false;
00544 
00545     const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
00546     uint64_t destSize = TD->getTypeAllocSize(StructTy);
00547 
00548     if (destSize < srcSize)
00549       return false;
00550   } else {
00551     return false;
00552   }
00553 
00554   // Check that src is not accessed except via the call and the memcpy.  This
00555   // guarantees that it holds only undefined values when passed in (so the final
00556   // memcpy can be dropped), that it is not read or written between the call and
00557   // the memcpy, and that writing beyond the end of it is undefined.
00558   SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
00559                                    srcAlloca->use_end());
00560   while (!srcUseList.empty()) {
00561     User* UI = srcUseList.back();
00562     srcUseList.pop_back();
00563 
00564     if (isa<BitCastInst>(UI)) {
00565       for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
00566            I != E; ++I)
00567         srcUseList.push_back(*I);
00568     } else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(UI)) {
00569       if (G->hasAllZeroIndices())
00570         for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
00571              I != E; ++I)
00572           srcUseList.push_back(*I);
00573       else
00574         return false;
00575     } else if (UI != C && UI != cpy) {
00576       return false;
00577     }
00578   }
00579 
00580   // Since we're changing the parameter to the callsite, we need to make sure
00581   // that what would be the new parameter dominates the callsite.
00582   DominatorTree& DT = getAnalysis<DominatorTree>();
00583   if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
00584     if (!DT.dominates(cpyDestInst, C))
00585       return false;
00586 
00587   // In addition to knowing that the call does not access src in some
00588   // unexpected manner, for example via a global, which we deduce from
00589   // the use analysis, we also need to know that it does not sneakily
00590   // access dest.  We rely on AA to figure this out for us.
00591   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
00592   if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
00593       AliasAnalysis::NoModRef)
00594     return false;
00595 
00596   // All the checks have passed, so do the transformation.
00597   bool changedArgument = false;
00598   for (unsigned i = 0; i < CS.arg_size(); ++i)
00599     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
00600       if (cpySrc->getType() != cpyDest->getType())
00601         cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
00602                                               cpyDest->getName(), C);
00603       changedArgument = true;
00604       if (CS.getArgument(i)->getType() != cpyDest->getType())
00605         CS.setArgument(i, CastInst::CreatePointerCast(cpyDest, 
00606                        CS.getArgument(i)->getType(), cpyDest->getName(), C));
00607       else
00608         CS.setArgument(i, cpyDest);
00609     }
00610 
00611   if (!changedArgument)
00612     return false;
00613 
00614   // Drop any cached information about the call, because we may have changed
00615   // its dependence information by changing its parameter.
00616   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
00617   MD.removeInstruction(C);
00618 
00619   // Remove the memcpy
00620   MD.removeInstruction(cpy);
00621   cpy->eraseFromParent();
00622   NumMemCpyInstr++;
00623 
00624   return true;
00625 }
00626 
00627 /// processMemCpy - perform simplication of memcpy's.  If we have memcpy A which
00628 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
00629 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
00630 ///  This allows later passes to remove the first memcpy altogether.
00631 bool MemCpyOpt::processMemCpy(MemCpyInst* M) {
00632   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
00633 
00634   // The are two possible optimizations we can do for memcpy:
00635   //   a) memcpy-memcpy xform which exposes redundance for DSE
00636   //   b) call-memcpy xform for return slot optimization
00637   MemDepResult dep = MD.getDependency(M);
00638   if (!dep.isClobber())
00639     return false;
00640   if (!isa<MemCpyInst>(dep.getInst())) {
00641     if (CallInst* C = dyn_cast<CallInst>(dep.getInst()))
00642       return performCallSlotOptzn(M, C);
00643     return false;
00644   }
00645   
00646   MemCpyInst* MDep = cast<MemCpyInst>(dep.getInst());
00647   
00648   // We can only transforms memcpy's where the dest of one is the source of the
00649   // other
00650   if (M->getSource() != MDep->getDest())
00651     return false;
00652   
00653   // Second, the length of the memcpy's must be the same, or the preceeding one
00654   // must be larger than the following one.
00655   ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
00656   ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
00657   if (!C1 || !C2)
00658     return false;
00659   
00660   uint64_t DepSize = C1->getValue().getZExtValue();
00661   uint64_t CpySize = C2->getValue().getZExtValue();
00662   
00663   if (DepSize < CpySize)
00664     return false;
00665   
00666   // Finally, we have to make sure that the dest of the second does not
00667   // alias the source of the first
00668   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
00669   if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
00670       AliasAnalysis::NoAlias)
00671     return false;
00672   else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
00673            AliasAnalysis::NoAlias)
00674     return false;
00675   else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
00676            != AliasAnalysis::NoAlias)
00677     return false;
00678   
00679   // If all checks passed, then we can transform these memcpy's
00680   const Type *Tys[1];
00681   Tys[0] = M->getLength()->getType();
00682   Function* MemCpyFun = Intrinsic::getDeclaration(
00683                                  M->getParent()->getParent()->getParent(),
00684                                  M->getIntrinsicID(), Tys, 1);
00685     
00686   Value *Args[4] = {
00687     M->getRawDest(), MDep->getRawSource(), M->getLength(), M->getAlignmentCst()
00688   };
00689   
00690   CallInst* C = CallInst::Create(MemCpyFun, Args, Args+4, "", M);
00691   
00692   
00693   // If C and M don't interfere, then this is a valid transformation.  If they
00694   // did, this would mean that the two sources overlap, which would be bad.
00695   if (MD.getDependency(C) == dep) {
00696     MD.removeInstruction(M);
00697     M->eraseFromParent();
00698     NumMemCpyInstr++;
00699     return true;
00700   }
00701   
00702   // Otherwise, there was no point in doing this, so we remove the call we
00703   // inserted and act like nothing happened.
00704   MD.removeInstruction(C);
00705   C->eraseFromParent();
00706   return false;
00707 }
00708 
00709 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
00710 // function.
00711 //
00712 bool MemCpyOpt::runOnFunction(Function& F) {
00713   
00714   bool changed = false;
00715   bool shouldContinue = true;
00716   
00717   while (shouldContinue) {
00718     shouldContinue = iterateOnFunction(F);
00719     changed |= shouldContinue;
00720   }
00721   
00722   return changed;
00723 }
00724 
00725 
00726 // MemCpyOpt::iterateOnFunction - Executes one iteration of GVN
00727 bool MemCpyOpt::iterateOnFunction(Function &F) {
00728   bool changed_function = false;
00729 
00730   // Walk all instruction in the function
00731   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
00732     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
00733          BI != BE;) {
00734       // Avoid invalidating the iterator
00735       Instruction* I = BI++;
00736       
00737       if (StoreInst *SI = dyn_cast<StoreInst>(I))
00738         changed_function |= processStore(SI, BI);
00739       else if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
00740         changed_function |= processMemCpy(M);
00741       }
00742     }
00743   }
00744   
00745   return changed_function;
00746 }