1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs various transformations related to eliminating memcpy
10 // calls, or transforming sets of stores into memset's.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/Loads.h"
25 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/Analysis/MemorySSA.h"
28 #include "llvm/Analysis/MemorySSAUpdater.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GetElementPtrTypeIterator.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InstrTypes.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/IR/Operator.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/InitializePasses.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/Scalar.h"
60 #include "llvm/Transforms/Utils/Local.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstdint>
64 #include <utility>
65 
66 using namespace llvm;
67 
68 #define DEBUG_TYPE "memcpyopt"
69 
70 static cl::opt<bool> EnableMemCpyOptWithoutLibcalls(
71     "enable-memcpyopt-without-libcalls", cl::init(false), cl::Hidden,
72     cl::desc("Enable memcpyopt even when libcalls are disabled"));
73 
74 static cl::opt<bool>
75     EnableMemorySSA("enable-memcpyopt-memoryssa", cl::init(true), cl::Hidden,
76                     cl::desc("Use MemorySSA-backed MemCpyOpt."));
77 
78 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
79 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
80 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
81 STATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
82 STATISTIC(NumCallSlot,    "Number of call slot optimizations performed");
83 
84 namespace {
85 
86 /// Represents a range of memset'd bytes with the ByteVal value.
87 /// This allows us to analyze stores like:
88 ///   store 0 -> P+1
89 ///   store 0 -> P+0
90 ///   store 0 -> P+3
91 ///   store 0 -> P+2
92 /// which sometimes happens with stores to arrays of structs etc.  When we see
93 /// the first store, we make a range [1, 2).  The second store extends the range
94 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
95 /// two ranges into [0, 3) which is memset'able.
96 struct MemsetRange {
97   // Start/End - A semi range that describes the span that this range covers.
98   // The range is closed at the start and open at the end: [Start, End).
99   int64_t Start, End;
100 
101   /// StartPtr - The getelementptr instruction that points to the start of the
102   /// range.
103   Value *StartPtr;
104 
105   /// Alignment - The known alignment of the first store.
106   unsigned Alignment;
107 
108   /// TheStores - The actual stores that make up this range.
109   SmallVector<Instruction*, 16> TheStores;
110 
111   bool isProfitableToUseMemset(const DataLayout &DL) const;
112 };
113 
114 } // end anonymous namespace
115 
116 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
117   // If we found more than 4 stores to merge or 16 bytes, use memset.
118   if (TheStores.size() >= 4 || End-Start >= 16) return true;
119 
120   // If there is nothing to merge, don't do anything.
121   if (TheStores.size() < 2) return false;
122 
123   // If any of the stores are a memset, then it is always good to extend the
124   // memset.
125   for (Instruction *SI : TheStores)
126     if (!isa<StoreInst>(SI))
127       return true;
128 
129   // Assume that the code generator is capable of merging pairs of stores
130   // together if it wants to.
131   if (TheStores.size() == 2) return false;
132 
133   // If we have fewer than 8 stores, it can still be worthwhile to do this.
134   // For example, merging 4 i8 stores into an i32 store is useful almost always.
135   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
136   // memset will be split into 2 32-bit stores anyway) and doing so can
137   // pessimize the llvm optimizer.
138   //
139   // Since we don't have perfect knowledge here, make some assumptions: assume
140   // the maximum GPR width is the same size as the largest legal integer
141   // size. If so, check to see whether we will end up actually reducing the
142   // number of stores used.
143   unsigned Bytes = unsigned(End-Start);
144   unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
145   if (MaxIntSize == 0)
146     MaxIntSize = 1;
147   unsigned NumPointerStores = Bytes / MaxIntSize;
148 
149   // Assume the remaining bytes if any are done a byte at a time.
150   unsigned NumByteStores = Bytes % MaxIntSize;
151 
152   // If we will reduce the # stores (according to this heuristic), do the
153   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
154   // etc.
155   return TheStores.size() > NumPointerStores+NumByteStores;
156 }
157 
158 namespace {
159 
160 class MemsetRanges {
161   using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
162 
163   /// A sorted list of the memset ranges.
164   SmallVector<MemsetRange, 8> Ranges;
165 
166   const DataLayout &DL;
167 
168 public:
169   MemsetRanges(const DataLayout &DL) : DL(DL) {}
170 
171   using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
172 
173   const_iterator begin() const { return Ranges.begin(); }
174   const_iterator end() const { return Ranges.end(); }
175   bool empty() const { return Ranges.empty(); }
176 
177   void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
178     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
179       addStore(OffsetFromFirst, SI);
180     else
181       addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
182   }
183 
184   void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
185     int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
186 
187     addRange(OffsetFromFirst, StoreSize, SI->getPointerOperand(),
188              SI->getAlign().value(), SI);
189   }
190 
191   void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
192     int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
193     addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
194   }
195 
196   void addRange(int64_t Start, int64_t Size, Value *Ptr,
197                 unsigned Alignment, Instruction *Inst);
198 };
199 
200 } // end anonymous namespace
201 
202 /// Add a new store to the MemsetRanges data structure.  This adds a
203 /// new range for the specified store at the specified offset, merging into
204 /// existing ranges as appropriate.
205 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
206                             unsigned Alignment, Instruction *Inst) {
207   int64_t End = Start+Size;
208 
209   range_iterator I = partition_point(
210       Ranges, [=](const MemsetRange &O) { return O.End < Start; });
211 
212   // We now know that I == E, in which case we didn't find anything to merge
213   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
214   // to insert a new range.  Handle this now.
215   if (I == Ranges.end() || End < I->Start) {
216     MemsetRange &R = *Ranges.insert(I, MemsetRange());
217     R.Start        = Start;
218     R.End          = End;
219     R.StartPtr     = Ptr;
220     R.Alignment    = Alignment;
221     R.TheStores.push_back(Inst);
222     return;
223   }
224 
225   // This store overlaps with I, add it.
226   I->TheStores.push_back(Inst);
227 
228   // At this point, we may have an interval that completely contains our store.
229   // If so, just add it to the interval and return.
230   if (I->Start <= Start && I->End >= End)
231     return;
232 
233   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
234   // but is not entirely contained within the range.
235 
236   // See if the range extends the start of the range.  In this case, it couldn't
237   // possibly cause it to join the prior range, because otherwise we would have
238   // stopped on *it*.
239   if (Start < I->Start) {
240     I->Start = Start;
241     I->StartPtr = Ptr;
242     I->Alignment = Alignment;
243   }
244 
245   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
246   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
247   // End.
248   if (End > I->End) {
249     I->End = End;
250     range_iterator NextI = I;
251     while (++NextI != Ranges.end() && End >= NextI->Start) {
252       // Merge the range in.
253       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
254       if (NextI->End > I->End)
255         I->End = NextI->End;
256       Ranges.erase(NextI);
257       NextI = I;
258     }
259   }
260 }
261 
262 //===----------------------------------------------------------------------===//
263 //                         MemCpyOptLegacyPass Pass
264 //===----------------------------------------------------------------------===//
265 
266 namespace {
267 
268 class MemCpyOptLegacyPass : public FunctionPass {
269   MemCpyOptPass Impl;
270 
271 public:
272   static char ID; // Pass identification, replacement for typeid
273 
274   MemCpyOptLegacyPass() : FunctionPass(ID) {
275     initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
276   }
277 
278   bool runOnFunction(Function &F) override;
279 
280 private:
281   // This transformation requires dominator postdominator info
282   void getAnalysisUsage(AnalysisUsage &AU) const override {
283     AU.setPreservesCFG();
284     AU.addRequired<AssumptionCacheTracker>();
285     AU.addRequired<DominatorTreeWrapperPass>();
286     AU.addPreserved<DominatorTreeWrapperPass>();
287     AU.addPreserved<GlobalsAAWrapperPass>();
288     AU.addRequired<TargetLibraryInfoWrapperPass>();
289     if (!EnableMemorySSA)
290       AU.addRequired<MemoryDependenceWrapperPass>();
291     AU.addPreserved<MemoryDependenceWrapperPass>();
292     AU.addRequired<AAResultsWrapperPass>();
293     AU.addPreserved<AAResultsWrapperPass>();
294     if (EnableMemorySSA)
295       AU.addRequired<MemorySSAWrapperPass>();
296     AU.addPreserved<MemorySSAWrapperPass>();
297   }
298 };
299 
300 } // end anonymous namespace
301 
302 char MemCpyOptLegacyPass::ID = 0;
303 
304 /// The public interface to this file...
305 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
306 
307 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
308                       false, false)
309 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
310 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
311 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
312 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
313 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
314 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
315 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
316 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
317                     false, false)
318 
319 // Check that V is either not accessible by the caller, or unwinding cannot
320 // occur between Start and End.
321 static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
322                                          Instruction *End) {
323   assert(Start->getParent() == End->getParent() && "Must be in same block");
324   if (!Start->getFunction()->doesNotThrow() &&
325       !isa<AllocaInst>(getUnderlyingObject(V))) {
326     for (const Instruction &I :
327          make_range(Start->getIterator(), End->getIterator())) {
328       if (I.mayThrow())
329         return true;
330     }
331   }
332   return false;
333 }
334 
335 void MemCpyOptPass::eraseInstruction(Instruction *I) {
336   if (MSSAU)
337     MSSAU->removeMemoryAccess(I);
338   if (MD)
339     MD->removeInstruction(I);
340   I->eraseFromParent();
341 }
342 
343 // Check for mod or ref of Loc between Start and End, excluding both boundaries.
344 // Start and End must be in the same block
345 static bool accessedBetween(AliasAnalysis &AA, MemoryLocation Loc,
346                             const MemoryUseOrDef *Start,
347                             const MemoryUseOrDef *End) {
348   assert(Start->getBlock() == End->getBlock() && "Only local supported");
349   for (const MemoryAccess &MA :
350        make_range(++Start->getIterator(), End->getIterator())) {
351     if (isModOrRefSet(AA.getModRefInfo(cast<MemoryUseOrDef>(MA).getMemoryInst(),
352                                        Loc)))
353       return true;
354   }
355   return false;
356 }
357 
358 // Check for mod of Loc between Start and End, excluding both boundaries.
359 // Start and End can be in different blocks.
360 static bool writtenBetween(MemorySSA *MSSA, MemoryLocation Loc,
361                            const MemoryUseOrDef *Start,
362                            const MemoryUseOrDef *End) {
363   // TODO: Only walk until we hit Start.
364   MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
365       End->getDefiningAccess(), Loc);
366   return !MSSA->dominates(Clobber, Start);
367 }
368 
369 /// When scanning forward over instructions, we look for some other patterns to
370 /// fold away. In particular, this looks for stores to neighboring locations of
371 /// memory. If it sees enough consecutive ones, it attempts to merge them
372 /// together into a memcpy/memset.
373 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
374                                                  Value *StartPtr,
375                                                  Value *ByteVal) {
376   const DataLayout &DL = StartInst->getModule()->getDataLayout();
377 
378   // Okay, so we now have a single store that can be splatable.  Scan to find
379   // all subsequent stores of the same value to offset from the same pointer.
380   // Join these together into ranges, so we can decide whether contiguous blocks
381   // are stored.
382   MemsetRanges Ranges(DL);
383 
384   BasicBlock::iterator BI(StartInst);
385 
386   // Keeps track of the last memory use or def before the insertion point for
387   // the new memset. The new MemoryDef for the inserted memsets will be inserted
388   // after MemInsertPoint. It points to either LastMemDef or to the last user
389   // before the insertion point of the memset, if there are any such users.
390   MemoryUseOrDef *MemInsertPoint = nullptr;
391   // Keeps track of the last MemoryDef between StartInst and the insertion point
392   // for the new memset. This will become the defining access of the inserted
393   // memsets.
394   MemoryDef *LastMemDef = nullptr;
395   for (++BI; !BI->isTerminator(); ++BI) {
396     if (MSSAU) {
397       auto *CurrentAcc = cast_or_null<MemoryUseOrDef>(
398           MSSAU->getMemorySSA()->getMemoryAccess(&*BI));
399       if (CurrentAcc) {
400         MemInsertPoint = CurrentAcc;
401         if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc))
402           LastMemDef = CurrentDef;
403       }
404     }
405 
406     // Calls that only access inaccessible memory do not block merging
407     // accessible stores.
408     if (auto *CB = dyn_cast<CallBase>(BI)) {
409       if (CB->onlyAccessesInaccessibleMemory())
410         continue;
411     }
412 
413     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
414       // If the instruction is readnone, ignore it, otherwise bail out.  We
415       // don't even allow readonly here because we don't want something like:
416       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
417       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
418         break;
419       continue;
420     }
421 
422     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
423       // If this is a store, see if we can merge it in.
424       if (!NextStore->isSimple()) break;
425 
426       Value *StoredVal = NextStore->getValueOperand();
427 
428       // Don't convert stores of non-integral pointer types to memsets (which
429       // stores integers).
430       if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
431         break;
432 
433       // Check to see if this stored value is of the same byte-splattable value.
434       Value *StoredByte = isBytewiseValue(StoredVal, DL);
435       if (isa<UndefValue>(ByteVal) && StoredByte)
436         ByteVal = StoredByte;
437       if (ByteVal != StoredByte)
438         break;
439 
440       // Check to see if this store is to a constant offset from the start ptr.
441       Optional<int64_t> Offset =
442           isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
443       if (!Offset)
444         break;
445 
446       Ranges.addStore(*Offset, NextStore);
447     } else {
448       MemSetInst *MSI = cast<MemSetInst>(BI);
449 
450       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
451           !isa<ConstantInt>(MSI->getLength()))
452         break;
453 
454       // Check to see if this store is to a constant offset from the start ptr.
455       Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
456       if (!Offset)
457         break;
458 
459       Ranges.addMemSet(*Offset, MSI);
460     }
461   }
462 
463   // If we have no ranges, then we just had a single store with nothing that
464   // could be merged in.  This is a very common case of course.
465   if (Ranges.empty())
466     return nullptr;
467 
468   // If we had at least one store that could be merged in, add the starting
469   // store as well.  We try to avoid this unless there is at least something
470   // interesting as a small compile-time optimization.
471   Ranges.addInst(0, StartInst);
472 
473   // If we create any memsets, we put it right before the first instruction that
474   // isn't part of the memset block.  This ensure that the memset is dominated
475   // by any addressing instruction needed by the start of the block.
476   IRBuilder<> Builder(&*BI);
477 
478   // Now that we have full information about ranges, loop over the ranges and
479   // emit memset's for anything big enough to be worthwhile.
480   Instruction *AMemSet = nullptr;
481   for (const MemsetRange &Range : Ranges) {
482     if (Range.TheStores.size() == 1) continue;
483 
484     // If it is profitable to lower this range to memset, do so now.
485     if (!Range.isProfitableToUseMemset(DL))
486       continue;
487 
488     // Otherwise, we do want to transform this!  Create a new memset.
489     // Get the starting pointer of the block.
490     StartPtr = Range.StartPtr;
491 
492     AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
493                                    MaybeAlign(Range.Alignment));
494     LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
495                                                    : Range.TheStores) dbgs()
496                                               << *SI << '\n';
497                dbgs() << "With: " << *AMemSet << '\n');
498     if (!Range.TheStores.empty())
499       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
500 
501     if (MSSAU) {
502       assert(LastMemDef && MemInsertPoint &&
503              "Both LastMemDef and MemInsertPoint need to be set");
504       auto *NewDef =
505           cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI
506                               ? MSSAU->createMemoryAccessBefore(
507                                     AMemSet, LastMemDef, MemInsertPoint)
508                               : MSSAU->createMemoryAccessAfter(
509                                     AMemSet, LastMemDef, MemInsertPoint));
510       MSSAU->insertDef(NewDef, /*RenameUses=*/true);
511       LastMemDef = NewDef;
512       MemInsertPoint = NewDef;
513     }
514 
515     // Zap all the stores.
516     for (Instruction *SI : Range.TheStores)
517       eraseInstruction(SI);
518 
519     ++NumMemSetInfer;
520   }
521 
522   return AMemSet;
523 }
524 
525 // This method try to lift a store instruction before position P.
526 // It will lift the store and its argument + that anything that
527 // may alias with these.
528 // The method returns true if it was successful.
529 bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
530   // If the store alias this position, early bail out.
531   MemoryLocation StoreLoc = MemoryLocation::get(SI);
532   if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc)))
533     return false;
534 
535   // Keep track of the arguments of all instruction we plan to lift
536   // so we can make sure to lift them as well if appropriate.
537   DenseSet<Instruction*> Args;
538   if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
539     if (Ptr->getParent() == SI->getParent())
540       Args.insert(Ptr);
541 
542   // Instruction to lift before P.
543   SmallVector<Instruction *, 8> ToLift{SI};
544 
545   // Memory locations of lifted instructions.
546   SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
547 
548   // Lifted calls.
549   SmallVector<const CallBase *, 8> Calls;
550 
551   const MemoryLocation LoadLoc = MemoryLocation::get(LI);
552 
553   for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
554     auto *C = &*I;
555 
556     // Make sure hoisting does not perform a store that was not guaranteed to
557     // happen.
558     if (!isGuaranteedToTransferExecutionToSuccessor(C))
559       return false;
560 
561     bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, None));
562 
563     bool NeedLift = false;
564     if (Args.erase(C))
565       NeedLift = true;
566     else if (MayAlias) {
567       NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) {
568         return isModOrRefSet(AA->getModRefInfo(C, ML));
569       });
570 
571       if (!NeedLift)
572         NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) {
573           return isModOrRefSet(AA->getModRefInfo(C, Call));
574         });
575     }
576 
577     if (!NeedLift)
578       continue;
579 
580     if (MayAlias) {
581       // Since LI is implicitly moved downwards past the lifted instructions,
582       // none of them may modify its source.
583       if (isModSet(AA->getModRefInfo(C, LoadLoc)))
584         return false;
585       else if (const auto *Call = dyn_cast<CallBase>(C)) {
586         // If we can't lift this before P, it's game over.
587         if (isModOrRefSet(AA->getModRefInfo(P, Call)))
588           return false;
589 
590         Calls.push_back(Call);
591       } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
592         // If we can't lift this before P, it's game over.
593         auto ML = MemoryLocation::get(C);
594         if (isModOrRefSet(AA->getModRefInfo(P, ML)))
595           return false;
596 
597         MemLocs.push_back(ML);
598       } else
599         // We don't know how to lift this instruction.
600         return false;
601     }
602 
603     ToLift.push_back(C);
604     for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
605       if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) {
606         if (A->getParent() == SI->getParent()) {
607           // Cannot hoist user of P above P
608           if(A == P) return false;
609           Args.insert(A);
610         }
611       }
612   }
613 
614   // Find MSSA insertion point. Normally P will always have a corresponding
615   // memory access before which we can insert. However, with non-standard AA
616   // pipelines, there may be a mismatch between AA and MSSA, in which case we
617   // will scan for a memory access before P. In either case, we know for sure
618   // that at least the load will have a memory access.
619   // TODO: Simplify this once P will be determined by MSSA, in which case the
620   // discrepancy can no longer occur.
621   MemoryUseOrDef *MemInsertPoint = nullptr;
622   if (MSSAU) {
623     if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) {
624       MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator());
625     } else {
626       const Instruction *ConstP = P;
627       for (const Instruction &I : make_range(++ConstP->getReverseIterator(),
628                                              ++LI->getReverseIterator())) {
629         if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
630           MemInsertPoint = MA;
631           break;
632         }
633       }
634     }
635   }
636 
637   // We made it, we need to lift.
638   for (auto *I : llvm::reverse(ToLift)) {
639     LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
640     I->moveBefore(P);
641     if (MSSAU) {
642       assert(MemInsertPoint && "Must have found insert point");
643       if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) {
644         MSSAU->moveAfter(MA, MemInsertPoint);
645         MemInsertPoint = MA;
646       }
647     }
648   }
649 
650   return true;
651 }
652 
653 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
654   if (!SI->isSimple()) return false;
655 
656   // Avoid merging nontemporal stores since the resulting
657   // memcpy/memset would not be able to preserve the nontemporal hint.
658   // In theory we could teach how to propagate the !nontemporal metadata to
659   // memset calls. However, that change would force the backend to
660   // conservatively expand !nontemporal memset calls back to sequences of
661   // store instructions (effectively undoing the merging).
662   if (SI->getMetadata(LLVMContext::MD_nontemporal))
663     return false;
664 
665   const DataLayout &DL = SI->getModule()->getDataLayout();
666 
667   Value *StoredVal = SI->getValueOperand();
668 
669   // Not all the transforms below are correct for non-integral pointers, bail
670   // until we've audited the individual pieces.
671   if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
672     return false;
673 
674   // Load to store forwarding can be interpreted as memcpy.
675   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
676     if (LI->isSimple() && LI->hasOneUse() &&
677         LI->getParent() == SI->getParent()) {
678 
679       auto *T = LI->getType();
680       // Don't introduce calls to memcpy/memmove intrinsics out of thin air if
681       // the corresponding libcalls are not available.
682       // TODO: We should really distinguish between libcall availability and
683       // our ability to introduce intrinsics.
684       if (T->isAggregateType() &&
685           (EnableMemCpyOptWithoutLibcalls ||
686            (TLI->has(LibFunc_memcpy) && TLI->has(LibFunc_memmove)))) {
687         MemoryLocation LoadLoc = MemoryLocation::get(LI);
688 
689         // We use alias analysis to check if an instruction may store to
690         // the memory we load from in between the load and the store. If
691         // such an instruction is found, we try to promote there instead
692         // of at the store position.
693         // TODO: Can use MSSA for this.
694         Instruction *P = SI;
695         for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
696           if (isModSet(AA->getModRefInfo(&I, LoadLoc))) {
697             P = &I;
698             break;
699           }
700         }
701 
702         // We found an instruction that may write to the loaded memory.
703         // We can try to promote at this position instead of the store
704         // position if nothing aliases the store memory after this and the store
705         // destination is not in the range.
706         if (P && P != SI) {
707           if (!moveUp(SI, P, LI))
708             P = nullptr;
709         }
710 
711         // If a valid insertion position is found, then we can promote
712         // the load/store pair to a memcpy.
713         if (P) {
714           // If we load from memory that may alias the memory we store to,
715           // memmove must be used to preserve semantic. If not, memcpy can
716           // be used. Also, if we load from constant memory, memcpy can be used
717           // as the constant memory won't be modified.
718           bool UseMemMove = false;
719           if (isModSet(AA->getModRefInfo(SI, LoadLoc)))
720             UseMemMove = true;
721 
722           uint64_t Size = DL.getTypeStoreSize(T);
723 
724           IRBuilder<> Builder(P);
725           Instruction *M;
726           if (UseMemMove)
727             M = Builder.CreateMemMove(
728                 SI->getPointerOperand(), SI->getAlign(),
729                 LI->getPointerOperand(), LI->getAlign(), Size);
730           else
731             M = Builder.CreateMemCpy(
732                 SI->getPointerOperand(), SI->getAlign(),
733                 LI->getPointerOperand(), LI->getAlign(), Size);
734 
735           LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
736                             << *M << "\n");
737 
738           if (MSSAU) {
739             auto *LastDef =
740                 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
741             auto *NewAccess =
742                 MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
743             MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
744           }
745 
746           eraseInstruction(SI);
747           eraseInstruction(LI);
748           ++NumMemCpyInstr;
749 
750           // Make sure we do not invalidate the iterator.
751           BBI = M->getIterator();
752           return true;
753         }
754       }
755 
756       // Detect cases where we're performing call slot forwarding, but
757       // happen to be using a load-store pair to implement it, rather than
758       // a memcpy.
759       CallInst *C = nullptr;
760       if (EnableMemorySSA) {
761         if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
762                 MSSA->getWalker()->getClobberingMemoryAccess(LI))) {
763           // The load most post-dom the call. Limit to the same block for now.
764           // TODO: Support non-local call-slot optimization?
765           if (LoadClobber->getBlock() == SI->getParent())
766             C = dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst());
767         }
768       } else {
769         MemDepResult ldep = MD->getDependency(LI);
770         if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
771           C = dyn_cast<CallInst>(ldep.getInst());
772       }
773 
774       if (C) {
775         // Check that nothing touches the dest of the "copy" between
776         // the call and the store.
777         MemoryLocation StoreLoc = MemoryLocation::get(SI);
778         if (EnableMemorySSA) {
779           if (accessedBetween(*AA, StoreLoc, MSSA->getMemoryAccess(C),
780                               MSSA->getMemoryAccess(SI)))
781             C = nullptr;
782         } else {
783           for (BasicBlock::iterator I = --SI->getIterator(),
784                                     E = C->getIterator();
785                I != E; --I) {
786             if (isModOrRefSet(AA->getModRefInfo(&*I, StoreLoc))) {
787               C = nullptr;
788               break;
789             }
790           }
791         }
792       }
793 
794       if (C) {
795         bool changed = performCallSlotOptzn(
796             LI, SI, SI->getPointerOperand()->stripPointerCasts(),
797             LI->getPointerOperand()->stripPointerCasts(),
798             DL.getTypeStoreSize(SI->getOperand(0)->getType()),
799             commonAlignment(SI->getAlign(), LI->getAlign()), C);
800         if (changed) {
801           eraseInstruction(SI);
802           eraseInstruction(LI);
803           ++NumMemCpyInstr;
804           return true;
805         }
806       }
807     }
808   }
809 
810   // The following code creates memset intrinsics out of thin air. Don't do
811   // this if the corresponding libfunc is not available.
812   // TODO: We should really distinguish between libcall availability and
813   // our ability to introduce intrinsics.
814   if (!(TLI->has(LibFunc_memset) || EnableMemCpyOptWithoutLibcalls))
815     return false;
816 
817   // There are two cases that are interesting for this code to handle: memcpy
818   // and memset.  Right now we only handle memset.
819 
820   // Ensure that the value being stored is something that can be memset'able a
821   // byte at a time like "0" or "-1" or any width, as well as things like
822   // 0xA0A0A0A0 and 0.0.
823   auto *V = SI->getOperand(0);
824   if (Value *ByteVal = isBytewiseValue(V, DL)) {
825     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
826                                               ByteVal)) {
827       BBI = I->getIterator(); // Don't invalidate iterator.
828       return true;
829     }
830 
831     // If we have an aggregate, we try to promote it to memset regardless
832     // of opportunity for merging as it can expose optimization opportunities
833     // in subsequent passes.
834     auto *T = V->getType();
835     if (T->isAggregateType()) {
836       uint64_t Size = DL.getTypeStoreSize(T);
837       IRBuilder<> Builder(SI);
838       auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
839                                      SI->getAlign());
840 
841       LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
842 
843       if (MSSAU) {
844         assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI)));
845         auto *LastDef =
846             cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
847         auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
848         MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
849       }
850 
851       eraseInstruction(SI);
852       NumMemSetInfer++;
853 
854       // Make sure we do not invalidate the iterator.
855       BBI = M->getIterator();
856       return true;
857     }
858   }
859 
860   return false;
861 }
862 
863 bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
864   // See if there is another memset or store neighboring this memset which
865   // allows us to widen out the memset to do a single larger store.
866   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
867     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
868                                               MSI->getValue())) {
869       BBI = I->getIterator(); // Don't invalidate iterator.
870       return true;
871     }
872   return false;
873 }
874 
875 /// Takes a memcpy and a call that it depends on,
876 /// and checks for the possibility of a call slot optimization by having
877 /// the call write its result directly into the destination of the memcpy.
878 bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
879                                          Instruction *cpyStore, Value *cpyDest,
880                                          Value *cpySrc, uint64_t cpyLen,
881                                          Align cpyAlign, CallInst *C) {
882   // The general transformation to keep in mind is
883   //
884   //   call @func(..., src, ...)
885   //   memcpy(dest, src, ...)
886   //
887   // ->
888   //
889   //   memcpy(dest, src, ...)
890   //   call @func(..., dest, ...)
891   //
892   // Since moving the memcpy is technically awkward, we additionally check that
893   // src only holds uninitialized values at the moment of the call, meaning that
894   // the memcpy can be discarded rather than moved.
895 
896   // Lifetime marks shouldn't be operated on.
897   if (Function *F = C->getCalledFunction())
898     if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
899       return false;
900 
901   // Require that src be an alloca.  This simplifies the reasoning considerably.
902   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
903   if (!srcAlloca)
904     return false;
905 
906   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
907   if (!srcArraySize)
908     return false;
909 
910   const DataLayout &DL = cpyLoad->getModule()->getDataLayout();
911   uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
912                      srcArraySize->getZExtValue();
913 
914   if (cpyLen < srcSize)
915     return false;
916 
917   // Check that accessing the first srcSize bytes of dest will not cause a
918   // trap.  Otherwise the transform is invalid since it might cause a trap
919   // to occur earlier than it otherwise would.
920   if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpyLen),
921                                           DL, C, DT))
922     return false;
923 
924   // Make sure that nothing can observe cpyDest being written early. There are
925   // a number of cases to consider:
926   //  1. cpyDest cannot be accessed between C and cpyStore as a precondition of
927   //     the transform.
928   //  2. C itself may not access cpyDest (prior to the transform). This is
929   //     checked further below.
930   //  3. If cpyDest is accessible to the caller of this function (potentially
931   //     captured and not based on an alloca), we need to ensure that we cannot
932   //     unwind between C and cpyStore. This is checked here.
933   //  4. If cpyDest is potentially captured, there may be accesses to it from
934   //     another thread. In this case, we need to check that cpyStore is
935   //     guaranteed to be executed if C is. As it is a non-atomic access, it
936   //     renders accesses from other threads undefined.
937   //     TODO: This is currently not checked.
938   if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore))
939     return false;
940 
941   // Check that dest points to memory that is at least as aligned as src.
942   Align srcAlign = srcAlloca->getAlign();
943   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
944   // If dest is not aligned enough and we can't increase its alignment then
945   // bail out.
946   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
947     return false;
948 
949   // Check that src is not accessed except via the call and the memcpy.  This
950   // guarantees that it holds only undefined values when passed in (so the final
951   // memcpy can be dropped), that it is not read or written between the call and
952   // the memcpy, and that writing beyond the end of it is undefined.
953   SmallVector<User *, 8> srcUseList(srcAlloca->users());
954   while (!srcUseList.empty()) {
955     User *U = srcUseList.pop_back_val();
956 
957     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
958       append_range(srcUseList, U->users());
959       continue;
960     }
961     if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
962       if (!G->hasAllZeroIndices())
963         return false;
964 
965       append_range(srcUseList, U->users());
966       continue;
967     }
968     if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
969       if (IT->isLifetimeStartOrEnd())
970         continue;
971 
972     if (U != C && U != cpyLoad)
973       return false;
974   }
975 
976   // Check that src isn't captured by the called function since the
977   // transformation can cause aliasing issues in that case.
978   for (unsigned ArgI = 0, E = C->arg_size(); ArgI != E; ++ArgI)
979     if (C->getArgOperand(ArgI) == cpySrc && !C->doesNotCapture(ArgI))
980       return false;
981 
982   // Since we're changing the parameter to the callsite, we need to make sure
983   // that what would be the new parameter dominates the callsite.
984   if (!DT->dominates(cpyDest, C)) {
985     // Support moving a constant index GEP before the call.
986     auto *GEP = dyn_cast<GetElementPtrInst>(cpyDest);
987     if (GEP && GEP->hasAllConstantIndices() &&
988         DT->dominates(GEP->getPointerOperand(), C))
989       GEP->moveBefore(C);
990     else
991       return false;
992   }
993 
994   // In addition to knowing that the call does not access src in some
995   // unexpected manner, for example via a global, which we deduce from
996   // the use analysis, we also need to know that it does not sneakily
997   // access dest.  We rely on AA to figure this out for us.
998   ModRefInfo MR = AA->getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
999   // If necessary, perform additional analysis.
1000   if (isModOrRefSet(MR))
1001     MR = AA->callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), DT);
1002   if (isModOrRefSet(MR))
1003     return false;
1004 
1005   // We can't create address space casts here because we don't know if they're
1006   // safe for the target.
1007   if (cpySrc->getType()->getPointerAddressSpace() !=
1008       cpyDest->getType()->getPointerAddressSpace())
1009     return false;
1010   for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
1011     if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
1012         cpySrc->getType()->getPointerAddressSpace() !=
1013             C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
1014       return false;
1015 
1016   // All the checks have passed, so do the transformation.
1017   bool changedArgument = false;
1018   for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
1019     if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
1020       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
1021         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
1022                                       cpyDest->getName(), C);
1023       changedArgument = true;
1024       if (C->getArgOperand(ArgI)->getType() == Dest->getType())
1025         C->setArgOperand(ArgI, Dest);
1026       else
1027         C->setArgOperand(ArgI, CastInst::CreatePointerCast(
1028                                    Dest, C->getArgOperand(ArgI)->getType(),
1029                                    Dest->getName(), C));
1030     }
1031 
1032   if (!changedArgument)
1033     return false;
1034 
1035   // If the destination wasn't sufficiently aligned then increase its alignment.
1036   if (!isDestSufficientlyAligned) {
1037     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
1038     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
1039   }
1040 
1041   // Drop any cached information about the call, because we may have changed
1042   // its dependence information by changing its parameter.
1043   if (MD)
1044     MD->removeInstruction(C);
1045 
1046   // Update AA metadata
1047   // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
1048   // handled here, but combineMetadata doesn't support them yet
1049   unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1050                          LLVMContext::MD_noalias,
1051                          LLVMContext::MD_invariant_group,
1052                          LLVMContext::MD_access_group};
1053   combineMetadata(C, cpyLoad, KnownIDs, true);
1054 
1055   ++NumCallSlot;
1056   return true;
1057 }
1058 
1059 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
1060 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
1061 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
1062                                                   MemCpyInst *MDep) {
1063   // We can only transforms memcpy's where the dest of one is the source of the
1064   // other.
1065   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
1066     return false;
1067 
1068   // If dep instruction is reading from our current input, then it is a noop
1069   // transfer and substituting the input won't change this instruction.  Just
1070   // ignore the input and let someone else zap MDep.  This handles cases like:
1071   //    memcpy(a <- a)
1072   //    memcpy(b <- a)
1073   if (M->getSource() == MDep->getSource())
1074     return false;
1075 
1076   // Second, the length of the memcpy's must be the same, or the preceding one
1077   // must be larger than the following one.
1078   if (MDep->getLength() != M->getLength()) {
1079     ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1080     ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
1081     if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1082       return false;
1083   }
1084 
1085   // Verify that the copied-from memory doesn't change in between the two
1086   // transfers.  For example, in:
1087   //    memcpy(a <- b)
1088   //    *b = 42;
1089   //    memcpy(c <- a)
1090   // It would be invalid to transform the second memcpy into memcpy(c <- b).
1091   //
1092   // TODO: If the code between M and MDep is transparent to the destination "c",
1093   // then we could still perform the xform by moving M up to the first memcpy.
1094   if (EnableMemorySSA) {
1095     // TODO: It would be sufficient to check the MDep source up to the memcpy
1096     // size of M, rather than MDep.
1097     if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1098                        MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(M)))
1099       return false;
1100   } else {
1101     // NOTE: This is conservative, it will stop on any read from the source loc,
1102     // not just the defining memcpy.
1103     MemDepResult SourceDep =
1104         MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1105                                      M->getIterator(), M->getParent());
1106     if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1107       return false;
1108   }
1109 
1110   // If the dest of the second might alias the source of the first, then the
1111   // source and dest might overlap. In addition, if the source of the first
1112   // points to constant memory, they won't overlap by definition. Otherwise, we
1113   // still want to eliminate the intermediate value, but we have to generate a
1114   // memmove instead of memcpy.
1115   bool UseMemMove = false;
1116   if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(MDep))))
1117     UseMemMove = true;
1118 
1119   // If all checks passed, then we can transform M.
1120   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
1121                     << *MDep << '\n' << *M << '\n');
1122 
1123   // TODO: Is this worth it if we're creating a less aligned memcpy? For
1124   // example we could be moving from movaps -> movq on x86.
1125   IRBuilder<> Builder(M);
1126   Instruction *NewM;
1127   if (UseMemMove)
1128     NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
1129                                  MDep->getRawSource(), MDep->getSourceAlign(),
1130                                  M->getLength(), M->isVolatile());
1131   else if (isa<MemCpyInlineInst>(M)) {
1132     // llvm.memcpy may be promoted to llvm.memcpy.inline, but the converse is
1133     // never allowed since that would allow the latter to be lowered as a call
1134     // to an external function.
1135     NewM = Builder.CreateMemCpyInline(
1136         M->getRawDest(), M->getDestAlign(), MDep->getRawSource(),
1137         MDep->getSourceAlign(), M->getLength(), M->isVolatile());
1138   } else
1139     NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
1140                                 MDep->getRawSource(), MDep->getSourceAlign(),
1141                                 M->getLength(), M->isVolatile());
1142 
1143   if (MSSAU) {
1144     assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)));
1145     auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1146     auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1147     MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1148   }
1149 
1150   // Remove the instruction we're replacing.
1151   eraseInstruction(M);
1152   ++NumMemCpyInstr;
1153   return true;
1154 }
1155 
1156 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
1157 /// \p MemSet.  Try to simplify \p MemSet to only set the trailing bytes that
1158 /// weren't copied over by \p MemCpy.
1159 ///
1160 /// In other words, transform:
1161 /// \code
1162 ///   memset(dst, c, dst_size);
1163 ///   memcpy(dst, src, src_size);
1164 /// \endcode
1165 /// into:
1166 /// \code
1167 ///   memcpy(dst, src, src_size);
1168 ///   memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1169 /// \endcode
1170 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1171                                                   MemSetInst *MemSet) {
1172   // We can only transform memset/memcpy with the same destination.
1173   if (!AA->isMustAlias(MemSet->getDest(), MemCpy->getDest()))
1174     return false;
1175 
1176   // Check that src and dst of the memcpy aren't the same. While memcpy
1177   // operands cannot partially overlap, exact equality is allowed.
1178   if (isModSet(AA->getModRefInfo(MemCpy, MemoryLocation::getForSource(MemCpy))))
1179     return false;
1180 
1181   if (EnableMemorySSA) {
1182     // We know that dst up to src_size is not written. We now need to make sure
1183     // that dst up to dst_size is not accessed. (If we did not move the memset,
1184     // checking for reads would be sufficient.)
1185     if (accessedBetween(*AA, MemoryLocation::getForDest(MemSet),
1186                         MSSA->getMemoryAccess(MemSet),
1187                         MSSA->getMemoryAccess(MemCpy))) {
1188       return false;
1189     }
1190   } else {
1191     // We have already checked that dst up to src_size is not accessed. We
1192     // need to make sure that there are no accesses up to dst_size either.
1193     MemDepResult DstDepInfo = MD->getPointerDependencyFrom(
1194         MemoryLocation::getForDest(MemSet), false, MemCpy->getIterator(),
1195         MemCpy->getParent());
1196     if (DstDepInfo.getInst() != MemSet)
1197       return false;
1198   }
1199 
1200   // Use the same i8* dest as the memcpy, killing the memset dest if different.
1201   Value *Dest = MemCpy->getRawDest();
1202   Value *DestSize = MemSet->getLength();
1203   Value *SrcSize = MemCpy->getLength();
1204 
1205   if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy))
1206     return false;
1207 
1208   // If the sizes are the same, simply drop the memset instead of generating
1209   // a replacement with zero size.
1210   if (DestSize == SrcSize) {
1211     eraseInstruction(MemSet);
1212     return true;
1213   }
1214 
1215   // By default, create an unaligned memset.
1216   unsigned Align = 1;
1217   // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1218   // of the sum.
1219   const unsigned DestAlign =
1220       std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
1221   if (DestAlign > 1)
1222     if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1223       Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1224 
1225   IRBuilder<> Builder(MemCpy);
1226 
1227   // If the sizes have different types, zext the smaller one.
1228   if (DestSize->getType() != SrcSize->getType()) {
1229     if (DestSize->getType()->getIntegerBitWidth() >
1230         SrcSize->getType()->getIntegerBitWidth())
1231       SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1232     else
1233       DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1234   }
1235 
1236   Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1237   Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1238   Value *MemsetLen = Builder.CreateSelect(
1239       Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1240   unsigned DestAS = Dest->getType()->getPointerAddressSpace();
1241   Instruction *NewMemSet = Builder.CreateMemSet(
1242       Builder.CreateGEP(Builder.getInt8Ty(),
1243                         Builder.CreatePointerCast(Dest,
1244                                                   Builder.getInt8PtrTy(DestAS)),
1245                         SrcSize),
1246       MemSet->getOperand(1), MemsetLen, MaybeAlign(Align));
1247 
1248   if (MSSAU) {
1249     assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&
1250            "MemCpy must be a MemoryDef");
1251     // The new memset is inserted after the memcpy, but it is known that its
1252     // defining access is the memset about to be removed which immediately
1253     // precedes the memcpy.
1254     auto *LastDef =
1255         cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1256     auto *NewAccess = MSSAU->createMemoryAccessBefore(
1257         NewMemSet, LastDef->getDefiningAccess(), LastDef);
1258     MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1259   }
1260 
1261   eraseInstruction(MemSet);
1262   return true;
1263 }
1264 
1265 /// Determine whether the instruction has undefined content for the given Size,
1266 /// either because it was freshly alloca'd or started its lifetime.
1267 static bool hasUndefContents(Instruction *I, Value *Size) {
1268   if (isa<AllocaInst>(I))
1269     return true;
1270 
1271   if (ConstantInt *CSize = dyn_cast<ConstantInt>(Size)) {
1272     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1273       if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1274         if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1275           if (LTSize->getZExtValue() >= CSize->getZExtValue())
1276             return true;
1277   }
1278 
1279   return false;
1280 }
1281 
1282 static bool hasUndefContentsMSSA(MemorySSA *MSSA, AliasAnalysis *AA, Value *V,
1283                                  MemoryDef *Def, Value *Size) {
1284   if (MSSA->isLiveOnEntryDef(Def))
1285     return isa<AllocaInst>(getUnderlyingObject(V));
1286 
1287   if (IntrinsicInst *II =
1288           dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) {
1289     if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1290       ConstantInt *LTSize = cast<ConstantInt>(II->getArgOperand(0));
1291 
1292       if (ConstantInt *CSize = dyn_cast<ConstantInt>(Size)) {
1293         if (AA->isMustAlias(V, II->getArgOperand(1)) &&
1294             LTSize->getZExtValue() >= CSize->getZExtValue())
1295           return true;
1296       }
1297 
1298       // If the lifetime.start covers a whole alloca (as it almost always
1299       // does) and we're querying a pointer based on that alloca, then we know
1300       // the memory is definitely undef, regardless of how exactly we alias.
1301       // The size also doesn't matter, as an out-of-bounds access would be UB.
1302       AllocaInst *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(V));
1303       if (getUnderlyingObject(II->getArgOperand(1)) == Alloca) {
1304         const DataLayout &DL = Alloca->getModule()->getDataLayout();
1305         if (Optional<TypeSize> AllocaSize = Alloca->getAllocationSizeInBits(DL))
1306           if (*AllocaSize == LTSize->getValue() * 8)
1307             return true;
1308       }
1309     }
1310   }
1311 
1312   return false;
1313 }
1314 
1315 /// Transform memcpy to memset when its source was just memset.
1316 /// In other words, turn:
1317 /// \code
1318 ///   memset(dst1, c, dst1_size);
1319 ///   memcpy(dst2, dst1, dst2_size);
1320 /// \endcode
1321 /// into:
1322 /// \code
1323 ///   memset(dst1, c, dst1_size);
1324 ///   memset(dst2, c, dst2_size);
1325 /// \endcode
1326 /// When dst2_size <= dst1_size.
1327 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1328                                                MemSetInst *MemSet) {
1329   // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1330   // memcpying from the same address. Otherwise it is hard to reason about.
1331   if (!AA->isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1332     return false;
1333 
1334   Value *MemSetSize = MemSet->getLength();
1335   Value *CopySize = MemCpy->getLength();
1336 
1337   if (MemSetSize != CopySize) {
1338     // Make sure the memcpy doesn't read any more than what the memset wrote.
1339     // Don't worry about sizes larger than i64.
1340 
1341     // A known memset size is required.
1342     ConstantInt *CMemSetSize = dyn_cast<ConstantInt>(MemSetSize);
1343     if (!CMemSetSize)
1344       return false;
1345 
1346     // A known memcpy size is also required.
1347     ConstantInt *CCopySize = dyn_cast<ConstantInt>(CopySize);
1348     if (!CCopySize)
1349       return false;
1350     if (CCopySize->getZExtValue() > CMemSetSize->getZExtValue()) {
1351       // If the memcpy is larger than the memset, but the memory was undef prior
1352       // to the memset, we can just ignore the tail. Technically we're only
1353       // interested in the bytes from MemSetSize..CopySize here, but as we can't
1354       // easily represent this location, we use the full 0..CopySize range.
1355       MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1356       bool CanReduceSize = false;
1357       if (EnableMemorySSA) {
1358         MemoryUseOrDef *MemSetAccess = MSSA->getMemoryAccess(MemSet);
1359         MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1360             MemSetAccess->getDefiningAccess(), MemCpyLoc);
1361         if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1362           if (hasUndefContentsMSSA(MSSA, AA, MemCpy->getSource(), MD, CopySize))
1363             CanReduceSize = true;
1364       } else {
1365         MemDepResult DepInfo = MD->getPointerDependencyFrom(
1366             MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
1367         if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
1368           CanReduceSize = true;
1369       }
1370 
1371       if (!CanReduceSize)
1372         return false;
1373       CopySize = MemSetSize;
1374     }
1375   }
1376 
1377   IRBuilder<> Builder(MemCpy);
1378   Instruction *NewM =
1379       Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1380                            CopySize, MaybeAlign(MemCpy->getDestAlignment()));
1381   if (MSSAU) {
1382     auto *LastDef =
1383         cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1384     auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1385     MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1386   }
1387 
1388   return true;
1389 }
1390 
1391 /// Perform simplification of memcpy's.  If we have memcpy A
1392 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1393 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
1394 /// circumstances). This allows later passes to remove the first memcpy
1395 /// altogether.
1396 bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
1397   // We can only optimize non-volatile memcpy's.
1398   if (M->isVolatile()) return false;
1399 
1400   // If the source and destination of the memcpy are the same, then zap it.
1401   if (M->getSource() == M->getDest()) {
1402     ++BBI;
1403     eraseInstruction(M);
1404     return true;
1405   }
1406 
1407   // If copying from a constant, try to turn the memcpy into a memset.
1408   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
1409     if (GV->isConstant() && GV->hasDefinitiveInitializer())
1410       if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
1411                                            M->getModule()->getDataLayout())) {
1412         IRBuilder<> Builder(M);
1413         Instruction *NewM =
1414             Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1415                                  MaybeAlign(M->getDestAlignment()), false);
1416         if (MSSAU) {
1417           auto *LastDef =
1418               cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1419           auto *NewAccess =
1420               MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1421           MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1422         }
1423 
1424         eraseInstruction(M);
1425         ++NumCpyToSet;
1426         return true;
1427       }
1428 
1429   if (EnableMemorySSA) {
1430     MemoryUseOrDef *MA = MSSA->getMemoryAccess(M);
1431     MemoryAccess *AnyClobber = MSSA->getWalker()->getClobberingMemoryAccess(MA);
1432     MemoryLocation DestLoc = MemoryLocation::getForDest(M);
1433     const MemoryAccess *DestClobber =
1434         MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc);
1435 
1436     // Try to turn a partially redundant memset + memcpy into
1437     // memcpy + smaller memset.  We don't need the memcpy size for this.
1438     // The memcpy most post-dom the memset, so limit this to the same basic
1439     // block. A non-local generalization is likely not worthwhile.
1440     if (auto *MD = dyn_cast<MemoryDef>(DestClobber))
1441       if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst()))
1442         if (DestClobber->getBlock() == M->getParent())
1443           if (processMemSetMemCpyDependence(M, MDep))
1444             return true;
1445 
1446     MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
1447         AnyClobber, MemoryLocation::getForSource(M));
1448 
1449     // There are four possible optimizations we can do for memcpy:
1450     //   a) memcpy-memcpy xform which exposes redundance for DSE.
1451     //   b) call-memcpy xform for return slot optimization.
1452     //   c) memcpy from freshly alloca'd space or space that has just started
1453     //      its lifetime copies undefined data, and we can therefore eliminate
1454     //      the memcpy in favor of the data that was already at the destination.
1455     //   d) memcpy from a just-memset'd source can be turned into memset.
1456     if (auto *MD = dyn_cast<MemoryDef>(SrcClobber)) {
1457       if (Instruction *MI = MD->getMemoryInst()) {
1458         if (ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength())) {
1459           if (auto *C = dyn_cast<CallInst>(MI)) {
1460             // The memcpy must post-dom the call. Limit to the same block for
1461             // now. Additionally, we need to ensure that there are no accesses
1462             // to dest between the call and the memcpy. Accesses to src will be
1463             // checked by performCallSlotOptzn().
1464             // TODO: Support non-local call-slot optimization?
1465             if (C->getParent() == M->getParent() &&
1466                 !accessedBetween(*AA, DestLoc, MD, MA)) {
1467               // FIXME: Can we pass in either of dest/src alignment here instead
1468               // of conservatively taking the minimum?
1469               Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1470                                          M->getSourceAlign().valueOrOne());
1471               if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
1472                                        CopySize->getZExtValue(), Alignment,
1473                                        C)) {
1474                 LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"
1475                                   << "    call: " << *C << "\n"
1476                                   << "    memcpy: " << *M << "\n");
1477                 eraseInstruction(M);
1478                 ++NumMemCpyInstr;
1479                 return true;
1480               }
1481             }
1482           }
1483         }
1484         if (auto *MDep = dyn_cast<MemCpyInst>(MI))
1485           return processMemCpyMemCpyDependence(M, MDep);
1486         if (auto *MDep = dyn_cast<MemSetInst>(MI)) {
1487           if (performMemCpyToMemSetOptzn(M, MDep)) {
1488             LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n");
1489             eraseInstruction(M);
1490             ++NumCpyToSet;
1491             return true;
1492           }
1493         }
1494       }
1495 
1496       if (hasUndefContentsMSSA(MSSA, AA, M->getSource(), MD, M->getLength())) {
1497         LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n");
1498         eraseInstruction(M);
1499         ++NumMemCpyInstr;
1500         return true;
1501       }
1502     }
1503   } else {
1504     MemDepResult DepInfo = MD->getDependency(M);
1505 
1506     // Try to turn a partially redundant memset + memcpy into
1507     // memcpy + smaller memset.  We don't need the memcpy size for this.
1508     if (DepInfo.isClobber())
1509       if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1510         if (processMemSetMemCpyDependence(M, MDep))
1511           return true;
1512 
1513     // There are four possible optimizations we can do for memcpy:
1514     //   a) memcpy-memcpy xform which exposes redundance for DSE.
1515     //   b) call-memcpy xform for return slot optimization.
1516     //   c) memcpy from freshly alloca'd space or space that has just started
1517     //      its lifetime copies undefined data, and we can therefore eliminate
1518     //      the memcpy in favor of the data that was already at the destination.
1519     //   d) memcpy from a just-memset'd source can be turned into memset.
1520     if (ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength())) {
1521       if (DepInfo.isClobber()) {
1522         if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1523           // FIXME: Can we pass in either of dest/src alignment here instead
1524           // of conservatively taking the minimum?
1525           Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1526                                      M->getSourceAlign().valueOrOne());
1527           if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
1528                                    CopySize->getZExtValue(), Alignment, C)) {
1529             eraseInstruction(M);
1530             ++NumMemCpyInstr;
1531             return true;
1532           }
1533         }
1534       }
1535     }
1536 
1537     MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
1538     MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1539         SrcLoc, true, M->getIterator(), M->getParent());
1540 
1541     if (SrcDepInfo.isClobber()) {
1542       if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1543         return processMemCpyMemCpyDependence(M, MDep);
1544     } else if (SrcDepInfo.isDef()) {
1545       if (hasUndefContents(SrcDepInfo.getInst(), M->getLength())) {
1546         eraseInstruction(M);
1547         ++NumMemCpyInstr;
1548         return true;
1549       }
1550     }
1551 
1552     if (SrcDepInfo.isClobber())
1553       if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1554         if (performMemCpyToMemSetOptzn(M, MDep)) {
1555           eraseInstruction(M);
1556           ++NumCpyToSet;
1557           return true;
1558         }
1559   }
1560 
1561   return false;
1562 }
1563 
1564 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1565 /// not to alias.
1566 bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1567   // See if the source could be modified by this memmove potentially.
1568   if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(M))))
1569     return false;
1570 
1571   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1572                     << "\n");
1573 
1574   // If not, then we know we can transform this.
1575   Type *ArgTys[3] = { M->getRawDest()->getType(),
1576                       M->getRawSource()->getType(),
1577                       M->getLength()->getType() };
1578   M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1579                                                  Intrinsic::memcpy, ArgTys));
1580 
1581   // For MemorySSA nothing really changes (except that memcpy may imply stricter
1582   // aliasing guarantees).
1583 
1584   // MemDep may have over conservative information about this instruction, just
1585   // conservatively flush it from the cache.
1586   if (MD)
1587     MD->removeInstruction(M);
1588 
1589   ++NumMoveToCpy;
1590   return true;
1591 }
1592 
1593 /// This is called on every byval argument in call sites.
1594 bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
1595   const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
1596   // Find out what feeds this byval argument.
1597   Value *ByValArg = CB.getArgOperand(ArgNo);
1598   Type *ByValTy = CB.getParamByValType(ArgNo);
1599   uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1600   MemoryLocation Loc(ByValArg, LocationSize::precise(ByValSize));
1601   MemCpyInst *MDep = nullptr;
1602   if (EnableMemorySSA) {
1603     MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
1604     if (!CallAccess)
1605       return false;
1606     MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1607         CallAccess->getDefiningAccess(), Loc);
1608     if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1609       MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
1610   } else {
1611     MemDepResult DepInfo = MD->getPointerDependencyFrom(
1612         Loc, true, CB.getIterator(), CB.getParent());
1613     if (!DepInfo.isClobber())
1614       return false;
1615     MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1616   }
1617 
1618   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
1619   // a memcpy, see if we can byval from the source of the memcpy instead of the
1620   // result.
1621   if (!MDep || MDep->isVolatile() ||
1622       ByValArg->stripPointerCasts() != MDep->getDest())
1623     return false;
1624 
1625   // The length of the memcpy must be larger or equal to the size of the byval.
1626   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1627   if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1628     return false;
1629 
1630   // Get the alignment of the byval.  If the call doesn't specify the alignment,
1631   // then it is some target specific value that we can't know.
1632   MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
1633   if (!ByValAlign) return false;
1634 
1635   // If it is greater than the memcpy, then we check to see if we can force the
1636   // source of the memcpy to the alignment we need.  If we fail, we bail out.
1637   MaybeAlign MemDepAlign = MDep->getSourceAlign();
1638   if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
1639       getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC,
1640                                  DT) < *ByValAlign)
1641     return false;
1642 
1643   // The address space of the memcpy source must match the byval argument
1644   if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1645       ByValArg->getType()->getPointerAddressSpace())
1646     return false;
1647 
1648   // Verify that the copied-from memory doesn't change in between the memcpy and
1649   // the byval call.
1650   //    memcpy(a <- b)
1651   //    *b = 42;
1652   //    foo(*a)
1653   // It would be invalid to transform the second memcpy into foo(*b).
1654   if (EnableMemorySSA) {
1655     if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1656                        MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(&CB)))
1657       return false;
1658   } else {
1659     // NOTE: This is conservative, it will stop on any read from the source loc,
1660     // not just the defining memcpy.
1661     MemDepResult SourceDep = MD->getPointerDependencyFrom(
1662         MemoryLocation::getForSource(MDep), false,
1663         CB.getIterator(), MDep->getParent());
1664     if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1665       return false;
1666   }
1667 
1668   Value *TmpCast = MDep->getSource();
1669   if (MDep->getSource()->getType() != ByValArg->getType()) {
1670     BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1671                                               "tmpcast", &CB);
1672     // Set the tmpcast's DebugLoc to MDep's
1673     TmpBitCast->setDebugLoc(MDep->getDebugLoc());
1674     TmpCast = TmpBitCast;
1675   }
1676 
1677   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
1678                     << "  " << *MDep << "\n"
1679                     << "  " << CB << "\n");
1680 
1681   // Otherwise we're good!  Update the byval argument.
1682   CB.setArgOperand(ArgNo, TmpCast);
1683   ++NumMemCpyInstr;
1684   return true;
1685 }
1686 
1687 /// Executes one iteration of MemCpyOptPass.
1688 bool MemCpyOptPass::iterateOnFunction(Function &F) {
1689   bool MadeChange = false;
1690 
1691   // Walk all instruction in the function.
1692   for (BasicBlock &BB : F) {
1693     // Skip unreachable blocks. For example processStore assumes that an
1694     // instruction in a BB can't be dominated by a later instruction in the
1695     // same BB (which is a scenario that can happen for an unreachable BB that
1696     // has itself as a predecessor).
1697     if (!DT->isReachableFromEntry(&BB))
1698       continue;
1699 
1700     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
1701         // Avoid invalidating the iterator.
1702       Instruction *I = &*BI++;
1703 
1704       bool RepeatInstruction = false;
1705 
1706       if (StoreInst *SI = dyn_cast<StoreInst>(I))
1707         MadeChange |= processStore(SI, BI);
1708       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1709         RepeatInstruction = processMemSet(M, BI);
1710       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1711         RepeatInstruction = processMemCpy(M, BI);
1712       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1713         RepeatInstruction = processMemMove(M);
1714       else if (auto *CB = dyn_cast<CallBase>(I)) {
1715         for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
1716           if (CB->isByValArgument(i))
1717             MadeChange |= processByValArgument(*CB, i);
1718       }
1719 
1720       // Reprocess the instruction if desired.
1721       if (RepeatInstruction) {
1722         if (BI != BB.begin())
1723           --BI;
1724         MadeChange = true;
1725       }
1726     }
1727   }
1728 
1729   return MadeChange;
1730 }
1731 
1732 PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
1733   auto *MD = !EnableMemorySSA ? &AM.getResult<MemoryDependenceAnalysis>(F)
1734                               : AM.getCachedResult<MemoryDependenceAnalysis>(F);
1735   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1736   auto *AA = &AM.getResult<AAManager>(F);
1737   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
1738   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1739   auto *MSSA = EnableMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F)
1740                                : AM.getCachedResult<MemorySSAAnalysis>(F);
1741 
1742   bool MadeChange =
1743       runImpl(F, MD, &TLI, AA, AC, DT, MSSA ? &MSSA->getMSSA() : nullptr);
1744   if (!MadeChange)
1745     return PreservedAnalyses::all();
1746 
1747   PreservedAnalyses PA;
1748   PA.preserveSet<CFGAnalyses>();
1749   if (MD)
1750     PA.preserve<MemoryDependenceAnalysis>();
1751   if (MSSA)
1752     PA.preserve<MemorySSAAnalysis>();
1753   return PA;
1754 }
1755 
1756 bool MemCpyOptPass::runImpl(Function &F, MemoryDependenceResults *MD_,
1757                             TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
1758                             AssumptionCache *AC_, DominatorTree *DT_,
1759                             MemorySSA *MSSA_) {
1760   bool MadeChange = false;
1761   MD = MD_;
1762   TLI = TLI_;
1763   AA = AA_;
1764   AC = AC_;
1765   DT = DT_;
1766   MSSA = MSSA_;
1767   MemorySSAUpdater MSSAU_(MSSA_);
1768   MSSAU = MSSA_ ? &MSSAU_ : nullptr;
1769 
1770   while (true) {
1771     if (!iterateOnFunction(F))
1772       break;
1773     MadeChange = true;
1774   }
1775 
1776   if (MSSA_ && VerifyMemorySSA)
1777     MSSA_->verifyMemorySSA();
1778 
1779   MD = nullptr;
1780   return MadeChange;
1781 }
1782 
1783 /// This is the main transformation entry point for a function.
1784 bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1785   if (skipFunction(F))
1786     return false;
1787 
1788   auto *MDWP = !EnableMemorySSA
1789       ? &getAnalysis<MemoryDependenceWrapperPass>()
1790       : getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
1791   auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1792   auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1793   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1794   auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1795   auto *MSSAWP = EnableMemorySSA
1796       ? &getAnalysis<MemorySSAWrapperPass>()
1797       : getAnalysisIfAvailable<MemorySSAWrapperPass>();
1798 
1799   return Impl.runImpl(F, MDWP ? & MDWP->getMemDep() : nullptr, TLI, AA, AC, DT,
1800                       MSSAWP ? &MSSAWP->getMSSA() : nullptr);
1801 }
1802