blob: 97fff9edd68f77233c9278ae47528db861c0207e [file] [log] [blame]
Owen Andersona723d1e2008-04-09 08:23:16 +00001//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs various transformations related to eliminating memcpy
11// calls, or transforming sets of stores into memset's.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "memcpyopt"
16#include "llvm/Transforms/Scalar.h"
Benjamin Kramera1120872010-12-24 21:17:12 +000017#include "llvm/GlobalVariable.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000018#include "llvm/IRBuilder.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000019#include "llvm/Instructions.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000020#include "llvm/IntrinsicInst.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000023#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000024#include "llvm/Analysis/Dominators.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000025#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattnerbb897102010-12-26 20:15:01 +000026#include "llvm/Analysis/ValueTracking.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000029#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000030#include "llvm/DataLayout.h"
Chris Lattner149f5282011-05-01 18:27:11 +000031#include "llvm/Target/TargetLibraryInfo.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Transforms/Utils/Local.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000033#include <list>
34using namespace llvm;
35
36STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
37STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000038STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000039STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000040
Benjamin Kramer39acdb02012-09-13 16:29:49 +000041static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Micah Villmow3574eca2012-10-08 16:38:25 +000042 bool &VariableIdxFound, const DataLayout &TD){
Owen Andersona723d1e2008-04-09 08:23:16 +000043 // Skip over the first indices.
44 gep_type_iterator GTI = gep_type_begin(GEP);
45 for (unsigned i = 1; i != Idx; ++i, ++GTI)
46 /*skip along*/;
Nadav Rotema94d6e82012-07-24 10:51:42 +000047
Owen Andersona723d1e2008-04-09 08:23:16 +000048 // Compute the offset implied by the rest of the indices.
49 int64_t Offset = 0;
50 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
51 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
52 if (OpC == 0)
53 return VariableIdxFound = true;
54 if (OpC->isZero()) continue; // No offset.
55
56 // Handle struct indices, which add their field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000057 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +000058 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
59 continue;
60 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000061
Owen Andersona723d1e2008-04-09 08:23:16 +000062 // Otherwise, we have a sequential type like an array or vector. Multiply
63 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +000064 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +000065 Offset += Size*OpC->getSExtValue();
66 }
67
68 return Offset;
69}
70
71/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
72/// constant offset, and return that constant offset. For example, Ptr1 might
73/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
74static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Micah Villmow3574eca2012-10-08 16:38:25 +000075 const DataLayout &TD) {
Chris Lattner2d5c0cd2011-01-12 01:43:46 +000076 Ptr1 = Ptr1->stripPointerCasts();
77 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer39acdb02012-09-13 16:29:49 +000078 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
79 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotema94d6e82012-07-24 10:51:42 +000080
Chris Lattner9fa11e92011-01-08 21:07:56 +000081 bool VariableIdxFound = false;
82
83 // If one pointer is a GEP and the other isn't, then see if the GEP is a
84 // constant offset from the base, as in "P" and "gep P, 1".
85 if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
86 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
87 return !VariableIdxFound;
88 }
89
90 if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
91 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
92 return !VariableIdxFound;
93 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000094
Owen Andersona723d1e2008-04-09 08:23:16 +000095 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
96 // base. After that base, they may have some number of common (and
97 // potentially variable) indices. After that they handle some constant
98 // offset, which determines their offset from each other. At this point, we
99 // handle no other case.
Owen Andersona723d1e2008-04-09 08:23:16 +0000100 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
101 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000102
Owen Andersona723d1e2008-04-09 08:23:16 +0000103 // Skip any common indices and track the GEP types.
104 unsigned Idx = 1;
105 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
106 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
107 break;
108
Owen Andersona723d1e2008-04-09 08:23:16 +0000109 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
110 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
111 if (VariableIdxFound) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000112
Owen Andersona723d1e2008-04-09 08:23:16 +0000113 Offset = Offset2-Offset1;
114 return true;
115}
116
117
118/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
119/// This allows us to analyze stores like:
120/// store 0 -> P+1
121/// store 0 -> P+0
122/// store 0 -> P+3
123/// store 0 -> P+2
124/// which sometimes happens with stores to arrays of structs etc. When we see
125/// the first store, we make a range [1, 2). The second store extends the range
126/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
127/// two ranges into [0, 3) which is memset'able.
128namespace {
129struct MemsetRange {
130 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000131 // The range is closed at the start and open at the end: [Start, End).
Owen Andersona723d1e2008-04-09 08:23:16 +0000132 int64_t Start, End;
133
134 /// StartPtr - The getelementptr instruction that points to the start of the
135 /// range.
136 Value *StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000137
Owen Andersona723d1e2008-04-09 08:23:16 +0000138 /// Alignment - The known alignment of the first store.
139 unsigned Alignment;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000140
Owen Andersona723d1e2008-04-09 08:23:16 +0000141 /// TheStores - The actual stores that make up this range.
Chris Lattner06511262011-01-08 20:54:51 +0000142 SmallVector<Instruction*, 16> TheStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000143
Micah Villmow3574eca2012-10-08 16:38:25 +0000144 bool isProfitableToUseMemset(const DataLayout &TD) const;
Owen Andersona723d1e2008-04-09 08:23:16 +0000145
146};
147} // end anon namespace
148
Micah Villmow3574eca2012-10-08 16:38:25 +0000149bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
Chad Rosiera4b6fd52011-12-05 22:53:09 +0000150 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosierd8bd26e2011-12-05 22:37:00 +0000151 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner06511262011-01-08 20:54:51 +0000152
153 // If there is nothing to merge, don't do anything.
154 if (TheStores.size() < 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000155
Chris Lattner06511262011-01-08 20:54:51 +0000156 // If any of the stores are a memset, then it is always good to extend the
157 // memset.
158 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
159 if (!isa<StoreInst>(TheStores[i]))
160 return true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000161
Owen Andersona723d1e2008-04-09 08:23:16 +0000162 // Assume that the code generator is capable of merging pairs of stores
163 // together if it wants to.
Chris Lattner06511262011-01-08 20:54:51 +0000164 if (TheStores.size() == 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000165
Owen Andersona723d1e2008-04-09 08:23:16 +0000166 // If we have fewer than 8 stores, it can still be worthwhile to do this.
167 // For example, merging 4 i8 stores into an i32 store is useful almost always.
168 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
169 // memset will be split into 2 32-bit stores anyway) and doing so can
170 // pessimize the llvm optimizer.
171 //
172 // Since we don't have perfect knowledge here, make some assumptions: assume
173 // the maximum GPR width is the same size as the pointer size and assume that
174 // this width can be stored. If so, check to see whether we will end up
175 // actually reducing the number of stores used.
176 unsigned Bytes = unsigned(End-Start);
Micah Villmow2c39b152012-10-15 16:24:29 +0000177 unsigned AS = cast<StoreInst>(TheStores[0])->getPointerAddressSpace();
178 unsigned NumPointerStores = Bytes/TD.getPointerSize(AS);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000179
Owen Andersona723d1e2008-04-09 08:23:16 +0000180 // Assume the remaining bytes if any are done a byte at a time.
Micah Villmow2c39b152012-10-15 16:24:29 +0000181 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize(AS);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000182
Owen Andersona723d1e2008-04-09 08:23:16 +0000183 // If we will reduce the # stores (according to this heuristic), do the
184 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
185 // etc.
186 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000187}
Owen Andersona723d1e2008-04-09 08:23:16 +0000188
189
190namespace {
191class MemsetRanges {
192 /// Ranges - A sorted list of the memset ranges. We use std::list here
193 /// because each element is relatively large and expensive to copy.
194 std::list<MemsetRange> Ranges;
195 typedef std::list<MemsetRange>::iterator range_iterator;
Micah Villmow3574eca2012-10-08 16:38:25 +0000196 const DataLayout &TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000197public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000198 MemsetRanges(const DataLayout &td) : TD(td) {}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000199
Owen Andersona723d1e2008-04-09 08:23:16 +0000200 typedef std::list<MemsetRange>::const_iterator const_iterator;
201 const_iterator begin() const { return Ranges.begin(); }
202 const_iterator end() const { return Ranges.end(); }
203 bool empty() const { return Ranges.empty(); }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000204
Chris Lattner67a716a2011-01-08 20:24:01 +0000205 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner06511262011-01-08 20:54:51 +0000206 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
207 addStore(OffsetFromFirst, SI);
208 else
209 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattner67a716a2011-01-08 20:24:01 +0000210 }
Chris Lattner06511262011-01-08 20:54:51 +0000211
212 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
213 int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000214
Chris Lattner06511262011-01-08 20:54:51 +0000215 addRange(OffsetFromFirst, StoreSize,
216 SI->getPointerOperand(), SI->getAlignment(), SI);
217 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000218
Chris Lattner06511262011-01-08 20:54:51 +0000219 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
220 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
221 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
222 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000223
Chris Lattner06511262011-01-08 20:54:51 +0000224 void addRange(int64_t Start, int64_t Size, Value *Ptr,
225 unsigned Alignment, Instruction *Inst);
226
Owen Andersona723d1e2008-04-09 08:23:16 +0000227};
Nadav Rotema94d6e82012-07-24 10:51:42 +0000228
Owen Andersona723d1e2008-04-09 08:23:16 +0000229} // end anon namespace
230
231
Chris Lattner06511262011-01-08 20:54:51 +0000232/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersona723d1e2008-04-09 08:23:16 +0000233/// new range for the specified store at the specified offset, merging into
234/// existing ranges as appropriate.
Chris Lattner06511262011-01-08 20:54:51 +0000235///
236/// Do a linear search of the ranges to see if this can be joined and/or to
237/// find the insertion point in the list. We keep the ranges sorted for
238/// simplicity here. This is a linear search of a linked list, which is ugly,
239/// however the number of ranges is limited, so this won't get crazy slow.
240void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
241 unsigned Alignment, Instruction *Inst) {
242 int64_t End = Start+Size;
Owen Andersona723d1e2008-04-09 08:23:16 +0000243 range_iterator I = Ranges.begin(), E = Ranges.end();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000244
Owen Andersona723d1e2008-04-09 08:23:16 +0000245 while (I != E && Start > I->End)
246 ++I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000247
Owen Andersona723d1e2008-04-09 08:23:16 +0000248 // We now know that I == E, in which case we didn't find anything to merge
249 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
250 // to insert a new range. Handle this now.
251 if (I == E || End < I->Start) {
252 MemsetRange &R = *Ranges.insert(I, MemsetRange());
253 R.Start = Start;
254 R.End = End;
Chris Lattner06511262011-01-08 20:54:51 +0000255 R.StartPtr = Ptr;
256 R.Alignment = Alignment;
257 R.TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000258 return;
259 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000260
Owen Andersona723d1e2008-04-09 08:23:16 +0000261 // This store overlaps with I, add it.
Chris Lattner06511262011-01-08 20:54:51 +0000262 I->TheStores.push_back(Inst);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000263
Owen Andersona723d1e2008-04-09 08:23:16 +0000264 // At this point, we may have an interval that completely contains our store.
265 // If so, just add it to the interval and return.
266 if (I->Start <= Start && I->End >= End)
267 return;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000268
Owen Andersona723d1e2008-04-09 08:23:16 +0000269 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
270 // but is not entirely contained within the range.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000271
Owen Andersona723d1e2008-04-09 08:23:16 +0000272 // See if the range extends the start of the range. In this case, it couldn't
273 // possibly cause it to join the prior range, because otherwise we would have
274 // stopped on *it*.
275 if (Start < I->Start) {
276 I->Start = Start;
Chris Lattner06511262011-01-08 20:54:51 +0000277 I->StartPtr = Ptr;
278 I->Alignment = Alignment;
Owen Andersona723d1e2008-04-09 08:23:16 +0000279 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000280
Owen Andersona723d1e2008-04-09 08:23:16 +0000281 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
282 // is in or right at the end of I), and that End >= I->Start. Extend I out to
283 // End.
284 if (End > I->End) {
285 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000286 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000287 while (++NextI != E && End >= NextI->Start) {
288 // Merge the range in.
289 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
290 if (NextI->End > I->End)
291 I->End = NextI->End;
292 Ranges.erase(NextI);
293 NextI = I;
294 }
295 }
296}
297
298//===----------------------------------------------------------------------===//
299// MemCpyOpt Pass
300//===----------------------------------------------------------------------===//
301
302namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000303 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000304 MemoryDependenceAnalysis *MD;
Chris Lattner149f5282011-05-01 18:27:11 +0000305 TargetLibraryInfo *TLI;
Micah Villmow3574eca2012-10-08 16:38:25 +0000306 const DataLayout *TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000307 public:
308 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000309 MemCpyOpt() : FunctionPass(ID) {
310 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000311 MD = 0;
Chris Lattner149f5282011-05-01 18:27:11 +0000312 TLI = 0;
313 TD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000314 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000315
Chris Lattner67a716a2011-01-08 20:24:01 +0000316 bool runOnFunction(Function &F);
317
Owen Andersona723d1e2008-04-09 08:23:16 +0000318 private:
319 // This transformation requires dominator postdominator info
320 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
321 AU.setPreservesCFG();
322 AU.addRequired<DominatorTree>();
323 AU.addRequired<MemoryDependenceAnalysis>();
324 AU.addRequired<AliasAnalysis>();
Chris Lattner149f5282011-05-01 18:27:11 +0000325 AU.addRequired<TargetLibraryInfo>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000326 AU.addPreserved<AliasAnalysis>();
327 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000328 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000329
Owen Andersona723d1e2008-04-09 08:23:16 +0000330 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000331 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000332 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000333 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000334 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000335 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000336 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000337 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
338 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000339 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattner67a716a2011-01-08 20:24:01 +0000340 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
341 Value *ByteVal);
342
Owen Andersona723d1e2008-04-09 08:23:16 +0000343 bool iterateOnFunction(Function &F);
344 };
Nadav Rotema94d6e82012-07-24 10:51:42 +0000345
Owen Andersona723d1e2008-04-09 08:23:16 +0000346 char MemCpyOpt::ID = 0;
347}
348
349// createMemCpyOptPass - The public interface to this file...
350FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
351
Owen Anderson2ab36d32010-10-12 19:48:12 +0000352INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
353 false, false)
354INITIALIZE_PASS_DEPENDENCY(DominatorTree)
355INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chris Lattner149f5282011-05-01 18:27:11 +0000356INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000357INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
358INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
359 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000360
Chris Lattner67a716a2011-01-08 20:24:01 +0000361/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersona723d1e2008-04-09 08:23:16 +0000362/// some other patterns to fold away. In particular, this looks for stores to
Duncan Sandsab4c3662011-02-15 09:23:02 +0000363/// neighboring locations of memory. If it sees enough consecutive ones, it
Chris Lattner67a716a2011-01-08 20:24:01 +0000364/// attempts to merge them together into a memcpy/memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000365Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattner67a716a2011-01-08 20:24:01 +0000366 Value *StartPtr, Value *ByteVal) {
367 if (TD == 0) return 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000368
Chris Lattner67a716a2011-01-08 20:24:01 +0000369 // Okay, so we now have a single store that can be splatable. Scan to find
370 // all subsequent stores of the same value to offset from the same pointer.
371 // Join these together into ranges, so we can decide whether contiguous blocks
372 // are stored.
373 MemsetRanges Ranges(*TD);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000374
Chris Lattner67a716a2011-01-08 20:24:01 +0000375 BasicBlock::iterator BI = StartInst;
376 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner06511262011-01-08 20:54:51 +0000377 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
378 // If the instruction is readnone, ignore it, otherwise bail out. We
379 // don't even allow readonly here because we don't want something like:
Chris Lattner67a716a2011-01-08 20:24:01 +0000380 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner06511262011-01-08 20:54:51 +0000381 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
382 break;
383 continue;
384 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000385
Chris Lattner06511262011-01-08 20:54:51 +0000386 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
387 // If this is a store, see if we can merge it in.
Eli Friedman56efe242011-08-17 22:22:24 +0000388 if (!NextStore->isSimple()) break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000389
Chris Lattner06511262011-01-08 20:54:51 +0000390 // Check to see if this stored value is of the same byte-splattable value.
391 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
392 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000393
Chris Lattner06511262011-01-08 20:54:51 +0000394 // Check to see if this store is to a constant offset from the start ptr.
395 int64_t Offset;
Chris Lattnerf4268502011-01-09 19:26:10 +0000396 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
397 Offset, *TD))
Chris Lattner06511262011-01-08 20:54:51 +0000398 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000399
Chris Lattner06511262011-01-08 20:54:51 +0000400 Ranges.addStore(Offset, NextStore);
401 } else {
402 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000403
Chris Lattner06511262011-01-08 20:54:51 +0000404 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
405 !isa<ConstantInt>(MSI->getLength()))
406 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000407
Chris Lattner06511262011-01-08 20:54:51 +0000408 // Check to see if this store is to a constant offset from the start ptr.
409 int64_t Offset;
410 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD))
411 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000412
Chris Lattner06511262011-01-08 20:54:51 +0000413 Ranges.addMemSet(Offset, MSI);
414 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000415 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000416
Chris Lattner67a716a2011-01-08 20:24:01 +0000417 // If we have no ranges, then we just had a single store with nothing that
418 // could be merged in. This is a very common case of course.
419 if (Ranges.empty())
420 return 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000421
Chris Lattner67a716a2011-01-08 20:24:01 +0000422 // If we had at least one store that could be merged in, add the starting
423 // store as well. We try to avoid this unless there is at least something
424 // interesting as a small compile-time optimization.
425 Ranges.addInst(0, StartInst);
426
427 // If we create any memsets, we put it right before the first instruction that
428 // isn't part of the memset block. This ensure that the memset is dominated
429 // by any addressing instruction needed by the start of the block.
430 IRBuilder<> Builder(BI);
431
432 // Now that we have full information about ranges, loop over the ranges and
433 // emit memset's for anything big enough to be worthwhile.
434 Instruction *AMemSet = 0;
435 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
436 I != E; ++I) {
437 const MemsetRange &Range = *I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000438
Chris Lattner67a716a2011-01-08 20:24:01 +0000439 if (Range.TheStores.size() == 1) continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000440
Chris Lattner67a716a2011-01-08 20:24:01 +0000441 // If it is profitable to lower this range to memset, do so now.
442 if (!Range.isProfitableToUseMemset(*TD))
443 continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000444
Chris Lattner67a716a2011-01-08 20:24:01 +0000445 // Otherwise, we do want to transform this! Create a new memset.
446 // Get the starting pointer of the block.
447 StartPtr = Range.StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000448
Chris Lattner67a716a2011-01-08 20:24:01 +0000449 // Determine alignment
450 unsigned Alignment = Range.Alignment;
451 if (Alignment == 0) {
Nadav Rotema94d6e82012-07-24 10:51:42 +0000452 Type *EltType =
Chris Lattner67a716a2011-01-08 20:24:01 +0000453 cast<PointerType>(StartPtr->getType())->getElementType();
454 Alignment = TD->getABITypeAlignment(EltType);
455 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000456
457 AMemSet =
Chris Lattner67a716a2011-01-08 20:24:01 +0000458 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000459
Chris Lattner67a716a2011-01-08 20:24:01 +0000460 DEBUG(dbgs() << "Replace stores:\n";
461 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
462 dbgs() << *Range.TheStores[i] << '\n';
463 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelb90584a2011-05-04 21:58:58 +0000464
465 if (!Range.TheStores.empty())
466 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
467
Chris Lattner67a716a2011-01-08 20:24:01 +0000468 // Zap all the stores.
Chris Lattner06511262011-01-08 20:54:51 +0000469 for (SmallVector<Instruction*, 16>::const_iterator
Chris Lattner67a716a2011-01-08 20:24:01 +0000470 SI = Range.TheStores.begin(),
Chris Lattner8a629572011-01-08 22:19:21 +0000471 SE = Range.TheStores.end(); SI != SE; ++SI) {
472 MD->removeInstruction(*SI);
Chris Lattner67a716a2011-01-08 20:24:01 +0000473 (*SI)->eraseFromParent();
Chris Lattner8a629572011-01-08 22:19:21 +0000474 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000475 ++NumMemSetInfer;
476 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000477
Chris Lattner67a716a2011-01-08 20:24:01 +0000478 return AMemSet;
479}
480
481
Chris Lattner61c6ba82009-09-01 17:09:55 +0000482bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman56efe242011-08-17 22:22:24 +0000483 if (!SI->isSimple()) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000484
Chris Lattner67a716a2011-01-08 20:24:01 +0000485 if (TD == 0) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000486
487 // Detect cases where we're performing call slot forwarding, but
488 // happen to be using a load-store pair to implement it, rather than
489 // a memcpy.
490 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman56efe242011-08-17 22:22:24 +0000491 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedman5d40ef22011-06-15 01:25:56 +0000492 LI->getParent() == SI->getParent()) {
Eli Friedman70d893e2011-06-02 21:24:42 +0000493 MemDepResult ldep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000494 CallInst *C = 0;
Eli Friedman70d893e2011-06-02 21:24:42 +0000495 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
496 C = dyn_cast<CallInst>(ldep.getInst());
497
498 if (C) {
499 // Check that nothing touches the dest of the "copy" between
500 // the call and the store.
Eli Friedman5d40ef22011-06-15 01:25:56 +0000501 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
502 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
503 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
504 E = C; I != E; --I) {
505 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
Eli Friedman70d893e2011-06-02 21:24:42 +0000506 C = 0;
Eli Friedman5d40ef22011-06-15 01:25:56 +0000507 break;
508 }
Eli Friedman70d893e2011-06-02 21:24:42 +0000509 }
510 }
511
Owen Anderson65491212010-10-15 22:52:12 +0000512 if (C) {
Duncan Sandsf5874752012-10-04 10:54:40 +0000513 unsigned storeAlign = SI->getAlignment();
514 if (!storeAlign)
515 storeAlign = TD->getABITypeAlignment(SI->getOperand(0)->getType());
516 unsigned loadAlign = LI->getAlignment();
517 if (!loadAlign)
518 loadAlign = TD->getABITypeAlignment(LI->getType());
519
Owen Anderson65491212010-10-15 22:52:12 +0000520 bool changed = performCallSlotOptzn(LI,
Nadav Rotema94d6e82012-07-24 10:51:42 +0000521 SI->getPointerOperand()->stripPointerCasts(),
Owen Anderson65491212010-10-15 22:52:12 +0000522 LI->getPointerOperand()->stripPointerCasts(),
Duncan Sandsf5874752012-10-04 10:54:40 +0000523 TD->getTypeStoreSize(SI->getOperand(0)->getType()),
524 std::min(storeAlign, loadAlign), C);
Owen Anderson65491212010-10-15 22:52:12 +0000525 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000526 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000527 SI->eraseFromParent();
Chris Lattnerf4268502011-01-09 19:26:10 +0000528 MD->removeInstruction(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000529 LI->eraseFromParent();
530 ++NumMemCpyInstr;
531 return true;
532 }
533 }
534 }
535 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000536
Owen Andersona723d1e2008-04-09 08:23:16 +0000537 // There are two cases that are interesting for this code to handle: memcpy
538 // and memset. Right now we only handle memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000539
Owen Andersona723d1e2008-04-09 08:23:16 +0000540 // Ensure that the value being stored is something that can be memset'able a
541 // byte at a time like "0" or "-1" or any width, as well as things like
542 // 0xA0A0A0A0 and 0.0.
Chris Lattner67a716a2011-01-08 20:24:01 +0000543 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
544 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
545 ByteVal)) {
546 BBI = I; // Don't invalidate iterator.
547 return true;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000548 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000549
Chris Lattner67a716a2011-01-08 20:24:01 +0000550 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000551}
552
Chris Lattnerd90a1922011-01-08 21:19:19 +0000553bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
554 // See if there is another memset or store neighboring this memset which
555 // allows us to widen out the memset to do a single larger store.
Chris Lattner0468e3e2011-01-08 22:11:56 +0000556 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
557 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
558 MSI->getValue())) {
559 BBI = I; // Don't invalidate iterator.
560 return true;
561 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000562 return false;
563}
564
Owen Andersona723d1e2008-04-09 08:23:16 +0000565
566/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
567/// and checks for the possibility of a call slot optimization by having
568/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000569bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
570 Value *cpyDest, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000571 uint64_t cpyLen, unsigned cpyAlign,
572 CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000573 // The general transformation to keep in mind is
574 //
575 // call @func(..., src, ...)
576 // memcpy(dest, src, ...)
577 //
578 // ->
579 //
580 // memcpy(dest, src, ...)
581 // call @func(..., dest, ...)
582 //
583 // Since moving the memcpy is technically awkward, we additionally check that
584 // src only holds uninitialized values at the moment of the call, meaning that
585 // the memcpy can be discarded rather than moved.
586
587 // Deliberately get the source and destination with bitcasts stripped away,
588 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000589 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000590
Owen Andersona723d1e2008-04-09 08:23:16 +0000591 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000592 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000593 if (!srcAlloca)
594 return false;
595
596 // Check that all of src is copied to dest.
Chris Lattner67a716a2011-01-08 20:24:01 +0000597 if (TD == 0) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000598
Chris Lattner61c6ba82009-09-01 17:09:55 +0000599 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000600 if (!srcArraySize)
601 return false;
602
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000603 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000604 srcArraySize->getZExtValue();
605
Owen Anderson65491212010-10-15 22:52:12 +0000606 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000607 return false;
608
609 // Check that accessing the first srcSize bytes of dest will not cause a
610 // trap. Otherwise the transform is invalid since it might cause a trap
611 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000612 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000613 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000614 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000615 if (!destArraySize)
616 return false;
617
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000618 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000619 destArraySize->getZExtValue();
620
621 if (destSize < srcSize)
622 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000623 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000624 // If the destination is an sret parameter then only accesses that are
625 // outside of the returned struct type can trap.
626 if (!A->hasStructRetAttr())
627 return false;
628
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000629 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000630 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000631
632 if (destSize < srcSize)
633 return false;
634 } else {
635 return false;
636 }
637
Duncan Sands3372c5a2012-10-05 07:29:46 +0000638 // Check that dest points to memory that is at least as aligned as src.
639 unsigned srcAlign = srcAlloca->getAlignment();
640 if (!srcAlign)
641 srcAlign = TD->getABITypeAlignment(srcAlloca->getAllocatedType());
642 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
643 // If dest is not aligned enough and we can't increase its alignment then
644 // bail out.
645 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
646 return false;
647
Owen Andersona723d1e2008-04-09 08:23:16 +0000648 // Check that src is not accessed except via the call and the memcpy. This
649 // guarantees that it holds only undefined values when passed in (so the final
650 // memcpy can be dropped), that it is not read or written between the call and
651 // the memcpy, and that writing beyond the end of it is undefined.
652 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
653 srcAlloca->use_end());
654 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000655 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000656
Owen Anderson009e4f72008-06-01 22:26:26 +0000657 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000658 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
659 I != E; ++I)
660 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000661 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000662 if (G->hasAllZeroIndices())
663 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
664 I != E; ++I)
665 srcUseList.push_back(*I);
666 else
667 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000668 } else if (UI != C && UI != cpy) {
669 return false;
670 }
671 }
672
673 // Since we're changing the parameter to the callsite, we need to make sure
674 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000675 DominatorTree &DT = getAnalysis<DominatorTree>();
676 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000677 if (!DT.dominates(cpyDestInst, C))
678 return false;
679
680 // In addition to knowing that the call does not access src in some
681 // unexpected manner, for example via a global, which we deduce from
682 // the use analysis, we also need to know that it does not sneakily
683 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000684 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chad Rosier3a884f52012-05-14 20:35:04 +0000685 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
686 // If necessary, perform additional analysis.
687 if (MR != AliasAnalysis::NoModRef)
688 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
689 if (MR != AliasAnalysis::NoModRef)
Owen Andersona723d1e2008-04-09 08:23:16 +0000690 return false;
691
692 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000693 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000694 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000695 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sands7508f942012-10-04 13:53:21 +0000696 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
697 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
698 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000699 changedArgument = true;
Duncan Sands7508f942012-10-04 13:53:21 +0000700 if (CS.getArgument(i)->getType() == Dest->getType())
701 CS.setArgument(i, Dest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000702 else
Duncan Sands7508f942012-10-04 13:53:21 +0000703 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
704 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000705 }
706
Owen Anderson12cb36c2008-06-01 21:52:16 +0000707 if (!changedArgument)
708 return false;
709
Duncan Sandsf5874752012-10-04 10:54:40 +0000710 // If the destination wasn't sufficiently aligned then increase its alignment.
711 if (!isDestSufficientlyAligned) {
712 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
713 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
714 }
715
Owen Andersona723d1e2008-04-09 08:23:16 +0000716 // Drop any cached information about the call, because we may have changed
717 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000718 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000719
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000720 // Remove the memcpy.
721 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000722 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000723
724 return true;
725}
726
Chris Lattner43f8e432010-11-18 07:02:37 +0000727/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
728/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
729/// copy from MDep's input if we can. MSize is the size of M's copy.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000730///
Chris Lattner43f8e432010-11-18 07:02:37 +0000731bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
732 uint64_t MSize) {
733 // We can only transforms memcpy's where the dest of one is the source of the
734 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000735 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000736 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000737
Chris Lattnerf7f35462010-12-09 07:39:50 +0000738 // If dep instruction is reading from our current input, then it is a noop
739 // transfer and substituting the input won't change this instruction. Just
740 // ignore the input and let someone else zap MDep. This handles cases like:
741 // memcpy(a <- a)
742 // memcpy(b <- a)
743 if (M->getSource() == MDep->getSource())
744 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000745
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000746 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner43f8e432010-11-18 07:02:37 +0000747 // must be larger than the following one.
Dan Gohman8fb25c52011-01-21 22:07:57 +0000748 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
749 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
750 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
751 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000752
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000753 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000754
755 // Verify that the copied-from memory doesn't change in between the two
756 // transfers. For example, in:
757 // memcpy(a <- b)
758 // *b = 42;
759 // memcpy(c <- a)
760 // It would be invalid to transform the second memcpy into memcpy(c <- b).
761 //
762 // TODO: If the code between M and MDep is transparent to the destination "c",
763 // then we could still perform the xform by moving M up to the first memcpy.
764 //
765 // NOTE: This is conservative, it will stop on any read from the source loc,
766 // not just the defining memcpy.
767 MemDepResult SourceDep =
768 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
769 false, M, M->getParent());
770 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
771 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000772
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000773 // If the dest of the second might alias the source of the first, then the
774 // source and dest might overlap. We still want to eliminate the intermediate
775 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000776 bool UseMemMove = false;
777 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
778 UseMemMove = true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000779
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000780 // If all checks passed, then we can transform M.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000781
Chris Lattner43f8e432010-11-18 07:02:37 +0000782 // Make sure to use the lesser of the alignment of the source and the dest
783 // since we're changing where we're reading from, but don't want to increase
784 // the alignment past what can be read from or written to.
785 // TODO: Is this worth it if we're creating a less aligned memcpy? For
786 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000787 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000788
Chris Lattner61db1f52010-12-26 22:57:41 +0000789 IRBuilder<> Builder(M);
790 if (UseMemMove)
791 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
792 Align, M->isVolatile());
793 else
794 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
795 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000796
Chris Lattner604f6fe2010-11-21 08:06:10 +0000797 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000798 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000799 M->eraseFromParent();
800 ++NumMemCpyInstr;
801 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000802}
803
804
Gabor Greif7d3056b2010-07-28 22:50:26 +0000805/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
806/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
807/// B to be a memcpy from X to Z (or potentially a memmove, depending on
808/// circumstances). This allows later passes to remove the first memcpy
809/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000810bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000811 // We can only optimize statically-sized memcpy's that are non-volatile.
812 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
813 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000814
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000815 // If the source and destination of the memcpy are the same, then zap it.
816 if (M->getSource() == M->getDest()) {
817 MD->removeInstruction(M);
818 M->eraseFromParent();
819 return false;
820 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000821
822 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000823 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000824 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000825 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000826 IRBuilder<> Builder(M);
827 Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
828 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000829 MD->removeInstruction(M);
830 M->eraseFromParent();
831 ++NumCpyToSet;
832 return true;
833 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000834
Owen Andersona8bd6582008-04-21 07:45:10 +0000835 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000836 // a) memcpy-memcpy xform which exposes redundance for DSE.
837 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000838 MemDepResult DepInfo = MD->getDependency(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000839 if (DepInfo.isClobber()) {
840 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
841 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Duncan Sandsf5874752012-10-04 10:54:40 +0000842 CopySize->getZExtValue(), M->getAlignment(),
843 C)) {
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000844 MD->removeInstruction(M);
845 M->eraseFromParent();
846 return true;
847 }
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000848 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000849 }
Ahmed Charlesb83a67e2012-02-13 06:30:56 +0000850
851 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000852 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
853 M, M->getParent());
854 if (SrcDepInfo.isClobber()) {
855 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
856 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
857 }
858
Owen Anderson02e99882008-04-29 21:51:00 +0000859 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000860}
861
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000862/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
863/// are guaranteed not to alias.
864bool MemCpyOpt::processMemMove(MemMoveInst *M) {
865 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
866
Chris Lattner149f5282011-05-01 18:27:11 +0000867 if (!TLI->has(LibFunc::memmove))
868 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000869
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000870 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000871 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000872 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000873
David Greenecb33fd12010-01-05 01:27:47 +0000874 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000875
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000876 // If not, then we know we can transform this.
877 Module *Mod = M->getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +0000878 Type *ArgTys[3] = { M->getRawDest()->getType(),
879 M->getRawSource()->getType(),
880 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000881 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000882 ArgTys));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000883
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000884 // MemDep may have over conservative information about this instruction, just
885 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000886 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000887
888 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000889 return true;
890}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000891
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000892/// processByValArgument - This is called on every byval argument in call sites.
893bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Chris Lattner67a716a2011-01-08 20:24:01 +0000894 if (TD == 0) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000895
Chris Lattner604f6fe2010-11-21 08:06:10 +0000896 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000897 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewycky865703e2011-10-12 00:14:31 +0000898 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Chris Lattnerb5a31962010-12-01 01:24:55 +0000899 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000900 MemDepResult DepInfo =
901 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
902 true, CS.getInstruction(),
903 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000904 if (!DepInfo.isClobber())
905 return false;
906
907 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
908 // a memcpy, see if we can byval from the source of the memcpy instead of the
909 // result.
910 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
911 if (MDep == 0 || MDep->isVolatile() ||
912 ByValArg->stripPointerCasts() != MDep->getDest())
913 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000914
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000915 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000916 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000917 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000918 return false;
919
Chris Lattnerb3f06732011-05-23 00:03:39 +0000920 // Get the alignment of the byval. If the call doesn't specify the alignment,
921 // then it is some target specific value that we can't know.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000922 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattnerb3f06732011-05-23 00:03:39 +0000923 if (ByValAlign == 0) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000924
Chris Lattnerb3f06732011-05-23 00:03:39 +0000925 // If it is greater than the memcpy, then we check to see if we can force the
926 // source of the memcpy to the alignment we need. If we fail, we bail out.
927 if (MDep->getAlignment() < ByValAlign &&
928 getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, TD) < ByValAlign)
929 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000930
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000931 // Verify that the copied-from memory doesn't change in between the memcpy and
932 // the byval call.
933 // memcpy(a <- b)
934 // *b = 42;
935 // foo(*a)
936 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000937 //
938 // NOTE: This is conservative, it will stop on any read from the source loc,
939 // not just the defining memcpy.
940 MemDepResult SourceDep =
941 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
942 false, CS.getInstruction(), MDep->getParent());
943 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
944 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000945
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000946 Value *TmpCast = MDep->getSource();
947 if (MDep->getSource()->getType() != ByValArg->getType())
948 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
949 "tmpcast", CS.getInstruction());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000950
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000951 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
952 << " " << *MDep << "\n"
953 << " " << *CS.getInstruction() << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000954
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000955 // Otherwise we're good! Update the byval argument.
956 CS.setArgument(ArgNo, TmpCast);
957 ++NumMemCpyInstr;
958 return true;
959}
960
961/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000962bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000963 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000964
Chris Lattner61c6ba82009-09-01 17:09:55 +0000965 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000966 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000967 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000968 // Avoid invalidating the iterator.
969 Instruction *I = BI++;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000970
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000971 bool RepeatInstruction = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000972
Owen Andersona8bd6582008-04-21 07:45:10 +0000973 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000974 MadeChange |= processStore(SI, BI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000975 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
976 RepeatInstruction = processMemSet(M, BI);
977 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000978 RepeatInstruction = processMemCpy(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000979 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000980 RepeatInstruction = processMemMove(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000981 else if (CallSite CS = (Value*)I) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000982 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky173862e2011-11-20 19:09:04 +0000983 if (CS.isByValArgument(i))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000984 MadeChange |= processByValArgument(CS, i);
985 }
986
987 // Reprocess the instruction if desired.
988 if (RepeatInstruction) {
Chris Lattner8a629572011-01-08 22:19:21 +0000989 if (BI != BB->begin()) --BI;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000990 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000991 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000992 }
993 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000994
Chris Lattner61c6ba82009-09-01 17:09:55 +0000995 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000996}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000997
998// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
999// function.
1000//
1001bool MemCpyOpt::runOnFunction(Function &F) {
1002 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001003 MD = &getAnalysis<MemoryDependenceAnalysis>();
Micah Villmow3574eca2012-10-08 16:38:25 +00001004 TD = getAnalysisIfAvailable<DataLayout>();
Chris Lattner149f5282011-05-01 18:27:11 +00001005 TLI = &getAnalysis<TargetLibraryInfo>();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001006
Chris Lattner149f5282011-05-01 18:27:11 +00001007 // If we don't have at least memset and memcpy, there is little point of doing
1008 // anything here. These are required by a freestanding implementation, so if
1009 // even they are disabled, there is no point in trying hard.
1010 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1011 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001012
Chris Lattner61c6ba82009-09-01 17:09:55 +00001013 while (1) {
1014 if (!iterateOnFunction(F))
1015 break;
1016 MadeChange = true;
1017 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001018
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001019 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +00001020 return MadeChange;
1021}