MemCpyOptimizer.cpp revision 239462
155682Smarkm//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
272445Sassar//
355682Smarkm//                     The LLVM Compiler Infrastructure
455682Smarkm//
555682Smarkm// This file is distributed under the University of Illinois Open Source
655682Smarkm// License. See LICENSE.TXT for details.
755682Smarkm//
855682Smarkm//===----------------------------------------------------------------------===//
955682Smarkm//
1055682Smarkm// This pass performs various transformations related to eliminating memcpy
1155682Smarkm// calls, or transforming sets of stores into memset's.
1255682Smarkm//
1355682Smarkm//===----------------------------------------------------------------------===//
1455682Smarkm
1555682Smarkm#define DEBUG_TYPE "memcpyopt"
1655682Smarkm#include "llvm/Transforms/Scalar.h"
1755682Smarkm#include "llvm/GlobalVariable.h"
1855682Smarkm#include "llvm/IRBuilder.h"
1955682Smarkm#include "llvm/Instructions.h"
2055682Smarkm#include "llvm/IntrinsicInst.h"
2155682Smarkm#include "llvm/ADT/SmallVector.h"
2255682Smarkm#include "llvm/ADT/Statistic.h"
2355682Smarkm#include "llvm/Analysis/AliasAnalysis.h"
2455682Smarkm#include "llvm/Analysis/Dominators.h"
2555682Smarkm#include "llvm/Analysis/MemoryDependenceAnalysis.h"
2655682Smarkm#include "llvm/Analysis/ValueTracking.h"
2755682Smarkm#include "llvm/Support/Debug.h"
2855682Smarkm#include "llvm/Support/GetElementPtrTypeIterator.h"
2955682Smarkm#include "llvm/Support/raw_ostream.h"
3055682Smarkm#include "llvm/Target/TargetData.h"
3155682Smarkm#include "llvm/Target/TargetLibraryInfo.h"
3255682Smarkm#include "llvm/Transforms/Utils/Local.h"
3355682Smarkm#include <list>
3455682Smarkmusing namespace llvm;
3572445Sassar
3655682SmarkmSTATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
37178825SdfrSTATISTIC(NumMemSetInfer, "Number of memsets inferred");
3872445SassarSTATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
3955682SmarkmSTATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
4055682Smarkm
4155682Smarkmstatic int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
4255682Smarkm                                  bool &VariableIdxFound, const TargetData &TD){
43178825Sdfr  // Skip over the first indices.
4455682Smarkm  gep_type_iterator GTI = gep_type_begin(GEP);
4555682Smarkm  for (unsigned i = 1; i != Idx; ++i, ++GTI)
4655682Smarkm    /*skip along*/;
4755682Smarkm
4855682Smarkm  // Compute the offset implied by the rest of the indices.
4978527Sassar  int64_t Offset = 0;
5078527Sassar  for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5155682Smarkm    ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
5278527Sassar    if (OpC == 0)
5355682Smarkm      return VariableIdxFound = true;
5455682Smarkm    if (OpC->isZero()) continue;  // No offset.
5555682Smarkm
56178825Sdfr    // Handle struct indices, which add their field offset to the pointer.
5755682Smarkm    if (StructType *STy = dyn_cast<StructType>(*GTI)) {
5855682Smarkm      Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5955682Smarkm      continue;
6055682Smarkm    }
61178825Sdfr
6278527Sassar    // Otherwise, we have a sequential type like an array or vector.  Multiply
6378527Sassar    // the index by the ElementSize.
6478527Sassar    uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
6555682Smarkm    Offset += Size*OpC->getSExtValue();
6678527Sassar  }
6755682Smarkm
6878527Sassar  return Offset;
6978527Sassar}
7055682Smarkm
7178527Sassar/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
7255682Smarkm/// constant offset, and return that constant offset.  For example, Ptr1 might
7355682Smarkm/// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
7455682Smarkmstatic bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
75178825Sdfr                            const TargetData &TD) {
7655682Smarkm  Ptr1 = Ptr1->stripPointerCasts();
7755682Smarkm  Ptr2 = Ptr2->stripPointerCasts();
7855682Smarkm  GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
7955682Smarkm  GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
8055682Smarkm
81178825Sdfr  bool VariableIdxFound = false;
82178825Sdfr
83178825Sdfr  // If one pointer is a GEP and the other isn't, then see if the GEP is a
8478527Sassar  // constant offset from the base, as in "P" and "gep P, 1".
8578527Sassar  if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
8678527Sassar    Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
8755682Smarkm    return !VariableIdxFound;
8878527Sassar  }
8955682Smarkm
9055682Smarkm  if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
9155682Smarkm    Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
9255682Smarkm    return !VariableIdxFound;
93178825Sdfr  }
94178825Sdfr
95178825Sdfr  // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
96178825Sdfr  // base.  After that base, they may have some number of common (and
9755682Smarkm  // potentially variable) indices.  After that they handle some constant
9855682Smarkm  // offset, which determines their offset from each other.  At this point, we
9955682Smarkm  // handle no other case.
100178825Sdfr  if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
10155682Smarkm    return false;
10255682Smarkm
10355682Smarkm  // Skip any common indices and track the GEP types.
10455682Smarkm  unsigned Idx = 1;
10555682Smarkm  for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
106178825Sdfr    if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
10772445Sassar      break;
10872445Sassar
10972445Sassar  int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
11072445Sassar  int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
11172445Sassar  if (VariableIdxFound) return false;
112178825Sdfr
11355682Smarkm  Offset = Offset2-Offset1;
11455682Smarkm  return true;
11555682Smarkm}
11655682Smarkm
11755682Smarkm
11855682Smarkm/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
11955682Smarkm/// This allows us to analyze stores like:
12055682Smarkm///   store 0 -> P+1
12155682Smarkm///   store 0 -> P+0
12255682Smarkm///   store 0 -> P+3
12355682Smarkm///   store 0 -> P+2
124178825Sdfr/// which sometimes happens with stores to arrays of structs etc.  When we see
12555682Smarkm/// the first store, we make a range [1, 2).  The second store extends the range
12655682Smarkm/// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
12755682Smarkm/// two ranges into [0, 3) which is memset'able.
12855682Smarkmnamespace {
12955682Smarkmstruct MemsetRange {
13055682Smarkm  // Start/End - A semi range that describes the span that this range covers.
13178527Sassar  // The range is closed at the start and open at the end: [Start, End).
13278527Sassar  int64_t Start, End;
13378527Sassar
13478527Sassar  /// StartPtr - The getelementptr instruction that points to the start of the
13578527Sassar  /// range.
13678527Sassar  Value *StartPtr;
13778527Sassar
13878527Sassar  /// Alignment - The known alignment of the first store.
13955682Smarkm  unsigned Alignment;
14055682Smarkm
14155682Smarkm  /// TheStores - The actual stores that make up this range.
14255682Smarkm  SmallVector<Instruction*, 16> TheStores;
14355682Smarkm
14455682Smarkm  bool isProfitableToUseMemset(const TargetData &TD) const;
145178825Sdfr
14655682Smarkm};
14755682Smarkm} // end anon namespace
14855682Smarkm
14955682Smarkmbool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
15055682Smarkm  // If we found more than 4 stores to merge or 16 bytes, use memset.
15155682Smarkm  if (TheStores.size() >= 4 || End-Start >= 16) return true;
152178825Sdfr
15355682Smarkm  // If there is nothing to merge, don't do anything.
15455682Smarkm  if (TheStores.size() < 2) return false;
15555682Smarkm
15678527Sassar  // If any of the stores are a memset, then it is always good to extend the
15778527Sassar  // memset.
15878527Sassar  for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
15978527Sassar    if (!isa<StoreInst>(TheStores[i]))
16078527Sassar      return true;
16178527Sassar
16278527Sassar  // Assume that the code generator is capable of merging pairs of stores
16378527Sassar  // together if it wants to.
16455682Smarkm  if (TheStores.size() == 2) return false;
16555682Smarkm
16655682Smarkm  // If we have fewer than 8 stores, it can still be worthwhile to do this.
167178825Sdfr  // For example, merging 4 i8 stores into an i32 store is useful almost always.
16855682Smarkm  // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
16955682Smarkm  // memset will be split into 2 32-bit stores anyway) and doing so can
17055682Smarkm  // pessimize the llvm optimizer.
17155682Smarkm  //
17255682Smarkm  // Since we don't have perfect knowledge here, make some assumptions: assume
17355682Smarkm  // the maximum GPR width is the same size as the pointer size and assume that
17455682Smarkm  // this width can be stored.  If so, check to see whether we will end up
17555682Smarkm  // actually reducing the number of stores used.
17655682Smarkm  unsigned Bytes = unsigned(End-Start);
17755682Smarkm  unsigned NumPointerStores = Bytes/TD.getPointerSize();
17855682Smarkm
17957416Smarkm  // Assume the remaining bytes if any are done a byte at a time.
18055682Smarkm  unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
18157416Smarkm
18272445Sassar  // If we will reduce the # stores (according to this heuristic), do the
18372445Sassar  // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
18455682Smarkm  // etc.
18572445Sassar  return TheStores.size() > NumPointerStores+NumByteStores;
18672445Sassar}
18772445Sassar
18872445Sassar
18972445Sassarnamespace {
19055682Smarkmclass MemsetRanges {
19155682Smarkm  /// Ranges - A sorted list of the memset ranges.  We use std::list here
192178825Sdfr  /// because each element is relatively large and expensive to copy.
19355682Smarkm  std::list<MemsetRange> Ranges;
19455682Smarkm  typedef std::list<MemsetRange>::iterator range_iterator;
19572445Sassar  const TargetData &TD;
19655682Smarkmpublic:
19755682Smarkm  MemsetRanges(const TargetData &td) : TD(td) {}
19855682Smarkm
19955682Smarkm  typedef std::list<MemsetRange>::const_iterator const_iterator;
20078527Sassar  const_iterator begin() const { return Ranges.begin(); }
20178527Sassar  const_iterator end() const { return Ranges.end(); }
20255682Smarkm  bool empty() const { return Ranges.empty(); }
20355682Smarkm
20455682Smarkm  void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
20578527Sassar    if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
20678527Sassar      addStore(OffsetFromFirst, SI);
20778527Sassar    else
20878527Sassar      addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
20978527Sassar  }
21078527Sassar
21155682Smarkm  void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
21255682Smarkm    int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
21355682Smarkm
21455682Smarkm    addRange(OffsetFromFirst, StoreSize,
21555682Smarkm             SI->getPointerOperand(), SI->getAlignment(), SI);
21655682Smarkm  }
21755682Smarkm
21878527Sassar  void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
21955682Smarkm    int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
22055682Smarkm    addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
22155682Smarkm  }
22255682Smarkm
22378527Sassar  void addRange(int64_t Start, int64_t Size, Value *Ptr,
22455682Smarkm                unsigned Alignment, Instruction *Inst);
22578527Sassar
22678527Sassar};
22755682Smarkm
22855682Smarkm} // end anon namespace
22955682Smarkm
23078527Sassar
23178527Sassar/// addRange - Add a new store to the MemsetRanges data structure.  This adds a
23278527Sassar/// new range for the specified store at the specified offset, merging into
23355682Smarkm/// existing ranges as appropriate.
23478527Sassar///
23555682Smarkm/// Do a linear search of the ranges to see if this can be joined and/or to
23655682Smarkm/// find the insertion point in the list.  We keep the ranges sorted for
23755682Smarkm/// simplicity here.  This is a linear search of a linked list, which is ugly,
23855682Smarkm/// however the number of ranges is limited, so this won't get crazy slow.
23955682Smarkmvoid MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
240178825Sdfr                            unsigned Alignment, Instruction *Inst) {
24155682Smarkm  int64_t End = Start+Size;
24255682Smarkm  range_iterator I = Ranges.begin(), E = Ranges.end();
24355682Smarkm
24455682Smarkm  while (I != E && Start > I->End)
24555682Smarkm    ++I;
24655682Smarkm
247178825Sdfr  // We now know that I == E, in which case we didn't find anything to merge
24855682Smarkm  // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
24955682Smarkm  // to insert a new range.  Handle this now.
25055682Smarkm  if (I == E || End < I->Start) {
25155682Smarkm    MemsetRange &R = *Ranges.insert(I, MemsetRange());
25255682Smarkm    R.Start        = Start;
25355682Smarkm    R.End          = End;
25455682Smarkm    R.StartPtr     = Ptr;
25555682Smarkm    R.Alignment    = Alignment;
25655682Smarkm    R.TheStores.push_back(Inst);
25755682Smarkm    return;
25855682Smarkm  }
25955682Smarkm
26055682Smarkm  // This store overlaps with I, add it.
26178527Sassar  I->TheStores.push_back(Inst);
26255682Smarkm
26355682Smarkm  // At this point, we may have an interval that completely contains our store.
26472445Sassar  // If so, just add it to the interval and return.
265178825Sdfr  if (I->Start <= Start && I->End >= End)
26655682Smarkm    return;
26755682Smarkm
26855682Smarkm  // Now we know that Start <= I->End and End >= I->Start so the range overlaps
26955682Smarkm  // but is not entirely contained within the range.
27055682Smarkm
27155682Smarkm  // See if the range extends the start of the range.  In this case, it couldn't
272178825Sdfr  // possibly cause it to join the prior range, because otherwise we would have
27355682Smarkm  // stopped on *it*.
27455682Smarkm  if (Start < I->Start) {
27555682Smarkm    I->Start = Start;
27655682Smarkm    I->StartPtr = Ptr;
27755682Smarkm    I->Alignment = Alignment;
27855682Smarkm  }
279178825Sdfr
28072445Sassar  // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
28172445Sassar  // is in or right at the end of I), and that End >= I->Start.  Extend I out to
28272445Sassar  // End.
28372445Sassar  if (End > I->End) {
28472445Sassar    I->End = End;
28572445Sassar    range_iterator NextI = I;
28672445Sassar    while (++NextI != E && End >= NextI->Start) {
28772445Sassar      // Merge the range in.
28872445Sassar      I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
28978527Sassar      if (NextI->End > I->End)
29078527Sassar        I->End = NextI->End;
29178527Sassar      Ranges.erase(NextI);
29272445Sassar      NextI = I;
29378527Sassar    }
29472445Sassar  }
29572445Sassar}
29690926Snectar
29772445Sassar//===----------------------------------------------------------------------===//
29872445Sassar//                         MemCpyOpt Pass
29972445Sassar//===----------------------------------------------------------------------===//
30072445Sassar
30178527Sassarnamespace {
30278527Sassar  class MemCpyOpt : public FunctionPass {
30372445Sassar    MemoryDependenceAnalysis *MD;
30478527Sassar    TargetLibraryInfo *TLI;
30572445Sassar    const TargetData *TD;
30672445Sassar  public:
30772445Sassar    static char ID; // Pass identification, replacement for typeid
30872445Sassar    MemCpyOpt() : FunctionPass(ID) {
30972445Sassar      initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
31072445Sassar      MD = 0;
31172445Sassar      TLI = 0;
31272445Sassar      TD = 0;
313    }
314
315    bool runOnFunction(Function &F);
316
317  private:
318    // This transformation requires dominator postdominator info
319    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
320      AU.setPreservesCFG();
321      AU.addRequired<DominatorTree>();
322      AU.addRequired<MemoryDependenceAnalysis>();
323      AU.addRequired<AliasAnalysis>();
324      AU.addRequired<TargetLibraryInfo>();
325      AU.addPreserved<AliasAnalysis>();
326      AU.addPreserved<MemoryDependenceAnalysis>();
327    }
328
329    // Helper fuctions
330    bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
331    bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
332    bool processMemCpy(MemCpyInst *M);
333    bool processMemMove(MemMoveInst *M);
334    bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
335                              uint64_t cpyLen, CallInst *C);
336    bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
337                                       uint64_t MSize);
338    bool processByValArgument(CallSite CS, unsigned ArgNo);
339    Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
340                                      Value *ByteVal);
341
342    bool iterateOnFunction(Function &F);
343  };
344
345  char MemCpyOpt::ID = 0;
346}
347
348// createMemCpyOptPass - The public interface to this file...
349FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
350
351INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
352                      false, false)
353INITIALIZE_PASS_DEPENDENCY(DominatorTree)
354INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
355INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
356INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
357INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
358                    false, false)
359
360/// tryMergingIntoMemset - When scanning forward over instructions, we look for
361/// some other patterns to fold away.  In particular, this looks for stores to
362/// neighboring locations of memory.  If it sees enough consecutive ones, it
363/// attempts to merge them together into a memcpy/memset.
364Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
365                                             Value *StartPtr, Value *ByteVal) {
366  if (TD == 0) return 0;
367
368  // Okay, so we now have a single store that can be splatable.  Scan to find
369  // all subsequent stores of the same value to offset from the same pointer.
370  // Join these together into ranges, so we can decide whether contiguous blocks
371  // are stored.
372  MemsetRanges Ranges(*TD);
373
374  BasicBlock::iterator BI = StartInst;
375  for (++BI; !isa<TerminatorInst>(BI); ++BI) {
376    if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
377      // If the instruction is readnone, ignore it, otherwise bail out.  We
378      // don't even allow readonly here because we don't want something like:
379      // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
380      if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
381        break;
382      continue;
383    }
384
385    if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
386      // If this is a store, see if we can merge it in.
387      if (!NextStore->isSimple()) break;
388
389      // Check to see if this stored value is of the same byte-splattable value.
390      if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
391        break;
392
393      // Check to see if this store is to a constant offset from the start ptr.
394      int64_t Offset;
395      if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
396                           Offset, *TD))
397        break;
398
399      Ranges.addStore(Offset, NextStore);
400    } else {
401      MemSetInst *MSI = cast<MemSetInst>(BI);
402
403      if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
404          !isa<ConstantInt>(MSI->getLength()))
405        break;
406
407      // Check to see if this store is to a constant offset from the start ptr.
408      int64_t Offset;
409      if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD))
410        break;
411
412      Ranges.addMemSet(Offset, MSI);
413    }
414  }
415
416  // If we have no ranges, then we just had a single store with nothing that
417  // could be merged in.  This is a very common case of course.
418  if (Ranges.empty())
419    return 0;
420
421  // If we had at least one store that could be merged in, add the starting
422  // store as well.  We try to avoid this unless there is at least something
423  // interesting as a small compile-time optimization.
424  Ranges.addInst(0, StartInst);
425
426  // If we create any memsets, we put it right before the first instruction that
427  // isn't part of the memset block.  This ensure that the memset is dominated
428  // by any addressing instruction needed by the start of the block.
429  IRBuilder<> Builder(BI);
430
431  // Now that we have full information about ranges, loop over the ranges and
432  // emit memset's for anything big enough to be worthwhile.
433  Instruction *AMemSet = 0;
434  for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
435       I != E; ++I) {
436    const MemsetRange &Range = *I;
437
438    if (Range.TheStores.size() == 1) continue;
439
440    // If it is profitable to lower this range to memset, do so now.
441    if (!Range.isProfitableToUseMemset(*TD))
442      continue;
443
444    // Otherwise, we do want to transform this!  Create a new memset.
445    // Get the starting pointer of the block.
446    StartPtr = Range.StartPtr;
447
448    // Determine alignment
449    unsigned Alignment = Range.Alignment;
450    if (Alignment == 0) {
451      Type *EltType =
452        cast<PointerType>(StartPtr->getType())->getElementType();
453      Alignment = TD->getABITypeAlignment(EltType);
454    }
455
456    AMemSet =
457      Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
458
459    DEBUG(dbgs() << "Replace stores:\n";
460          for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
461            dbgs() << *Range.TheStores[i] << '\n';
462          dbgs() << "With: " << *AMemSet << '\n');
463
464    if (!Range.TheStores.empty())
465      AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
466
467    // Zap all the stores.
468    for (SmallVector<Instruction*, 16>::const_iterator
469         SI = Range.TheStores.begin(),
470         SE = Range.TheStores.end(); SI != SE; ++SI) {
471      MD->removeInstruction(*SI);
472      (*SI)->eraseFromParent();
473    }
474    ++NumMemSetInfer;
475  }
476
477  return AMemSet;
478}
479
480
481bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
482  if (!SI->isSimple()) return false;
483
484  if (TD == 0) return false;
485
486  // Detect cases where we're performing call slot forwarding, but
487  // happen to be using a load-store pair to implement it, rather than
488  // a memcpy.
489  if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
490    if (LI->isSimple() && LI->hasOneUse() &&
491        LI->getParent() == SI->getParent()) {
492      MemDepResult ldep = MD->getDependency(LI);
493      CallInst *C = 0;
494      if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
495        C = dyn_cast<CallInst>(ldep.getInst());
496
497      if (C) {
498        // Check that nothing touches the dest of the "copy" between
499        // the call and the store.
500        AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
501        AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
502        for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
503                                  E = C; I != E; --I) {
504          if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
505            C = 0;
506            break;
507          }
508        }
509      }
510
511      if (C) {
512        bool changed = performCallSlotOptzn(LI,
513                        SI->getPointerOperand()->stripPointerCasts(),
514                        LI->getPointerOperand()->stripPointerCasts(),
515                        TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
516        if (changed) {
517          MD->removeInstruction(SI);
518          SI->eraseFromParent();
519          MD->removeInstruction(LI);
520          LI->eraseFromParent();
521          ++NumMemCpyInstr;
522          return true;
523        }
524      }
525    }
526  }
527
528  // There are two cases that are interesting for this code to handle: memcpy
529  // and memset.  Right now we only handle memset.
530
531  // Ensure that the value being stored is something that can be memset'able a
532  // byte at a time like "0" or "-1" or any width, as well as things like
533  // 0xA0A0A0A0 and 0.0.
534  if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
535    if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
536                                              ByteVal)) {
537      BBI = I;  // Don't invalidate iterator.
538      return true;
539    }
540
541  return false;
542}
543
544bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
545  // See if there is another memset or store neighboring this memset which
546  // allows us to widen out the memset to do a single larger store.
547  if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
548    if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
549                                              MSI->getValue())) {
550      BBI = I;  // Don't invalidate iterator.
551      return true;
552    }
553  return false;
554}
555
556
557/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
558/// and checks for the possibility of a call slot optimization by having
559/// the call write its result directly into the destination of the memcpy.
560bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
561                                     Value *cpyDest, Value *cpySrc,
562                                     uint64_t cpyLen, CallInst *C) {
563  // The general transformation to keep in mind is
564  //
565  //   call @func(..., src, ...)
566  //   memcpy(dest, src, ...)
567  //
568  // ->
569  //
570  //   memcpy(dest, src, ...)
571  //   call @func(..., dest, ...)
572  //
573  // Since moving the memcpy is technically awkward, we additionally check that
574  // src only holds uninitialized values at the moment of the call, meaning that
575  // the memcpy can be discarded rather than moved.
576
577  // Deliberately get the source and destination with bitcasts stripped away,
578  // because we'll need to do type comparisons based on the underlying type.
579  CallSite CS(C);
580
581  // Require that src be an alloca.  This simplifies the reasoning considerably.
582  AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
583  if (!srcAlloca)
584    return false;
585
586  // Check that all of src is copied to dest.
587  if (TD == 0) return false;
588
589  ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
590  if (!srcArraySize)
591    return false;
592
593  uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
594    srcArraySize->getZExtValue();
595
596  if (cpyLen < srcSize)
597    return false;
598
599  // Check that accessing the first srcSize bytes of dest will not cause a
600  // trap.  Otherwise the transform is invalid since it might cause a trap
601  // to occur earlier than it otherwise would.
602  if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
603    // The destination is an alloca.  Check it is larger than srcSize.
604    ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
605    if (!destArraySize)
606      return false;
607
608    uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
609      destArraySize->getZExtValue();
610
611    if (destSize < srcSize)
612      return false;
613  } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
614    // If the destination is an sret parameter then only accesses that are
615    // outside of the returned struct type can trap.
616    if (!A->hasStructRetAttr())
617      return false;
618
619    Type *StructTy = cast<PointerType>(A->getType())->getElementType();
620    uint64_t destSize = TD->getTypeAllocSize(StructTy);
621
622    if (destSize < srcSize)
623      return false;
624  } else {
625    return false;
626  }
627
628  // Check that src is not accessed except via the call and the memcpy.  This
629  // guarantees that it holds only undefined values when passed in (so the final
630  // memcpy can be dropped), that it is not read or written between the call and
631  // the memcpy, and that writing beyond the end of it is undefined.
632  SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
633                                   srcAlloca->use_end());
634  while (!srcUseList.empty()) {
635    User *UI = srcUseList.pop_back_val();
636
637    if (isa<BitCastInst>(UI)) {
638      for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
639           I != E; ++I)
640        srcUseList.push_back(*I);
641    } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
642      if (G->hasAllZeroIndices())
643        for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
644             I != E; ++I)
645          srcUseList.push_back(*I);
646      else
647        return false;
648    } else if (UI != C && UI != cpy) {
649      return false;
650    }
651  }
652
653  // Since we're changing the parameter to the callsite, we need to make sure
654  // that what would be the new parameter dominates the callsite.
655  DominatorTree &DT = getAnalysis<DominatorTree>();
656  if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
657    if (!DT.dominates(cpyDestInst, C))
658      return false;
659
660  // In addition to knowing that the call does not access src in some
661  // unexpected manner, for example via a global, which we deduce from
662  // the use analysis, we also need to know that it does not sneakily
663  // access dest.  We rely on AA to figure this out for us.
664  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
665  AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
666  // If necessary, perform additional analysis.
667  if (MR != AliasAnalysis::NoModRef)
668    MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
669  if (MR != AliasAnalysis::NoModRef)
670    return false;
671
672  // All the checks have passed, so do the transformation.
673  bool changedArgument = false;
674  for (unsigned i = 0; i < CS.arg_size(); ++i)
675    if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
676      if (cpySrc->getType() != cpyDest->getType())
677        cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
678                                              cpyDest->getName(), C);
679      changedArgument = true;
680      if (CS.getArgument(i)->getType() == cpyDest->getType())
681        CS.setArgument(i, cpyDest);
682      else
683        CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
684                          CS.getArgument(i)->getType(), cpyDest->getName(), C));
685    }
686
687  if (!changedArgument)
688    return false;
689
690  // Drop any cached information about the call, because we may have changed
691  // its dependence information by changing its parameter.
692  MD->removeInstruction(C);
693
694  // Remove the memcpy.
695  MD->removeInstruction(cpy);
696  ++NumMemCpyInstr;
697
698  return true;
699}
700
701/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
702/// memory dependence of memcpy 'M' is the memcpy 'MDep'.  Try to simplify M to
703/// copy from MDep's input if we can.  MSize is the size of M's copy.
704///
705bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
706                                              uint64_t MSize) {
707  // We can only transforms memcpy's where the dest of one is the source of the
708  // other.
709  if (M->getSource() != MDep->getDest() || MDep->isVolatile())
710    return false;
711
712  // If dep instruction is reading from our current input, then it is a noop
713  // transfer and substituting the input won't change this instruction.  Just
714  // ignore the input and let someone else zap MDep.  This handles cases like:
715  //    memcpy(a <- a)
716  //    memcpy(b <- a)
717  if (M->getSource() == MDep->getSource())
718    return false;
719
720  // Second, the length of the memcpy's must be the same, or the preceding one
721  // must be larger than the following one.
722  ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
723  ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
724  if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
725    return false;
726
727  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
728
729  // Verify that the copied-from memory doesn't change in between the two
730  // transfers.  For example, in:
731  //    memcpy(a <- b)
732  //    *b = 42;
733  //    memcpy(c <- a)
734  // It would be invalid to transform the second memcpy into memcpy(c <- b).
735  //
736  // TODO: If the code between M and MDep is transparent to the destination "c",
737  // then we could still perform the xform by moving M up to the first memcpy.
738  //
739  // NOTE: This is conservative, it will stop on any read from the source loc,
740  // not just the defining memcpy.
741  MemDepResult SourceDep =
742    MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
743                                 false, M, M->getParent());
744  if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
745    return false;
746
747  // If the dest of the second might alias the source of the first, then the
748  // source and dest might overlap.  We still want to eliminate the intermediate
749  // value, but we have to generate a memmove instead of memcpy.
750  bool UseMemMove = false;
751  if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
752    UseMemMove = true;
753
754  // If all checks passed, then we can transform M.
755
756  // Make sure to use the lesser of the alignment of the source and the dest
757  // since we're changing where we're reading from, but don't want to increase
758  // the alignment past what can be read from or written to.
759  // TODO: Is this worth it if we're creating a less aligned memcpy? For
760  // example we could be moving from movaps -> movq on x86.
761  unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
762
763  IRBuilder<> Builder(M);
764  if (UseMemMove)
765    Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
766                          Align, M->isVolatile());
767  else
768    Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
769                         Align, M->isVolatile());
770
771  // Remove the instruction we're replacing.
772  MD->removeInstruction(M);
773  M->eraseFromParent();
774  ++NumMemCpyInstr;
775  return true;
776}
777
778
779/// processMemCpy - perform simplification of memcpy's.  If we have memcpy A
780/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
781/// B to be a memcpy from X to Z (or potentially a memmove, depending on
782/// circumstances). This allows later passes to remove the first memcpy
783/// altogether.
784bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
785  // We can only optimize statically-sized memcpy's that are non-volatile.
786  ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
787  if (CopySize == 0 || M->isVolatile()) return false;
788
789  // If the source and destination of the memcpy are the same, then zap it.
790  if (M->getSource() == M->getDest()) {
791    MD->removeInstruction(M);
792    M->eraseFromParent();
793    return false;
794  }
795
796  // If copying from a constant, try to turn the memcpy into a memset.
797  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
798    if (GV->isConstant() && GV->hasDefinitiveInitializer())
799      if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
800        IRBuilder<> Builder(M);
801        Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
802                             M->getAlignment(), false);
803        MD->removeInstruction(M);
804        M->eraseFromParent();
805        ++NumCpyToSet;
806        return true;
807      }
808
809  // The are two possible optimizations we can do for memcpy:
810  //   a) memcpy-memcpy xform which exposes redundance for DSE.
811  //   b) call-memcpy xform for return slot optimization.
812  MemDepResult DepInfo = MD->getDependency(M);
813  if (DepInfo.isClobber()) {
814    if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
815      if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
816                               CopySize->getZExtValue(), C)) {
817        MD->removeInstruction(M);
818        M->eraseFromParent();
819        return true;
820      }
821    }
822  }
823
824  AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
825  MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
826                                                         M, M->getParent());
827  if (SrcDepInfo.isClobber()) {
828    if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
829      return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
830  }
831
832  return false;
833}
834
835/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
836/// are guaranteed not to alias.
837bool MemCpyOpt::processMemMove(MemMoveInst *M) {
838  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
839
840  if (!TLI->has(LibFunc::memmove))
841    return false;
842
843  // See if the pointers alias.
844  if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
845    return false;
846
847  DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
848
849  // If not, then we know we can transform this.
850  Module *Mod = M->getParent()->getParent()->getParent();
851  Type *ArgTys[3] = { M->getRawDest()->getType(),
852                      M->getRawSource()->getType(),
853                      M->getLength()->getType() };
854  M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
855                                                 ArgTys));
856
857  // MemDep may have over conservative information about this instruction, just
858  // conservatively flush it from the cache.
859  MD->removeInstruction(M);
860
861  ++NumMoveToCpy;
862  return true;
863}
864
865/// processByValArgument - This is called on every byval argument in call sites.
866bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
867  if (TD == 0) return false;
868
869  // Find out what feeds this byval argument.
870  Value *ByValArg = CS.getArgument(ArgNo);
871  Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
872  uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
873  MemDepResult DepInfo =
874    MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
875                                 true, CS.getInstruction(),
876                                 CS.getInstruction()->getParent());
877  if (!DepInfo.isClobber())
878    return false;
879
880  // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
881  // a memcpy, see if we can byval from the source of the memcpy instead of the
882  // result.
883  MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
884  if (MDep == 0 || MDep->isVolatile() ||
885      ByValArg->stripPointerCasts() != MDep->getDest())
886    return false;
887
888  // The length of the memcpy must be larger or equal to the size of the byval.
889  ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
890  if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
891    return false;
892
893  // Get the alignment of the byval.  If the call doesn't specify the alignment,
894  // then it is some target specific value that we can't know.
895  unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
896  if (ByValAlign == 0) return false;
897
898  // If it is greater than the memcpy, then we check to see if we can force the
899  // source of the memcpy to the alignment we need.  If we fail, we bail out.
900  if (MDep->getAlignment() < ByValAlign &&
901      getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, TD) < ByValAlign)
902    return false;
903
904  // Verify that the copied-from memory doesn't change in between the memcpy and
905  // the byval call.
906  //    memcpy(a <- b)
907  //    *b = 42;
908  //    foo(*a)
909  // It would be invalid to transform the second memcpy into foo(*b).
910  //
911  // NOTE: This is conservative, it will stop on any read from the source loc,
912  // not just the defining memcpy.
913  MemDepResult SourceDep =
914    MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
915                                 false, CS.getInstruction(), MDep->getParent());
916  if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
917    return false;
918
919  Value *TmpCast = MDep->getSource();
920  if (MDep->getSource()->getType() != ByValArg->getType())
921    TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
922                              "tmpcast", CS.getInstruction());
923
924  DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
925               << "  " << *MDep << "\n"
926               << "  " << *CS.getInstruction() << "\n");
927
928  // Otherwise we're good!  Update the byval argument.
929  CS.setArgument(ArgNo, TmpCast);
930  ++NumMemCpyInstr;
931  return true;
932}
933
934/// iterateOnFunction - Executes one iteration of MemCpyOpt.
935bool MemCpyOpt::iterateOnFunction(Function &F) {
936  bool MadeChange = false;
937
938  // Walk all instruction in the function.
939  for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
940    for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
941      // Avoid invalidating the iterator.
942      Instruction *I = BI++;
943
944      bool RepeatInstruction = false;
945
946      if (StoreInst *SI = dyn_cast<StoreInst>(I))
947        MadeChange |= processStore(SI, BI);
948      else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
949        RepeatInstruction = processMemSet(M, BI);
950      else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
951        RepeatInstruction = processMemCpy(M);
952      else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
953        RepeatInstruction = processMemMove(M);
954      else if (CallSite CS = (Value*)I) {
955        for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
956          if (CS.isByValArgument(i))
957            MadeChange |= processByValArgument(CS, i);
958      }
959
960      // Reprocess the instruction if desired.
961      if (RepeatInstruction) {
962        if (BI != BB->begin()) --BI;
963        MadeChange = true;
964      }
965    }
966  }
967
968  return MadeChange;
969}
970
971// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
972// function.
973//
974bool MemCpyOpt::runOnFunction(Function &F) {
975  bool MadeChange = false;
976  MD = &getAnalysis<MemoryDependenceAnalysis>();
977  TD = getAnalysisIfAvailable<TargetData>();
978  TLI = &getAnalysis<TargetLibraryInfo>();
979
980  // If we don't have at least memset and memcpy, there is little point of doing
981  // anything here.  These are required by a freestanding implementation, so if
982  // even they are disabled, there is no point in trying hard.
983  if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
984    return false;
985
986  while (1) {
987    if (!iterateOnFunction(F))
988      break;
989    MadeChange = true;
990  }
991
992  MD = 0;
993  return MadeChange;
994}
995