1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs various transformations related to eliminating memcpy
10 // calls, or transforming sets of stores into memset's.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/Loads.h"
25 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/Analysis/MemorySSA.h"
28 #include "llvm/Analysis/MemorySSAUpdater.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GetElementPtrTypeIterator.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InstrTypes.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/IR/Operator.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/InitializePasses.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/Scalar.h"
60 #include "llvm/Transforms/Utils/Local.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstdint>
64 #include <utility>
65 
66 using namespace llvm;
67 
68 #define DEBUG_TYPE "memcpyopt"
69 
70 // TODO: Actually implement MemorySSA-based MemCpyOpt.
71 static cl::opt<bool>
72     EnableMemorySSA("enable-memcpyopt-memoryssa", cl::init(false), cl::Hidden,
73                     cl::desc("Use MemorySSA-backed MemCpyOpt."));
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 (StoreInst *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     int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
183 
184     addRange(OffsetFromFirst, StoreSize, 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<MemoryDependenceWrapperPass>();
287     AU.addPreserved<MemoryDependenceWrapperPass>();
288     AU.addRequired<AAResultsWrapperPass>();
289     AU.addPreserved<AAResultsWrapperPass>();
290     if (EnableMemorySSA)
291       AU.addRequired<MemorySSAWrapperPass>();
292     AU.addPreserved<MemorySSAWrapperPass>();
293   }
294 };
295 
296 } // end anonymous namespace
297 
298 char MemCpyOptLegacyPass::ID = 0;
299 
300 /// The public interface to this file...
301 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
302 
303 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
304                       false, false)
305 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
306 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
307 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
308 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
309 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
310 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
311 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
312                     false, false)
313 
314 // Check that V is either not accessible by the caller, or unwinding cannot
315 // occur between Start and End.
316 static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
317                                          Instruction *End) {
318   assert(Start->getParent() == End->getParent() && "Must be in same block");
319   if (!Start->getFunction()->doesNotThrow() &&
320       !isa<AllocaInst>(getUnderlyingObject(V))) {
321     for (const Instruction &I :
322          make_range(Start->getIterator(), End->getIterator())) {
323       if (I.mayThrow())
324         return true;
325     }
326   }
327   return false;
328 }
329 
330 void MemCpyOptPass::eraseInstruction(Instruction *I) {
331   if (MSSAU)
332     MSSAU->removeMemoryAccess(I);
333   MD->removeInstruction(I);
334   I->eraseFromParent();
335 }
336 
337 /// When scanning forward over instructions, we look for some other patterns to
338 /// fold away. In particular, this looks for stores to neighboring locations of
339 /// memory. If it sees enough consecutive ones, it attempts to merge them
340 /// together into a memcpy/memset.
341 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
342                                                  Value *StartPtr,
343                                                  Value *ByteVal) {
344   const DataLayout &DL = StartInst->getModule()->getDataLayout();
345 
346   // Okay, so we now have a single store that can be splatable.  Scan to find
347   // all subsequent stores of the same value to offset from the same pointer.
348   // Join these together into ranges, so we can decide whether contiguous blocks
349   // are stored.
350   MemsetRanges Ranges(DL);
351 
352   BasicBlock::iterator BI(StartInst);
353 
354   // Keeps track of the last memory use or def before the insertion point for
355   // the new memset. The new MemoryDef for the inserted memsets will be inserted
356   // after MemInsertPoint. It points to either LastMemDef or to the last user
357   // before the insertion point of the memset, if there are any such users.
358   MemoryUseOrDef *MemInsertPoint = nullptr;
359   // Keeps track of the last MemoryDef between StartInst and the insertion point
360   // for the new memset. This will become the defining access of the inserted
361   // memsets.
362   MemoryDef *LastMemDef = nullptr;
363   for (++BI; !BI->isTerminator(); ++BI) {
364     if (MSSAU) {
365       auto *CurrentAcc = cast_or_null<MemoryUseOrDef>(
366           MSSAU->getMemorySSA()->getMemoryAccess(&*BI));
367       if (CurrentAcc) {
368         MemInsertPoint = CurrentAcc;
369         if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc))
370           LastMemDef = CurrentDef;
371       }
372     }
373 
374     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
375       // If the instruction is readnone, ignore it, otherwise bail out.  We
376       // don't even allow readonly here because we don't want something like:
377       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
378       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
379         break;
380       continue;
381     }
382 
383     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
384       // If this is a store, see if we can merge it in.
385       if (!NextStore->isSimple()) break;
386 
387       Value *StoredVal = NextStore->getValueOperand();
388 
389       // Don't convert stores of non-integral pointer types to memsets (which
390       // stores integers).
391       if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
392         break;
393 
394       // Check to see if this stored value is of the same byte-splattable value.
395       Value *StoredByte = isBytewiseValue(StoredVal, DL);
396       if (isa<UndefValue>(ByteVal) && StoredByte)
397         ByteVal = StoredByte;
398       if (ByteVal != StoredByte)
399         break;
400 
401       // Check to see if this store is to a constant offset from the start ptr.
402       Optional<int64_t> Offset =
403           isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
404       if (!Offset)
405         break;
406 
407       Ranges.addStore(*Offset, NextStore);
408     } else {
409       MemSetInst *MSI = cast<MemSetInst>(BI);
410 
411       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
412           !isa<ConstantInt>(MSI->getLength()))
413         break;
414 
415       // Check to see if this store is to a constant offset from the start ptr.
416       Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
417       if (!Offset)
418         break;
419 
420       Ranges.addMemSet(*Offset, MSI);
421     }
422   }
423 
424   // If we have no ranges, then we just had a single store with nothing that
425   // could be merged in.  This is a very common case of course.
426   if (Ranges.empty())
427     return nullptr;
428 
429   // If we had at least one store that could be merged in, add the starting
430   // store as well.  We try to avoid this unless there is at least something
431   // interesting as a small compile-time optimization.
432   Ranges.addInst(0, StartInst);
433 
434   // If we create any memsets, we put it right before the first instruction that
435   // isn't part of the memset block.  This ensure that the memset is dominated
436   // by any addressing instruction needed by the start of the block.
437   IRBuilder<> Builder(&*BI);
438 
439   // Now that we have full information about ranges, loop over the ranges and
440   // emit memset's for anything big enough to be worthwhile.
441   Instruction *AMemSet = nullptr;
442   for (const MemsetRange &Range : Ranges) {
443     if (Range.TheStores.size() == 1) continue;
444 
445     // If it is profitable to lower this range to memset, do so now.
446     if (!Range.isProfitableToUseMemset(DL))
447       continue;
448 
449     // Otherwise, we do want to transform this!  Create a new memset.
450     // Get the starting pointer of the block.
451     StartPtr = Range.StartPtr;
452 
453     AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
454                                    MaybeAlign(Range.Alignment));
455     LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
456                                                    : Range.TheStores) dbgs()
457                                               << *SI << '\n';
458                dbgs() << "With: " << *AMemSet << '\n');
459     if (!Range.TheStores.empty())
460       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
461 
462     if (MSSAU) {
463       assert(LastMemDef && MemInsertPoint &&
464              "Both LastMemDef and MemInsertPoint need to be set");
465       auto *NewDef =
466           cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI
467                               ? MSSAU->createMemoryAccessBefore(
468                                     AMemSet, LastMemDef, MemInsertPoint)
469                               : MSSAU->createMemoryAccessAfter(
470                                     AMemSet, LastMemDef, MemInsertPoint));
471       MSSAU->insertDef(NewDef, /*RenameUses=*/true);
472       LastMemDef = NewDef;
473       MemInsertPoint = NewDef;
474     }
475 
476     // Zap all the stores.
477     for (Instruction *SI : Range.TheStores)
478       eraseInstruction(SI);
479 
480     ++NumMemSetInfer;
481   }
482 
483   return AMemSet;
484 }
485 
486 // This method try to lift a store instruction before position P.
487 // It will lift the store and its argument + that anything that
488 // may alias with these.
489 // The method returns true if it was successful.
490 bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
491   // If the store alias this position, early bail out.
492   MemoryLocation StoreLoc = MemoryLocation::get(SI);
493   if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc)))
494     return false;
495 
496   // Keep track of the arguments of all instruction we plan to lift
497   // so we can make sure to lift them as well if appropriate.
498   DenseSet<Instruction*> Args;
499   if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
500     if (Ptr->getParent() == SI->getParent())
501       Args.insert(Ptr);
502 
503   // Instruction to lift before P.
504   SmallVector<Instruction *, 8> ToLift{SI};
505 
506   // Memory locations of lifted instructions.
507   SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
508 
509   // Lifted calls.
510   SmallVector<const CallBase *, 8> Calls;
511 
512   const MemoryLocation LoadLoc = MemoryLocation::get(LI);
513 
514   for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
515     auto *C = &*I;
516 
517     // Make sure hoisting does not perform a store that was not guaranteed to
518     // happen.
519     if (!isGuaranteedToTransferExecutionToSuccessor(C))
520       return false;
521 
522     bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, None));
523 
524     bool NeedLift = false;
525     if (Args.erase(C))
526       NeedLift = true;
527     else if (MayAlias) {
528       NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) {
529         return isModOrRefSet(AA->getModRefInfo(C, ML));
530       });
531 
532       if (!NeedLift)
533         NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) {
534           return isModOrRefSet(AA->getModRefInfo(C, Call));
535         });
536     }
537 
538     if (!NeedLift)
539       continue;
540 
541     if (MayAlias) {
542       // Since LI is implicitly moved downwards past the lifted instructions,
543       // none of them may modify its source.
544       if (isModSet(AA->getModRefInfo(C, LoadLoc)))
545         return false;
546       else if (const auto *Call = dyn_cast<CallBase>(C)) {
547         // If we can't lift this before P, it's game over.
548         if (isModOrRefSet(AA->getModRefInfo(P, Call)))
549           return false;
550 
551         Calls.push_back(Call);
552       } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
553         // If we can't lift this before P, it's game over.
554         auto ML = MemoryLocation::get(C);
555         if (isModOrRefSet(AA->getModRefInfo(P, ML)))
556           return false;
557 
558         MemLocs.push_back(ML);
559       } else
560         // We don't know how to lift this instruction.
561         return false;
562     }
563 
564     ToLift.push_back(C);
565     for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
566       if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) {
567         if (A->getParent() == SI->getParent()) {
568           // Cannot hoist user of P above P
569           if(A == P) return false;
570           Args.insert(A);
571         }
572       }
573   }
574 
575   // Find MSSA insertion point. Normally P will always have a corresponding
576   // memory access before which we can insert. However, with non-standard AA
577   // pipelines, there may be a mismatch between AA and MSSA, in which case we
578   // will scan for a memory access before P. In either case, we know for sure
579   // that at least the load will have a memory access.
580   // TODO: Simplify this once P will be determined by MSSA, in which case the
581   // discrepancy can no longer occur.
582   MemoryUseOrDef *MemInsertPoint = nullptr;
583   if (MSSAU) {
584     if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) {
585       MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator());
586     } else {
587       const Instruction *ConstP = P;
588       for (const Instruction &I : make_range(++ConstP->getReverseIterator(),
589                                              ++LI->getReverseIterator())) {
590         if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
591           MemInsertPoint = MA;
592           break;
593         }
594       }
595     }
596   }
597 
598   // We made it, we need to lift.
599   for (auto *I : llvm::reverse(ToLift)) {
600     LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
601     I->moveBefore(P);
602     if (MSSAU) {
603       assert(MemInsertPoint && "Must have found insert point");
604       if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) {
605         MSSAU->moveAfter(MA, MemInsertPoint);
606         MemInsertPoint = MA;
607       }
608     }
609   }
610 
611   return true;
612 }
613 
614 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
615   if (!SI->isSimple()) return false;
616 
617   // Avoid merging nontemporal stores since the resulting
618   // memcpy/memset would not be able to preserve the nontemporal hint.
619   // In theory we could teach how to propagate the !nontemporal metadata to
620   // memset calls. However, that change would force the backend to
621   // conservatively expand !nontemporal memset calls back to sequences of
622   // store instructions (effectively undoing the merging).
623   if (SI->getMetadata(LLVMContext::MD_nontemporal))
624     return false;
625 
626   const DataLayout &DL = SI->getModule()->getDataLayout();
627 
628   Value *StoredVal = SI->getValueOperand();
629 
630   // Not all the transforms below are correct for non-integral pointers, bail
631   // until we've audited the individual pieces.
632   if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
633     return false;
634 
635   // Load to store forwarding can be interpreted as memcpy.
636   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
637     if (LI->isSimple() && LI->hasOneUse() &&
638         LI->getParent() == SI->getParent()) {
639 
640       auto *T = LI->getType();
641       if (T->isAggregateType()) {
642         MemoryLocation LoadLoc = MemoryLocation::get(LI);
643 
644         // We use alias analysis to check if an instruction may store to
645         // the memory we load from in between the load and the store. If
646         // such an instruction is found, we try to promote there instead
647         // of at the store position.
648         Instruction *P = SI;
649         for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
650           if (isModSet(AA->getModRefInfo(&I, LoadLoc))) {
651             P = &I;
652             break;
653           }
654         }
655 
656         // We found an instruction that may write to the loaded memory.
657         // We can try to promote at this position instead of the store
658         // position if nothing alias the store memory after this and the store
659         // destination is not in the range.
660         if (P && P != SI) {
661           if (!moveUp(SI, P, LI))
662             P = nullptr;
663         }
664 
665         // If a valid insertion position is found, then we can promote
666         // the load/store pair to a memcpy.
667         if (P) {
668           // If we load from memory that may alias the memory we store to,
669           // memmove must be used to preserve semantic. If not, memcpy can
670           // be used.
671           bool UseMemMove = false;
672           if (!AA->isNoAlias(MemoryLocation::get(SI), LoadLoc))
673             UseMemMove = true;
674 
675           uint64_t Size = DL.getTypeStoreSize(T);
676 
677           IRBuilder<> Builder(P);
678           Instruction *M;
679           if (UseMemMove)
680             M = Builder.CreateMemMove(
681                 SI->getPointerOperand(), SI->getAlign(),
682                 LI->getPointerOperand(), LI->getAlign(), Size);
683           else
684             M = Builder.CreateMemCpy(
685                 SI->getPointerOperand(), SI->getAlign(),
686                 LI->getPointerOperand(), LI->getAlign(), Size);
687 
688           LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
689                             << *M << "\n");
690 
691           if (MSSAU) {
692             auto *LastDef =
693                 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
694             auto *NewAccess =
695                 MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
696             MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
697           }
698 
699           eraseInstruction(SI);
700           eraseInstruction(LI);
701           ++NumMemCpyInstr;
702 
703           // Make sure we do not invalidate the iterator.
704           BBI = M->getIterator();
705           return true;
706         }
707       }
708 
709       // Detect cases where we're performing call slot forwarding, but
710       // happen to be using a load-store pair to implement it, rather than
711       // a memcpy.
712       MemDepResult ldep = MD->getDependency(LI);
713       CallInst *C = nullptr;
714       if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
715         C = dyn_cast<CallInst>(ldep.getInst());
716 
717       if (C) {
718         // Check that nothing touches the dest of the "copy" between
719         // the call and the store.
720         MemoryLocation StoreLoc = MemoryLocation::get(SI);
721         for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
722              I != E; --I) {
723           if (isModOrRefSet(AA->getModRefInfo(&*I, StoreLoc))) {
724             C = nullptr;
725             break;
726           }
727         }
728       }
729 
730       if (C) {
731         bool changed = performCallSlotOptzn(
732             LI, SI, SI->getPointerOperand()->stripPointerCasts(),
733             LI->getPointerOperand()->stripPointerCasts(),
734             DL.getTypeStoreSize(SI->getOperand(0)->getType()),
735             commonAlignment(SI->getAlign(), LI->getAlign()), C);
736         if (changed) {
737           eraseInstruction(SI);
738           eraseInstruction(LI);
739           ++NumMemCpyInstr;
740           return true;
741         }
742       }
743     }
744   }
745 
746   // There are two cases that are interesting for this code to handle: memcpy
747   // and memset.  Right now we only handle memset.
748 
749   // Ensure that the value being stored is something that can be memset'able a
750   // byte at a time like "0" or "-1" or any width, as well as things like
751   // 0xA0A0A0A0 and 0.0.
752   auto *V = SI->getOperand(0);
753   if (Value *ByteVal = isBytewiseValue(V, DL)) {
754     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
755                                               ByteVal)) {
756       BBI = I->getIterator(); // Don't invalidate iterator.
757       return true;
758     }
759 
760     // If we have an aggregate, we try to promote it to memset regardless
761     // of opportunity for merging as it can expose optimization opportunities
762     // in subsequent passes.
763     auto *T = V->getType();
764     if (T->isAggregateType()) {
765       uint64_t Size = DL.getTypeStoreSize(T);
766       IRBuilder<> Builder(SI);
767       auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
768                                      SI->getAlign());
769 
770       LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
771 
772       if (MSSAU) {
773         assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI)));
774         auto *LastDef =
775             cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
776         auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
777         MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
778       }
779 
780       eraseInstruction(SI);
781       NumMemSetInfer++;
782 
783       // Make sure we do not invalidate the iterator.
784       BBI = M->getIterator();
785       return true;
786     }
787   }
788 
789   return false;
790 }
791 
792 bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
793   // See if there is another memset or store neighboring this memset which
794   // allows us to widen out the memset to do a single larger store.
795   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
796     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
797                                               MSI->getValue())) {
798       BBI = I->getIterator(); // Don't invalidate iterator.
799       return true;
800     }
801   return false;
802 }
803 
804 /// Takes a memcpy and a call that it depends on,
805 /// and checks for the possibility of a call slot optimization by having
806 /// the call write its result directly into the destination of the memcpy.
807 bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
808                                          Instruction *cpyStore, Value *cpyDest,
809                                          Value *cpySrc, uint64_t cpyLen,
810                                          Align cpyAlign, CallInst *C) {
811   // The general transformation to keep in mind is
812   //
813   //   call @func(..., src, ...)
814   //   memcpy(dest, src, ...)
815   //
816   // ->
817   //
818   //   memcpy(dest, src, ...)
819   //   call @func(..., dest, ...)
820   //
821   // Since moving the memcpy is technically awkward, we additionally check that
822   // src only holds uninitialized values at the moment of the call, meaning that
823   // the memcpy can be discarded rather than moved.
824 
825   // Lifetime marks shouldn't be operated on.
826   if (Function *F = C->getCalledFunction())
827     if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
828       return false;
829 
830   // Require that src be an alloca.  This simplifies the reasoning considerably.
831   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
832   if (!srcAlloca)
833     return false;
834 
835   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
836   if (!srcArraySize)
837     return false;
838 
839   const DataLayout &DL = cpyLoad->getModule()->getDataLayout();
840   uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
841                      srcArraySize->getZExtValue();
842 
843   if (cpyLen < srcSize)
844     return false;
845 
846   // Check that accessing the first srcSize bytes of dest will not cause a
847   // trap.  Otherwise the transform is invalid since it might cause a trap
848   // to occur earlier than it otherwise would.
849   if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpyLen),
850                                           DL, C, DT))
851     return false;
852 
853   // Make sure that nothing can observe cpyDest being written early. There are
854   // a number of cases to consider:
855   //  1. cpyDest cannot be accessed between C and cpyStore as a precondition of
856   //     the transform.
857   //  2. C itself may not access cpyDest (prior to the transform). This is
858   //     checked further below.
859   //  3. If cpyDest is accessible to the caller of this function (potentially
860   //     captured and not based on an alloca), we need to ensure that we cannot
861   //     unwind between C and cpyStore. This is checked here.
862   //  4. If cpyDest is potentially captured, there may be accesses to it from
863   //     another thread. In this case, we need to check that cpyStore is
864   //     guaranteed to be executed if C is. As it is a non-atomic access, it
865   //     renders accesses from other threads undefined.
866   //     TODO: This is currently not checked.
867   if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore))
868     return false;
869 
870   // Check that dest points to memory that is at least as aligned as src.
871   Align srcAlign = srcAlloca->getAlign();
872   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
873   // If dest is not aligned enough and we can't increase its alignment then
874   // bail out.
875   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
876     return false;
877 
878   // Check that src is not accessed except via the call and the memcpy.  This
879   // guarantees that it holds only undefined values when passed in (so the final
880   // memcpy can be dropped), that it is not read or written between the call and
881   // the memcpy, and that writing beyond the end of it is undefined.
882   SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
883                                    srcAlloca->user_end());
884   while (!srcUseList.empty()) {
885     User *U = srcUseList.pop_back_val();
886 
887     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
888       for (User *UU : U->users())
889         srcUseList.push_back(UU);
890       continue;
891     }
892     if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
893       if (!G->hasAllZeroIndices())
894         return false;
895 
896       for (User *UU : U->users())
897         srcUseList.push_back(UU);
898       continue;
899     }
900     if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
901       if (IT->isLifetimeStartOrEnd())
902         continue;
903 
904     if (U != C && U != cpyLoad)
905       return false;
906   }
907 
908   // Check that src isn't captured by the called function since the
909   // transformation can cause aliasing issues in that case.
910   for (unsigned ArgI = 0, E = C->arg_size(); ArgI != E; ++ArgI)
911     if (C->getArgOperand(ArgI) == cpySrc && !C->doesNotCapture(ArgI))
912       return false;
913 
914   // Since we're changing the parameter to the callsite, we need to make sure
915   // that what would be the new parameter dominates the callsite.
916   // TODO: Support moving instructions like GEPs upwards.
917   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
918     if (!DT->dominates(cpyDestInst, C))
919       return false;
920 
921   // In addition to knowing that the call does not access src in some
922   // unexpected manner, for example via a global, which we deduce from
923   // the use analysis, we also need to know that it does not sneakily
924   // access dest.  We rely on AA to figure this out for us.
925   ModRefInfo MR = AA->getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
926   // If necessary, perform additional analysis.
927   if (isModOrRefSet(MR))
928     MR = AA->callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), DT);
929   if (isModOrRefSet(MR))
930     return false;
931 
932   // We can't create address space casts here because we don't know if they're
933   // safe for the target.
934   if (cpySrc->getType()->getPointerAddressSpace() !=
935       cpyDest->getType()->getPointerAddressSpace())
936     return false;
937   for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
938     if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
939         cpySrc->getType()->getPointerAddressSpace() !=
940             C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
941       return false;
942 
943   // All the checks have passed, so do the transformation.
944   bool changedArgument = false;
945   for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
946     if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
947       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
948         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
949                                       cpyDest->getName(), C);
950       changedArgument = true;
951       if (C->getArgOperand(ArgI)->getType() == Dest->getType())
952         C->setArgOperand(ArgI, Dest);
953       else
954         C->setArgOperand(ArgI, CastInst::CreatePointerCast(
955                                    Dest, C->getArgOperand(ArgI)->getType(),
956                                    Dest->getName(), C));
957     }
958 
959   if (!changedArgument)
960     return false;
961 
962   // If the destination wasn't sufficiently aligned then increase its alignment.
963   if (!isDestSufficientlyAligned) {
964     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
965     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
966   }
967 
968   // Drop any cached information about the call, because we may have changed
969   // its dependence information by changing its parameter.
970   MD->removeInstruction(C);
971 
972   // Update AA metadata
973   // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
974   // handled here, but combineMetadata doesn't support them yet
975   unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
976                          LLVMContext::MD_noalias,
977                          LLVMContext::MD_invariant_group,
978                          LLVMContext::MD_access_group};
979   combineMetadata(C, cpyLoad, KnownIDs, true);
980 
981   ++NumCallSlot;
982   return true;
983 }
984 
985 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
986 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
987 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
988                                                   MemCpyInst *MDep) {
989   // We can only transforms memcpy's where the dest of one is the source of the
990   // other.
991   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
992     return false;
993 
994   // If dep instruction is reading from our current input, then it is a noop
995   // transfer and substituting the input won't change this instruction.  Just
996   // ignore the input and let someone else zap MDep.  This handles cases like:
997   //    memcpy(a <- a)
998   //    memcpy(b <- a)
999   if (M->getSource() == MDep->getSource())
1000     return false;
1001 
1002   // Second, the length of the memcpy's must be the same, or the preceding one
1003   // must be larger than the following one.
1004   ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1005   ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
1006   if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1007     return false;
1008 
1009   // Verify that the copied-from memory doesn't change in between the two
1010   // transfers.  For example, in:
1011   //    memcpy(a <- b)
1012   //    *b = 42;
1013   //    memcpy(c <- a)
1014   // It would be invalid to transform the second memcpy into memcpy(c <- b).
1015   //
1016   // TODO: If the code between M and MDep is transparent to the destination "c",
1017   // then we could still perform the xform by moving M up to the first memcpy.
1018   //
1019   // NOTE: This is conservative, it will stop on any read from the source loc,
1020   // not just the defining memcpy.
1021   MemDepResult SourceDep =
1022       MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1023                                    M->getIterator(), M->getParent());
1024   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1025     return false;
1026 
1027   // If the dest of the second might alias the source of the first, then the
1028   // source and dest might overlap.  We still want to eliminate the intermediate
1029   // value, but we have to generate a memmove instead of memcpy.
1030   bool UseMemMove = false;
1031   if (!AA->isNoAlias(MemoryLocation::getForDest(M),
1032                      MemoryLocation::getForSource(MDep)))
1033     UseMemMove = true;
1034 
1035   // If all checks passed, then we can transform M.
1036   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
1037                     << *MDep << '\n' << *M << '\n');
1038 
1039   // TODO: Is this worth it if we're creating a less aligned memcpy? For
1040   // example we could be moving from movaps -> movq on x86.
1041   IRBuilder<> Builder(M);
1042   Instruction *NewM;
1043   if (UseMemMove)
1044     NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
1045                                  MDep->getRawSource(), MDep->getSourceAlign(),
1046                                  M->getLength(), M->isVolatile());
1047   else
1048     NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
1049                                 MDep->getRawSource(), MDep->getSourceAlign(),
1050                                 M->getLength(), M->isVolatile());
1051 
1052   if (MSSAU) {
1053     assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)));
1054     auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1055     auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1056     MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1057   }
1058 
1059   // Remove the instruction we're replacing.
1060   eraseInstruction(M);
1061   ++NumMemCpyInstr;
1062   return true;
1063 }
1064 
1065 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
1066 /// \p MemSet.  Try to simplify \p MemSet to only set the trailing bytes that
1067 /// weren't copied over by \p MemCpy.
1068 ///
1069 /// In other words, transform:
1070 /// \code
1071 ///   memset(dst, c, dst_size);
1072 ///   memcpy(dst, src, src_size);
1073 /// \endcode
1074 /// into:
1075 /// \code
1076 ///   memcpy(dst, src, src_size);
1077 ///   memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1078 /// \endcode
1079 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1080                                                   MemSetInst *MemSet) {
1081   // We can only transform memset/memcpy with the same destination.
1082   if (MemSet->getDest() != MemCpy->getDest())
1083     return false;
1084 
1085   // Check that src and dst of the memcpy aren't the same. While memcpy
1086   // operands cannot partially overlap, exact equality is allowed.
1087   if (!AA->isNoAlias(MemoryLocation(MemCpy->getSource(),
1088                                     LocationSize::precise(1)),
1089                      MemoryLocation(MemCpy->getDest(),
1090                                     LocationSize::precise(1))))
1091     return false;
1092 
1093   // Check that there are no other dependencies on the memset destination.
1094   MemDepResult DstDepInfo =
1095       MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1096                                    MemCpy->getIterator(), MemCpy->getParent());
1097   if (DstDepInfo.getInst() != MemSet)
1098     return false;
1099 
1100   // Use the same i8* dest as the memcpy, killing the memset dest if different.
1101   Value *Dest = MemCpy->getRawDest();
1102   Value *DestSize = MemSet->getLength();
1103   Value *SrcSize = MemCpy->getLength();
1104 
1105   if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy))
1106     return false;
1107 
1108   // By default, create an unaligned memset.
1109   unsigned Align = 1;
1110   // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1111   // of the sum.
1112   const unsigned DestAlign =
1113       std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
1114   if (DestAlign > 1)
1115     if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1116       Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1117 
1118   IRBuilder<> Builder(MemCpy);
1119 
1120   // If the sizes have different types, zext the smaller one.
1121   if (DestSize->getType() != SrcSize->getType()) {
1122     if (DestSize->getType()->getIntegerBitWidth() >
1123         SrcSize->getType()->getIntegerBitWidth())
1124       SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1125     else
1126       DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1127   }
1128 
1129   Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1130   Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1131   Value *MemsetLen = Builder.CreateSelect(
1132       Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1133   Instruction *NewMemSet = Builder.CreateMemSet(
1134       Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest,
1135                         SrcSize),
1136       MemSet->getOperand(1), MemsetLen, MaybeAlign(Align));
1137 
1138   if (MSSAU) {
1139     assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&
1140            "MemCpy must be a MemoryDef");
1141     // The new memset is inserted after the memcpy, but it is known that its
1142     // defining access is the memset about to be removed which immediately
1143     // precedes the memcpy.
1144     auto *LastDef =
1145         cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1146     auto *NewAccess = MSSAU->createMemoryAccessBefore(
1147         NewMemSet, LastDef->getDefiningAccess(), LastDef);
1148     MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1149   }
1150 
1151   eraseInstruction(MemSet);
1152   return true;
1153 }
1154 
1155 /// Determine whether the instruction has undefined content for the given Size,
1156 /// either because it was freshly alloca'd or started its lifetime.
1157 static bool hasUndefContents(Instruction *I, ConstantInt *Size) {
1158   if (isa<AllocaInst>(I))
1159     return true;
1160 
1161   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1162     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1163       if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1164         if (LTSize->getZExtValue() >= Size->getZExtValue())
1165           return true;
1166 
1167   return false;
1168 }
1169 
1170 /// Transform memcpy to memset when its source was just memset.
1171 /// In other words, turn:
1172 /// \code
1173 ///   memset(dst1, c, dst1_size);
1174 ///   memcpy(dst2, dst1, dst2_size);
1175 /// \endcode
1176 /// into:
1177 /// \code
1178 ///   memset(dst1, c, dst1_size);
1179 ///   memset(dst2, c, dst2_size);
1180 /// \endcode
1181 /// When dst2_size <= dst1_size.
1182 ///
1183 /// The \p MemCpy must have a Constant length.
1184 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1185                                                MemSetInst *MemSet) {
1186   // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1187   // memcpying from the same address. Otherwise it is hard to reason about.
1188   if (!AA->isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1189     return false;
1190 
1191   // A known memset size is required.
1192   ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1193   if (!MemSetSize)
1194     return false;
1195 
1196   // Make sure the memcpy doesn't read any more than what the memset wrote.
1197   // Don't worry about sizes larger than i64.
1198   ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1199   if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) {
1200     // If the memcpy is larger than the memset, but the memory was undef prior
1201     // to the memset, we can just ignore the tail. Technically we're only
1202     // interested in the bytes from MemSetSize..CopySize here, but as we can't
1203     // easily represent this location, we use the full 0..CopySize range.
1204     MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1205     MemDepResult DepInfo = MD->getPointerDependencyFrom(
1206         MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
1207     if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
1208       CopySize = MemSetSize;
1209     else
1210       return false;
1211   }
1212 
1213   IRBuilder<> Builder(MemCpy);
1214   Instruction *NewM =
1215       Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1216                            CopySize, MaybeAlign(MemCpy->getDestAlignment()));
1217   if (MSSAU) {
1218     auto *LastDef =
1219         cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1220     auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1221     MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1222   }
1223 
1224   return true;
1225 }
1226 
1227 /// Perform simplification of memcpy's.  If we have memcpy A
1228 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1229 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
1230 /// circumstances). This allows later passes to remove the first memcpy
1231 /// altogether.
1232 bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
1233   // We can only optimize non-volatile memcpy's.
1234   if (M->isVolatile()) return false;
1235 
1236   // If the source and destination of the memcpy are the same, then zap it.
1237   if (M->getSource() == M->getDest()) {
1238     ++BBI;
1239     eraseInstruction(M);
1240     return true;
1241   }
1242 
1243   // If copying from a constant, try to turn the memcpy into a memset.
1244   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
1245     if (GV->isConstant() && GV->hasDefinitiveInitializer())
1246       if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
1247                                            M->getModule()->getDataLayout())) {
1248         IRBuilder<> Builder(M);
1249         Instruction *NewM =
1250             Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1251                                  MaybeAlign(M->getDestAlignment()), false);
1252         if (MSSAU) {
1253           auto *LastDef =
1254               cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1255           auto *NewAccess =
1256               MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1257           MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1258         }
1259 
1260         eraseInstruction(M);
1261         ++NumCpyToSet;
1262         return true;
1263       }
1264 
1265   MemDepResult DepInfo = MD->getDependency(M);
1266 
1267   // Try to turn a partially redundant memset + memcpy into
1268   // memcpy + smaller memset.  We don't need the memcpy size for this.
1269   if (DepInfo.isClobber())
1270     if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1271       if (processMemSetMemCpyDependence(M, MDep))
1272         return true;
1273 
1274   // The optimizations after this point require the memcpy size.
1275   ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
1276   if (!CopySize) return false;
1277 
1278   // There are four possible optimizations we can do for memcpy:
1279   //   a) memcpy-memcpy xform which exposes redundance for DSE.
1280   //   b) call-memcpy xform for return slot optimization.
1281   //   c) memcpy from freshly alloca'd space or space that has just started its
1282   //      lifetime copies undefined data, and we can therefore eliminate the
1283   //      memcpy in favor of the data that was already at the destination.
1284   //   d) memcpy from a just-memset'd source can be turned into memset.
1285   if (DepInfo.isClobber()) {
1286     if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1287       // FIXME: Can we pass in either of dest/src alignment here instead
1288       // of conservatively taking the minimum?
1289       Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1290                                  M->getSourceAlign().valueOrOne());
1291       if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
1292                                CopySize->getZExtValue(), Alignment, C)) {
1293         eraseInstruction(M);
1294         ++NumMemCpyInstr;
1295         return true;
1296       }
1297     }
1298   }
1299 
1300   MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
1301   MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1302       SrcLoc, true, M->getIterator(), M->getParent());
1303 
1304   if (SrcDepInfo.isClobber()) {
1305     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1306       return processMemCpyMemCpyDependence(M, MDep);
1307   } else if (SrcDepInfo.isDef()) {
1308     if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) {
1309       eraseInstruction(M);
1310       ++NumMemCpyInstr;
1311       return true;
1312     }
1313   }
1314 
1315   if (SrcDepInfo.isClobber())
1316     if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1317       if (performMemCpyToMemSetOptzn(M, MDep)) {
1318         eraseInstruction(M);
1319         ++NumCpyToSet;
1320         return true;
1321       }
1322 
1323   return false;
1324 }
1325 
1326 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1327 /// not to alias.
1328 bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1329   if (!TLI->has(LibFunc_memmove))
1330     return false;
1331 
1332   // See if the pointers alias.
1333   if (!AA->isNoAlias(MemoryLocation::getForDest(M),
1334                      MemoryLocation::getForSource(M)))
1335     return false;
1336 
1337   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1338                     << "\n");
1339 
1340   // If not, then we know we can transform this.
1341   Type *ArgTys[3] = { M->getRawDest()->getType(),
1342                       M->getRawSource()->getType(),
1343                       M->getLength()->getType() };
1344   M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1345                                                  Intrinsic::memcpy, ArgTys));
1346 
1347   // For MemorySSA nothing really changes (except that memcpy may imply stricter
1348   // aliasing guarantees).
1349 
1350   // MemDep may have over conservative information about this instruction, just
1351   // conservatively flush it from the cache.
1352   MD->removeInstruction(M);
1353 
1354   ++NumMoveToCpy;
1355   return true;
1356 }
1357 
1358 /// This is called on every byval argument in call sites.
1359 bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
1360   const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
1361   // Find out what feeds this byval argument.
1362   Value *ByValArg = CB.getArgOperand(ArgNo);
1363   Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1364   uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1365   MemDepResult DepInfo = MD->getPointerDependencyFrom(
1366       MemoryLocation(ByValArg, LocationSize::precise(ByValSize)), true,
1367       CB.getIterator(), CB.getParent());
1368   if (!DepInfo.isClobber())
1369     return false;
1370 
1371   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
1372   // a memcpy, see if we can byval from the source of the memcpy instead of the
1373   // result.
1374   MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1375   if (!MDep || MDep->isVolatile() ||
1376       ByValArg->stripPointerCasts() != MDep->getDest())
1377     return false;
1378 
1379   // The length of the memcpy must be larger or equal to the size of the byval.
1380   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1381   if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1382     return false;
1383 
1384   // Get the alignment of the byval.  If the call doesn't specify the alignment,
1385   // then it is some target specific value that we can't know.
1386   MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
1387   if (!ByValAlign) return false;
1388 
1389   // If it is greater than the memcpy, then we check to see if we can force the
1390   // source of the memcpy to the alignment we need.  If we fail, we bail out.
1391   MaybeAlign MemDepAlign = MDep->getSourceAlign();
1392   if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
1393       getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC,
1394                                  DT) < *ByValAlign)
1395     return false;
1396 
1397   // The address space of the memcpy source must match the byval argument
1398   if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1399       ByValArg->getType()->getPointerAddressSpace())
1400     return false;
1401 
1402   // Verify that the copied-from memory doesn't change in between the memcpy and
1403   // the byval call.
1404   //    memcpy(a <- b)
1405   //    *b = 42;
1406   //    foo(*a)
1407   // It would be invalid to transform the second memcpy into foo(*b).
1408   //
1409   // NOTE: This is conservative, it will stop on any read from the source loc,
1410   // not just the defining memcpy.
1411   MemDepResult SourceDep = MD->getPointerDependencyFrom(
1412       MemoryLocation::getForSource(MDep), false,
1413       CB.getIterator(), MDep->getParent());
1414   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1415     return false;
1416 
1417   Value *TmpCast = MDep->getSource();
1418   if (MDep->getSource()->getType() != ByValArg->getType()) {
1419     BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1420                                               "tmpcast", &CB);
1421     // Set the tmpcast's DebugLoc to MDep's
1422     TmpBitCast->setDebugLoc(MDep->getDebugLoc());
1423     TmpCast = TmpBitCast;
1424   }
1425 
1426   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
1427                     << "  " << *MDep << "\n"
1428                     << "  " << CB << "\n");
1429 
1430   // Otherwise we're good!  Update the byval argument.
1431   CB.setArgOperand(ArgNo, TmpCast);
1432   ++NumMemCpyInstr;
1433   return true;
1434 }
1435 
1436 /// Executes one iteration of MemCpyOptPass.
1437 bool MemCpyOptPass::iterateOnFunction(Function &F) {
1438   bool MadeChange = false;
1439 
1440   // Walk all instruction in the function.
1441   for (BasicBlock &BB : F) {
1442     // Skip unreachable blocks. For example processStore assumes that an
1443     // instruction in a BB can't be dominated by a later instruction in the
1444     // same BB (which is a scenario that can happen for an unreachable BB that
1445     // has itself as a predecessor).
1446     if (!DT->isReachableFromEntry(&BB))
1447       continue;
1448 
1449     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
1450         // Avoid invalidating the iterator.
1451       Instruction *I = &*BI++;
1452 
1453       bool RepeatInstruction = false;
1454 
1455       if (StoreInst *SI = dyn_cast<StoreInst>(I))
1456         MadeChange |= processStore(SI, BI);
1457       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1458         RepeatInstruction = processMemSet(M, BI);
1459       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1460         RepeatInstruction = processMemCpy(M, BI);
1461       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1462         RepeatInstruction = processMemMove(M);
1463       else if (auto *CB = dyn_cast<CallBase>(I)) {
1464         for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
1465           if (CB->isByValArgument(i))
1466             MadeChange |= processByValArgument(*CB, i);
1467       }
1468 
1469       // Reprocess the instruction if desired.
1470       if (RepeatInstruction) {
1471         if (BI != BB.begin())
1472           --BI;
1473         MadeChange = true;
1474       }
1475     }
1476   }
1477 
1478   return MadeChange;
1479 }
1480 
1481 PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
1482   auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1483   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1484   auto *AA = &AM.getResult<AAManager>(F);
1485   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
1486   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1487   auto *MSSA = EnableMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F)
1488                                : AM.getCachedResult<MemorySSAAnalysis>(F);
1489 
1490   bool MadeChange =
1491       runImpl(F, &MD, &TLI, AA, AC, DT, MSSA ? &MSSA->getMSSA() : nullptr);
1492   if (!MadeChange)
1493     return PreservedAnalyses::all();
1494 
1495   PreservedAnalyses PA;
1496   PA.preserveSet<CFGAnalyses>();
1497   PA.preserve<GlobalsAA>();
1498   PA.preserve<MemoryDependenceAnalysis>();
1499   if (MSSA)
1500     PA.preserve<MemorySSAAnalysis>();
1501   return PA;
1502 }
1503 
1504 bool MemCpyOptPass::runImpl(Function &F, MemoryDependenceResults *MD_,
1505                             TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
1506                             AssumptionCache *AC_, DominatorTree *DT_,
1507                             MemorySSA *MSSA_) {
1508   bool MadeChange = false;
1509   MD = MD_;
1510   TLI = TLI_;
1511   AA = AA_;
1512   AC = AC_;
1513   DT = DT_;
1514   MemorySSAUpdater MSSAU_(MSSA_);
1515   MSSAU = MSSA_ ? &MSSAU_ : nullptr;
1516   // If we don't have at least memset and memcpy, there is little point of doing
1517   // anything here.  These are required by a freestanding implementation, so if
1518   // even they are disabled, there is no point in trying hard.
1519   if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
1520     return false;
1521 
1522   while (true) {
1523     if (!iterateOnFunction(F))
1524       break;
1525     MadeChange = true;
1526   }
1527 
1528   if (MSSA_ && VerifyMemorySSA)
1529     MSSA_->verifyMemorySSA();
1530 
1531   MD = nullptr;
1532   return MadeChange;
1533 }
1534 
1535 /// This is the main transformation entry point for a function.
1536 bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1537   if (skipFunction(F))
1538     return false;
1539 
1540   auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1541   auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1542   auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1543   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1544   auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1545   auto *MSSAWP = EnableMemorySSA
1546       ? &getAnalysis<MemorySSAWrapperPass>()
1547       : getAnalysisIfAvailable<MemorySSAWrapperPass>();
1548 
1549   return Impl.runImpl(F, MD, TLI, AA, AC, DT,
1550                       MSSAWP ? &MSSAWP->getMSSA() : nullptr);
1551 }
1552