blob: 00ee14578573f9dc2f5a51eeb0e2542d07a8aabe [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"
Owen Andersona723d1e2008-04-09 08:23:16 +000018#include "llvm/IntrinsicInst.h"
19#include "llvm/Instructions.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000020#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattnerbb897102010-12-26 20:15:01 +000025#include "llvm/Analysis/ValueTracking.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000028#include "llvm/Support/raw_ostream.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000029#include "llvm/Target/TargetData.h"
30#include <list>
31using namespace llvm;
32
33STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
34STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000035STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000036STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000037
Owen Andersona723d1e2008-04-09 08:23:16 +000038static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
39 bool &VariableIdxFound, TargetData &TD) {
40 // Skip over the first indices.
41 gep_type_iterator GTI = gep_type_begin(GEP);
42 for (unsigned i = 1; i != Idx; ++i, ++GTI)
43 /*skip along*/;
44
45 // Compute the offset implied by the rest of the indices.
46 int64_t Offset = 0;
47 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
48 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
49 if (OpC == 0)
50 return VariableIdxFound = true;
51 if (OpC->isZero()) continue; // No offset.
52
53 // Handle struct indices, which add their field offset to the pointer.
54 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
55 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
56 continue;
57 }
58
59 // Otherwise, we have a sequential type like an array or vector. Multiply
60 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +000061 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +000062 Offset += Size*OpC->getSExtValue();
63 }
64
65 return Offset;
66}
67
68/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
69/// constant offset, and return that constant offset. For example, Ptr1 might
70/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
71static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
72 TargetData &TD) {
73 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
74 // base. After that base, they may have some number of common (and
75 // potentially variable) indices. After that they handle some constant
76 // offset, which determines their offset from each other. At this point, we
77 // handle no other case.
78 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
79 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
80 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
81 return false;
82
83 // Skip any common indices and track the GEP types.
84 unsigned Idx = 1;
85 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
86 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
87 break;
88
89 bool VariableIdxFound = false;
90 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
91 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
92 if (VariableIdxFound) return false;
93
94 Offset = Offset2-Offset1;
95 return true;
96}
97
98
99/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
100/// This allows us to analyze stores like:
101/// store 0 -> P+1
102/// store 0 -> P+0
103/// store 0 -> P+3
104/// store 0 -> P+2
105/// which sometimes happens with stores to arrays of structs etc. When we see
106/// the first store, we make a range [1, 2). The second store extends the range
107/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
108/// two ranges into [0, 3) which is memset'able.
109namespace {
110struct MemsetRange {
111 // Start/End - A semi range that describes the span that this range covers.
112 // The range is closed at the start and open at the end: [Start, End).
113 int64_t Start, End;
114
115 /// StartPtr - The getelementptr instruction that points to the start of the
116 /// range.
117 Value *StartPtr;
118
119 /// Alignment - The known alignment of the first store.
120 unsigned Alignment;
121
122 /// TheStores - The actual stores that make up this range.
123 SmallVector<StoreInst*, 16> TheStores;
124
125 bool isProfitableToUseMemset(const TargetData &TD) const;
126
127};
128} // end anon namespace
129
130bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
131 // If we found more than 8 stores to merge or 64 bytes, use memset.
132 if (TheStores.size() >= 8 || End-Start >= 64) return true;
133
134 // Assume that the code generator is capable of merging pairs of stores
135 // together if it wants to.
136 if (TheStores.size() <= 2) return false;
137
138 // If we have fewer than 8 stores, it can still be worthwhile to do this.
139 // For example, merging 4 i8 stores into an i32 store is useful almost always.
140 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
141 // memset will be split into 2 32-bit stores anyway) and doing so can
142 // pessimize the llvm optimizer.
143 //
144 // Since we don't have perfect knowledge here, make some assumptions: assume
145 // the maximum GPR width is the same size as the pointer size and assume that
146 // this width can be stored. If so, check to see whether we will end up
147 // actually reducing the number of stores used.
148 unsigned Bytes = unsigned(End-Start);
149 unsigned NumPointerStores = Bytes/TD.getPointerSize();
150
151 // Assume the remaining bytes if any are done a byte at a time.
152 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
153
154 // If we will reduce the # stores (according to this heuristic), do the
155 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
156 // etc.
157 return TheStores.size() > NumPointerStores+NumByteStores;
158}
159
160
161namespace {
162class MemsetRanges {
163 /// Ranges - A sorted list of the memset ranges. We use std::list here
164 /// because each element is relatively large and expensive to copy.
165 std::list<MemsetRange> Ranges;
166 typedef std::list<MemsetRange>::iterator range_iterator;
167 TargetData &TD;
168public:
169 MemsetRanges(TargetData &td) : TD(td) {}
170
171 typedef std::list<MemsetRange>::const_iterator const_iterator;
172 const_iterator begin() const { return Ranges.begin(); }
173 const_iterator end() const { return Ranges.end(); }
174 bool empty() const { return Ranges.empty(); }
175
176 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
177};
178
179} // end anon namespace
180
181
182/// addStore - Add a new store to the MemsetRanges data structure. This adds a
183/// new range for the specified store at the specified offset, merging into
184/// existing ranges as appropriate.
185void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
186 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
187
188 // Do a linear search of the ranges to see if this can be joined and/or to
189 // find the insertion point in the list. We keep the ranges sorted for
190 // simplicity here. This is a linear search of a linked list, which is ugly,
191 // however the number of ranges is limited, so this won't get crazy slow.
192 range_iterator I = Ranges.begin(), E = Ranges.end();
193
194 while (I != E && Start > I->End)
195 ++I;
196
197 // We now know that I == E, in which case we didn't find anything to merge
198 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
199 // to insert a new range. Handle this now.
200 if (I == E || End < I->Start) {
201 MemsetRange &R = *Ranges.insert(I, MemsetRange());
202 R.Start = Start;
203 R.End = End;
204 R.StartPtr = SI->getPointerOperand();
205 R.Alignment = SI->getAlignment();
206 R.TheStores.push_back(SI);
207 return;
208 }
209
210 // This store overlaps with I, add it.
211 I->TheStores.push_back(SI);
212
213 // At this point, we may have an interval that completely contains our store.
214 // If so, just add it to the interval and return.
215 if (I->Start <= Start && I->End >= End)
216 return;
217
218 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
219 // but is not entirely contained within the range.
220
221 // See if the range extends the start of the range. In this case, it couldn't
222 // possibly cause it to join the prior range, because otherwise we would have
223 // stopped on *it*.
224 if (Start < I->Start) {
225 I->Start = Start;
226 I->StartPtr = SI->getPointerOperand();
Dan Gohman264d2452009-09-14 23:39:10 +0000227 I->Alignment = SI->getAlignment();
Owen Andersona723d1e2008-04-09 08:23:16 +0000228 }
229
230 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
231 // is in or right at the end of I), and that End >= I->Start. Extend I out to
232 // End.
233 if (End > I->End) {
234 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000235 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000236 while (++NextI != E && End >= NextI->Start) {
237 // Merge the range in.
238 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
239 if (NextI->End > I->End)
240 I->End = NextI->End;
241 Ranges.erase(NextI);
242 NextI = I;
243 }
244 }
245}
246
247//===----------------------------------------------------------------------===//
248// MemCpyOpt Pass
249//===----------------------------------------------------------------------===//
250
251namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000252 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000253 MemoryDependenceAnalysis *MD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000254 bool runOnFunction(Function &F);
255 public:
256 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000257 MemCpyOpt() : FunctionPass(ID) {
258 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000259 MD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000260 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000261
262 private:
263 // This transformation requires dominator postdominator info
264 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
265 AU.setPreservesCFG();
266 AU.addRequired<DominatorTree>();
267 AU.addRequired<MemoryDependenceAnalysis>();
268 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000269 AU.addPreserved<AliasAnalysis>();
270 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000271 }
272
273 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000274 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
275 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000276 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000277 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
278 uint64_t cpyLen, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000279 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
280 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000281 bool processByValArgument(CallSite CS, unsigned ArgNo);
Owen Andersona723d1e2008-04-09 08:23:16 +0000282 bool iterateOnFunction(Function &F);
283 };
284
285 char MemCpyOpt::ID = 0;
286}
287
288// createMemCpyOptPass - The public interface to this file...
289FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
290
Owen Anderson2ab36d32010-10-12 19:48:12 +0000291INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
292 false, false)
293INITIALIZE_PASS_DEPENDENCY(DominatorTree)
294INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
295INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
296INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
297 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000298
Owen Andersona723d1e2008-04-09 08:23:16 +0000299/// processStore - When GVN is scanning forward over instructions, we look for
300/// some other patterns to fold away. In particular, this looks for stores to
301/// neighboring locations of memory. If it sees enough consequtive ones
302/// (currently 4) it attempts to merge them together into a memcpy/memset.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000303bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000304 if (SI->isVolatile()) return false;
305
Owen Anderson65491212010-10-15 22:52:12 +0000306 TargetData *TD = getAnalysisIfAvailable<TargetData>();
307 if (!TD) return false;
308
309 // Detect cases where we're performing call slot forwarding, but
310 // happen to be using a load-store pair to implement it, rather than
311 // a memcpy.
312 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
313 if (!LI->isVolatile() && LI->hasOneUse()) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000314 MemDepResult dep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000315 CallInst *C = 0;
316 if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
317 C = dyn_cast<CallInst>(dep.getInst());
318
319 if (C) {
320 bool changed = performCallSlotOptzn(LI,
321 SI->getPointerOperand()->stripPointerCasts(),
322 LI->getPointerOperand()->stripPointerCasts(),
323 TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
324 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000325 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000326 SI->eraseFromParent();
327 LI->eraseFromParent();
328 ++NumMemCpyInstr;
329 return true;
330 }
331 }
332 }
333 }
334
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000335 LLVMContext &Context = SI->getContext();
336
Owen Andersona723d1e2008-04-09 08:23:16 +0000337 // There are two cases that are interesting for this code to handle: memcpy
338 // and memset. Right now we only handle memset.
339
340 // Ensure that the value being stored is something that can be memset'able a
341 // byte at a time like "0" or "-1" or any width, as well as things like
342 // 0xA0A0A0A0 and 0.0.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000343 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
Owen Andersona723d1e2008-04-09 08:23:16 +0000344 if (!ByteVal)
345 return false;
346
Owen Andersona723d1e2008-04-09 08:23:16 +0000347 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohmana195b7f2009-07-28 00:37:06 +0000348 Module *M = SI->getParent()->getParent()->getParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000349
350 // Okay, so we now have a single store that can be splatable. Scan to find
351 // all subsequent stores of the same value to offset from the same pointer.
352 // Join these together into ranges, so we can decide whether contiguous blocks
353 // are stored.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000354 MemsetRanges Ranges(*TD);
Owen Andersona723d1e2008-04-09 08:23:16 +0000355
356 Value *StartPtr = SI->getPointerOperand();
357
358 BasicBlock::iterator BI = SI;
359 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
360 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
361 // If the call is readnone, ignore it, otherwise bail out. We don't even
362 // allow readonly here because we don't want something like:
363 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Gabor Greifa292b2f2010-07-27 16:44:23 +0000364 if (AA.getModRefBehavior(CallSite(BI)) ==
Owen Andersona723d1e2008-04-09 08:23:16 +0000365 AliasAnalysis::DoesNotAccessMemory)
366 continue;
367
368 // TODO: If this is a memset, try to join it in.
369
370 break;
371 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
372 break;
373
374 // If this is a non-store instruction it is fine, ignore it.
375 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
376 if (NextStore == 0) continue;
377
378 // If this is a store, see if we can merge it in.
379 if (NextStore->isVolatile()) break;
380
381 // Check to see if this stored value is of the same byte-splattable value.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000382 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
Owen Andersona723d1e2008-04-09 08:23:16 +0000383 break;
384
385 // Check to see if this store is to a constant offset from the start ptr.
386 int64_t Offset;
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000387 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000388 break;
389
390 Ranges.addStore(Offset, NextStore);
391 }
392
393 // If we have no ranges, then we just had a single store with nothing that
394 // could be merged in. This is a very common case of course.
395 if (Ranges.empty())
396 return false;
397
398 // If we had at least one store that could be merged in, add the starting
399 // store as well. We try to avoid this unless there is at least something
400 // interesting as a small compile-time optimization.
401 Ranges.addStore(0, SI);
Owen Andersona723d1e2008-04-09 08:23:16 +0000402
Owen Andersona723d1e2008-04-09 08:23:16 +0000403
404 // Now that we have full information about ranges, loop over the ranges and
405 // emit memset's for anything big enough to be worthwhile.
406 bool MadeChange = false;
407 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
408 I != E; ++I) {
409 const MemsetRange &Range = *I;
410
411 if (Range.TheStores.size() == 1) continue;
412
413 // If it is profitable to lower this range to memset, do so now.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000414 if (!Range.isProfitableToUseMemset(*TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000415 continue;
416
417 // Otherwise, we do want to transform this! Create a new memset. We put
418 // the memset right before the first instruction that isn't part of this
419 // memset block. This ensure that the memset is dominated by any addressing
420 // instruction needed by the start of the block.
421 BasicBlock::iterator InsertPt = BI;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000422
Owen Andersona723d1e2008-04-09 08:23:16 +0000423 // Get the starting pointer of the block.
424 StartPtr = Range.StartPtr;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000425
426 // Determine alignment
427 unsigned Alignment = Range.Alignment;
428 if (Alignment == 0) {
429 const Type *EltType =
430 cast<PointerType>(StartPtr->getType())->getElementType();
431 Alignment = TD->getABITypeAlignment(EltType);
432 }
433
Owen Andersona723d1e2008-04-09 08:23:16 +0000434 // Cast the start ptr to be i8* as memset requires.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000435 const PointerType* StartPTy = cast<PointerType>(StartPtr->getType());
436 const PointerType *i8Ptr = Type::getInt8PtrTy(Context,
437 StartPTy->getAddressSpace());
438 if (StartPTy!= i8Ptr)
Daniel Dunbar460f6562009-07-26 09:48:23 +0000439 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getName(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000440 InsertPt);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000441
Owen Andersona723d1e2008-04-09 08:23:16 +0000442 Value *Ops[] = {
443 StartPtr, ByteVal, // Start, value
Owen Andersone922c022009-07-22 00:24:57 +0000444 // size
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000445 ConstantInt::get(Type::getInt64Ty(Context), Range.End-Range.Start),
Owen Andersone922c022009-07-22 00:24:57 +0000446 // align
Mon P Wang20adc9d2010-04-04 03:10:48 +0000447 ConstantInt::get(Type::getInt32Ty(Context), Alignment),
448 // volatile
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000449 ConstantInt::getFalse(Context),
Owen Andersona723d1e2008-04-09 08:23:16 +0000450 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000451 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
452
453 Function *MemSetF = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
454
455 Value *C = CallInst::Create(MemSetF, Ops, Ops+5, "", InsertPt);
David Greenecb33fd12010-01-05 01:27:47 +0000456 DEBUG(dbgs() << "Replace stores:\n";
Owen Andersona723d1e2008-04-09 08:23:16 +0000457 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000458 dbgs() << *Range.TheStores[i] << '\n';
Jeffrey Yasskin8e68c382010-12-23 00:58:24 +0000459 dbgs() << "With: " << *C << '\n'); (void)C;
Owen Andersona723d1e2008-04-09 08:23:16 +0000460
Owen Andersona8bd6582008-04-21 07:45:10 +0000461 // Don't invalidate the iterator
462 BBI = BI;
463
Owen Andersona723d1e2008-04-09 08:23:16 +0000464 // Zap all the stores.
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000465 for (SmallVector<StoreInst*, 16>::const_iterator
466 SI = Range.TheStores.begin(),
Owen Andersona8bd6582008-04-21 07:45:10 +0000467 SE = Range.TheStores.end(); SI != SE; ++SI)
468 (*SI)->eraseFromParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000469 ++NumMemSetInfer;
470 MadeChange = true;
471 }
472
473 return MadeChange;
474}
475
476
477/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
478/// and checks for the possibility of a call slot optimization by having
479/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000480bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
481 Value *cpyDest, Value *cpySrc,
482 uint64_t cpyLen, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000483 // The general transformation to keep in mind is
484 //
485 // call @func(..., src, ...)
486 // memcpy(dest, src, ...)
487 //
488 // ->
489 //
490 // memcpy(dest, src, ...)
491 // call @func(..., dest, ...)
492 //
493 // Since moving the memcpy is technically awkward, we additionally check that
494 // src only holds uninitialized values at the moment of the call, meaning that
495 // the memcpy can be discarded rather than moved.
496
497 // Deliberately get the source and destination with bitcasts stripped away,
498 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000499 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000500
Owen Andersona723d1e2008-04-09 08:23:16 +0000501 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000502 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000503 if (!srcAlloca)
504 return false;
505
506 // Check that all of src is copied to dest.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000507 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000508 if (!TD) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000509
Chris Lattner61c6ba82009-09-01 17:09:55 +0000510 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000511 if (!srcArraySize)
512 return false;
513
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000514 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000515 srcArraySize->getZExtValue();
516
Owen Anderson65491212010-10-15 22:52:12 +0000517 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000518 return false;
519
520 // Check that accessing the first srcSize bytes of dest will not cause a
521 // trap. Otherwise the transform is invalid since it might cause a trap
522 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000523 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000524 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000525 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000526 if (!destArraySize)
527 return false;
528
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000529 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000530 destArraySize->getZExtValue();
531
532 if (destSize < srcSize)
533 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000534 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000535 // If the destination is an sret parameter then only accesses that are
536 // outside of the returned struct type can trap.
537 if (!A->hasStructRetAttr())
538 return false;
539
Chris Lattner61c6ba82009-09-01 17:09:55 +0000540 const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000541 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000542
543 if (destSize < srcSize)
544 return false;
545 } else {
546 return false;
547 }
548
549 // Check that src is not accessed except via the call and the memcpy. This
550 // guarantees that it holds only undefined values when passed in (so the final
551 // memcpy can be dropped), that it is not read or written between the call and
552 // the memcpy, and that writing beyond the end of it is undefined.
553 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
554 srcAlloca->use_end());
555 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000556 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000557
Owen Anderson009e4f72008-06-01 22:26:26 +0000558 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000559 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
560 I != E; ++I)
561 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000562 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000563 if (G->hasAllZeroIndices())
564 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
565 I != E; ++I)
566 srcUseList.push_back(*I);
567 else
568 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000569 } else if (UI != C && UI != cpy) {
570 return false;
571 }
572 }
573
574 // Since we're changing the parameter to the callsite, we need to make sure
575 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000576 DominatorTree &DT = getAnalysis<DominatorTree>();
577 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000578 if (!DT.dominates(cpyDestInst, C))
579 return false;
580
581 // In addition to knowing that the call does not access src in some
582 // unexpected manner, for example via a global, which we deduce from
583 // the use analysis, we also need to know that it does not sneakily
584 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000585 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson65491212010-10-15 22:52:12 +0000586 if (AA.getModRefInfo(C, cpyDest, srcSize) !=
Owen Andersona723d1e2008-04-09 08:23:16 +0000587 AliasAnalysis::NoModRef)
588 return false;
589
590 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000591 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000592 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000593 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000594 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000595 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000596 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000597 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000598 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000599 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000600 else
601 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
602 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000603 }
604
Owen Anderson12cb36c2008-06-01 21:52:16 +0000605 if (!changedArgument)
606 return false;
607
Owen Andersona723d1e2008-04-09 08:23:16 +0000608 // Drop any cached information about the call, because we may have changed
609 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000610 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000611
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000612 // Remove the memcpy.
613 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000614 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000615
616 return true;
617}
618
Chris Lattner43f8e432010-11-18 07:02:37 +0000619/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
620/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
621/// copy from MDep's input if we can. MSize is the size of M's copy.
622///
623bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
624 uint64_t MSize) {
625 // We can only transforms memcpy's where the dest of one is the source of the
626 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000627 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000628 return false;
629
Chris Lattnerf7f35462010-12-09 07:39:50 +0000630 // If dep instruction is reading from our current input, then it is a noop
631 // transfer and substituting the input won't change this instruction. Just
632 // ignore the input and let someone else zap MDep. This handles cases like:
633 // memcpy(a <- a)
634 // memcpy(b <- a)
635 if (M->getSource() == MDep->getSource())
636 return false;
637
Chris Lattner43f8e432010-11-18 07:02:37 +0000638 // Second, the length of the memcpy's must be the same, or the preceeding one
639 // must be larger than the following one.
640 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
641 if (!C1) return false;
642
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000643 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000644
645 // Verify that the copied-from memory doesn't change in between the two
646 // transfers. For example, in:
647 // memcpy(a <- b)
648 // *b = 42;
649 // memcpy(c <- a)
650 // It would be invalid to transform the second memcpy into memcpy(c <- b).
651 //
652 // TODO: If the code between M and MDep is transparent to the destination "c",
653 // then we could still perform the xform by moving M up to the first memcpy.
654 //
655 // NOTE: This is conservative, it will stop on any read from the source loc,
656 // not just the defining memcpy.
657 MemDepResult SourceDep =
658 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
659 false, M, M->getParent());
660 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
661 return false;
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000662
663 // If the dest of the second might alias the source of the first, then the
664 // source and dest might overlap. We still want to eliminate the intermediate
665 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000666 Intrinsic::ID ResultFn = Intrinsic::memcpy;
Dan Gohman387f28a2010-12-16 02:51:19 +0000667 if (AA.alias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)) !=
668 AliasAnalysis::NoAlias)
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000669 ResultFn = Intrinsic::memmove;
Chris Lattner43f8e432010-11-18 07:02:37 +0000670
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000671 // If all checks passed, then we can transform M.
Chris Lattner245b7f62010-11-18 07:38:43 +0000672 const Type *ArgTys[3] = {
673 M->getRawDest()->getType(),
Chris Lattner43f8e432010-11-18 07:02:37 +0000674 MDep->getRawSource()->getType(),
Chris Lattner245b7f62010-11-18 07:38:43 +0000675 M->getLength()->getType()
676 };
Chris Lattner43f8e432010-11-18 07:02:37 +0000677 Function *MemCpyFun =
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000678 Intrinsic::getDeclaration(MDep->getParent()->getParent()->getParent(),
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000679 ResultFn, ArgTys, 3);
Chris Lattner43f8e432010-11-18 07:02:37 +0000680
681 // Make sure to use the lesser of the alignment of the source and the dest
682 // since we're changing where we're reading from, but don't want to increase
683 // the alignment past what can be read from or written to.
684 // TODO: Is this worth it if we're creating a less aligned memcpy? For
685 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000686 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Chris Lattner43f8e432010-11-18 07:02:37 +0000687 Value *Args[5] = {
Chris Lattnerd528be62010-11-18 08:07:09 +0000688 M->getRawDest(),
689 MDep->getRawSource(),
690 M->getLength(),
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000691 ConstantInt::get(Type::getInt32Ty(MemCpyFun->getContext()), Align),
Chris Lattnerd528be62010-11-18 08:07:09 +0000692 M->getVolatileCst()
Chris Lattner43f8e432010-11-18 07:02:37 +0000693 };
Chris Lattner604f6fe2010-11-21 08:06:10 +0000694 CallInst::Create(MemCpyFun, Args, Args+5, "", M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000695
Chris Lattner604f6fe2010-11-21 08:06:10 +0000696 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000697 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000698 M->eraseFromParent();
699 ++NumMemCpyInstr;
700 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000701}
702
703
Gabor Greif7d3056b2010-07-28 22:50:26 +0000704/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
705/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
706/// B to be a memcpy from X to Z (or potentially a memmove, depending on
707/// circumstances). This allows later passes to remove the first memcpy
708/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000709bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000710 // We can only optimize statically-sized memcpy's that are non-volatile.
711 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
712 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000713
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000714 // If the source and destination of the memcpy are the same, then zap it.
715 if (M->getSource() == M->getDest()) {
716 MD->removeInstruction(M);
717 M->eraseFromParent();
718 return false;
719 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000720
721 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000722 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000723 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000724 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
725 Value *Ops[] = {
726 M->getRawDest(), ByteVal, // Start, value
727 CopySize, // Size
728 M->getAlignmentCst(), // Alignment
729 ConstantInt::getFalse(M->getContext()), // volatile
730 };
731 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
732 Module *Mod = M->getParent()->getParent()->getParent();
733 Function *MemSetF = Intrinsic::getDeclaration(Mod, Intrinsic::memset,
734 Tys, 2);
735 CallInst::Create(MemSetF, Ops, Ops+5, "", M);
736 MD->removeInstruction(M);
737 M->eraseFromParent();
738 ++NumCpyToSet;
739 return true;
740 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000741
Owen Andersona8bd6582008-04-21 07:45:10 +0000742 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000743 // a) memcpy-memcpy xform which exposes redundance for DSE.
744 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000745 MemDepResult DepInfo = MD->getDependency(M);
746 if (!DepInfo.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000747 return false;
Owen Andersona8bd6582008-04-21 07:45:10 +0000748
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000749 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()))
750 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Owen Andersona723d1e2008-04-09 08:23:16 +0000751
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000752 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000753 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
754 CopySize->getZExtValue(), C)) {
755 M->eraseFromParent();
756 return true;
757 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000758 }
Owen Anderson02e99882008-04-29 21:51:00 +0000759 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000760}
761
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000762/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
763/// are guaranteed not to alias.
764bool MemCpyOpt::processMemMove(MemMoveInst *M) {
765 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
766
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000767 // See if the pointers alias.
Dan Gohman387f28a2010-12-16 02:51:19 +0000768 if (AA.alias(AA.getLocationForDest(M),
769 AA.getLocationForSource(M)) !=
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000770 AliasAnalysis::NoAlias)
771 return false;
772
David Greenecb33fd12010-01-05 01:27:47 +0000773 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000774
775 // If not, then we know we can transform this.
776 Module *Mod = M->getParent()->getParent()->getParent();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000777 const Type *ArgTys[3] = { M->getRawDest()->getType(),
778 M->getRawSource()->getType(),
779 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000780 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
781 ArgTys, 3));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000782
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000783 // MemDep may have over conservative information about this instruction, just
784 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000785 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000786
787 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000788 return true;
789}
790
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000791/// processByValArgument - This is called on every byval argument in call sites.
792bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
793 TargetData *TD = getAnalysisIfAvailable<TargetData>();
794 if (!TD) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000795
Chris Lattner604f6fe2010-11-21 08:06:10 +0000796 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000797 Value *ByValArg = CS.getArgument(ArgNo);
Chris Lattnerb5a31962010-12-01 01:24:55 +0000798 const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType();
799 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000800 MemDepResult DepInfo =
801 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
802 true, CS.getInstruction(),
803 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000804 if (!DepInfo.isClobber())
805 return false;
806
807 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
808 // a memcpy, see if we can byval from the source of the memcpy instead of the
809 // result.
810 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
811 if (MDep == 0 || MDep->isVolatile() ||
812 ByValArg->stripPointerCasts() != MDep->getDest())
813 return false;
814
815 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000816 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000817 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000818 return false;
819
820 // Get the alignment of the byval. If it is greater than the memcpy, then we
821 // can't do the substitution. If the call doesn't specify the alignment, then
822 // it is some target specific value that we can't know.
823 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
824 if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign)
825 return false;
826
827 // Verify that the copied-from memory doesn't change in between the memcpy and
828 // the byval call.
829 // memcpy(a <- b)
830 // *b = 42;
831 // foo(*a)
832 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000833 //
834 // NOTE: This is conservative, it will stop on any read from the source loc,
835 // not just the defining memcpy.
836 MemDepResult SourceDep =
837 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
838 false, CS.getInstruction(), MDep->getParent());
839 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
840 return false;
841
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000842 Value *TmpCast = MDep->getSource();
843 if (MDep->getSource()->getType() != ByValArg->getType())
844 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
845 "tmpcast", CS.getInstruction());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000846
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000847 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
848 << " " << *MDep << "\n"
849 << " " << *CS.getInstruction() << "\n");
850
851 // Otherwise we're good! Update the byval argument.
852 CS.setArgument(ArgNo, TmpCast);
853 ++NumMemCpyInstr;
854 return true;
855}
856
857/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000858bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000859 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000860
Chris Lattner61c6ba82009-09-01 17:09:55 +0000861 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000862 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000863 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000864 // Avoid invalidating the iterator.
865 Instruction *I = BI++;
Owen Andersona8bd6582008-04-21 07:45:10 +0000866
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000867 bool RepeatInstruction = false;
868
Owen Andersona8bd6582008-04-21 07:45:10 +0000869 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000870 MadeChange |= processStore(SI, BI);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000871 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) {
872 RepeatInstruction = processMemCpy(M);
873 } else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) {
874 RepeatInstruction = processMemMove(M);
875 } else if (CallSite CS = (Value*)I) {
876 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
877 if (CS.paramHasAttr(i+1, Attribute::ByVal))
878 MadeChange |= processByValArgument(CS, i);
879 }
880
881 // Reprocess the instruction if desired.
882 if (RepeatInstruction) {
883 --BI;
884 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000885 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000886 }
887 }
888
Chris Lattner61c6ba82009-09-01 17:09:55 +0000889 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000890}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000891
892// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
893// function.
894//
895bool MemCpyOpt::runOnFunction(Function &F) {
896 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000897 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000898 while (1) {
899 if (!iterateOnFunction(F))
900 break;
901 MadeChange = true;
902 }
903
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000904 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000905 return MadeChange;
906}