Remove useless DEBUG
[oota-llvm.git] / lib / Transforms / Scalar / MemCpyOptimizer.cpp
1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs various transformations related to eliminating memcpy
11 // calls, or transforming sets of stores into memset's.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/GetElementPtrTypeIterator.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include <algorithm>
35 using namespace llvm;
36
37 #define DEBUG_TYPE "memcpyopt"
38
39 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
40 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
41 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
42 STATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
43
44 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
45                                   bool &VariableIdxFound,
46                                   const DataLayout &DL) {
47   // Skip over the first indices.
48   gep_type_iterator GTI = gep_type_begin(GEP);
49   for (unsigned i = 1; i != Idx; ++i, ++GTI)
50     /*skip along*/;
51
52   // Compute the offset implied by the rest of the indices.
53   int64_t Offset = 0;
54   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
55     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
56     if (!OpC)
57       return VariableIdxFound = true;
58     if (OpC->isZero()) continue;  // No offset.
59
60     // Handle struct indices, which add their field offset to the pointer.
61     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
62       Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
63       continue;
64     }
65
66     // Otherwise, we have a sequential type like an array or vector.  Multiply
67     // the index by the ElementSize.
68     uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
69     Offset += Size*OpC->getSExtValue();
70   }
71
72   return Offset;
73 }
74
75 /// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
76 /// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
77 /// might be &A[40]. In this case offset would be -8.
78 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
79                             const DataLayout &DL) {
80   Ptr1 = Ptr1->stripPointerCasts();
81   Ptr2 = Ptr2->stripPointerCasts();
82
83   // Handle the trivial case first.
84   if (Ptr1 == Ptr2) {
85     Offset = 0;
86     return true;
87   }
88
89   GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
90   GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
91
92   bool VariableIdxFound = false;
93
94   // If one pointer is a GEP and the other isn't, then see if the GEP is a
95   // constant offset from the base, as in "P" and "gep P, 1".
96   if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
97     Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
98     return !VariableIdxFound;
99   }
100
101   if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
102     Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
103     return !VariableIdxFound;
104   }
105
106   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
107   // base.  After that base, they may have some number of common (and
108   // potentially variable) indices.  After that they handle some constant
109   // offset, which determines their offset from each other.  At this point, we
110   // handle no other case.
111   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
112     return false;
113
114   // Skip any common indices and track the GEP types.
115   unsigned Idx = 1;
116   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
117     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
118       break;
119
120   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
121   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
122   if (VariableIdxFound) return false;
123
124   Offset = Offset2-Offset1;
125   return true;
126 }
127
128
129 /// Represents a range of memset'd bytes with the ByteVal value.
130 /// This allows us to analyze stores like:
131 ///   store 0 -> P+1
132 ///   store 0 -> P+0
133 ///   store 0 -> P+3
134 ///   store 0 -> P+2
135 /// which sometimes happens with stores to arrays of structs etc.  When we see
136 /// the first store, we make a range [1, 2).  The second store extends the range
137 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
138 /// two ranges into [0, 3) which is memset'able.
139 namespace {
140 struct MemsetRange {
141   // Start/End - A semi range that describes the span that this range covers.
142   // The range is closed at the start and open at the end: [Start, End).
143   int64_t Start, End;
144
145   /// StartPtr - The getelementptr instruction that points to the start of the
146   /// range.
147   Value *StartPtr;
148
149   /// Alignment - The known alignment of the first store.
150   unsigned Alignment;
151
152   /// TheStores - The actual stores that make up this range.
153   SmallVector<Instruction*, 16> TheStores;
154
155   bool isProfitableToUseMemset(const DataLayout &DL) const;
156 };
157 } // end anon namespace
158
159 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
160   // If we found more than 4 stores to merge or 16 bytes, use memset.
161   if (TheStores.size() >= 4 || End-Start >= 16) return true;
162
163   // If there is nothing to merge, don't do anything.
164   if (TheStores.size() < 2) return false;
165
166   // If any of the stores are a memset, then it is always good to extend the
167   // memset.
168   for (Instruction *SI : TheStores)
169     if (!isa<StoreInst>(SI))
170       return true;
171
172   // Assume that the code generator is capable of merging pairs of stores
173   // together if it wants to.
174   if (TheStores.size() == 2) return false;
175
176   // If we have fewer than 8 stores, it can still be worthwhile to do this.
177   // For example, merging 4 i8 stores into an i32 store is useful almost always.
178   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
179   // memset will be split into 2 32-bit stores anyway) and doing so can
180   // pessimize the llvm optimizer.
181   //
182   // Since we don't have perfect knowledge here, make some assumptions: assume
183   // the maximum GPR width is the same size as the largest legal integer
184   // size. If so, check to see whether we will end up actually reducing the
185   // number of stores used.
186   unsigned Bytes = unsigned(End-Start);
187   unsigned MaxIntSize = DL.getLargestLegalIntTypeSize();
188   if (MaxIntSize == 0)
189     MaxIntSize = 1;
190   unsigned NumPointerStores = Bytes / MaxIntSize;
191
192   // Assume the remaining bytes if any are done a byte at a time.
193   unsigned NumByteStores = Bytes % MaxIntSize;
194
195   // If we will reduce the # stores (according to this heuristic), do the
196   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
197   // etc.
198   return TheStores.size() > NumPointerStores+NumByteStores;
199 }
200
201
202 namespace {
203 class MemsetRanges {
204   /// A sorted list of the memset ranges.
205   SmallVector<MemsetRange, 8> Ranges;
206   typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
207   const DataLayout &DL;
208 public:
209   MemsetRanges(const DataLayout &DL) : DL(DL) {}
210
211   typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
212   const_iterator begin() const { return Ranges.begin(); }
213   const_iterator end() const { return Ranges.end(); }
214   bool empty() const { return Ranges.empty(); }
215
216   void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
217     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
218       addStore(OffsetFromFirst, SI);
219     else
220       addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
221   }
222
223   void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
224     int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
225
226     addRange(OffsetFromFirst, StoreSize,
227              SI->getPointerOperand(), SI->getAlignment(), SI);
228   }
229
230   void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
231     int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
232     addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
233   }
234
235   void addRange(int64_t Start, int64_t Size, Value *Ptr,
236                 unsigned Alignment, Instruction *Inst);
237
238 };
239
240 } // end anon namespace
241
242
243 /// Add a new store to the MemsetRanges data structure.  This adds a
244 /// new range for the specified store at the specified offset, merging into
245 /// existing ranges as appropriate.
246 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
247                             unsigned Alignment, Instruction *Inst) {
248   int64_t End = Start+Size;
249
250   range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
251     [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
252
253   // We now know that I == E, in which case we didn't find anything to merge
254   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
255   // to insert a new range.  Handle this now.
256   if (I == Ranges.end() || End < I->Start) {
257     MemsetRange &R = *Ranges.insert(I, MemsetRange());
258     R.Start        = Start;
259     R.End          = End;
260     R.StartPtr     = Ptr;
261     R.Alignment    = Alignment;
262     R.TheStores.push_back(Inst);
263     return;
264   }
265
266   // This store overlaps with I, add it.
267   I->TheStores.push_back(Inst);
268
269   // At this point, we may have an interval that completely contains our store.
270   // If so, just add it to the interval and return.
271   if (I->Start <= Start && I->End >= End)
272     return;
273
274   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
275   // but is not entirely contained within the range.
276
277   // See if the range extends the start of the range.  In this case, it couldn't
278   // possibly cause it to join the prior range, because otherwise we would have
279   // stopped on *it*.
280   if (Start < I->Start) {
281     I->Start = Start;
282     I->StartPtr = Ptr;
283     I->Alignment = Alignment;
284   }
285
286   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
287   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
288   // End.
289   if (End > I->End) {
290     I->End = End;
291     range_iterator NextI = I;
292     while (++NextI != Ranges.end() && End >= NextI->Start) {
293       // Merge the range in.
294       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
295       if (NextI->End > I->End)
296         I->End = NextI->End;
297       Ranges.erase(NextI);
298       NextI = I;
299     }
300   }
301 }
302
303 //===----------------------------------------------------------------------===//
304 //                         MemCpyOpt Pass
305 //===----------------------------------------------------------------------===//
306
307 namespace {
308   class MemCpyOpt : public FunctionPass {
309     MemoryDependenceAnalysis *MD;
310     TargetLibraryInfo *TLI;
311   public:
312     static char ID; // Pass identification, replacement for typeid
313     MemCpyOpt() : FunctionPass(ID) {
314       initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
315       MD = nullptr;
316       TLI = nullptr;
317     }
318
319     bool runOnFunction(Function &F) override;
320
321   private:
322     // This transformation requires dominator postdominator info
323     void getAnalysisUsage(AnalysisUsage &AU) const override {
324       AU.setPreservesCFG();
325       AU.addRequired<AssumptionCacheTracker>();
326       AU.addRequired<DominatorTreeWrapperPass>();
327       AU.addRequired<MemoryDependenceAnalysis>();
328       AU.addRequired<AAResultsWrapperPass>();
329       AU.addRequired<TargetLibraryInfoWrapperPass>();
330       AU.addPreserved<GlobalsAAWrapperPass>();
331       AU.addPreserved<MemoryDependenceAnalysis>();
332     }
333
334     // Helper functions
335     bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
336     bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
337     bool processMemCpy(MemCpyInst *M);
338     bool processMemMove(MemMoveInst *M);
339     bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
340                               uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
341     bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
342     bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
343     bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
344     bool processByValArgument(CallSite CS, unsigned ArgNo);
345     Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
346                                       Value *ByteVal);
347
348     bool iterateOnFunction(Function &F);
349   };
350
351   char MemCpyOpt::ID = 0;
352 }
353
354 /// The public interface to this file...
355 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
356
357 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
358                       false, false)
359 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
360 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
361 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
362 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
363 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
364 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
365 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
366                     false, false)
367
368 /// When scanning forward over instructions, we look for some other patterns to
369 /// fold away. In particular, this looks for stores to neighboring locations of
370 /// memory. If it sees enough consecutive ones, it attempts to merge them
371 /// together into a memcpy/memset.
372 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
373                                              Value *StartPtr, Value *ByteVal) {
374   const DataLayout &DL = StartInst->getModule()->getDataLayout();
375
376   // Okay, so we now have a single store that can be splatable.  Scan to find
377   // all subsequent stores of the same value to offset from the same pointer.
378   // Join these together into ranges, so we can decide whether contiguous blocks
379   // are stored.
380   MemsetRanges Ranges(DL);
381
382   BasicBlock::iterator BI(StartInst);
383   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
384     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
385       // If the instruction is readnone, ignore it, otherwise bail out.  We
386       // don't even allow readonly here because we don't want something like:
387       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
388       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
389         break;
390       continue;
391     }
392
393     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
394       // If this is a store, see if we can merge it in.
395       if (!NextStore->isSimple()) break;
396
397       // Check to see if this stored value is of the same byte-splattable value.
398       if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
399         break;
400
401       // Check to see if this store is to a constant offset from the start ptr.
402       int64_t Offset;
403       if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
404                            DL))
405         break;
406
407       Ranges.addStore(Offset, NextStore);
408     } else {
409       MemSetInst *MSI = cast<MemSetInst>(BI);
410
411       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
412           !isa<ConstantInt>(MSI->getLength()))
413         break;
414
415       // Check to see if this store is to a constant offset from the start ptr.
416       int64_t Offset;
417       if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
418         break;
419
420       Ranges.addMemSet(Offset, MSI);
421     }
422   }
423
424   // If we have no ranges, then we just had a single store with nothing that
425   // could be merged in.  This is a very common case of course.
426   if (Ranges.empty())
427     return nullptr;
428
429   // If we had at least one store that could be merged in, add the starting
430   // store as well.  We try to avoid this unless there is at least something
431   // interesting as a small compile-time optimization.
432   Ranges.addInst(0, StartInst);
433
434   // If we create any memsets, we put it right before the first instruction that
435   // isn't part of the memset block.  This ensure that the memset is dominated
436   // by any addressing instruction needed by the start of the block.
437   IRBuilder<> Builder(&*BI);
438
439   // Now that we have full information about ranges, loop over the ranges and
440   // emit memset's for anything big enough to be worthwhile.
441   Instruction *AMemSet = nullptr;
442   for (const MemsetRange &Range : Ranges) {
443
444     if (Range.TheStores.size() == 1) continue;
445
446     // If it is profitable to lower this range to memset, do so now.
447     if (!Range.isProfitableToUseMemset(DL))
448       continue;
449
450     // Otherwise, we do want to transform this!  Create a new memset.
451     // Get the starting pointer of the block.
452     StartPtr = Range.StartPtr;
453
454     // Determine alignment
455     unsigned Alignment = Range.Alignment;
456     if (Alignment == 0) {
457       Type *EltType =
458         cast<PointerType>(StartPtr->getType())->getElementType();
459       Alignment = DL.getABITypeAlignment(EltType);
460     }
461
462     AMemSet =
463       Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
464
465     DEBUG(dbgs() << "Replace stores:\n";
466           for (Instruction *SI : Range.TheStores)
467             dbgs() << *SI << '\n';
468           dbgs() << "With: " << *AMemSet << '\n');
469
470     if (!Range.TheStores.empty())
471       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
472
473     // Zap all the stores.
474     for (Instruction *SI : Range.TheStores) {
475       MD->removeInstruction(SI);
476       SI->eraseFromParent();
477     }
478     ++NumMemSetInfer;
479   }
480
481   return AMemSet;
482 }
483
484 static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
485                                      const LoadInst *LI) {
486   unsigned StoreAlign = SI->getAlignment();
487   if (!StoreAlign)
488     StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
489   unsigned LoadAlign = LI->getAlignment();
490   if (!LoadAlign)
491     LoadAlign = DL.getABITypeAlignment(LI->getType());
492
493   return std::min(StoreAlign, LoadAlign);
494 }
495
496 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
497   if (!SI->isSimple()) return false;
498
499   // Avoid merging nontemporal stores since the resulting
500   // memcpy/memset would not be able to preserve the nontemporal hint.
501   // In theory we could teach how to propagate the !nontemporal metadata to
502   // memset calls. However, that change would force the backend to
503   // conservatively expand !nontemporal memset calls back to sequences of
504   // store instructions (effectively undoing the merging).
505   if (SI->getMetadata(LLVMContext::MD_nontemporal))
506     return false;
507
508   const DataLayout &DL = SI->getModule()->getDataLayout();
509
510   // Load to store forwarding can be interpreted as memcpy.
511   if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
512     if (LI->isSimple() && LI->hasOneUse() &&
513         LI->getParent() == SI->getParent()) {
514
515       auto *T = LI->getType();
516       if (T->isAggregateType()) {
517         AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
518         MemoryLocation LoadLoc = MemoryLocation::get(LI);
519
520         // We use alias analysis to check if an instruction may store to
521         // the memory we load from in between the load and the store. If
522         // such an instruction is found, we try to promote there instead
523         // of at the store position.
524         Instruction *P = SI;
525         for (BasicBlock::iterator I = ++LI->getIterator(), E = SI->getIterator();
526              I != E; ++I) {
527           if (!(AA.getModRefInfo(&*I, LoadLoc) & MRI_Mod))
528             continue;
529
530           // We found an instruction that may write to the loaded memory.
531           // We can try to promote at this position instead of the store
532           // position if nothing alias the store memory after this.
533           P = &*I;
534           for (; I != E; ++I) {
535             MemoryLocation StoreLoc = MemoryLocation::get(SI);
536             if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
537               P = nullptr;
538               break;
539             }
540           }
541
542           break;
543         }
544
545         // If a valid insertion position is found, then we can promote
546         // the load/store pair to a memcpy.
547         if (P) {
548           // If we load from memory that may alias the memory we store to,
549           // memmove must be used to preserve semantic. If not, memcpy can
550           // be used.
551           bool UseMemMove = false;
552           if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
553             UseMemMove = true;
554
555           unsigned Align = findCommonAlignment(DL, SI, LI);
556           uint64_t Size = DL.getTypeStoreSize(T);
557
558           IRBuilder<> Builder(P);
559           Instruction *M;
560           if (UseMemMove)
561             M = Builder.CreateMemMove(SI->getPointerOperand(),
562                                       LI->getPointerOperand(), Size,
563                                       Align, SI->isVolatile());
564           else
565             M = Builder.CreateMemCpy(SI->getPointerOperand(),
566                                      LI->getPointerOperand(), Size,
567                                      Align, SI->isVolatile());
568
569           DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
570                        << " => " << *M << "\n");
571
572           MD->removeInstruction(SI);
573           SI->eraseFromParent();
574           MD->removeInstruction(LI);
575           LI->eraseFromParent();
576           ++NumMemCpyInstr;
577
578           // Make sure we do not invalidate the iterator.
579           BBI = M->getIterator();
580           return true;
581         }
582       }
583
584       // Detect cases where we're performing call slot forwarding, but
585       // happen to be using a load-store pair to implement it, rather than
586       // a memcpy.
587       MemDepResult ldep = MD->getDependency(LI);
588       CallInst *C = nullptr;
589       if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
590         C = dyn_cast<CallInst>(ldep.getInst());
591
592       if (C) {
593         // Check that nothing touches the dest of the "copy" between
594         // the call and the store.
595         AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
596         MemoryLocation StoreLoc = MemoryLocation::get(SI);
597         for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
598              I != E; --I) {
599           if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
600             C = nullptr;
601             break;
602           }
603         }
604       }
605
606       if (C) {
607         bool changed = performCallSlotOptzn(
608             LI, SI->getPointerOperand()->stripPointerCasts(),
609             LI->getPointerOperand()->stripPointerCasts(),
610             DL.getTypeStoreSize(SI->getOperand(0)->getType()),
611             findCommonAlignment(DL, SI, LI), C);
612         if (changed) {
613           MD->removeInstruction(SI);
614           SI->eraseFromParent();
615           MD->removeInstruction(LI);
616           LI->eraseFromParent();
617           ++NumMemCpyInstr;
618           return true;
619         }
620       }
621     }
622   }
623
624   // There are two cases that are interesting for this code to handle: memcpy
625   // and memset.  Right now we only handle memset.
626
627   // Ensure that the value being stored is something that can be memset'able a
628   // byte at a time like "0" or "-1" or any width, as well as things like
629   // 0xA0A0A0A0 and 0.0.
630   if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
631     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
632                                               ByteVal)) {
633       BBI = I->getIterator(); // Don't invalidate iterator.
634       return true;
635     }
636
637   return false;
638 }
639
640 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
641   // See if there is another memset or store neighboring this memset which
642   // allows us to widen out the memset to do a single larger store.
643   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
644     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
645                                               MSI->getValue())) {
646       BBI = I->getIterator(); // Don't invalidate iterator.
647       return true;
648     }
649   return false;
650 }
651
652
653 /// Takes a memcpy and a call that it depends on,
654 /// and checks for the possibility of a call slot optimization by having
655 /// the call write its result directly into the destination of the memcpy.
656 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
657                                      Value *cpyDest, Value *cpySrc,
658                                      uint64_t cpyLen, unsigned cpyAlign,
659                                      CallInst *C) {
660   // The general transformation to keep in mind is
661   //
662   //   call @func(..., src, ...)
663   //   memcpy(dest, src, ...)
664   //
665   // ->
666   //
667   //   memcpy(dest, src, ...)
668   //   call @func(..., dest, ...)
669   //
670   // Since moving the memcpy is technically awkward, we additionally check that
671   // src only holds uninitialized values at the moment of the call, meaning that
672   // the memcpy can be discarded rather than moved.
673
674   // Deliberately get the source and destination with bitcasts stripped away,
675   // because we'll need to do type comparisons based on the underlying type.
676   CallSite CS(C);
677
678   // Require that src be an alloca.  This simplifies the reasoning considerably.
679   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
680   if (!srcAlloca)
681     return false;
682
683   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
684   if (!srcArraySize)
685     return false;
686
687   const DataLayout &DL = cpy->getModule()->getDataLayout();
688   uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
689                      srcArraySize->getZExtValue();
690
691   if (cpyLen < srcSize)
692     return false;
693
694   // Check that accessing the first srcSize bytes of dest will not cause a
695   // trap.  Otherwise the transform is invalid since it might cause a trap
696   // to occur earlier than it otherwise would.
697   if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
698     // The destination is an alloca.  Check it is larger than srcSize.
699     ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
700     if (!destArraySize)
701       return false;
702
703     uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
704                         destArraySize->getZExtValue();
705
706     if (destSize < srcSize)
707       return false;
708   } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
709     if (A->getDereferenceableBytes() < srcSize) {
710       // If the destination is an sret parameter then only accesses that are
711       // outside of the returned struct type can trap.
712       if (!A->hasStructRetAttr())
713         return false;
714
715       Type *StructTy = cast<PointerType>(A->getType())->getElementType();
716       if (!StructTy->isSized()) {
717         // The call may never return and hence the copy-instruction may never
718         // be executed, and therefore it's not safe to say "the destination
719         // has at least <cpyLen> bytes, as implied by the copy-instruction",
720         return false;
721       }
722
723       uint64_t destSize = DL.getTypeAllocSize(StructTy);
724       if (destSize < srcSize)
725         return false;
726     }
727   } else {
728     return false;
729   }
730
731   // Check that dest points to memory that is at least as aligned as src.
732   unsigned srcAlign = srcAlloca->getAlignment();
733   if (!srcAlign)
734     srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
735   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
736   // If dest is not aligned enough and we can't increase its alignment then
737   // bail out.
738   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
739     return false;
740
741   // Check that src is not accessed except via the call and the memcpy.  This
742   // guarantees that it holds only undefined values when passed in (so the final
743   // memcpy can be dropped), that it is not read or written between the call and
744   // the memcpy, and that writing beyond the end of it is undefined.
745   SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
746                                    srcAlloca->user_end());
747   while (!srcUseList.empty()) {
748     User *U = srcUseList.pop_back_val();
749
750     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
751       for (User *UU : U->users())
752         srcUseList.push_back(UU);
753       continue;
754     }
755     if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
756       if (!G->hasAllZeroIndices())
757         return false;
758
759       for (User *UU : U->users())
760         srcUseList.push_back(UU);
761       continue;
762     }
763     if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
764       if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
765           IT->getIntrinsicID() == Intrinsic::lifetime_end)
766         continue;
767
768     if (U != C && U != cpy)
769       return false;
770   }
771
772   // Check that src isn't captured by the called function since the
773   // transformation can cause aliasing issues in that case.
774   for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
775     if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
776       return false;
777
778   // Since we're changing the parameter to the callsite, we need to make sure
779   // that what would be the new parameter dominates the callsite.
780   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
781   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
782     if (!DT.dominates(cpyDestInst, C))
783       return false;
784
785   // In addition to knowing that the call does not access src in some
786   // unexpected manner, for example via a global, which we deduce from
787   // the use analysis, we also need to know that it does not sneakily
788   // access dest.  We rely on AA to figure this out for us.
789   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
790   ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
791   // If necessary, perform additional analysis.
792   if (MR != MRI_NoModRef)
793     MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
794   if (MR != MRI_NoModRef)
795     return false;
796
797   // All the checks have passed, so do the transformation.
798   bool changedArgument = false;
799   for (unsigned i = 0; i < CS.arg_size(); ++i)
800     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
801       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
802         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
803                                       cpyDest->getName(), C);
804       changedArgument = true;
805       if (CS.getArgument(i)->getType() == Dest->getType())
806         CS.setArgument(i, Dest);
807       else
808         CS.setArgument(i, CastInst::CreatePointerCast(Dest,
809                           CS.getArgument(i)->getType(), Dest->getName(), C));
810     }
811
812   if (!changedArgument)
813     return false;
814
815   // If the destination wasn't sufficiently aligned then increase its alignment.
816   if (!isDestSufficientlyAligned) {
817     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
818     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
819   }
820
821   // Drop any cached information about the call, because we may have changed
822   // its dependence information by changing its parameter.
823   MD->removeInstruction(C);
824
825   // Update AA metadata
826   // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
827   // handled here, but combineMetadata doesn't support them yet
828   unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
829                          LLVMContext::MD_noalias,
830                          LLVMContext::MD_invariant_group};
831   combineMetadata(C, cpy, KnownIDs);
832
833   // Remove the memcpy.
834   MD->removeInstruction(cpy);
835   ++NumMemCpyInstr;
836
837   return true;
838 }
839
840 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
841 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
842 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep) {
843   // We can only transforms memcpy's where the dest of one is the source of the
844   // other.
845   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
846     return false;
847
848   // If dep instruction is reading from our current input, then it is a noop
849   // transfer and substituting the input won't change this instruction.  Just
850   // ignore the input and let someone else zap MDep.  This handles cases like:
851   //    memcpy(a <- a)
852   //    memcpy(b <- a)
853   if (M->getSource() == MDep->getSource())
854     return false;
855
856   // Second, the length of the memcpy's must be the same, or the preceding one
857   // must be larger than the following one.
858   ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
859   ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
860   if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
861     return false;
862
863   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
864
865   // Verify that the copied-from memory doesn't change in between the two
866   // transfers.  For example, in:
867   //    memcpy(a <- b)
868   //    *b = 42;
869   //    memcpy(c <- a)
870   // It would be invalid to transform the second memcpy into memcpy(c <- b).
871   //
872   // TODO: If the code between M and MDep is transparent to the destination "c",
873   // then we could still perform the xform by moving M up to the first memcpy.
874   //
875   // NOTE: This is conservative, it will stop on any read from the source loc,
876   // not just the defining memcpy.
877   MemDepResult SourceDep =
878       MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
879                                    M->getIterator(), M->getParent());
880   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
881     return false;
882
883   // If the dest of the second might alias the source of the first, then the
884   // source and dest might overlap.  We still want to eliminate the intermediate
885   // value, but we have to generate a memmove instead of memcpy.
886   bool UseMemMove = false;
887   if (!AA.isNoAlias(MemoryLocation::getForDest(M),
888                     MemoryLocation::getForSource(MDep)))
889     UseMemMove = true;
890
891   // If all checks passed, then we can transform M.
892
893   // Make sure to use the lesser of the alignment of the source and the dest
894   // since we're changing where we're reading from, but don't want to increase
895   // the alignment past what can be read from or written to.
896   // TODO: Is this worth it if we're creating a less aligned memcpy? For
897   // example we could be moving from movaps -> movq on x86.
898   unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
899
900   IRBuilder<> Builder(M);
901   if (UseMemMove)
902     Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
903                           Align, M->isVolatile());
904   else
905     Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
906                          Align, M->isVolatile());
907
908   // Remove the instruction we're replacing.
909   MD->removeInstruction(M);
910   M->eraseFromParent();
911   ++NumMemCpyInstr;
912   return true;
913 }
914
915 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
916 /// \p MemSet.  Try to simplify \p MemSet to only set the trailing bytes that
917 /// weren't copied over by \p MemCpy.
918 ///
919 /// In other words, transform:
920 /// \code
921 ///   memset(dst, c, dst_size);
922 ///   memcpy(dst, src, src_size);
923 /// \endcode
924 /// into:
925 /// \code
926 ///   memcpy(dst, src, src_size);
927 ///   memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
928 /// \endcode
929 bool MemCpyOpt::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
930                                               MemSetInst *MemSet) {
931   // We can only transform memset/memcpy with the same destination.
932   if (MemSet->getDest() != MemCpy->getDest())
933     return false;
934
935   // Check that there are no other dependencies on the memset destination.
936   MemDepResult DstDepInfo =
937       MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
938                                    MemCpy->getIterator(), MemCpy->getParent());
939   if (DstDepInfo.getInst() != MemSet)
940     return false;
941
942   // Use the same i8* dest as the memcpy, killing the memset dest if different.
943   Value *Dest = MemCpy->getRawDest();
944   Value *DestSize = MemSet->getLength();
945   Value *SrcSize = MemCpy->getLength();
946
947   // By default, create an unaligned memset.
948   unsigned Align = 1;
949   // If Dest is aligned, and SrcSize is constant, use the minimum alignment
950   // of the sum.
951   const unsigned DestAlign =
952       std::max(MemSet->getAlignment(), MemCpy->getAlignment());
953   if (DestAlign > 1)
954     if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
955       Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
956
957   IRBuilder<> Builder(MemCpy);
958
959   // If the sizes have different types, zext the smaller one.
960   if (DestSize->getType() != SrcSize->getType()) {
961     if (DestSize->getType()->getIntegerBitWidth() >
962         SrcSize->getType()->getIntegerBitWidth())
963       SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
964     else
965       DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
966   }
967
968   Value *MemsetLen =
969       Builder.CreateSelect(Builder.CreateICmpULE(DestSize, SrcSize),
970                            ConstantInt::getNullValue(DestSize->getType()),
971                            Builder.CreateSub(DestSize, SrcSize));
972   Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
973                        MemsetLen, Align);
974
975   MD->removeInstruction(MemSet);
976   MemSet->eraseFromParent();
977   return true;
978 }
979
980 /// Transform memcpy to memset when its source was just memset.
981 /// In other words, turn:
982 /// \code
983 ///   memset(dst1, c, dst1_size);
984 ///   memcpy(dst2, dst1, dst2_size);
985 /// \endcode
986 /// into:
987 /// \code
988 ///   memset(dst1, c, dst1_size);
989 ///   memset(dst2, c, dst2_size);
990 /// \endcode
991 /// When dst2_size <= dst1_size.
992 ///
993 /// The \p MemCpy must have a Constant length.
994 bool MemCpyOpt::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
995                                            MemSetInst *MemSet) {
996   // This only makes sense on memcpy(..., memset(...), ...).
997   if (MemSet->getRawDest() != MemCpy->getRawSource())
998     return false;
999
1000   ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1001   ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1002   // Make sure the memcpy doesn't read any more than what the memset wrote.
1003   // Don't worry about sizes larger than i64.
1004   if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
1005     return false;
1006
1007   IRBuilder<> Builder(MemCpy);
1008   Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1009                        CopySize, MemCpy->getAlignment());
1010   return true;
1011 }
1012
1013 /// Perform simplification of memcpy's.  If we have memcpy A
1014 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1015 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
1016 /// circumstances). This allows later passes to remove the first memcpy
1017 /// altogether.
1018 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
1019   // We can only optimize non-volatile memcpy's.
1020   if (M->isVolatile()) return false;
1021
1022   // If the source and destination of the memcpy are the same, then zap it.
1023   if (M->getSource() == M->getDest()) {
1024     MD->removeInstruction(M);
1025     M->eraseFromParent();
1026     return false;
1027   }
1028
1029   // If copying from a constant, try to turn the memcpy into a memset.
1030   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
1031     if (GV->isConstant() && GV->hasDefinitiveInitializer())
1032       if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
1033         IRBuilder<> Builder(M);
1034         Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1035                              M->getAlignment(), false);
1036         MD->removeInstruction(M);
1037         M->eraseFromParent();
1038         ++NumCpyToSet;
1039         return true;
1040       }
1041
1042   MemDepResult DepInfo = MD->getDependency(M);
1043
1044   // Try to turn a partially redundant memset + memcpy into
1045   // memcpy + smaller memset.  We don't need the memcpy size for this.
1046   if (DepInfo.isClobber())
1047     if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1048       if (processMemSetMemCpyDependence(M, MDep))
1049         return true;
1050
1051   // The optimizations after this point require the memcpy size.
1052   ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
1053   if (!CopySize) return false;
1054
1055   // There are four possible optimizations we can do for memcpy:
1056   //   a) memcpy-memcpy xform which exposes redundance for DSE.
1057   //   b) call-memcpy xform for return slot optimization.
1058   //   c) memcpy from freshly alloca'd space or space that has just started its
1059   //      lifetime copies undefined data, and we can therefore eliminate the
1060   //      memcpy in favor of the data that was already at the destination.
1061   //   d) memcpy from a just-memset'd source can be turned into memset.
1062   if (DepInfo.isClobber()) {
1063     if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1064       if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
1065                                CopySize->getZExtValue(), M->getAlignment(),
1066                                C)) {
1067         MD->removeInstruction(M);
1068         M->eraseFromParent();
1069         return true;
1070       }
1071     }
1072   }
1073
1074   MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
1075   MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1076       SrcLoc, true, M->getIterator(), M->getParent());
1077
1078   if (SrcDepInfo.isClobber()) {
1079     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1080       return processMemCpyMemCpyDependence(M, MDep);
1081   } else if (SrcDepInfo.isDef()) {
1082     Instruction *I = SrcDepInfo.getInst();
1083     bool hasUndefContents = false;
1084
1085     if (isa<AllocaInst>(I)) {
1086       hasUndefContents = true;
1087     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1088       if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1089         if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1090           if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1091             hasUndefContents = true;
1092     }
1093
1094     if (hasUndefContents) {
1095       MD->removeInstruction(M);
1096       M->eraseFromParent();
1097       ++NumMemCpyInstr;
1098       return true;
1099     }
1100   }
1101
1102   if (SrcDepInfo.isClobber())
1103     if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1104       if (performMemCpyToMemSetOptzn(M, MDep)) {
1105         MD->removeInstruction(M);
1106         M->eraseFromParent();
1107         ++NumCpyToSet;
1108         return true;
1109       }
1110
1111   return false;
1112 }
1113
1114 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1115 /// not to alias.
1116 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
1117   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1118
1119   if (!TLI->has(LibFunc::memmove))
1120     return false;
1121
1122   // See if the pointers alias.
1123   if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1124                     MemoryLocation::getForSource(M)))
1125     return false;
1126
1127   DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
1128
1129   // If not, then we know we can transform this.
1130   Type *ArgTys[3] = { M->getRawDest()->getType(),
1131                       M->getRawSource()->getType(),
1132                       M->getLength()->getType() };
1133   M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1134                                                  Intrinsic::memcpy, ArgTys));
1135
1136   // MemDep may have over conservative information about this instruction, just
1137   // conservatively flush it from the cache.
1138   MD->removeInstruction(M);
1139
1140   ++NumMoveToCpy;
1141   return true;
1142 }
1143
1144 /// This is called on every byval argument in call sites.
1145 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
1146   const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
1147   // Find out what feeds this byval argument.
1148   Value *ByValArg = CS.getArgument(ArgNo);
1149   Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1150   uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1151   MemDepResult DepInfo = MD->getPointerDependencyFrom(
1152       MemoryLocation(ByValArg, ByValSize), true,
1153       CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
1154   if (!DepInfo.isClobber())
1155     return false;
1156
1157   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
1158   // a memcpy, see if we can byval from the source of the memcpy instead of the
1159   // result.
1160   MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1161   if (!MDep || MDep->isVolatile() ||
1162       ByValArg->stripPointerCasts() != MDep->getDest())
1163     return false;
1164
1165   // The length of the memcpy must be larger or equal to the size of the byval.
1166   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1167   if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1168     return false;
1169
1170   // Get the alignment of the byval.  If the call doesn't specify the alignment,
1171   // then it is some target specific value that we can't know.
1172   unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
1173   if (ByValAlign == 0) return false;
1174
1175   // If it is greater than the memcpy, then we check to see if we can force the
1176   // source of the memcpy to the alignment we need.  If we fail, we bail out.
1177   AssumptionCache &AC =
1178       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
1179           *CS->getParent()->getParent());
1180   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1181   if (MDep->getAlignment() < ByValAlign &&
1182       getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
1183                                  CS.getInstruction(), &AC, &DT) < ByValAlign)
1184     return false;
1185
1186   // Verify that the copied-from memory doesn't change in between the memcpy and
1187   // the byval call.
1188   //    memcpy(a <- b)
1189   //    *b = 42;
1190   //    foo(*a)
1191   // It would be invalid to transform the second memcpy into foo(*b).
1192   //
1193   // NOTE: This is conservative, it will stop on any read from the source loc,
1194   // not just the defining memcpy.
1195   MemDepResult SourceDep = MD->getPointerDependencyFrom(
1196       MemoryLocation::getForSource(MDep), false,
1197       CS.getInstruction()->getIterator(), MDep->getParent());
1198   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1199     return false;
1200
1201   Value *TmpCast = MDep->getSource();
1202   if (MDep->getSource()->getType() != ByValArg->getType())
1203     TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1204                               "tmpcast", CS.getInstruction());
1205
1206   DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
1207                << "  " << *MDep << "\n"
1208                << "  " << *CS.getInstruction() << "\n");
1209
1210   // Otherwise we're good!  Update the byval argument.
1211   CS.setArgument(ArgNo, TmpCast);
1212   ++NumMemCpyInstr;
1213   return true;
1214 }
1215
1216 /// Executes one iteration of MemCpyOpt.
1217 bool MemCpyOpt::iterateOnFunction(Function &F) {
1218   bool MadeChange = false;
1219
1220   // Walk all instruction in the function.
1221   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
1222     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
1223       // Avoid invalidating the iterator.
1224       Instruction *I = &*BI++;
1225
1226       bool RepeatInstruction = false;
1227
1228       if (StoreInst *SI = dyn_cast<StoreInst>(I))
1229         MadeChange |= processStore(SI, BI);
1230       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1231         RepeatInstruction = processMemSet(M, BI);
1232       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1233         RepeatInstruction = processMemCpy(M);
1234       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1235         RepeatInstruction = processMemMove(M);
1236       else if (auto CS = CallSite(I)) {
1237         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
1238           if (CS.isByValArgument(i))
1239             MadeChange |= processByValArgument(CS, i);
1240       }
1241
1242       // Reprocess the instruction if desired.
1243       if (RepeatInstruction) {
1244         if (BI != BB->begin()) --BI;
1245         MadeChange = true;
1246       }
1247     }
1248   }
1249
1250   return MadeChange;
1251 }
1252
1253 /// This is the main transformation entry point for a function.
1254 bool MemCpyOpt::runOnFunction(Function &F) {
1255   if (skipOptnoneFunction(F))
1256     return false;
1257
1258   bool MadeChange = false;
1259   MD = &getAnalysis<MemoryDependenceAnalysis>();
1260   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1261
1262   // If we don't have at least memset and memcpy, there is little point of doing
1263   // anything here.  These are required by a freestanding implementation, so if
1264   // even they are disabled, there is no point in trying hard.
1265   if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1266     return false;
1267
1268   while (1) {
1269     if (!iterateOnFunction(F))
1270       break;
1271     MadeChange = true;
1272   }
1273
1274   MD = nullptr;
1275   return MadeChange;
1276 }