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 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/ADT/SmallVector.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/Analysis/AliasAnalysis.h"
00019 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00020 #include "llvm/Analysis/ValueTracking.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/Dominators.h"
00023 #include "llvm/IR/GetElementPtrTypeIterator.h"
00024 #include "llvm/IR/GlobalVariable.h"
00025 #include "llvm/IR/IRBuilder.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/IR/IntrinsicInst.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Target/TargetLibraryInfo.h"
00031 #include "llvm/Transforms/Utils/Local.h"
00032 #include <list>
00033 using namespace llvm;
00034 
00035 #define DEBUG_TYPE "memcpyopt"
00036 
00037 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
00038 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
00039 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
00040 STATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
00041 
00042 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
00043                                   bool &VariableIdxFound, const DataLayout &TD){
00044   // Skip over the first indices.
00045   gep_type_iterator GTI = gep_type_begin(GEP);
00046   for (unsigned i = 1; i != Idx; ++i, ++GTI)
00047     /*skip along*/;
00048 
00049   // Compute the offset implied by the rest of the indices.
00050   int64_t Offset = 0;
00051   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
00052     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
00053     if (OpC == 0)
00054       return VariableIdxFound = true;
00055     if (OpC->isZero()) continue;  // No offset.
00056 
00057     // Handle struct indices, which add their field offset to the pointer.
00058     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00059       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
00060       continue;
00061     }
00062 
00063     // Otherwise, we have a sequential type like an array or vector.  Multiply
00064     // the index by the ElementSize.
00065     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
00066     Offset += Size*OpC->getSExtValue();
00067   }
00068 
00069   return Offset;
00070 }
00071 
00072 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
00073 /// constant offset, and return that constant offset.  For example, Ptr1 might
00074 /// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
00075 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
00076                             const DataLayout &TD) {
00077   Ptr1 = Ptr1->stripPointerCasts();
00078   Ptr2 = Ptr2->stripPointerCasts();
00079 
00080   // Handle the trivial case first.
00081   if (Ptr1 == Ptr2) {
00082     Offset = 0;
00083     return true;
00084   }
00085 
00086   GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
00087   GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
00088 
00089   bool VariableIdxFound = false;
00090 
00091   // If one pointer is a GEP and the other isn't, then see if the GEP is a
00092   // constant offset from the base, as in "P" and "gep P, 1".
00093   if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
00094     Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
00095     return !VariableIdxFound;
00096   }
00097 
00098   if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
00099     Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
00100     return !VariableIdxFound;
00101   }
00102 
00103   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
00104   // base.  After that base, they may have some number of common (and
00105   // potentially variable) indices.  After that they handle some constant
00106   // offset, which determines their offset from each other.  At this point, we
00107   // handle no other case.
00108   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
00109     return false;
00110 
00111   // Skip any common indices and track the GEP types.
00112   unsigned Idx = 1;
00113   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
00114     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
00115       break;
00116 
00117   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
00118   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
00119   if (VariableIdxFound) return false;
00120 
00121   Offset = Offset2-Offset1;
00122   return true;
00123 }
00124 
00125 
00126 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
00127 /// This allows us to analyze stores like:
00128 ///   store 0 -> P+1
00129 ///   store 0 -> P+0
00130 ///   store 0 -> P+3
00131 ///   store 0 -> P+2
00132 /// which sometimes happens with stores to arrays of structs etc.  When we see
00133 /// the first store, we make a range [1, 2).  The second store extends the range
00134 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
00135 /// two ranges into [0, 3) which is memset'able.
00136 namespace {
00137 struct MemsetRange {
00138   // Start/End - A semi range that describes the span that this range covers.
00139   // The range is closed at the start and open at the end: [Start, End).
00140   int64_t Start, End;
00141 
00142   /// StartPtr - The getelementptr instruction that points to the start of the
00143   /// range.
00144   Value *StartPtr;
00145 
00146   /// Alignment - The known alignment of the first store.
00147   unsigned Alignment;
00148 
00149   /// TheStores - The actual stores that make up this range.
00150   SmallVector<Instruction*, 16> TheStores;
00151 
00152   bool isProfitableToUseMemset(const DataLayout &TD) const;
00153 
00154 };
00155 } // end anon namespace
00156 
00157 bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
00158   // If we found more than 4 stores to merge or 16 bytes, use memset.
00159   if (TheStores.size() >= 4 || End-Start >= 16) return true;
00160 
00161   // If there is nothing to merge, don't do anything.
00162   if (TheStores.size() < 2) return false;
00163 
00164   // If any of the stores are a memset, then it is always good to extend the
00165   // memset.
00166   for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
00167     if (!isa<StoreInst>(TheStores[i]))
00168       return true;
00169 
00170   // Assume that the code generator is capable of merging pairs of stores
00171   // together if it wants to.
00172   if (TheStores.size() == 2) return false;
00173 
00174   // If we have fewer than 8 stores, it can still be worthwhile to do this.
00175   // For example, merging 4 i8 stores into an i32 store is useful almost always.
00176   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
00177   // memset will be split into 2 32-bit stores anyway) and doing so can
00178   // pessimize the llvm optimizer.
00179   //
00180   // Since we don't have perfect knowledge here, make some assumptions: assume
00181   // the maximum GPR width is the same size as the largest legal integer
00182   // size. If so, check to see whether we will end up actually reducing the
00183   // number of stores used.
00184   unsigned Bytes = unsigned(End-Start);
00185   unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
00186   if (MaxIntSize == 0)
00187     MaxIntSize = 1;
00188   unsigned NumPointerStores = Bytes / MaxIntSize;
00189 
00190   // Assume the remaining bytes if any are done a byte at a time.
00191   unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
00192 
00193   // If we will reduce the # stores (according to this heuristic), do the
00194   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
00195   // etc.
00196   return TheStores.size() > NumPointerStores+NumByteStores;
00197 }
00198 
00199 
00200 namespace {
00201 class MemsetRanges {
00202   /// Ranges - A sorted list of the memset ranges.  We use std::list here
00203   /// because each element is relatively large and expensive to copy.
00204   std::list<MemsetRange> Ranges;
00205   typedef std::list<MemsetRange>::iterator range_iterator;
00206   const DataLayout &DL;
00207 public:
00208   MemsetRanges(const DataLayout &DL) : DL(DL) {}
00209 
00210   typedef std::list<MemsetRange>::const_iterator const_iterator;
00211   const_iterator begin() const { return Ranges.begin(); }
00212   const_iterator end() const { return Ranges.end(); }
00213   bool empty() const { return Ranges.empty(); }
00214 
00215   void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
00216     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00217       addStore(OffsetFromFirst, SI);
00218     else
00219       addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
00220   }
00221 
00222   void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
00223     int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
00224 
00225     addRange(OffsetFromFirst, StoreSize,
00226              SI->getPointerOperand(), SI->getAlignment(), SI);
00227   }
00228 
00229   void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
00230     int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
00231     addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
00232   }
00233 
00234   void addRange(int64_t Start, int64_t Size, Value *Ptr,
00235                 unsigned Alignment, Instruction *Inst);
00236 
00237 };
00238 
00239 } // end anon namespace
00240 
00241 
00242 /// addRange - Add a new store to the MemsetRanges data structure.  This adds a
00243 /// new range for the specified store at the specified offset, merging into
00244 /// existing ranges as appropriate.
00245 ///
00246 /// Do a linear search of the ranges to see if this can be joined and/or to
00247 /// find the insertion point in the list.  We keep the ranges sorted for
00248 /// simplicity here.  This is a linear search of a linked list, which is ugly,
00249 /// however the number of ranges is limited, so this won't get crazy slow.
00250 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
00251                             unsigned Alignment, Instruction *Inst) {
00252   int64_t End = Start+Size;
00253   range_iterator I = Ranges.begin(), E = Ranges.end();
00254 
00255   while (I != E && Start > I->End)
00256     ++I;
00257 
00258   // We now know that I == E, in which case we didn't find anything to merge
00259   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
00260   // to insert a new range.  Handle this now.
00261   if (I == E || End < I->Start) {
00262     MemsetRange &R = *Ranges.insert(I, MemsetRange());
00263     R.Start        = Start;
00264     R.End          = End;
00265     R.StartPtr     = Ptr;
00266     R.Alignment    = Alignment;
00267     R.TheStores.push_back(Inst);
00268     return;
00269   }
00270 
00271   // This store overlaps with I, add it.
00272   I->TheStores.push_back(Inst);
00273 
00274   // At this point, we may have an interval that completely contains our store.
00275   // If so, just add it to the interval and return.
00276   if (I->Start <= Start && I->End >= End)
00277     return;
00278 
00279   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
00280   // but is not entirely contained within the range.
00281 
00282   // See if the range extends the start of the range.  In this case, it couldn't
00283   // possibly cause it to join the prior range, because otherwise we would have
00284   // stopped on *it*.
00285   if (Start < I->Start) {
00286     I->Start = Start;
00287     I->StartPtr = Ptr;
00288     I->Alignment = Alignment;
00289   }
00290 
00291   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
00292   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
00293   // End.
00294   if (End > I->End) {
00295     I->End = End;
00296     range_iterator NextI = I;
00297     while (++NextI != E && End >= NextI->Start) {
00298       // Merge the range in.
00299       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
00300       if (NextI->End > I->End)
00301         I->End = NextI->End;
00302       Ranges.erase(NextI);
00303       NextI = I;
00304     }
00305   }
00306 }
00307 
00308 //===----------------------------------------------------------------------===//
00309 //                         MemCpyOpt Pass
00310 //===----------------------------------------------------------------------===//
00311 
00312 namespace {
00313   class MemCpyOpt : public FunctionPass {
00314     MemoryDependenceAnalysis *MD;
00315     TargetLibraryInfo *TLI;
00316     const DataLayout *DL;
00317   public:
00318     static char ID; // Pass identification, replacement for typeid
00319     MemCpyOpt() : FunctionPass(ID) {
00320       initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
00321       MD = 0;
00322       TLI = 0;
00323       DL = 0;
00324     }
00325 
00326     bool runOnFunction(Function &F) override;
00327 
00328   private:
00329     // This transformation requires dominator postdominator info
00330     void getAnalysisUsage(AnalysisUsage &AU) const override {
00331       AU.setPreservesCFG();
00332       AU.addRequired<DominatorTreeWrapperPass>();
00333       AU.addRequired<MemoryDependenceAnalysis>();
00334       AU.addRequired<AliasAnalysis>();
00335       AU.addRequired<TargetLibraryInfo>();
00336       AU.addPreserved<AliasAnalysis>();
00337       AU.addPreserved<MemoryDependenceAnalysis>();
00338     }
00339 
00340     // Helper fuctions
00341     bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
00342     bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
00343     bool processMemCpy(MemCpyInst *M);
00344     bool processMemMove(MemMoveInst *M);
00345     bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
00346                               uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
00347     bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
00348                                        uint64_t MSize);
00349     bool processByValArgument(CallSite CS, unsigned ArgNo);
00350     Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
00351                                       Value *ByteVal);
00352 
00353     bool iterateOnFunction(Function &F);
00354   };
00355 
00356   char MemCpyOpt::ID = 0;
00357 }
00358 
00359 // createMemCpyOptPass - The public interface to this file...
00360 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
00361 
00362 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00363                       false, false)
00364 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00365 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00366 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00367 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00368 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00369                     false, false)
00370 
00371 /// tryMergingIntoMemset - When scanning forward over instructions, we look for
00372 /// some other patterns to fold away.  In particular, this looks for stores to
00373 /// neighboring locations of memory.  If it sees enough consecutive ones, it
00374 /// attempts to merge them together into a memcpy/memset.
00375 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
00376                                              Value *StartPtr, Value *ByteVal) {
00377   if (DL == 0) return 0;
00378 
00379   // Okay, so we now have a single store that can be splatable.  Scan to find
00380   // all subsequent stores of the same value to offset from the same pointer.
00381   // Join these together into ranges, so we can decide whether contiguous blocks
00382   // are stored.
00383   MemsetRanges Ranges(*DL);
00384 
00385   BasicBlock::iterator BI = StartInst;
00386   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
00387     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
00388       // If the instruction is readnone, ignore it, otherwise bail out.  We
00389       // don't even allow readonly here because we don't want something like:
00390       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
00391       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
00392         break;
00393       continue;
00394     }
00395 
00396     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
00397       // If this is a store, see if we can merge it in.
00398       if (!NextStore->isSimple()) break;
00399 
00400       // Check to see if this stored value is of the same byte-splattable value.
00401       if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
00402         break;
00403 
00404       // Check to see if this store is to a constant offset from the start ptr.
00405       int64_t Offset;
00406       if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
00407                            Offset, *DL))
00408         break;
00409 
00410       Ranges.addStore(Offset, NextStore);
00411     } else {
00412       MemSetInst *MSI = cast<MemSetInst>(BI);
00413 
00414       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
00415           !isa<ConstantInt>(MSI->getLength()))
00416         break;
00417 
00418       // Check to see if this store is to a constant offset from the start ptr.
00419       int64_t Offset;
00420       if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
00421         break;
00422 
00423       Ranges.addMemSet(Offset, MSI);
00424     }
00425   }
00426 
00427   // If we have no ranges, then we just had a single store with nothing that
00428   // could be merged in.  This is a very common case of course.
00429   if (Ranges.empty())
00430     return 0;
00431 
00432   // If we had at least one store that could be merged in, add the starting
00433   // store as well.  We try to avoid this unless there is at least something
00434   // interesting as a small compile-time optimization.
00435   Ranges.addInst(0, StartInst);
00436 
00437   // If we create any memsets, we put it right before the first instruction that
00438   // isn't part of the memset block.  This ensure that the memset is dominated
00439   // by any addressing instruction needed by the start of the block.
00440   IRBuilder<> Builder(BI);
00441 
00442   // Now that we have full information about ranges, loop over the ranges and
00443   // emit memset's for anything big enough to be worthwhile.
00444   Instruction *AMemSet = 0;
00445   for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
00446        I != E; ++I) {
00447     const MemsetRange &Range = *I;
00448 
00449     if (Range.TheStores.size() == 1) continue;
00450 
00451     // If it is profitable to lower this range to memset, do so now.
00452     if (!Range.isProfitableToUseMemset(*DL))
00453       continue;
00454 
00455     // Otherwise, we do want to transform this!  Create a new memset.
00456     // Get the starting pointer of the block.
00457     StartPtr = Range.StartPtr;
00458 
00459     // Determine alignment
00460     unsigned Alignment = Range.Alignment;
00461     if (Alignment == 0) {
00462       Type *EltType =
00463         cast<PointerType>(StartPtr->getType())->getElementType();
00464       Alignment = DL->getABITypeAlignment(EltType);
00465     }
00466 
00467     AMemSet =
00468       Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
00469 
00470     DEBUG(dbgs() << "Replace stores:\n";
00471           for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
00472             dbgs() << *Range.TheStores[i] << '\n';
00473           dbgs() << "With: " << *AMemSet << '\n');
00474 
00475     if (!Range.TheStores.empty())
00476       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
00477 
00478     // Zap all the stores.
00479     for (SmallVectorImpl<Instruction *>::const_iterator
00480          SI = Range.TheStores.begin(),
00481          SE = Range.TheStores.end(); SI != SE; ++SI) {
00482       MD->removeInstruction(*SI);
00483       (*SI)->eraseFromParent();
00484     }
00485     ++NumMemSetInfer;
00486   }
00487 
00488   return AMemSet;
00489 }
00490 
00491 
00492 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
00493   if (!SI->isSimple()) return false;
00494 
00495   if (DL == 0) return false;
00496 
00497   // Detect cases where we're performing call slot forwarding, but
00498   // happen to be using a load-store pair to implement it, rather than
00499   // a memcpy.
00500   if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
00501     if (LI->isSimple() && LI->hasOneUse() &&
00502         LI->getParent() == SI->getParent()) {
00503       MemDepResult ldep = MD->getDependency(LI);
00504       CallInst *C = 0;
00505       if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
00506         C = dyn_cast<CallInst>(ldep.getInst());
00507 
00508       if (C) {
00509         // Check that nothing touches the dest of the "copy" between
00510         // the call and the store.
00511         AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00512         AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
00513         for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
00514                                   E = C; I != E; --I) {
00515           if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
00516             C = 0;
00517             break;
00518           }
00519         }
00520       }
00521 
00522       if (C) {
00523         unsigned storeAlign = SI->getAlignment();
00524         if (!storeAlign)
00525           storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
00526         unsigned loadAlign = LI->getAlignment();
00527         if (!loadAlign)
00528           loadAlign = DL->getABITypeAlignment(LI->getType());
00529 
00530         bool changed = performCallSlotOptzn(LI,
00531                         SI->getPointerOperand()->stripPointerCasts(),
00532                         LI->getPointerOperand()->stripPointerCasts(),
00533                         DL->getTypeStoreSize(SI->getOperand(0)->getType()),
00534                         std::min(storeAlign, loadAlign), C);
00535         if (changed) {
00536           MD->removeInstruction(SI);
00537           SI->eraseFromParent();
00538           MD->removeInstruction(LI);
00539           LI->eraseFromParent();
00540           ++NumMemCpyInstr;
00541           return true;
00542         }
00543       }
00544     }
00545   }
00546 
00547   // There are two cases that are interesting for this code to handle: memcpy
00548   // and memset.  Right now we only handle memset.
00549 
00550   // Ensure that the value being stored is something that can be memset'able a
00551   // byte at a time like "0" or "-1" or any width, as well as things like
00552   // 0xA0A0A0A0 and 0.0.
00553   if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
00554     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
00555                                               ByteVal)) {
00556       BBI = I;  // Don't invalidate iterator.
00557       return true;
00558     }
00559 
00560   return false;
00561 }
00562 
00563 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
00564   // See if there is another memset or store neighboring this memset which
00565   // allows us to widen out the memset to do a single larger store.
00566   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
00567     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
00568                                               MSI->getValue())) {
00569       BBI = I;  // Don't invalidate iterator.
00570       return true;
00571     }
00572   return false;
00573 }
00574 
00575 
00576 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
00577 /// and checks for the possibility of a call slot optimization by having
00578 /// the call write its result directly into the destination of the memcpy.
00579 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
00580                                      Value *cpyDest, Value *cpySrc,
00581                                      uint64_t cpyLen, unsigned cpyAlign,
00582                                      CallInst *C) {
00583   // The general transformation to keep in mind is
00584   //
00585   //   call @func(..., src, ...)
00586   //   memcpy(dest, src, ...)
00587   //
00588   // ->
00589   //
00590   //   memcpy(dest, src, ...)
00591   //   call @func(..., dest, ...)
00592   //
00593   // Since moving the memcpy is technically awkward, we additionally check that
00594   // src only holds uninitialized values at the moment of the call, meaning that
00595   // the memcpy can be discarded rather than moved.
00596 
00597   // Deliberately get the source and destination with bitcasts stripped away,
00598   // because we'll need to do type comparisons based on the underlying type.
00599   CallSite CS(C);
00600 
00601   // Require that src be an alloca.  This simplifies the reasoning considerably.
00602   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
00603   if (!srcAlloca)
00604     return false;
00605 
00606   // Check that all of src is copied to dest.
00607   if (DL == 0) return false;
00608 
00609   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
00610   if (!srcArraySize)
00611     return false;
00612 
00613   uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
00614     srcArraySize->getZExtValue();
00615 
00616   if (cpyLen < srcSize)
00617     return false;
00618 
00619   // Check that accessing the first srcSize bytes of dest will not cause a
00620   // trap.  Otherwise the transform is invalid since it might cause a trap
00621   // to occur earlier than it otherwise would.
00622   if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
00623     // The destination is an alloca.  Check it is larger than srcSize.
00624     ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
00625     if (!destArraySize)
00626       return false;
00627 
00628     uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
00629       destArraySize->getZExtValue();
00630 
00631     if (destSize < srcSize)
00632       return false;
00633   } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
00634     // If the destination is an sret parameter then only accesses that are
00635     // outside of the returned struct type can trap.
00636     if (!A->hasStructRetAttr())
00637       return false;
00638 
00639     Type *StructTy = cast<PointerType>(A->getType())->getElementType();
00640     if (!StructTy->isSized()) {
00641       // The call may never return and hence the copy-instruction may never
00642       // be executed, and therefore it's not safe to say "the destination
00643       // has at least <cpyLen> bytes, as implied by the copy-instruction",
00644       return false;
00645     }
00646 
00647     uint64_t destSize = DL->getTypeAllocSize(StructTy);
00648     if (destSize < srcSize)
00649       return false;
00650   } else {
00651     return false;
00652   }
00653 
00654   // Check that dest points to memory that is at least as aligned as src.
00655   unsigned srcAlign = srcAlloca->getAlignment();
00656   if (!srcAlign)
00657     srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
00658   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
00659   // If dest is not aligned enough and we can't increase its alignment then
00660   // bail out.
00661   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
00662     return false;
00663 
00664   // Check that src is not accessed except via the call and the memcpy.  This
00665   // guarantees that it holds only undefined values when passed in (so the final
00666   // memcpy can be dropped), that it is not read or written between the call and
00667   // the memcpy, and that writing beyond the end of it is undefined.
00668   SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
00669                                    srcAlloca->user_end());
00670   while (!srcUseList.empty()) {
00671     User *U = srcUseList.pop_back_val();
00672 
00673     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
00674       for (User *UU : U->users())
00675         srcUseList.push_back(UU);
00676     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
00677       if (G->hasAllZeroIndices())
00678         for (User *UU : U->users())
00679           srcUseList.push_back(UU);
00680       else
00681         return false;
00682     } else if (U != C && U != cpy) {
00683       return false;
00684     }
00685   }
00686 
00687   // Since we're changing the parameter to the callsite, we need to make sure
00688   // that what would be the new parameter dominates the callsite.
00689   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00690   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
00691     if (!DT.dominates(cpyDestInst, C))
00692       return false;
00693 
00694   // In addition to knowing that the call does not access src in some
00695   // unexpected manner, for example via a global, which we deduce from
00696   // the use analysis, we also need to know that it does not sneakily
00697   // access dest.  We rely on AA to figure this out for us.
00698   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00699   AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
00700   // If necessary, perform additional analysis.
00701   if (MR != AliasAnalysis::NoModRef)
00702     MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
00703   if (MR != AliasAnalysis::NoModRef)
00704     return false;
00705 
00706   // All the checks have passed, so do the transformation.
00707   bool changedArgument = false;
00708   for (unsigned i = 0; i < CS.arg_size(); ++i)
00709     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
00710       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
00711         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
00712                                       cpyDest->getName(), C);
00713       changedArgument = true;
00714       if (CS.getArgument(i)->getType() == Dest->getType())
00715         CS.setArgument(i, Dest);
00716       else
00717         CS.setArgument(i, CastInst::CreatePointerCast(Dest,
00718                           CS.getArgument(i)->getType(), Dest->getName(), C));
00719     }
00720 
00721   if (!changedArgument)
00722     return false;
00723 
00724   // If the destination wasn't sufficiently aligned then increase its alignment.
00725   if (!isDestSufficientlyAligned) {
00726     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
00727     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
00728   }
00729 
00730   // Drop any cached information about the call, because we may have changed
00731   // its dependence information by changing its parameter.
00732   MD->removeInstruction(C);
00733 
00734   // Remove the memcpy.
00735   MD->removeInstruction(cpy);
00736   ++NumMemCpyInstr;
00737 
00738   return true;
00739 }
00740 
00741 /// processMemCpyMemCpyDependence - We've found that the (upward scanning)
00742 /// memory dependence of memcpy 'M' is the memcpy 'MDep'.  Try to simplify M to
00743 /// copy from MDep's input if we can.  MSize is the size of M's copy.
00744 ///
00745 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
00746                                               uint64_t MSize) {
00747   // We can only transforms memcpy's where the dest of one is the source of the
00748   // other.
00749   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
00750     return false;
00751 
00752   // If dep instruction is reading from our current input, then it is a noop
00753   // transfer and substituting the input won't change this instruction.  Just
00754   // ignore the input and let someone else zap MDep.  This handles cases like:
00755   //    memcpy(a <- a)
00756   //    memcpy(b <- a)
00757   if (M->getSource() == MDep->getSource())
00758     return false;
00759 
00760   // Second, the length of the memcpy's must be the same, or the preceding one
00761   // must be larger than the following one.
00762   ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
00763   ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
00764   if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
00765     return false;
00766 
00767   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00768 
00769   // Verify that the copied-from memory doesn't change in between the two
00770   // transfers.  For example, in:
00771   //    memcpy(a <- b)
00772   //    *b = 42;
00773   //    memcpy(c <- a)
00774   // It would be invalid to transform the second memcpy into memcpy(c <- b).
00775   //
00776   // TODO: If the code between M and MDep is transparent to the destination "c",
00777   // then we could still perform the xform by moving M up to the first memcpy.
00778   //
00779   // NOTE: This is conservative, it will stop on any read from the source loc,
00780   // not just the defining memcpy.
00781   MemDepResult SourceDep =
00782     MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
00783                                  false, M, M->getParent());
00784   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
00785     return false;
00786 
00787   // If the dest of the second might alias the source of the first, then the
00788   // source and dest might overlap.  We still want to eliminate the intermediate
00789   // value, but we have to generate a memmove instead of memcpy.
00790   bool UseMemMove = false;
00791   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
00792     UseMemMove = true;
00793 
00794   // If all checks passed, then we can transform M.
00795 
00796   // Make sure to use the lesser of the alignment of the source and the dest
00797   // since we're changing where we're reading from, but don't want to increase
00798   // the alignment past what can be read from or written to.
00799   // TODO: Is this worth it if we're creating a less aligned memcpy? For
00800   // example we could be moving from movaps -> movq on x86.
00801   unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
00802 
00803   IRBuilder<> Builder(M);
00804   if (UseMemMove)
00805     Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00806                           Align, M->isVolatile());
00807   else
00808     Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00809                          Align, M->isVolatile());
00810 
00811   // Remove the instruction we're replacing.
00812   MD->removeInstruction(M);
00813   M->eraseFromParent();
00814   ++NumMemCpyInstr;
00815   return true;
00816 }
00817 
00818 
00819 /// processMemCpy - perform simplification of memcpy's.  If we have memcpy A
00820 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
00821 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
00822 /// circumstances). This allows later passes to remove the first memcpy
00823 /// altogether.
00824 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
00825   // We can only optimize non-volatile memcpy's.
00826   if (M->isVolatile()) return false;
00827 
00828   // If the source and destination of the memcpy are the same, then zap it.
00829   if (M->getSource() == M->getDest()) {
00830     MD->removeInstruction(M);
00831     M->eraseFromParent();
00832     return false;
00833   }
00834 
00835   // If copying from a constant, try to turn the memcpy into a memset.
00836   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
00837     if (GV->isConstant() && GV->hasDefinitiveInitializer())
00838       if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
00839         IRBuilder<> Builder(M);
00840         Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
00841                              M->getAlignment(), false);
00842         MD->removeInstruction(M);
00843         M->eraseFromParent();
00844         ++NumCpyToSet;
00845         return true;
00846       }
00847 
00848   // The optimizations after this point require the memcpy size.
00849   ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
00850   if (CopySize == 0) return false;
00851 
00852   // The are three possible optimizations we can do for memcpy:
00853   //   a) memcpy-memcpy xform which exposes redundance for DSE.
00854   //   b) call-memcpy xform for return slot optimization.
00855   //   c) memcpy from freshly alloca'd space or space that has just started its
00856   //      lifetime copies undefined data, and we can therefore eliminate the
00857   //      memcpy in favor of the data that was already at the destination.
00858   MemDepResult DepInfo = MD->getDependency(M);
00859   if (DepInfo.isClobber()) {
00860     if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
00861       if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
00862                                CopySize->getZExtValue(), M->getAlignment(),
00863                                C)) {
00864         MD->removeInstruction(M);
00865         M->eraseFromParent();
00866         return true;
00867       }
00868     }
00869   }
00870 
00871   AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
00872   MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
00873                                                          M, M->getParent());
00874   if (SrcDepInfo.isClobber()) {
00875     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
00876       return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
00877   } else if (SrcDepInfo.isDef()) {
00878     Instruction *I = SrcDepInfo.getInst();
00879     bool hasUndefContents = false;
00880 
00881     if (isa<AllocaInst>(I)) {
00882       hasUndefContents = true;
00883     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00884       if (II->getIntrinsicID() == Intrinsic::lifetime_start)
00885         if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
00886           if (LTSize->getZExtValue() >= CopySize->getZExtValue())
00887             hasUndefContents = true;
00888     }
00889 
00890     if (hasUndefContents) {
00891       MD->removeInstruction(M);
00892       M->eraseFromParent();
00893       ++NumMemCpyInstr;
00894       return true;
00895     }
00896   }
00897 
00898   return false;
00899 }
00900 
00901 /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
00902 /// are guaranteed not to alias.
00903 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
00904   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00905 
00906   if (!TLI->has(LibFunc::memmove))
00907     return false;
00908 
00909   // See if the pointers alias.
00910   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
00911     return false;
00912 
00913   DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
00914 
00915   // If not, then we know we can transform this.
00916   Module *Mod = M->getParent()->getParent()->getParent();
00917   Type *ArgTys[3] = { M->getRawDest()->getType(),
00918                       M->getRawSource()->getType(),
00919                       M->getLength()->getType() };
00920   M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
00921                                                  ArgTys));
00922 
00923   // MemDep may have over conservative information about this instruction, just
00924   // conservatively flush it from the cache.
00925   MD->removeInstruction(M);
00926 
00927   ++NumMoveToCpy;
00928   return true;
00929 }
00930 
00931 /// processByValArgument - This is called on every byval argument in call sites.
00932 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
00933   if (DL == 0) return false;
00934 
00935   // Find out what feeds this byval argument.
00936   Value *ByValArg = CS.getArgument(ArgNo);
00937   Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
00938   uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
00939   MemDepResult DepInfo =
00940     MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
00941                                  true, CS.getInstruction(),
00942                                  CS.getInstruction()->getParent());
00943   if (!DepInfo.isClobber())
00944     return false;
00945 
00946   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
00947   // a memcpy, see if we can byval from the source of the memcpy instead of the
00948   // result.
00949   MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
00950   if (MDep == 0 || MDep->isVolatile() ||
00951       ByValArg->stripPointerCasts() != MDep->getDest())
00952     return false;
00953 
00954   // The length of the memcpy must be larger or equal to the size of the byval.
00955   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
00956   if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
00957     return false;
00958 
00959   // Get the alignment of the byval.  If the call doesn't specify the alignment,
00960   // then it is some target specific value that we can't know.
00961   unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
00962   if (ByValAlign == 0) return false;
00963 
00964   // If it is greater than the memcpy, then we check to see if we can force the
00965   // source of the memcpy to the alignment we need.  If we fail, we bail out.
00966   if (MDep->getAlignment() < ByValAlign &&
00967       getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, DL) < ByValAlign)
00968     return false;
00969 
00970   // Verify that the copied-from memory doesn't change in between the memcpy and
00971   // the byval call.
00972   //    memcpy(a <- b)
00973   //    *b = 42;
00974   //    foo(*a)
00975   // It would be invalid to transform the second memcpy into foo(*b).
00976   //
00977   // NOTE: This is conservative, it will stop on any read from the source loc,
00978   // not just the defining memcpy.
00979   MemDepResult SourceDep =
00980     MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
00981                                  false, CS.getInstruction(), MDep->getParent());
00982   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
00983     return false;
00984 
00985   Value *TmpCast = MDep->getSource();
00986   if (MDep->getSource()->getType() != ByValArg->getType())
00987     TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
00988                               "tmpcast", CS.getInstruction());
00989 
00990   DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
00991                << "  " << *MDep << "\n"
00992                << "  " << *CS.getInstruction() << "\n");
00993 
00994   // Otherwise we're good!  Update the byval argument.
00995   CS.setArgument(ArgNo, TmpCast);
00996   ++NumMemCpyInstr;
00997   return true;
00998 }
00999 
01000 /// iterateOnFunction - Executes one iteration of MemCpyOpt.
01001 bool MemCpyOpt::iterateOnFunction(Function &F) {
01002   bool MadeChange = false;
01003 
01004   // Walk all instruction in the function.
01005   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
01006     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
01007       // Avoid invalidating the iterator.
01008       Instruction *I = BI++;
01009 
01010       bool RepeatInstruction = false;
01011 
01012       if (StoreInst *SI = dyn_cast<StoreInst>(I))
01013         MadeChange |= processStore(SI, BI);
01014       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
01015         RepeatInstruction = processMemSet(M, BI);
01016       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
01017         RepeatInstruction = processMemCpy(M);
01018       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
01019         RepeatInstruction = processMemMove(M);
01020       else if (CallSite CS = (Value*)I) {
01021         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
01022           if (CS.isByValArgument(i))
01023             MadeChange |= processByValArgument(CS, i);
01024       }
01025 
01026       // Reprocess the instruction if desired.
01027       if (RepeatInstruction) {
01028         if (BI != BB->begin()) --BI;
01029         MadeChange = true;
01030       }
01031     }
01032   }
01033 
01034   return MadeChange;
01035 }
01036 
01037 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
01038 // function.
01039 //
01040 bool MemCpyOpt::runOnFunction(Function &F) {
01041   if (skipOptnoneFunction(F))
01042     return false;
01043 
01044   bool MadeChange = false;
01045   MD = &getAnalysis<MemoryDependenceAnalysis>();
01046   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01047   DL = DLP ? &DLP->getDataLayout() : 0;
01048   TLI = &getAnalysis<TargetLibraryInfo>();
01049 
01050   // If we don't have at least memset and memcpy, there is little point of doing
01051   // anything here.  These are required by a freestanding implementation, so if
01052   // even they are disabled, there is no point in trying hard.
01053   if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
01054     return false;
01055 
01056   while (1) {
01057     if (!iterateOnFunction(F))
01058       break;
01059     MadeChange = true;
01060   }
01061 
01062   MD = 0;
01063   return MadeChange;
01064 }