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