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