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