LLVM  mainline
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/AssumptionCache.h"
00020 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00021 #include "llvm/Analysis/TargetLibraryInfo.h"
00022 #include "llvm/Analysis/ValueTracking.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/Dominators.h"
00025 #include "llvm/IR/GetElementPtrTypeIterator.h"
00026 #include "llvm/IR/GlobalVariable.h"
00027 #include "llvm/IR/IRBuilder.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/raw_ostream.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,
00045                                   const DataLayout &DL) {
00046   // Skip over the first indices.
00047   gep_type_iterator GTI = gep_type_begin(GEP);
00048   for (unsigned i = 1; i != Idx; ++i, ++GTI)
00049     /*skip along*/;
00050 
00051   // Compute the offset implied by the rest of the indices.
00052   int64_t Offset = 0;
00053   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
00054     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
00055     if (!OpC)
00056       return VariableIdxFound = true;
00057     if (OpC->isZero()) continue;  // No offset.
00058 
00059     // Handle struct indices, which add their field offset to the pointer.
00060     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00061       Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
00062       continue;
00063     }
00064 
00065     // Otherwise, we have a sequential type like an array or vector.  Multiply
00066     // the index by the ElementSize.
00067     uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
00068     Offset += Size*OpC->getSExtValue();
00069   }
00070 
00071   return Offset;
00072 }
00073 
00074 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
00075 /// constant offset, and return that constant offset.  For example, Ptr1 might
00076 /// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
00077 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
00078                             const DataLayout &DL) {
00079   Ptr1 = Ptr1->stripPointerCasts();
00080   Ptr2 = Ptr2->stripPointerCasts();
00081 
00082   // Handle the trivial case first.
00083   if (Ptr1 == Ptr2) {
00084     Offset = 0;
00085     return true;
00086   }
00087 
00088   GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
00089   GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
00090 
00091   bool VariableIdxFound = false;
00092 
00093   // If one pointer is a GEP and the other isn't, then see if the GEP is a
00094   // constant offset from the base, as in "P" and "gep P, 1".
00095   if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
00096     Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
00097     return !VariableIdxFound;
00098   }
00099 
00100   if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
00101     Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
00102     return !VariableIdxFound;
00103   }
00104 
00105   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
00106   // base.  After that base, they may have some number of common (and
00107   // potentially variable) indices.  After that they handle some constant
00108   // offset, which determines their offset from each other.  At this point, we
00109   // handle no other case.
00110   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
00111     return false;
00112 
00113   // Skip any common indices and track the GEP types.
00114   unsigned Idx = 1;
00115   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
00116     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
00117       break;
00118 
00119   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
00120   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
00121   if (VariableIdxFound) return false;
00122 
00123   Offset = Offset2-Offset1;
00124   return true;
00125 }
00126 
00127 
00128 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
00129 /// This allows us to analyze stores like:
00130 ///   store 0 -> P+1
00131 ///   store 0 -> P+0
00132 ///   store 0 -> P+3
00133 ///   store 0 -> P+2
00134 /// which sometimes happens with stores to arrays of structs etc.  When we see
00135 /// the first store, we make a range [1, 2).  The second store extends the range
00136 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
00137 /// two ranges into [0, 3) which is memset'able.
00138 namespace {
00139 struct MemsetRange {
00140   // Start/End - A semi range that describes the span that this range covers.
00141   // The range is closed at the start and open at the end: [Start, End).
00142   int64_t Start, End;
00143 
00144   /// StartPtr - The getelementptr instruction that points to the start of the
00145   /// range.
00146   Value *StartPtr;
00147 
00148   /// Alignment - The known alignment of the first store.
00149   unsigned Alignment;
00150 
00151   /// TheStores - The actual stores that make up this range.
00152   SmallVector<Instruction*, 16> TheStores;
00153 
00154   bool isProfitableToUseMemset(const DataLayout &DL) const;
00155 };
00156 } // end anon namespace
00157 
00158 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) 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 = DL.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   public:
00318     static char ID; // Pass identification, replacement for typeid
00319     MemCpyOpt() : FunctionPass(ID) {
00320       initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
00321       MD = nullptr;
00322       TLI = nullptr;
00323     }
00324 
00325     bool runOnFunction(Function &F) override;
00326 
00327   private:
00328     // This transformation requires dominator postdominator info
00329     void getAnalysisUsage(AnalysisUsage &AU) const override {
00330       AU.setPreservesCFG();
00331       AU.addRequired<AssumptionCacheTracker>();
00332       AU.addRequired<DominatorTreeWrapperPass>();
00333       AU.addRequired<MemoryDependenceAnalysis>();
00334       AU.addRequired<AliasAnalysis>();
00335       AU.addRequired<TargetLibraryInfoWrapperPass>();
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 processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
00350     bool processByValArgument(CallSite CS, unsigned ArgNo);
00351     Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
00352                                       Value *ByteVal);
00353 
00354     bool iterateOnFunction(Function &F);
00355   };
00356 
00357   char MemCpyOpt::ID = 0;
00358 }
00359 
00360 // createMemCpyOptPass - The public interface to this file...
00361 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
00362 
00363 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00364                       false, false)
00365 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00366 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00367 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00368 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00369 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00370 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00371                     false, false)
00372 
00373 /// tryMergingIntoMemset - When scanning forward over instructions, we look for
00374 /// some other patterns to fold away.  In particular, this looks for stores to
00375 /// neighboring locations of memory.  If it sees enough consecutive ones, it
00376 /// attempts to merge them together into a memcpy/memset.
00377 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
00378                                              Value *StartPtr, Value *ByteVal) {
00379   const DataLayout &DL = StartInst->getModule()->getDataLayout();
00380 
00381   // Okay, so we now have a single store that can be splatable.  Scan to find
00382   // all subsequent stores of the same value to offset from the same pointer.
00383   // Join these together into ranges, so we can decide whether contiguous blocks
00384   // are stored.
00385   MemsetRanges Ranges(DL);
00386 
00387   BasicBlock::iterator BI = StartInst;
00388   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
00389     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
00390       // If the instruction is readnone, ignore it, otherwise bail out.  We
00391       // don't even allow readonly here because we don't want something like:
00392       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
00393       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
00394         break;
00395       continue;
00396     }
00397 
00398     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
00399       // If this is a store, see if we can merge it in.
00400       if (!NextStore->isSimple()) break;
00401 
00402       // Check to see if this stored value is of the same byte-splattable value.
00403       if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
00404         break;
00405 
00406       // Check to see if this store is to a constant offset from the start ptr.
00407       int64_t Offset;
00408       if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
00409                            DL))
00410         break;
00411 
00412       Ranges.addStore(Offset, NextStore);
00413     } else {
00414       MemSetInst *MSI = cast<MemSetInst>(BI);
00415 
00416       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
00417           !isa<ConstantInt>(MSI->getLength()))
00418         break;
00419 
00420       // Check to see if this store is to a constant offset from the start ptr.
00421       int64_t Offset;
00422       if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
00423         break;
00424 
00425       Ranges.addMemSet(Offset, MSI);
00426     }
00427   }
00428 
00429   // If we have no ranges, then we just had a single store with nothing that
00430   // could be merged in.  This is a very common case of course.
00431   if (Ranges.empty())
00432     return nullptr;
00433 
00434   // If we had at least one store that could be merged in, add the starting
00435   // store as well.  We try to avoid this unless there is at least something
00436   // interesting as a small compile-time optimization.
00437   Ranges.addInst(0, StartInst);
00438 
00439   // If we create any memsets, we put it right before the first instruction that
00440   // isn't part of the memset block.  This ensure that the memset is dominated
00441   // by any addressing instruction needed by the start of the block.
00442   IRBuilder<> Builder(BI);
00443 
00444   // Now that we have full information about ranges, loop over the ranges and
00445   // emit memset's for anything big enough to be worthwhile.
00446   Instruction *AMemSet = nullptr;
00447   for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
00448        I != E; ++I) {
00449     const MemsetRange &Range = *I;
00450 
00451     if (Range.TheStores.size() == 1) continue;
00452 
00453     // If it is profitable to lower this range to memset, do so now.
00454     if (!Range.isProfitableToUseMemset(DL))
00455       continue;
00456 
00457     // Otherwise, we do want to transform this!  Create a new memset.
00458     // Get the starting pointer of the block.
00459     StartPtr = Range.StartPtr;
00460 
00461     // Determine alignment
00462     unsigned Alignment = Range.Alignment;
00463     if (Alignment == 0) {
00464       Type *EltType =
00465         cast<PointerType>(StartPtr->getType())->getElementType();
00466       Alignment = DL.getABITypeAlignment(EltType);
00467     }
00468 
00469     AMemSet =
00470       Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
00471 
00472     DEBUG(dbgs() << "Replace stores:\n";
00473           for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
00474             dbgs() << *Range.TheStores[i] << '\n';
00475           dbgs() << "With: " << *AMemSet << '\n');
00476 
00477     if (!Range.TheStores.empty())
00478       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
00479 
00480     // Zap all the stores.
00481     for (SmallVectorImpl<Instruction *>::const_iterator
00482          SI = Range.TheStores.begin(),
00483          SE = Range.TheStores.end(); SI != SE; ++SI) {
00484       MD->removeInstruction(*SI);
00485       (*SI)->eraseFromParent();
00486     }
00487     ++NumMemSetInfer;
00488   }
00489 
00490   return AMemSet;
00491 }
00492 
00493 
00494 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
00495   if (!SI->isSimple()) return false;
00496   const DataLayout &DL = SI->getModule()->getDataLayout();
00497 
00498   // Detect cases where we're performing call slot forwarding, but
00499   // happen to be using a load-store pair to implement it, rather than
00500   // a memcpy.
00501   if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
00502     if (LI->isSimple() && LI->hasOneUse() &&
00503         LI->getParent() == SI->getParent()) {
00504       MemDepResult ldep = MD->getDependency(LI);
00505       CallInst *C = nullptr;
00506       if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
00507         C = dyn_cast<CallInst>(ldep.getInst());
00508 
00509       if (C) {
00510         // Check that nothing touches the dest of the "copy" between
00511         // the call and the store.
00512         AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00513         AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
00514         for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
00515                                   E = C; I != E; --I) {
00516           if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
00517             C = nullptr;
00518             break;
00519           }
00520         }
00521       }
00522 
00523       if (C) {
00524         unsigned storeAlign = SI->getAlignment();
00525         if (!storeAlign)
00526           storeAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
00527         unsigned loadAlign = LI->getAlignment();
00528         if (!loadAlign)
00529           loadAlign = DL.getABITypeAlignment(LI->getType());
00530 
00531         bool changed = performCallSlotOptzn(
00532             LI, SI->getPointerOperand()->stripPointerCasts(),
00533             LI->getPointerOperand()->stripPointerCasts(),
00534             DL.getTypeStoreSize(SI->getOperand(0)->getType()),
00535             std::min(storeAlign, loadAlign), C);
00536         if (changed) {
00537           MD->removeInstruction(SI);
00538           SI->eraseFromParent();
00539           MD->removeInstruction(LI);
00540           LI->eraseFromParent();
00541           ++NumMemCpyInstr;
00542           return true;
00543         }
00544       }
00545     }
00546   }
00547 
00548   // There are two cases that are interesting for this code to handle: memcpy
00549   // and memset.  Right now we only handle memset.
00550 
00551   // Ensure that the value being stored is something that can be memset'able a
00552   // byte at a time like "0" or "-1" or any width, as well as things like
00553   // 0xA0A0A0A0 and 0.0.
00554   if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
00555     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
00556                                               ByteVal)) {
00557       BBI = I;  // Don't invalidate iterator.
00558       return true;
00559     }
00560 
00561   return false;
00562 }
00563 
00564 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
00565   // See if there is another memset or store neighboring this memset which
00566   // allows us to widen out the memset to do a single larger store.
00567   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
00568     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
00569                                               MSI->getValue())) {
00570       BBI = I;  // Don't invalidate iterator.
00571       return true;
00572     }
00573   return false;
00574 }
00575 
00576 
00577 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
00578 /// and checks for the possibility of a call slot optimization by having
00579 /// the call write its result directly into the destination of the memcpy.
00580 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
00581                                      Value *cpyDest, Value *cpySrc,
00582                                      uint64_t cpyLen, unsigned cpyAlign,
00583                                      CallInst *C) {
00584   // The general transformation to keep in mind is
00585   //
00586   //   call @func(..., src, ...)
00587   //   memcpy(dest, src, ...)
00588   //
00589   // ->
00590   //
00591   //   memcpy(dest, src, ...)
00592   //   call @func(..., dest, ...)
00593   //
00594   // Since moving the memcpy is technically awkward, we additionally check that
00595   // src only holds uninitialized values at the moment of the call, meaning that
00596   // the memcpy can be discarded rather than moved.
00597 
00598   // Deliberately get the source and destination with bitcasts stripped away,
00599   // because we'll need to do type comparisons based on the underlying type.
00600   CallSite CS(C);
00601 
00602   // Require that src be an alloca.  This simplifies the reasoning considerably.
00603   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
00604   if (!srcAlloca)
00605     return false;
00606 
00607   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
00608   if (!srcArraySize)
00609     return false;
00610 
00611   const DataLayout &DL = cpy->getModule()->getDataLayout();
00612   uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
00613                      srcArraySize->getZExtValue();
00614 
00615   if (cpyLen < srcSize)
00616     return false;
00617 
00618   // Check that accessing the first srcSize bytes of dest will not cause a
00619   // trap.  Otherwise the transform is invalid since it might cause a trap
00620   // to occur earlier than it otherwise would.
00621   if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
00622     // The destination is an alloca.  Check it is larger than srcSize.
00623     ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
00624     if (!destArraySize)
00625       return false;
00626 
00627     uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
00628                         destArraySize->getZExtValue();
00629 
00630     if (destSize < srcSize)
00631       return false;
00632   } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
00633     if (A->getDereferenceableBytes() < srcSize) {
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     }
00651   } else {
00652     return false;
00653   }
00654 
00655   // Check that dest points to memory that is at least as aligned as src.
00656   unsigned srcAlign = srcAlloca->getAlignment();
00657   if (!srcAlign)
00658     srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
00659   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
00660   // If dest is not aligned enough and we can't increase its alignment then
00661   // bail out.
00662   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
00663     return false;
00664 
00665   // Check that src is not accessed except via the call and the memcpy.  This
00666   // guarantees that it holds only undefined values when passed in (so the final
00667   // memcpy can be dropped), that it is not read or written between the call and
00668   // the memcpy, and that writing beyond the end of it is undefined.
00669   SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
00670                                    srcAlloca->user_end());
00671   while (!srcUseList.empty()) {
00672     User *U = srcUseList.pop_back_val();
00673 
00674     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
00675       for (User *UU : U->users())
00676         srcUseList.push_back(UU);
00677       continue;
00678     }
00679     if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
00680       if (!G->hasAllZeroIndices())
00681         return false;
00682 
00683       for (User *UU : U->users())
00684         srcUseList.push_back(UU);
00685       continue;
00686     }
00687     if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
00688       if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
00689           IT->getIntrinsicID() == Intrinsic::lifetime_end)
00690         continue;
00691 
00692     if (U != C && U != cpy)
00693       return false;
00694   }
00695 
00696   // Check that src isn't captured by the called function since the
00697   // transformation can cause aliasing issues in that case.
00698   for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
00699     if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
00700       return false;
00701 
00702   // Since we're changing the parameter to the callsite, we need to make sure
00703   // that what would be the new parameter dominates the callsite.
00704   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00705   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
00706     if (!DT.dominates(cpyDestInst, C))
00707       return false;
00708 
00709   // In addition to knowing that the call does not access src in some
00710   // unexpected manner, for example via a global, which we deduce from
00711   // the use analysis, we also need to know that it does not sneakily
00712   // access dest.  We rely on AA to figure this out for us.
00713   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00714   AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
00715   // If necessary, perform additional analysis.
00716   if (MR != AliasAnalysis::NoModRef)
00717     MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
00718   if (MR != AliasAnalysis::NoModRef)
00719     return false;
00720 
00721   // All the checks have passed, so do the transformation.
00722   bool changedArgument = false;
00723   for (unsigned i = 0; i < CS.arg_size(); ++i)
00724     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
00725       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
00726         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
00727                                       cpyDest->getName(), C);
00728       changedArgument = true;
00729       if (CS.getArgument(i)->getType() == Dest->getType())
00730         CS.setArgument(i, Dest);
00731       else
00732         CS.setArgument(i, CastInst::CreatePointerCast(Dest,
00733                           CS.getArgument(i)->getType(), Dest->getName(), C));
00734     }
00735 
00736   if (!changedArgument)
00737     return false;
00738 
00739   // If the destination wasn't sufficiently aligned then increase its alignment.
00740   if (!isDestSufficientlyAligned) {
00741     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
00742     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
00743   }
00744 
00745   // Drop any cached information about the call, because we may have changed
00746   // its dependence information by changing its parameter.
00747   MD->removeInstruction(C);
00748 
00749   // Update AA metadata
00750   // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
00751   // handled here, but combineMetadata doesn't support them yet
00752   unsigned KnownIDs[] = {
00753     LLVMContext::MD_tbaa,
00754     LLVMContext::MD_alias_scope,
00755     LLVMContext::MD_noalias,
00756   };
00757   combineMetadata(C, cpy, KnownIDs);
00758 
00759   // Remove the memcpy.
00760   MD->removeInstruction(cpy);
00761   ++NumMemCpyInstr;
00762 
00763   return true;
00764 }
00765 
00766 /// processMemCpyMemCpyDependence - We've found that the (upward scanning)
00767 /// memory dependence of memcpy 'M' is the memcpy 'MDep'.  Try to simplify M to
00768 /// copy from MDep's input if we can.  MSize is the size of M's copy.
00769 ///
00770 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
00771                                               uint64_t MSize) {
00772   // We can only transforms memcpy's where the dest of one is the source of the
00773   // other.
00774   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
00775     return false;
00776 
00777   // If dep instruction is reading from our current input, then it is a noop
00778   // transfer and substituting the input won't change this instruction.  Just
00779   // ignore the input and let someone else zap MDep.  This handles cases like:
00780   //    memcpy(a <- a)
00781   //    memcpy(b <- a)
00782   if (M->getSource() == MDep->getSource())
00783     return false;
00784 
00785   // Second, the length of the memcpy's must be the same, or the preceding one
00786   // must be larger than the following one.
00787   ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
00788   ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
00789   if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
00790     return false;
00791 
00792   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00793 
00794   // Verify that the copied-from memory doesn't change in between the two
00795   // transfers.  For example, in:
00796   //    memcpy(a <- b)
00797   //    *b = 42;
00798   //    memcpy(c <- a)
00799   // It would be invalid to transform the second memcpy into memcpy(c <- b).
00800   //
00801   // TODO: If the code between M and MDep is transparent to the destination "c",
00802   // then we could still perform the xform by moving M up to the first memcpy.
00803   //
00804   // NOTE: This is conservative, it will stop on any read from the source loc,
00805   // not just the defining memcpy.
00806   MemDepResult SourceDep =
00807     MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
00808                                  false, M, M->getParent());
00809   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
00810     return false;
00811 
00812   // If the dest of the second might alias the source of the first, then the
00813   // source and dest might overlap.  We still want to eliminate the intermediate
00814   // value, but we have to generate a memmove instead of memcpy.
00815   bool UseMemMove = false;
00816   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
00817     UseMemMove = true;
00818 
00819   // If all checks passed, then we can transform M.
00820 
00821   // Make sure to use the lesser of the alignment of the source and the dest
00822   // since we're changing where we're reading from, but don't want to increase
00823   // the alignment past what can be read from or written to.
00824   // TODO: Is this worth it if we're creating a less aligned memcpy? For
00825   // example we could be moving from movaps -> movq on x86.
00826   unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
00827 
00828   IRBuilder<> Builder(M);
00829   if (UseMemMove)
00830     Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00831                           Align, M->isVolatile());
00832   else
00833     Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00834                          Align, M->isVolatile());
00835 
00836   // Remove the instruction we're replacing.
00837   MD->removeInstruction(M);
00838   M->eraseFromParent();
00839   ++NumMemCpyInstr;
00840   return true;
00841 }
00842 
00843 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
00844 /// \p MemSet.  Try to simplify \p MemSet to only set the trailing bytes that
00845 /// weren't copied over by \p MemCpy.
00846 ///
00847 /// In other words, transform:
00848 /// \code
00849 ///   memset(dst, c, dst_size);
00850 ///   memcpy(dst, src, src_size);
00851 /// \endcode
00852 /// into:
00853 /// \code
00854 ///   memcpy(dst, src, src_size);
00855 ///   memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
00856 /// \endcode
00857 bool MemCpyOpt::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
00858                                               MemSetInst *MemSet) {
00859   // We can only transform memset/memcpy with the same destination.
00860   if (MemSet->getDest() != MemCpy->getDest())
00861     return false;
00862 
00863   Value *Dest = MemSet->getDest();
00864   Value *DestSize = MemSet->getLength();
00865   Value *SrcSize = MemCpy->getLength();
00866 
00867   // By default, create an unaligned memset.
00868   unsigned Align = 1;
00869   // If Dest is aligned, and SrcSize is constant, use the minimum alignment
00870   // of the sum.
00871   const unsigned DestAlign =
00872       std::max(MemSet->getAlignment(), MemCpy->getAlignment());
00873   if (DestAlign > 1)
00874     if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
00875       Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
00876 
00877   IRBuilder<> Builder(MemCpy->getNextNode());
00878 
00879   // If the sizes have different types, zext the smaller one.
00880   if (DestSize->getType() != SrcSize->getType()) {
00881     if (DestSize->getType()->getIntegerBitWidth() >
00882         SrcSize->getType()->getIntegerBitWidth())
00883       SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
00884     else
00885       DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
00886   }
00887 
00888   Value *MemsetLen =
00889       Builder.CreateSelect(Builder.CreateICmpULE(DestSize, SrcSize),
00890                            ConstantInt::getNullValue(DestSize->getType()),
00891                            Builder.CreateSub(DestSize, SrcSize));
00892   Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
00893                        MemsetLen, Align);
00894 
00895   MD->removeInstruction(MemSet);
00896   MemSet->eraseFromParent();
00897   return true;
00898 }
00899 
00900 /// processMemCpy - perform simplification of memcpy's.  If we have memcpy A
00901 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
00902 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
00903 /// circumstances). This allows later passes to remove the first memcpy
00904 /// altogether.
00905 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
00906   // We can only optimize non-volatile memcpy's.
00907   if (M->isVolatile()) return false;
00908 
00909   // If the source and destination of the memcpy are the same, then zap it.
00910   if (M->getSource() == M->getDest()) {
00911     MD->removeInstruction(M);
00912     M->eraseFromParent();
00913     return false;
00914   }
00915 
00916   // If copying from a constant, try to turn the memcpy into a memset.
00917   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
00918     if (GV->isConstant() && GV->hasDefinitiveInitializer())
00919       if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
00920         IRBuilder<> Builder(M);
00921         Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
00922                              M->getAlignment(), false);
00923         MD->removeInstruction(M);
00924         M->eraseFromParent();
00925         ++NumCpyToSet;
00926         return true;
00927       }
00928 
00929   AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
00930   MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
00931                                                          M, M->getParent());
00932 
00933   // Try to turn a partially redundant memset + memcpy into
00934   // memcpy + smaller memset.  We don't need the memcpy size for this.
00935   if (SrcDepInfo.isClobber())
00936     if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
00937       if (processMemSetMemCpyDependence(M, MDep))
00938         return true;
00939 
00940   // The optimizations after this point require the memcpy size.
00941   ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
00942   if (!CopySize) return false;
00943 
00944   // The are three possible optimizations we can do for memcpy:
00945   //   a) memcpy-memcpy xform which exposes redundance for DSE.
00946   //   b) call-memcpy xform for return slot optimization.
00947   //   c) memcpy from freshly alloca'd space or space that has just started its
00948   //      lifetime copies undefined data, and we can therefore eliminate the
00949   //      memcpy in favor of the data that was already at the destination.
00950   MemDepResult DepInfo = MD->getDependency(M);
00951   if (DepInfo.isClobber()) {
00952     if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
00953       if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
00954                                CopySize->getZExtValue(), M->getAlignment(),
00955                                C)) {
00956         MD->removeInstruction(M);
00957         M->eraseFromParent();
00958         return true;
00959       }
00960     }
00961   }
00962 
00963   if (SrcDepInfo.isClobber()) {
00964     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
00965       return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
00966   } else if (SrcDepInfo.isDef()) {
00967     Instruction *I = SrcDepInfo.getInst();
00968     bool hasUndefContents = false;
00969 
00970     if (isa<AllocaInst>(I)) {
00971       hasUndefContents = true;
00972     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00973       if (II->getIntrinsicID() == Intrinsic::lifetime_start)
00974         if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
00975           if (LTSize->getZExtValue() >= CopySize->getZExtValue())
00976             hasUndefContents = true;
00977     }
00978 
00979     if (hasUndefContents) {
00980       MD->removeInstruction(M);
00981       M->eraseFromParent();
00982       ++NumMemCpyInstr;
00983       return true;
00984     }
00985   }
00986 
00987   return false;
00988 }
00989 
00990 /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
00991 /// are guaranteed not to alias.
00992 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
00993   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00994 
00995   if (!TLI->has(LibFunc::memmove))
00996     return false;
00997 
00998   // See if the pointers alias.
00999   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
01000     return false;
01001 
01002   DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
01003 
01004   // If not, then we know we can transform this.
01005   Module *Mod = M->getParent()->getParent()->getParent();
01006   Type *ArgTys[3] = { M->getRawDest()->getType(),
01007                       M->getRawSource()->getType(),
01008                       M->getLength()->getType() };
01009   M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
01010                                                  ArgTys));
01011 
01012   // MemDep may have over conservative information about this instruction, just
01013   // conservatively flush it from the cache.
01014   MD->removeInstruction(M);
01015 
01016   ++NumMoveToCpy;
01017   return true;
01018 }
01019 
01020 /// processByValArgument - This is called on every byval argument in call sites.
01021 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
01022   const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
01023   // Find out what feeds this byval argument.
01024   Value *ByValArg = CS.getArgument(ArgNo);
01025   Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
01026   uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
01027   MemDepResult DepInfo =
01028     MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
01029                                  true, CS.getInstruction(),
01030                                  CS.getInstruction()->getParent());
01031   if (!DepInfo.isClobber())
01032     return false;
01033 
01034   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
01035   // a memcpy, see if we can byval from the source of the memcpy instead of the
01036   // result.
01037   MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
01038   if (!MDep || MDep->isVolatile() ||
01039       ByValArg->stripPointerCasts() != MDep->getDest())
01040     return false;
01041 
01042   // The length of the memcpy must be larger or equal to the size of the byval.
01043   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
01044   if (!C1 || C1->getValue().getZExtValue() < ByValSize)
01045     return false;
01046 
01047   // Get the alignment of the byval.  If the call doesn't specify the alignment,
01048   // then it is some target specific value that we can't know.
01049   unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
01050   if (ByValAlign == 0) return false;
01051 
01052   // If it is greater than the memcpy, then we check to see if we can force the
01053   // source of the memcpy to the alignment we need.  If we fail, we bail out.
01054   AssumptionCache &AC =
01055       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
01056           *CS->getParent()->getParent());
01057   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01058   if (MDep->getAlignment() < ByValAlign &&
01059       getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
01060                                  CS.getInstruction(), &AC, &DT) < ByValAlign)
01061     return false;
01062 
01063   // Verify that the copied-from memory doesn't change in between the memcpy and
01064   // the byval call.
01065   //    memcpy(a <- b)
01066   //    *b = 42;
01067   //    foo(*a)
01068   // It would be invalid to transform the second memcpy into foo(*b).
01069   //
01070   // NOTE: This is conservative, it will stop on any read from the source loc,
01071   // not just the defining memcpy.
01072   MemDepResult SourceDep =
01073     MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
01074                                  false, CS.getInstruction(), MDep->getParent());
01075   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
01076     return false;
01077 
01078   Value *TmpCast = MDep->getSource();
01079   if (MDep->getSource()->getType() != ByValArg->getType())
01080     TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
01081                               "tmpcast", CS.getInstruction());
01082 
01083   DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
01084                << "  " << *MDep << "\n"
01085                << "  " << *CS.getInstruction() << "\n");
01086 
01087   // Otherwise we're good!  Update the byval argument.
01088   CS.setArgument(ArgNo, TmpCast);
01089   ++NumMemCpyInstr;
01090   return true;
01091 }
01092 
01093 /// iterateOnFunction - Executes one iteration of MemCpyOpt.
01094 bool MemCpyOpt::iterateOnFunction(Function &F) {
01095   bool MadeChange = false;
01096 
01097   // Walk all instruction in the function.
01098   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
01099     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
01100       // Avoid invalidating the iterator.
01101       Instruction *I = BI++;
01102 
01103       bool RepeatInstruction = false;
01104 
01105       if (StoreInst *SI = dyn_cast<StoreInst>(I))
01106         MadeChange |= processStore(SI, BI);
01107       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
01108         RepeatInstruction = processMemSet(M, BI);
01109       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
01110         RepeatInstruction = processMemCpy(M);
01111       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
01112         RepeatInstruction = processMemMove(M);
01113       else if (auto CS = CallSite(I)) {
01114         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
01115           if (CS.isByValArgument(i))
01116             MadeChange |= processByValArgument(CS, i);
01117       }
01118 
01119       // Reprocess the instruction if desired.
01120       if (RepeatInstruction) {
01121         if (BI != BB->begin()) --BI;
01122         MadeChange = true;
01123       }
01124     }
01125   }
01126 
01127   return MadeChange;
01128 }
01129 
01130 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
01131 // function.
01132 //
01133 bool MemCpyOpt::runOnFunction(Function &F) {
01134   if (skipOptnoneFunction(F))
01135     return false;
01136 
01137   bool MadeChange = false;
01138   MD = &getAnalysis<MemoryDependenceAnalysis>();
01139   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
01140 
01141   // If we don't have at least memset and memcpy, there is little point of doing
01142   // anything here.  These are required by a freestanding implementation, so if
01143   // even they are disabled, there is no point in trying hard.
01144   if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
01145     return false;
01146 
01147   while (1) {
01148     if (!iterateOnFunction(F))
01149       break;
01150     MadeChange = true;
01151   }
01152 
01153   MD = nullptr;
01154   return MadeChange;
01155 }