1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs various transformations related to eliminating memcpy
11 // calls, or transforming sets of stores into memset's.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetLibraryInfo.h"
31 #include "llvm/Transforms/Utils/Local.h"
35 #define DEBUG_TYPE "memcpyopt"
37 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
38 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
39 STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
40 STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
42 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
43 bool &VariableIdxFound, const DataLayout &TD){
44 // Skip over the first indices.
45 gep_type_iterator GTI = gep_type_begin(GEP);
46 for (unsigned i = 1; i != Idx; ++i, ++GTI)
49 // Compute the offset implied by the rest of the indices.
51 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
52 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
54 return VariableIdxFound = true;
55 if (OpC->isZero()) continue; // No offset.
57 // Handle struct indices, which add their field offset to the pointer.
58 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
59 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
63 // Otherwise, we have a sequential type like an array or vector. Multiply
64 // the index by the ElementSize.
65 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
66 Offset += Size*OpC->getSExtValue();
72 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
73 /// constant offset, and return that constant offset. For example, Ptr1 might
74 /// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
75 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
76 const DataLayout &TD) {
77 Ptr1 = Ptr1->stripPointerCasts();
78 Ptr2 = Ptr2->stripPointerCasts();
80 // Handle the trivial case first.
86 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
87 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
89 bool VariableIdxFound = false;
91 // If one pointer is a GEP and the other isn't, then see if the GEP is a
92 // constant offset from the base, as in "P" and "gep P, 1".
93 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
94 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
95 return !VariableIdxFound;
98 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
99 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
100 return !VariableIdxFound;
103 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
104 // base. After that base, they may have some number of common (and
105 // potentially variable) indices. After that they handle some constant
106 // offset, which determines their offset from each other. At this point, we
107 // handle no other case.
108 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
111 // Skip any common indices and track the GEP types.
113 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
114 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
117 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
118 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
119 if (VariableIdxFound) return false;
121 Offset = Offset2-Offset1;
126 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
127 /// This allows us to analyze stores like:
132 /// which sometimes happens with stores to arrays of structs etc. When we see
133 /// the first store, we make a range [1, 2). The second store extends the range
134 /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
135 /// two ranges into [0, 3) which is memset'able.
138 // Start/End - A semi range that describes the span that this range covers.
139 // The range is closed at the start and open at the end: [Start, End).
142 /// StartPtr - The getelementptr instruction that points to the start of the
146 /// Alignment - The known alignment of the first store.
149 /// TheStores - The actual stores that make up this range.
150 SmallVector<Instruction*, 16> TheStores;
152 bool isProfitableToUseMemset(const DataLayout &TD) const;
155 } // end anon namespace
157 bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
158 // If we found more than 4 stores to merge or 16 bytes, use memset.
159 if (TheStores.size() >= 4 || End-Start >= 16) return true;
161 // If there is nothing to merge, don't do anything.
162 if (TheStores.size() < 2) return false;
164 // If any of the stores are a memset, then it is always good to extend the
166 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
167 if (!isa<StoreInst>(TheStores[i]))
170 // Assume that the code generator is capable of merging pairs of stores
171 // together if it wants to.
172 if (TheStores.size() == 2) return false;
174 // If we have fewer than 8 stores, it can still be worthwhile to do this.
175 // For example, merging 4 i8 stores into an i32 store is useful almost always.
176 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
177 // memset will be split into 2 32-bit stores anyway) and doing so can
178 // pessimize the llvm optimizer.
180 // Since we don't have perfect knowledge here, make some assumptions: assume
181 // the maximum GPR width is the same size as the largest legal integer
182 // size. If so, check to see whether we will end up actually reducing the
183 // number of stores used.
184 unsigned Bytes = unsigned(End-Start);
185 unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
188 unsigned NumPointerStores = Bytes / MaxIntSize;
190 // Assume the remaining bytes if any are done a byte at a time.
191 unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
193 // If we will reduce the # stores (according to this heuristic), do the
194 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
196 return TheStores.size() > NumPointerStores+NumByteStores;
202 /// Ranges - A sorted list of the memset ranges. We use std::list here
203 /// because each element is relatively large and expensive to copy.
204 std::list<MemsetRange> Ranges;
205 typedef std::list<MemsetRange>::iterator range_iterator;
206 const DataLayout &DL;
208 MemsetRanges(const DataLayout &DL) : DL(DL) {}
210 typedef std::list<MemsetRange>::const_iterator const_iterator;
211 const_iterator begin() const { return Ranges.begin(); }
212 const_iterator end() const { return Ranges.end(); }
213 bool empty() const { return Ranges.empty(); }
215 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
216 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
217 addStore(OffsetFromFirst, SI);
219 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
222 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
223 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
225 addRange(OffsetFromFirst, StoreSize,
226 SI->getPointerOperand(), SI->getAlignment(), SI);
229 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
230 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
231 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
234 void addRange(int64_t Start, int64_t Size, Value *Ptr,
235 unsigned Alignment, Instruction *Inst);
239 } // end anon namespace
242 /// addRange - Add a new store to the MemsetRanges data structure. This adds a
243 /// new range for the specified store at the specified offset, merging into
244 /// existing ranges as appropriate.
246 /// Do a linear search of the ranges to see if this can be joined and/or to
247 /// find the insertion point in the list. We keep the ranges sorted for
248 /// simplicity here. This is a linear search of a linked list, which is ugly,
249 /// however the number of ranges is limited, so this won't get crazy slow.
250 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
251 unsigned Alignment, Instruction *Inst) {
252 int64_t End = Start+Size;
253 range_iterator I = Ranges.begin(), E = Ranges.end();
255 while (I != E && Start > I->End)
258 // We now know that I == E, in which case we didn't find anything to merge
259 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
260 // to insert a new range. Handle this now.
261 if (I == E || End < I->Start) {
262 MemsetRange &R = *Ranges.insert(I, MemsetRange());
266 R.Alignment = Alignment;
267 R.TheStores.push_back(Inst);
271 // This store overlaps with I, add it.
272 I->TheStores.push_back(Inst);
274 // At this point, we may have an interval that completely contains our store.
275 // If so, just add it to the interval and return.
276 if (I->Start <= Start && I->End >= End)
279 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
280 // but is not entirely contained within the range.
282 // See if the range extends the start of the range. In this case, it couldn't
283 // possibly cause it to join the prior range, because otherwise we would have
285 if (Start < I->Start) {
288 I->Alignment = Alignment;
291 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
292 // is in or right at the end of I), and that End >= I->Start. Extend I out to
296 range_iterator NextI = I;
297 while (++NextI != E && End >= NextI->Start) {
298 // Merge the range in.
299 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
300 if (NextI->End > I->End)
308 //===----------------------------------------------------------------------===//
310 //===----------------------------------------------------------------------===//
313 class MemCpyOpt : public FunctionPass {
314 MemoryDependenceAnalysis *MD;
315 TargetLibraryInfo *TLI;
316 const DataLayout *DL;
318 static char ID; // Pass identification, replacement for typeid
319 MemCpyOpt() : FunctionPass(ID) {
320 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
326 bool runOnFunction(Function &F) override;
329 // This transformation requires dominator postdominator info
330 void getAnalysisUsage(AnalysisUsage &AU) const override {
331 AU.setPreservesCFG();
332 AU.addRequired<DominatorTreeWrapperPass>();
333 AU.addRequired<MemoryDependenceAnalysis>();
334 AU.addRequired<AliasAnalysis>();
335 AU.addRequired<TargetLibraryInfo>();
336 AU.addPreserved<AliasAnalysis>();
337 AU.addPreserved<MemoryDependenceAnalysis>();
341 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
342 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
343 bool processMemCpy(MemCpyInst *M);
344 bool processMemMove(MemMoveInst *M);
345 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
346 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
347 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
349 bool processByValArgument(CallSite CS, unsigned ArgNo);
350 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
353 bool iterateOnFunction(Function &F);
356 char MemCpyOpt::ID = 0;
359 // createMemCpyOptPass - The public interface to this file...
360 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
362 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
364 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
365 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
366 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
367 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
368 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
371 /// tryMergingIntoMemset - When scanning forward over instructions, we look for
372 /// some other patterns to fold away. In particular, this looks for stores to
373 /// neighboring locations of memory. If it sees enough consecutive ones, it
374 /// attempts to merge them together into a memcpy/memset.
375 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
376 Value *StartPtr, Value *ByteVal) {
377 if (!DL) return nullptr;
379 // Okay, so we now have a single store that can be splatable. Scan to find
380 // all subsequent stores of the same value to offset from the same pointer.
381 // Join these together into ranges, so we can decide whether contiguous blocks
383 MemsetRanges Ranges(*DL);
385 BasicBlock::iterator BI = StartInst;
386 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
387 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
388 // If the instruction is readnone, ignore it, otherwise bail out. We
389 // don't even allow readonly here because we don't want something like:
390 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
391 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
396 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
397 // If this is a store, see if we can merge it in.
398 if (!NextStore->isSimple()) break;
400 // Check to see if this stored value is of the same byte-splattable value.
401 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
404 // Check to see if this store is to a constant offset from the start ptr.
406 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
410 Ranges.addStore(Offset, NextStore);
412 MemSetInst *MSI = cast<MemSetInst>(BI);
414 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
415 !isa<ConstantInt>(MSI->getLength()))
418 // Check to see if this store is to a constant offset from the start ptr.
420 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
423 Ranges.addMemSet(Offset, MSI);
427 // If we have no ranges, then we just had a single store with nothing that
428 // could be merged in. This is a very common case of course.
432 // If we had at least one store that could be merged in, add the starting
433 // store as well. We try to avoid this unless there is at least something
434 // interesting as a small compile-time optimization.
435 Ranges.addInst(0, StartInst);
437 // If we create any memsets, we put it right before the first instruction that
438 // isn't part of the memset block. This ensure that the memset is dominated
439 // by any addressing instruction needed by the start of the block.
440 IRBuilder<> Builder(BI);
442 // Now that we have full information about ranges, loop over the ranges and
443 // emit memset's for anything big enough to be worthwhile.
444 Instruction *AMemSet = nullptr;
445 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
447 const MemsetRange &Range = *I;
449 if (Range.TheStores.size() == 1) continue;
451 // If it is profitable to lower this range to memset, do so now.
452 if (!Range.isProfitableToUseMemset(*DL))
455 // Otherwise, we do want to transform this! Create a new memset.
456 // Get the starting pointer of the block.
457 StartPtr = Range.StartPtr;
459 // Determine alignment
460 unsigned Alignment = Range.Alignment;
461 if (Alignment == 0) {
463 cast<PointerType>(StartPtr->getType())->getElementType();
464 Alignment = DL->getABITypeAlignment(EltType);
468 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
470 DEBUG(dbgs() << "Replace stores:\n";
471 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
472 dbgs() << *Range.TheStores[i] << '\n';
473 dbgs() << "With: " << *AMemSet << '\n');
475 if (!Range.TheStores.empty())
476 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
478 // Zap all the stores.
479 for (SmallVectorImpl<Instruction *>::const_iterator
480 SI = Range.TheStores.begin(),
481 SE = Range.TheStores.end(); SI != SE; ++SI) {
482 MD->removeInstruction(*SI);
483 (*SI)->eraseFromParent();
492 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
493 if (!SI->isSimple()) return false;
495 if (!DL) return false;
497 // Detect cases where we're performing call slot forwarding, but
498 // happen to be using a load-store pair to implement it, rather than
500 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
501 if (LI->isSimple() && LI->hasOneUse() &&
502 LI->getParent() == SI->getParent()) {
503 MemDepResult ldep = MD->getDependency(LI);
504 CallInst *C = nullptr;
505 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
506 C = dyn_cast<CallInst>(ldep.getInst());
509 // Check that nothing touches the dest of the "copy" between
510 // the call and the store.
511 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
512 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
513 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
514 E = C; I != E; --I) {
515 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
523 unsigned storeAlign = SI->getAlignment();
525 storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
526 unsigned loadAlign = LI->getAlignment();
528 loadAlign = DL->getABITypeAlignment(LI->getType());
530 bool changed = performCallSlotOptzn(LI,
531 SI->getPointerOperand()->stripPointerCasts(),
532 LI->getPointerOperand()->stripPointerCasts(),
533 DL->getTypeStoreSize(SI->getOperand(0)->getType()),
534 std::min(storeAlign, loadAlign), C);
536 MD->removeInstruction(SI);
537 SI->eraseFromParent();
538 MD->removeInstruction(LI);
539 LI->eraseFromParent();
547 // There are two cases that are interesting for this code to handle: memcpy
548 // and memset. Right now we only handle memset.
550 // Ensure that the value being stored is something that can be memset'able a
551 // byte at a time like "0" or "-1" or any width, as well as things like
552 // 0xA0A0A0A0 and 0.0.
553 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
554 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
556 BBI = I; // Don't invalidate iterator.
563 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
564 // See if there is another memset or store neighboring this memset which
565 // allows us to widen out the memset to do a single larger store.
566 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
567 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
569 BBI = I; // Don't invalidate iterator.
576 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
577 /// and checks for the possibility of a call slot optimization by having
578 /// the call write its result directly into the destination of the memcpy.
579 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
580 Value *cpyDest, Value *cpySrc,
581 uint64_t cpyLen, unsigned cpyAlign,
583 // The general transformation to keep in mind is
585 // call @func(..., src, ...)
586 // memcpy(dest, src, ...)
590 // memcpy(dest, src, ...)
591 // call @func(..., dest, ...)
593 // Since moving the memcpy is technically awkward, we additionally check that
594 // src only holds uninitialized values at the moment of the call, meaning that
595 // the memcpy can be discarded rather than moved.
597 // Deliberately get the source and destination with bitcasts stripped away,
598 // because we'll need to do type comparisons based on the underlying type.
601 // Require that src be an alloca. This simplifies the reasoning considerably.
602 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
606 // Check that all of src is copied to dest.
607 if (!DL) return false;
609 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
613 uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
614 srcArraySize->getZExtValue();
616 if (cpyLen < srcSize)
619 // Check that accessing the first srcSize bytes of dest will not cause a
620 // trap. Otherwise the transform is invalid since it might cause a trap
621 // to occur earlier than it otherwise would.
622 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
623 // The destination is an alloca. Check it is larger than srcSize.
624 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
628 uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
629 destArraySize->getZExtValue();
631 if (destSize < srcSize)
633 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
634 // If the destination is an sret parameter then only accesses that are
635 // outside of the returned struct type can trap.
636 if (!A->hasStructRetAttr())
639 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
640 if (!StructTy->isSized()) {
641 // The call may never return and hence the copy-instruction may never
642 // be executed, and therefore it's not safe to say "the destination
643 // has at least <cpyLen> bytes, as implied by the copy-instruction",
647 uint64_t destSize = DL->getTypeAllocSize(StructTy);
648 if (destSize < srcSize)
654 // Check that dest points to memory that is at least as aligned as src.
655 unsigned srcAlign = srcAlloca->getAlignment();
657 srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
658 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
659 // If dest is not aligned enough and we can't increase its alignment then
661 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
664 // Check that src is not accessed except via the call and the memcpy. This
665 // guarantees that it holds only undefined values when passed in (so the final
666 // memcpy can be dropped), that it is not read or written between the call and
667 // the memcpy, and that writing beyond the end of it is undefined.
668 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
669 srcAlloca->user_end());
670 while (!srcUseList.empty()) {
671 User *U = srcUseList.pop_back_val();
673 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
674 for (User *UU : U->users())
675 srcUseList.push_back(UU);
676 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
677 if (G->hasAllZeroIndices())
678 for (User *UU : U->users())
679 srcUseList.push_back(UU);
682 } else if (U != C && U != cpy) {
687 // Check that src isn't captured by the called function since the
688 // transformation can cause aliasing issues in that case.
689 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
690 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
693 // Since we're changing the parameter to the callsite, we need to make sure
694 // that what would be the new parameter dominates the callsite.
695 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
696 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
697 if (!DT.dominates(cpyDestInst, C))
700 // In addition to knowing that the call does not access src in some
701 // unexpected manner, for example via a global, which we deduce from
702 // the use analysis, we also need to know that it does not sneakily
703 // access dest. We rely on AA to figure this out for us.
704 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
705 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
706 // If necessary, perform additional analysis.
707 if (MR != AliasAnalysis::NoModRef)
708 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
709 if (MR != AliasAnalysis::NoModRef)
712 // All the checks have passed, so do the transformation.
713 bool changedArgument = false;
714 for (unsigned i = 0; i < CS.arg_size(); ++i)
715 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
716 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
717 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
718 cpyDest->getName(), C);
719 changedArgument = true;
720 if (CS.getArgument(i)->getType() == Dest->getType())
721 CS.setArgument(i, Dest);
723 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
724 CS.getArgument(i)->getType(), Dest->getName(), C));
727 if (!changedArgument)
730 // If the destination wasn't sufficiently aligned then increase its alignment.
731 if (!isDestSufficientlyAligned) {
732 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
733 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
736 // Drop any cached information about the call, because we may have changed
737 // its dependence information by changing its parameter.
738 MD->removeInstruction(C);
740 // Remove the memcpy.
741 MD->removeInstruction(cpy);
747 /// processMemCpyMemCpyDependence - We've found that the (upward scanning)
748 /// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
749 /// copy from MDep's input if we can. MSize is the size of M's copy.
751 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
753 // We can only transforms memcpy's where the dest of one is the source of the
755 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
758 // If dep instruction is reading from our current input, then it is a noop
759 // transfer and substituting the input won't change this instruction. Just
760 // ignore the input and let someone else zap MDep. This handles cases like:
763 if (M->getSource() == MDep->getSource())
766 // Second, the length of the memcpy's must be the same, or the preceding one
767 // must be larger than the following one.
768 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
769 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
770 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
773 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
775 // Verify that the copied-from memory doesn't change in between the two
776 // transfers. For example, in:
780 // It would be invalid to transform the second memcpy into memcpy(c <- b).
782 // TODO: If the code between M and MDep is transparent to the destination "c",
783 // then we could still perform the xform by moving M up to the first memcpy.
785 // NOTE: This is conservative, it will stop on any read from the source loc,
786 // not just the defining memcpy.
787 MemDepResult SourceDep =
788 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
789 false, M, M->getParent());
790 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
793 // If the dest of the second might alias the source of the first, then the
794 // source and dest might overlap. We still want to eliminate the intermediate
795 // value, but we have to generate a memmove instead of memcpy.
796 bool UseMemMove = false;
797 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
800 // If all checks passed, then we can transform M.
802 // Make sure to use the lesser of the alignment of the source and the dest
803 // since we're changing where we're reading from, but don't want to increase
804 // the alignment past what can be read from or written to.
805 // TODO: Is this worth it if we're creating a less aligned memcpy? For
806 // example we could be moving from movaps -> movq on x86.
807 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
809 IRBuilder<> Builder(M);
811 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
812 Align, M->isVolatile());
814 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
815 Align, M->isVolatile());
817 // Remove the instruction we're replacing.
818 MD->removeInstruction(M);
819 M->eraseFromParent();
825 /// processMemCpy - perform simplification of memcpy's. If we have memcpy A
826 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
827 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
828 /// circumstances). This allows later passes to remove the first memcpy
830 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
831 // We can only optimize non-volatile memcpy's.
832 if (M->isVolatile()) return false;
834 // If the source and destination of the memcpy are the same, then zap it.
835 if (M->getSource() == M->getDest()) {
836 MD->removeInstruction(M);
837 M->eraseFromParent();
841 // If copying from a constant, try to turn the memcpy into a memset.
842 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
843 if (GV->isConstant() && GV->hasDefinitiveInitializer())
844 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
845 IRBuilder<> Builder(M);
846 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
847 M->getAlignment(), false);
848 MD->removeInstruction(M);
849 M->eraseFromParent();
854 // The optimizations after this point require the memcpy size.
855 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
856 if (!CopySize) return false;
858 // The are three possible optimizations we can do for memcpy:
859 // a) memcpy-memcpy xform which exposes redundance for DSE.
860 // b) call-memcpy xform for return slot optimization.
861 // c) memcpy from freshly alloca'd space or space that has just started its
862 // lifetime copies undefined data, and we can therefore eliminate the
863 // memcpy in favor of the data that was already at the destination.
864 MemDepResult DepInfo = MD->getDependency(M);
865 if (DepInfo.isClobber()) {
866 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
867 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
868 CopySize->getZExtValue(), M->getAlignment(),
870 MD->removeInstruction(M);
871 M->eraseFromParent();
877 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
878 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
880 if (SrcDepInfo.isClobber()) {
881 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
882 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
883 } else if (SrcDepInfo.isDef()) {
884 Instruction *I = SrcDepInfo.getInst();
885 bool hasUndefContents = false;
887 if (isa<AllocaInst>(I)) {
888 hasUndefContents = true;
889 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
890 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
891 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
892 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
893 hasUndefContents = true;
896 if (hasUndefContents) {
897 MD->removeInstruction(M);
898 M->eraseFromParent();
907 /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
908 /// are guaranteed not to alias.
909 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
910 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
912 if (!TLI->has(LibFunc::memmove))
915 // See if the pointers alias.
916 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
919 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
921 // If not, then we know we can transform this.
922 Module *Mod = M->getParent()->getParent()->getParent();
923 Type *ArgTys[3] = { M->getRawDest()->getType(),
924 M->getRawSource()->getType(),
925 M->getLength()->getType() };
926 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
929 // MemDep may have over conservative information about this instruction, just
930 // conservatively flush it from the cache.
931 MD->removeInstruction(M);
937 /// processByValArgument - This is called on every byval argument in call sites.
938 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
939 if (!DL) return false;
941 // Find out what feeds this byval argument.
942 Value *ByValArg = CS.getArgument(ArgNo);
943 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
944 uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
945 MemDepResult DepInfo =
946 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
947 true, CS.getInstruction(),
948 CS.getInstruction()->getParent());
949 if (!DepInfo.isClobber())
952 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
953 // a memcpy, see if we can byval from the source of the memcpy instead of the
955 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
956 if (!MDep || MDep->isVolatile() ||
957 ByValArg->stripPointerCasts() != MDep->getDest())
960 // The length of the memcpy must be larger or equal to the size of the byval.
961 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
962 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
965 // Get the alignment of the byval. If the call doesn't specify the alignment,
966 // then it is some target specific value that we can't know.
967 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
968 if (ByValAlign == 0) return false;
970 // If it is greater than the memcpy, then we check to see if we can force the
971 // source of the memcpy to the alignment we need. If we fail, we bail out.
972 if (MDep->getAlignment() < ByValAlign &&
973 getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, DL) < ByValAlign)
976 // Verify that the copied-from memory doesn't change in between the memcpy and
981 // It would be invalid to transform the second memcpy into foo(*b).
983 // NOTE: This is conservative, it will stop on any read from the source loc,
984 // not just the defining memcpy.
985 MemDepResult SourceDep =
986 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
987 false, CS.getInstruction(), MDep->getParent());
988 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
991 Value *TmpCast = MDep->getSource();
992 if (MDep->getSource()->getType() != ByValArg->getType())
993 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
994 "tmpcast", CS.getInstruction());
996 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
997 << " " << *MDep << "\n"
998 << " " << *CS.getInstruction() << "\n");
1000 // Otherwise we're good! Update the byval argument.
1001 CS.setArgument(ArgNo, TmpCast);
1006 /// iterateOnFunction - Executes one iteration of MemCpyOpt.
1007 bool MemCpyOpt::iterateOnFunction(Function &F) {
1008 bool MadeChange = false;
1010 // Walk all instruction in the function.
1011 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
1012 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
1013 // Avoid invalidating the iterator.
1014 Instruction *I = BI++;
1016 bool RepeatInstruction = false;
1018 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1019 MadeChange |= processStore(SI, BI);
1020 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1021 RepeatInstruction = processMemSet(M, BI);
1022 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1023 RepeatInstruction = processMemCpy(M);
1024 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1025 RepeatInstruction = processMemMove(M);
1026 else if (CallSite CS = (Value*)I) {
1027 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
1028 if (CS.isByValArgument(i))
1029 MadeChange |= processByValArgument(CS, i);
1032 // Reprocess the instruction if desired.
1033 if (RepeatInstruction) {
1034 if (BI != BB->begin()) --BI;
1043 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1046 bool MemCpyOpt::runOnFunction(Function &F) {
1047 if (skipOptnoneFunction(F))
1050 bool MadeChange = false;
1051 MD = &getAnalysis<MemoryDependenceAnalysis>();
1052 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1053 DL = DLP ? &DLP->getDataLayout() : nullptr;
1054 TLI = &getAnalysis<TargetLibraryInfo>();
1056 // If we don't have at least memset and memcpy, there is little point of doing
1057 // anything here. These are required by a freestanding implementation, so if
1058 // even they are disabled, there is no point in trying hard.
1059 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1063 if (!iterateOnFunction(F))