1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This pass performs various transformations related to eliminating memcpy
10 // calls, or transforming sets of stores into memset's.
12 //===----------------------------------------------------------------------===//
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/MemoryDependenceAnalysis.h"
25 #include "llvm/Analysis/MemoryLocation.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Argument.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GetElementPtrTypeIterator.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/IRBuilder.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/LLVMContext.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Operator.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"
65 #define DEBUG_TYPE "memcpyopt"
67 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
68 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
69 STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
70 STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
74 /// Represents a range of memset'd bytes with the ByteVal value.
75 /// This allows us to analyze stores like:
80 /// which sometimes happens with stores to arrays of structs etc. When we see
81 /// the first store, we make a range [1, 2). The second store extends the range
82 /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
83 /// two ranges into [0, 3) which is memset'able.
85 // Start/End - A semi range that describes the span that this range covers.
86 // The range is closed at the start and open at the end: [Start, End).
89 /// StartPtr - The getelementptr instruction that points to the start of the
93 /// Alignment - The known alignment of the first store.
96 /// TheStores - The actual stores that make up this range.
97 SmallVector<Instruction*, 16> TheStores;
99 bool isProfitableToUseMemset(const DataLayout &DL) const;
102 } // end anonymous namespace
104 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
105 // If we found more than 4 stores to merge or 16 bytes, use memset.
106 if (TheStores.size() >= 4 || End-Start >= 16) return true;
108 // If there is nothing to merge, don't do anything.
109 if (TheStores.size() < 2) return false;
111 // If any of the stores are a memset, then it is always good to extend the
113 for (Instruction *SI : TheStores)
114 if (!isa<StoreInst>(SI))
117 // Assume that the code generator is capable of merging pairs of stores
118 // together if it wants to.
119 if (TheStores.size() == 2) return false;
121 // If we have fewer than 8 stores, it can still be worthwhile to do this.
122 // For example, merging 4 i8 stores into an i32 store is useful almost always.
123 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
124 // memset will be split into 2 32-bit stores anyway) and doing so can
125 // pessimize the llvm optimizer.
127 // Since we don't have perfect knowledge here, make some assumptions: assume
128 // the maximum GPR width is the same size as the largest legal integer
129 // size. If so, check to see whether we will end up actually reducing the
130 // number of stores used.
131 unsigned Bytes = unsigned(End-Start);
132 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
135 unsigned NumPointerStores = Bytes / MaxIntSize;
137 // Assume the remaining bytes if any are done a byte at a time.
138 unsigned NumByteStores = Bytes % MaxIntSize;
140 // If we will reduce the # stores (according to this heuristic), do the
141 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
143 return TheStores.size() > NumPointerStores+NumByteStores;
149 using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
151 /// A sorted list of the memset ranges.
152 SmallVector<MemsetRange, 8> Ranges;
154 const DataLayout &DL;
157 MemsetRanges(const DataLayout &DL) : DL(DL) {}
159 using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
161 const_iterator begin() const { return Ranges.begin(); }
162 const_iterator end() const { return Ranges.end(); }
163 bool empty() const { return Ranges.empty(); }
165 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
166 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
167 addStore(OffsetFromFirst, SI);
169 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
172 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
173 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
175 addRange(OffsetFromFirst, StoreSize, SI->getPointerOperand(),
176 SI->getAlign().value(), SI);
179 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
180 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
181 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
184 void addRange(int64_t Start, int64_t Size, Value *Ptr,
185 unsigned Alignment, Instruction *Inst);
188 } // end anonymous namespace
190 /// Add a new store to the MemsetRanges data structure. This adds a
191 /// new range for the specified store at the specified offset, merging into
192 /// existing ranges as appropriate.
193 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
194 unsigned Alignment, Instruction *Inst) {
195 int64_t End = Start+Size;
197 range_iterator I = partition_point(
198 Ranges, [=](const MemsetRange &O) { return O.End < Start; });
200 // We now know that I == E, in which case we didn't find anything to merge
201 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
202 // to insert a new range. Handle this now.
203 if (I == Ranges.end() || End < I->Start) {
204 MemsetRange &R = *Ranges.insert(I, MemsetRange());
208 R.Alignment = Alignment;
209 R.TheStores.push_back(Inst);
213 // This store overlaps with I, add it.
214 I->TheStores.push_back(Inst);
216 // At this point, we may have an interval that completely contains our store.
217 // If so, just add it to the interval and return.
218 if (I->Start <= Start && I->End >= End)
221 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
222 // but is not entirely contained within the range.
224 // See if the range extends the start of the range. In this case, it couldn't
225 // possibly cause it to join the prior range, because otherwise we would have
227 if (Start < I->Start) {
230 I->Alignment = Alignment;
233 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
234 // is in or right at the end of I), and that End >= I->Start. Extend I out to
238 range_iterator NextI = I;
239 while (++NextI != Ranges.end() && End >= NextI->Start) {
240 // Merge the range in.
241 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
242 if (NextI->End > I->End)
250 //===----------------------------------------------------------------------===//
251 // MemCpyOptLegacyPass Pass
252 //===----------------------------------------------------------------------===//
256 class MemCpyOptLegacyPass : public FunctionPass {
260 static char ID; // Pass identification, replacement for typeid
262 MemCpyOptLegacyPass() : FunctionPass(ID) {
263 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
266 bool runOnFunction(Function &F) override;
269 // This transformation requires dominator postdominator info
270 void getAnalysisUsage(AnalysisUsage &AU) const override {
271 AU.setPreservesCFG();
272 AU.addRequired<AssumptionCacheTracker>();
273 AU.addRequired<DominatorTreeWrapperPass>();
274 AU.addRequired<MemoryDependenceWrapperPass>();
275 AU.addRequired<AAResultsWrapperPass>();
276 AU.addRequired<TargetLibraryInfoWrapperPass>();
277 AU.addPreserved<GlobalsAAWrapperPass>();
278 AU.addPreserved<MemoryDependenceWrapperPass>();
282 } // end anonymous namespace
284 char MemCpyOptLegacyPass::ID = 0;
286 /// The public interface to this file...
287 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
289 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
291 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
292 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
293 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
294 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
295 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
296 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
297 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
300 /// When scanning forward over instructions, we look for some other patterns to
301 /// fold away. In particular, this looks for stores to neighboring locations of
302 /// memory. If it sees enough consecutive ones, it attempts to merge them
303 /// together into a memcpy/memset.
304 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
307 const DataLayout &DL = StartInst->getModule()->getDataLayout();
309 // Okay, so we now have a single store that can be splatable. Scan to find
310 // all subsequent stores of the same value to offset from the same pointer.
311 // Join these together into ranges, so we can decide whether contiguous blocks
313 MemsetRanges Ranges(DL);
315 BasicBlock::iterator BI(StartInst);
316 for (++BI; !BI->isTerminator(); ++BI) {
317 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
318 // If the instruction is readnone, ignore it, otherwise bail out. We
319 // don't even allow readonly here because we don't want something like:
320 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
321 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
326 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
327 // If this is a store, see if we can merge it in.
328 if (!NextStore->isSimple()) break;
330 // Check to see if this stored value is of the same byte-splattable value.
331 Value *StoredByte = isBytewiseValue(NextStore->getOperand(0), DL);
332 if (isa<UndefValue>(ByteVal) && StoredByte)
333 ByteVal = StoredByte;
334 if (ByteVal != StoredByte)
337 // Check to see if this store is to a constant offset from the start ptr.
338 Optional<int64_t> Offset =
339 isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
343 Ranges.addStore(*Offset, NextStore);
345 MemSetInst *MSI = cast<MemSetInst>(BI);
347 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
348 !isa<ConstantInt>(MSI->getLength()))
351 // Check to see if this store is to a constant offset from the start ptr.
352 Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
356 Ranges.addMemSet(*Offset, MSI);
360 // If we have no ranges, then we just had a single store with nothing that
361 // could be merged in. This is a very common case of course.
365 // If we had at least one store that could be merged in, add the starting
366 // store as well. We try to avoid this unless there is at least something
367 // interesting as a small compile-time optimization.
368 Ranges.addInst(0, StartInst);
370 // If we create any memsets, we put it right before the first instruction that
371 // isn't part of the memset block. This ensure that the memset is dominated
372 // by any addressing instruction needed by the start of the block.
373 IRBuilder<> Builder(&*BI);
375 // Now that we have full information about ranges, loop over the ranges and
376 // emit memset's for anything big enough to be worthwhile.
377 Instruction *AMemSet = nullptr;
378 for (const MemsetRange &Range : Ranges) {
379 if (Range.TheStores.size() == 1) continue;
381 // If it is profitable to lower this range to memset, do so now.
382 if (!Range.isProfitableToUseMemset(DL))
385 // Otherwise, we do want to transform this! Create a new memset.
386 // Get the starting pointer of the block.
387 StartPtr = Range.StartPtr;
389 AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
390 MaybeAlign(Range.Alignment));
391 LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
392 : Range.TheStores) dbgs()
394 dbgs() << "With: " << *AMemSet << '\n');
396 if (!Range.TheStores.empty())
397 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
399 // Zap all the stores.
400 for (Instruction *SI : Range.TheStores) {
401 MD->removeInstruction(SI);
402 SI->eraseFromParent();
410 // This method try to lift a store instruction before position P.
411 // It will lift the store and its argument + that anything that
412 // may alias with these.
413 // The method returns true if it was successful.
414 static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P,
415 const LoadInst *LI) {
416 // If the store alias this position, early bail out.
417 MemoryLocation StoreLoc = MemoryLocation::get(SI);
418 if (isModOrRefSet(AA.getModRefInfo(P, StoreLoc)))
421 // Keep track of the arguments of all instruction we plan to lift
422 // so we can make sure to lift them as well if appropriate.
423 DenseSet<Instruction*> Args;
424 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
425 if (Ptr->getParent() == SI->getParent())
428 // Instruction to lift before P.
429 SmallVector<Instruction*, 8> ToLift;
431 // Memory locations of lifted instructions.
432 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
435 SmallVector<const CallBase *, 8> Calls;
437 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
439 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
442 bool MayAlias = isModOrRefSet(AA.getModRefInfo(C, None));
444 bool NeedLift = false;
448 NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
449 return isModOrRefSet(AA.getModRefInfo(C, ML));
453 NeedLift = llvm::any_of(Calls, [C, &AA](const CallBase *Call) {
454 return isModOrRefSet(AA.getModRefInfo(C, Call));
462 // Since LI is implicitly moved downwards past the lifted instructions,
463 // none of them may modify its source.
464 if (isModSet(AA.getModRefInfo(C, LoadLoc)))
466 else if (const auto *Call = dyn_cast<CallBase>(C)) {
467 // If we can't lift this before P, it's game over.
468 if (isModOrRefSet(AA.getModRefInfo(P, Call)))
471 Calls.push_back(Call);
472 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
473 // If we can't lift this before P, it's game over.
474 auto ML = MemoryLocation::get(C);
475 if (isModOrRefSet(AA.getModRefInfo(P, ML)))
478 MemLocs.push_back(ML);
480 // We don't know how to lift this instruction.
485 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
486 if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) {
487 if (A->getParent() == SI->getParent()) {
488 // Cannot hoist user of P above P
489 if(A == P) return false;
495 // We made it, we need to lift
496 for (auto *I : llvm::reverse(ToLift)) {
497 LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
504 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
505 if (!SI->isSimple()) return false;
507 // Avoid merging nontemporal stores since the resulting
508 // memcpy/memset would not be able to preserve the nontemporal hint.
509 // In theory we could teach how to propagate the !nontemporal metadata to
510 // memset calls. However, that change would force the backend to
511 // conservatively expand !nontemporal memset calls back to sequences of
512 // store instructions (effectively undoing the merging).
513 if (SI->getMetadata(LLVMContext::MD_nontemporal))
516 const DataLayout &DL = SI->getModule()->getDataLayout();
518 // Load to store forwarding can be interpreted as memcpy.
519 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
520 if (LI->isSimple() && LI->hasOneUse() &&
521 LI->getParent() == SI->getParent()) {
523 auto *T = LI->getType();
524 if (T->isAggregateType()) {
525 AliasAnalysis &AA = LookupAliasAnalysis();
526 MemoryLocation LoadLoc = MemoryLocation::get(LI);
528 // We use alias analysis to check if an instruction may store to
529 // the memory we load from in between the load and the store. If
530 // such an instruction is found, we try to promote there instead
531 // of at the store position.
533 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
534 if (isModSet(AA.getModRefInfo(&I, LoadLoc))) {
540 // We found an instruction that may write to the loaded memory.
541 // We can try to promote at this position instead of the store
542 // position if nothing alias the store memory after this and the store
543 // destination is not in the range.
545 if (!moveUp(AA, SI, P, LI))
549 // If a valid insertion position is found, then we can promote
550 // the load/store pair to a memcpy.
552 // If we load from memory that may alias the memory we store to,
553 // memmove must be used to preserve semantic. If not, memcpy can
555 bool UseMemMove = false;
556 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
559 uint64_t Size = DL.getTypeStoreSize(T);
561 IRBuilder<> Builder(P);
564 M = Builder.CreateMemMove(
565 SI->getPointerOperand(), SI->getAlign(),
566 LI->getPointerOperand(), LI->getAlign(), Size);
568 M = Builder.CreateMemCpy(
569 SI->getPointerOperand(), SI->getAlign(),
570 LI->getPointerOperand(), LI->getAlign(), Size);
572 LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
575 MD->removeInstruction(SI);
576 SI->eraseFromParent();
577 MD->removeInstruction(LI);
578 LI->eraseFromParent();
581 // Make sure we do not invalidate the iterator.
582 BBI = M->getIterator();
587 // Detect cases where we're performing call slot forwarding, but
588 // happen to be using a load-store pair to implement it, rather than
590 MemDepResult ldep = MD->getDependency(LI);
591 CallInst *C = nullptr;
592 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
593 C = dyn_cast<CallInst>(ldep.getInst());
596 // Check that nothing touches the dest of the "copy" between
597 // the call and the store.
598 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
599 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
600 AliasAnalysis &AA = LookupAliasAnalysis();
601 MemoryLocation StoreLoc = MemoryLocation::get(SI);
602 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
604 if (isModOrRefSet(AA.getModRefInfo(&*I, StoreLoc))) {
608 // The store to dest may never happen if an exception can be thrown
609 // between the load and the store.
610 if (I->mayThrow() && !CpyDestIsLocal) {
618 bool changed = performCallSlotOptzn(
619 LI, SI->getPointerOperand()->stripPointerCasts(),
620 LI->getPointerOperand()->stripPointerCasts(),
621 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
622 commonAlignment(SI->getAlign(), LI->getAlign()), C);
624 MD->removeInstruction(SI);
625 SI->eraseFromParent();
626 MD->removeInstruction(LI);
627 LI->eraseFromParent();
635 // There are two cases that are interesting for this code to handle: memcpy
636 // and memset. Right now we only handle memset.
638 // Ensure that the value being stored is something that can be memset'able a
639 // byte at a time like "0" or "-1" or any width, as well as things like
640 // 0xA0A0A0A0 and 0.0.
641 auto *V = SI->getOperand(0);
642 if (Value *ByteVal = isBytewiseValue(V, DL)) {
643 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
645 BBI = I->getIterator(); // Don't invalidate iterator.
649 // If we have an aggregate, we try to promote it to memset regardless
650 // of opportunity for merging as it can expose optimization opportunities
651 // in subsequent passes.
652 auto *T = V->getType();
653 if (T->isAggregateType()) {
654 uint64_t Size = DL.getTypeStoreSize(T);
655 IRBuilder<> Builder(SI);
656 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
659 LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
661 MD->removeInstruction(SI);
662 SI->eraseFromParent();
665 // Make sure we do not invalidate the iterator.
666 BBI = M->getIterator();
674 bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
675 // See if there is another memset or store neighboring this memset which
676 // allows us to widen out the memset to do a single larger store.
677 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
678 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
680 BBI = I->getIterator(); // Don't invalidate iterator.
686 /// Takes a memcpy and a call that it depends on,
687 /// and checks for the possibility of a call slot optimization by having
688 /// the call write its result directly into the destination of the memcpy.
689 bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
690 Value *cpySrc, uint64_t cpyLen,
691 Align cpyAlign, CallInst *C) {
692 // The general transformation to keep in mind is
694 // call @func(..., src, ...)
695 // memcpy(dest, src, ...)
699 // memcpy(dest, src, ...)
700 // call @func(..., dest, ...)
702 // Since moving the memcpy is technically awkward, we additionally check that
703 // src only holds uninitialized values at the moment of the call, meaning that
704 // the memcpy can be discarded rather than moved.
706 // Lifetime marks shouldn't be operated on.
707 if (Function *F = C->getCalledFunction())
708 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
711 // Require that src be an alloca. This simplifies the reasoning considerably.
712 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
716 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
720 const DataLayout &DL = cpy->getModule()->getDataLayout();
721 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
722 srcArraySize->getZExtValue();
724 if (cpyLen < srcSize)
727 // Check that accessing the first srcSize bytes of dest will not cause a
728 // trap. Otherwise the transform is invalid since it might cause a trap
729 // to occur earlier than it otherwise would.
730 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
731 // The destination is an alloca. Check it is larger than srcSize.
732 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
736 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
737 destArraySize->getZExtValue();
739 if (destSize < srcSize)
741 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
742 // The store to dest may never happen if the call can throw.
746 if (A->getDereferenceableBytes() < srcSize) {
747 // If the destination is an sret parameter then only accesses that are
748 // outside of the returned struct type can trap.
749 if (!A->hasStructRetAttr())
752 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
753 if (!StructTy->isSized()) {
754 // The call may never return and hence the copy-instruction may never
755 // be executed, and therefore it's not safe to say "the destination
756 // has at least <cpyLen> bytes, as implied by the copy-instruction",
760 uint64_t destSize = DL.getTypeAllocSize(StructTy);
761 if (destSize < srcSize)
768 // Check that dest points to memory that is at least as aligned as src.
769 Align srcAlign = srcAlloca->getAlign();
770 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
771 // If dest is not aligned enough and we can't increase its alignment then
773 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
776 // Check that src is not accessed except via the call and the memcpy. This
777 // guarantees that it holds only undefined values when passed in (so the final
778 // memcpy can be dropped), that it is not read or written between the call and
779 // the memcpy, and that writing beyond the end of it is undefined.
780 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
781 srcAlloca->user_end());
782 while (!srcUseList.empty()) {
783 User *U = srcUseList.pop_back_val();
785 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
786 for (User *UU : U->users())
787 srcUseList.push_back(UU);
790 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
791 if (!G->hasAllZeroIndices())
794 for (User *UU : U->users())
795 srcUseList.push_back(UU);
798 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
799 if (IT->isLifetimeStartOrEnd())
802 if (U != C && U != cpy)
806 // Check that src isn't captured by the called function since the
807 // transformation can cause aliasing issues in that case.
808 for (unsigned ArgI = 0, E = C->arg_size(); ArgI != E; ++ArgI)
809 if (C->getArgOperand(ArgI) == cpySrc && !C->doesNotCapture(ArgI))
812 // Since we're changing the parameter to the callsite, we need to make sure
813 // that what would be the new parameter dominates the callsite.
814 DominatorTree &DT = LookupDomTree();
815 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
816 if (!DT.dominates(cpyDestInst, C))
819 // In addition to knowing that the call does not access src in some
820 // unexpected manner, for example via a global, which we deduce from
821 // the use analysis, we also need to know that it does not sneakily
822 // access dest. We rely on AA to figure this out for us.
823 AliasAnalysis &AA = LookupAliasAnalysis();
824 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
825 // If necessary, perform additional analysis.
826 if (isModOrRefSet(MR))
827 MR = AA.callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), &DT);
828 if (isModOrRefSet(MR))
831 // We can't create address space casts here because we don't know if they're
832 // safe for the target.
833 if (cpySrc->getType()->getPointerAddressSpace() !=
834 cpyDest->getType()->getPointerAddressSpace())
836 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
837 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
838 cpySrc->getType()->getPointerAddressSpace() !=
839 C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
842 // All the checks have passed, so do the transformation.
843 bool changedArgument = false;
844 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
845 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
846 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
847 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
848 cpyDest->getName(), C);
849 changedArgument = true;
850 if (C->getArgOperand(ArgI)->getType() == Dest->getType())
851 C->setArgOperand(ArgI, Dest);
853 C->setArgOperand(ArgI, CastInst::CreatePointerCast(
854 Dest, C->getArgOperand(ArgI)->getType(),
855 Dest->getName(), C));
858 if (!changedArgument)
861 // If the destination wasn't sufficiently aligned then increase its alignment.
862 if (!isDestSufficientlyAligned) {
863 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
864 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
867 // Drop any cached information about the call, because we may have changed
868 // its dependence information by changing its parameter.
869 MD->removeInstruction(C);
871 // Update AA metadata
872 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
873 // handled here, but combineMetadata doesn't support them yet
874 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
875 LLVMContext::MD_noalias,
876 LLVMContext::MD_invariant_group,
877 LLVMContext::MD_access_group};
878 combineMetadata(C, cpy, KnownIDs, true);
880 // Remove the memcpy.
881 MD->removeInstruction(cpy);
887 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
888 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
889 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
891 // We can only transforms memcpy's where the dest of one is the source of the
893 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
896 // If dep instruction is reading from our current input, then it is a noop
897 // transfer and substituting the input won't change this instruction. Just
898 // ignore the input and let someone else zap MDep. This handles cases like:
901 if (M->getSource() == MDep->getSource())
904 // Second, the length of the memcpy's must be the same, or the preceding one
905 // must be larger than the following one.
906 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
907 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
908 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
911 AliasAnalysis &AA = LookupAliasAnalysis();
913 // Verify that the copied-from memory doesn't change in between the two
914 // transfers. For example, in:
918 // It would be invalid to transform the second memcpy into memcpy(c <- b).
920 // TODO: If the code between M and MDep is transparent to the destination "c",
921 // then we could still perform the xform by moving M up to the first memcpy.
923 // NOTE: This is conservative, it will stop on any read from the source loc,
924 // not just the defining memcpy.
925 MemDepResult SourceDep =
926 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
927 M->getIterator(), M->getParent());
928 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
931 // If the dest of the second might alias the source of the first, then the
932 // source and dest might overlap. We still want to eliminate the intermediate
933 // value, but we have to generate a memmove instead of memcpy.
934 bool UseMemMove = false;
935 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
936 MemoryLocation::getForSource(MDep)))
939 // If all checks passed, then we can transform M.
940 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
941 << *MDep << '\n' << *M << '\n');
943 // TODO: Is this worth it if we're creating a less aligned memcpy? For
944 // example we could be moving from movaps -> movq on x86.
945 IRBuilder<> Builder(M);
947 Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
948 MDep->getRawSource(), MDep->getSourceAlign(),
949 M->getLength(), M->isVolatile());
951 Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
952 MDep->getRawSource(), MDep->getSourceAlign(),
953 M->getLength(), M->isVolatile());
955 // Remove the instruction we're replacing.
956 MD->removeInstruction(M);
957 M->eraseFromParent();
962 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
963 /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
964 /// weren't copied over by \p MemCpy.
966 /// In other words, transform:
968 /// memset(dst, c, dst_size);
969 /// memcpy(dst, src, src_size);
973 /// memcpy(dst, src, src_size);
974 /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
976 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
977 MemSetInst *MemSet) {
978 // We can only transform memset/memcpy with the same destination.
979 if (MemSet->getDest() != MemCpy->getDest())
982 // Check that there are no other dependencies on the memset destination.
983 MemDepResult DstDepInfo =
984 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
985 MemCpy->getIterator(), MemCpy->getParent());
986 if (DstDepInfo.getInst() != MemSet)
989 // Use the same i8* dest as the memcpy, killing the memset dest if different.
990 Value *Dest = MemCpy->getRawDest();
991 Value *DestSize = MemSet->getLength();
992 Value *SrcSize = MemCpy->getLength();
994 // By default, create an unaligned memset.
996 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
998 const unsigned DestAlign =
999 std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
1001 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1002 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1004 IRBuilder<> Builder(MemCpy);
1006 // If the sizes have different types, zext the smaller one.
1007 if (DestSize->getType() != SrcSize->getType()) {
1008 if (DestSize->getType()->getIntegerBitWidth() >
1009 SrcSize->getType()->getIntegerBitWidth())
1010 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1012 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1015 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1016 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1017 Value *MemsetLen = Builder.CreateSelect(
1018 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1019 Builder.CreateMemSet(
1020 Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest,
1022 MemSet->getOperand(1), MemsetLen, MaybeAlign(Align));
1024 MD->removeInstruction(MemSet);
1025 MemSet->eraseFromParent();
1029 /// Determine whether the instruction has undefined content for the given Size,
1030 /// either because it was freshly alloca'd or started its lifetime.
1031 static bool hasUndefContents(Instruction *I, ConstantInt *Size) {
1032 if (isa<AllocaInst>(I))
1035 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1036 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1037 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1038 if (LTSize->getZExtValue() >= Size->getZExtValue())
1044 /// Transform memcpy to memset when its source was just memset.
1045 /// In other words, turn:
1047 /// memset(dst1, c, dst1_size);
1048 /// memcpy(dst2, dst1, dst2_size);
1052 /// memset(dst1, c, dst1_size);
1053 /// memset(dst2, c, dst2_size);
1055 /// When dst2_size <= dst1_size.
1057 /// The \p MemCpy must have a Constant length.
1058 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1059 MemSetInst *MemSet) {
1060 AliasAnalysis &AA = LookupAliasAnalysis();
1062 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1063 // memcpying from the same address. Otherwise it is hard to reason about.
1064 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1067 // A known memset size is required.
1068 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1072 // Make sure the memcpy doesn't read any more than what the memset wrote.
1073 // Don't worry about sizes larger than i64.
1074 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1075 if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) {
1076 // If the memcpy is larger than the memset, but the memory was undef prior
1077 // to the memset, we can just ignore the tail. Technically we're only
1078 // interested in the bytes from MemSetSize..CopySize here, but as we can't
1079 // easily represent this location, we use the full 0..CopySize range.
1080 MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1081 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1082 MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
1083 if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
1084 CopySize = MemSetSize;
1089 IRBuilder<> Builder(MemCpy);
1090 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1), CopySize,
1091 MaybeAlign(MemCpy->getDestAlignment()));
1095 /// Perform simplification of memcpy's. If we have memcpy A
1096 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1097 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
1098 /// circumstances). This allows later passes to remove the first memcpy
1100 bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
1101 // We can only optimize non-volatile memcpy's.
1102 if (M->isVolatile()) return false;
1104 // If the source and destination of the memcpy are the same, then zap it.
1105 if (M->getSource() == M->getDest()) {
1107 MD->removeInstruction(M);
1108 M->eraseFromParent();
1112 // If copying from a constant, try to turn the memcpy into a memset.
1113 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
1114 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1115 if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
1116 M->getModule()->getDataLayout())) {
1117 IRBuilder<> Builder(M);
1118 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1119 MaybeAlign(M->getDestAlignment()), false);
1120 MD->removeInstruction(M);
1121 M->eraseFromParent();
1126 MemDepResult DepInfo = MD->getDependency(M);
1128 // Try to turn a partially redundant memset + memcpy into
1129 // memcpy + smaller memset. We don't need the memcpy size for this.
1130 if (DepInfo.isClobber())
1131 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1132 if (processMemSetMemCpyDependence(M, MDep))
1135 // The optimizations after this point require the memcpy size.
1136 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
1137 if (!CopySize) return false;
1139 // There are four possible optimizations we can do for memcpy:
1140 // a) memcpy-memcpy xform which exposes redundance for DSE.
1141 // b) call-memcpy xform for return slot optimization.
1142 // c) memcpy from freshly alloca'd space or space that has just started its
1143 // lifetime copies undefined data, and we can therefore eliminate the
1144 // memcpy in favor of the data that was already at the destination.
1145 // d) memcpy from a just-memset'd source can be turned into memset.
1146 if (DepInfo.isClobber()) {
1147 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1148 // FIXME: Can we pass in either of dest/src alignment here instead
1149 // of conservatively taking the minimum?
1150 Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1151 M->getSourceAlign().valueOrOne());
1152 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
1153 CopySize->getZExtValue(), Alignment, C)) {
1154 MD->removeInstruction(M);
1155 M->eraseFromParent();
1161 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
1162 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1163 SrcLoc, true, M->getIterator(), M->getParent());
1165 if (SrcDepInfo.isClobber()) {
1166 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1167 return processMemCpyMemCpyDependence(M, MDep);
1168 } else if (SrcDepInfo.isDef()) {
1169 if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) {
1170 MD->removeInstruction(M);
1171 M->eraseFromParent();
1177 if (SrcDepInfo.isClobber())
1178 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1179 if (performMemCpyToMemSetOptzn(M, MDep)) {
1180 MD->removeInstruction(M);
1181 M->eraseFromParent();
1189 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1191 bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1192 AliasAnalysis &AA = LookupAliasAnalysis();
1194 if (!TLI->has(LibFunc_memmove))
1197 // See if the pointers alias.
1198 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1199 MemoryLocation::getForSource(M)))
1202 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1205 // If not, then we know we can transform this.
1206 Type *ArgTys[3] = { M->getRawDest()->getType(),
1207 M->getRawSource()->getType(),
1208 M->getLength()->getType() };
1209 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1210 Intrinsic::memcpy, ArgTys));
1212 // MemDep may have over conservative information about this instruction, just
1213 // conservatively flush it from the cache.
1214 MD->removeInstruction(M);
1220 /// This is called on every byval argument in call sites.
1221 bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
1222 const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
1223 // Find out what feeds this byval argument.
1224 Value *ByValArg = CB.getArgOperand(ArgNo);
1225 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1226 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1227 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1228 MemoryLocation(ByValArg, LocationSize::precise(ByValSize)), true,
1229 CB.getIterator(), CB.getParent());
1230 if (!DepInfo.isClobber())
1233 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1234 // a memcpy, see if we can byval from the source of the memcpy instead of the
1236 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1237 if (!MDep || MDep->isVolatile() ||
1238 ByValArg->stripPointerCasts() != MDep->getDest())
1241 // The length of the memcpy must be larger or equal to the size of the byval.
1242 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1243 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1246 // Get the alignment of the byval. If the call doesn't specify the alignment,
1247 // then it is some target specific value that we can't know.
1248 MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
1249 if (!ByValAlign) return false;
1251 // If it is greater than the memcpy, then we check to see if we can force the
1252 // source of the memcpy to the alignment we need. If we fail, we bail out.
1253 AssumptionCache &AC = LookupAssumptionCache();
1254 DominatorTree &DT = LookupDomTree();
1255 MaybeAlign MemDepAlign = MDep->getSourceAlign();
1256 if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
1257 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, &AC,
1261 // The address space of the memcpy source must match the byval argument
1262 if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1263 ByValArg->getType()->getPointerAddressSpace())
1266 // Verify that the copied-from memory doesn't change in between the memcpy and
1271 // It would be invalid to transform the second memcpy into foo(*b).
1273 // NOTE: This is conservative, it will stop on any read from the source loc,
1274 // not just the defining memcpy.
1275 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1276 MemoryLocation::getForSource(MDep), false,
1277 CB.getIterator(), MDep->getParent());
1278 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1281 Value *TmpCast = MDep->getSource();
1282 if (MDep->getSource()->getType() != ByValArg->getType()) {
1283 BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1285 // Set the tmpcast's DebugLoc to MDep's
1286 TmpBitCast->setDebugLoc(MDep->getDebugLoc());
1287 TmpCast = TmpBitCast;
1290 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
1291 << " " << *MDep << "\n"
1292 << " " << CB << "\n");
1294 // Otherwise we're good! Update the byval argument.
1295 CB.setArgOperand(ArgNo, TmpCast);
1300 /// Executes one iteration of MemCpyOptPass.
1301 bool MemCpyOptPass::iterateOnFunction(Function &F) {
1302 bool MadeChange = false;
1304 DominatorTree &DT = LookupDomTree();
1306 // Walk all instruction in the function.
1307 for (BasicBlock &BB : F) {
1308 // Skip unreachable blocks. For example processStore assumes that an
1309 // instruction in a BB can't be dominated by a later instruction in the
1310 // same BB (which is a scenario that can happen for an unreachable BB that
1311 // has itself as a predecessor).
1312 if (!DT.isReachableFromEntry(&BB))
1315 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
1316 // Avoid invalidating the iterator.
1317 Instruction *I = &*BI++;
1319 bool RepeatInstruction = false;
1321 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1322 MadeChange |= processStore(SI, BI);
1323 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1324 RepeatInstruction = processMemSet(M, BI);
1325 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1326 RepeatInstruction = processMemCpy(M, BI);
1327 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1328 RepeatInstruction = processMemMove(M);
1329 else if (auto *CB = dyn_cast<CallBase>(I)) {
1330 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
1331 if (CB->isByValArgument(i))
1332 MadeChange |= processByValArgument(*CB, i);
1335 // Reprocess the instruction if desired.
1336 if (RepeatInstruction) {
1337 if (BI != BB.begin())
1347 PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
1348 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1349 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1351 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
1352 return AM.getResult<AAManager>(F);
1354 auto LookupAssumptionCache = [&]() -> AssumptionCache & {
1355 return AM.getResult<AssumptionAnalysis>(F);
1357 auto LookupDomTree = [&]() -> DominatorTree & {
1358 return AM.getResult<DominatorTreeAnalysis>(F);
1361 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis,
1362 LookupAssumptionCache, LookupDomTree);
1364 return PreservedAnalyses::all();
1366 PreservedAnalyses PA;
1367 PA.preserveSet<CFGAnalyses>();
1368 PA.preserve<GlobalsAA>();
1369 PA.preserve<MemoryDependenceAnalysis>();
1373 bool MemCpyOptPass::runImpl(
1374 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_,
1375 std::function<AliasAnalysis &()> LookupAliasAnalysis_,
1376 std::function<AssumptionCache &()> LookupAssumptionCache_,
1377 std::function<DominatorTree &()> LookupDomTree_) {
1378 bool MadeChange = false;
1381 LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
1382 LookupAssumptionCache = std::move(LookupAssumptionCache_);
1383 LookupDomTree = std::move(LookupDomTree_);
1385 // If we don't have at least memset and memcpy, there is little point of doing
1386 // anything here. These are required by a freestanding implementation, so if
1387 // even they are disabled, there is no point in trying hard.
1388 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
1392 if (!iterateOnFunction(F))
1401 /// This is the main transformation entry point for a function.
1402 bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1403 if (skipFunction(F))
1406 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1407 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1409 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
1410 return getAnalysis<AAResultsWrapperPass>().getAAResults();
1412 auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & {
1413 return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1415 auto LookupDomTree = [this]() -> DominatorTree & {
1416 return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1419 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache,