LLVM API Documentation

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