blob: d7da538fa3e03dac0aecdd08fb59bec340e552c7 [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 Lattner61db1f52010-12-26 22:57:41 +000028#include "llvm/Support/IRBuilder.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000029#include "llvm/Support/raw_ostream.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000030#include "llvm/Target/TargetData.h"
31#include <list>
32using namespace llvm;
33
34STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
35STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000036STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000037STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000038
Owen Andersona723d1e2008-04-09 08:23:16 +000039static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
40 bool &VariableIdxFound, TargetData &TD) {
41 // Skip over the first indices.
42 gep_type_iterator GTI = gep_type_begin(GEP);
43 for (unsigned i = 1; i != Idx; ++i, ++GTI)
44 /*skip along*/;
45
46 // Compute the offset implied by the rest of the indices.
47 int64_t Offset = 0;
48 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
49 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
50 if (OpC == 0)
51 return VariableIdxFound = true;
52 if (OpC->isZero()) continue; // No offset.
53
54 // Handle struct indices, which add their field offset to the pointer.
55 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
56 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
57 continue;
58 }
59
60 // Otherwise, we have a sequential type like an array or vector. Multiply
61 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +000062 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +000063 Offset += Size*OpC->getSExtValue();
64 }
65
66 return Offset;
67}
68
69/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
70/// constant offset, and return that constant offset. For example, Ptr1 might
71/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
72static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
73 TargetData &TD) {
74 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
75 // base. After that base, they may have some number of common (and
76 // potentially variable) indices. After that they handle some constant
77 // offset, which determines their offset from each other. At this point, we
78 // handle no other case.
79 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
80 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
81 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
82 return false;
83
84 // Skip any common indices and track the GEP types.
85 unsigned Idx = 1;
86 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
87 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
88 break;
89
90 bool VariableIdxFound = false;
91 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
92 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
93 if (VariableIdxFound) return false;
94
95 Offset = Offset2-Offset1;
96 return true;
97}
98
99
100/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
101/// This allows us to analyze stores like:
102/// store 0 -> P+1
103/// store 0 -> P+0
104/// store 0 -> P+3
105/// store 0 -> P+2
106/// which sometimes happens with stores to arrays of structs etc. When we see
107/// the first store, we make a range [1, 2). The second store extends the range
108/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
109/// two ranges into [0, 3) which is memset'able.
110namespace {
111struct MemsetRange {
112 // Start/End - A semi range that describes the span that this range covers.
113 // The range is closed at the start and open at the end: [Start, End).
114 int64_t Start, End;
115
116 /// StartPtr - The getelementptr instruction that points to the start of the
117 /// range.
118 Value *StartPtr;
119
120 /// Alignment - The known alignment of the first store.
121 unsigned Alignment;
122
123 /// TheStores - The actual stores that make up this range.
124 SmallVector<StoreInst*, 16> TheStores;
125
126 bool isProfitableToUseMemset(const TargetData &TD) const;
127
128};
129} // end anon namespace
130
131bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
132 // If we found more than 8 stores to merge or 64 bytes, use memset.
133 if (TheStores.size() >= 8 || End-Start >= 64) return true;
134
135 // Assume that the code generator is capable of merging pairs of stores
136 // together if it wants to.
137 if (TheStores.size() <= 2) return false;
138
139 // If we have fewer than 8 stores, it can still be worthwhile to do this.
140 // For example, merging 4 i8 stores into an i32 store is useful almost always.
141 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
142 // memset will be split into 2 32-bit stores anyway) and doing so can
143 // pessimize the llvm optimizer.
144 //
145 // Since we don't have perfect knowledge here, make some assumptions: assume
146 // the maximum GPR width is the same size as the pointer size and assume that
147 // this width can be stored. If so, check to see whether we will end up
148 // actually reducing the number of stores used.
149 unsigned Bytes = unsigned(End-Start);
150 unsigned NumPointerStores = Bytes/TD.getPointerSize();
151
152 // Assume the remaining bytes if any are done a byte at a time.
153 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
154
155 // If we will reduce the # stores (according to this heuristic), do the
156 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
157 // etc.
158 return TheStores.size() > NumPointerStores+NumByteStores;
159}
160
161
162namespace {
163class MemsetRanges {
164 /// Ranges - A sorted list of the memset ranges. We use std::list here
165 /// because each element is relatively large and expensive to copy.
166 std::list<MemsetRange> Ranges;
167 typedef std::list<MemsetRange>::iterator range_iterator;
168 TargetData &TD;
169public:
170 MemsetRanges(TargetData &td) : TD(td) {}
171
172 typedef std::list<MemsetRange>::const_iterator const_iterator;
173 const_iterator begin() const { return Ranges.begin(); }
174 const_iterator end() const { return Ranges.end(); }
175 bool empty() const { return Ranges.empty(); }
176
177 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
178};
179
180} // end anon namespace
181
182
183/// addStore - Add a new store to the MemsetRanges data structure. This adds a
184/// new range for the specified store at the specified offset, merging into
185/// existing ranges as appropriate.
186void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
187 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
188
189 // Do a linear search of the ranges to see if this can be joined and/or to
190 // find the insertion point in the list. We keep the ranges sorted for
191 // simplicity here. This is a linear search of a linked list, which is ugly,
192 // however the number of ranges is limited, so this won't get crazy slow.
193 range_iterator I = Ranges.begin(), E = Ranges.end();
194
195 while (I != E && Start > I->End)
196 ++I;
197
198 // We now know that I == E, in which case we didn't find anything to merge
199 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
200 // to insert a new range. Handle this now.
201 if (I == E || End < I->Start) {
202 MemsetRange &R = *Ranges.insert(I, MemsetRange());
203 R.Start = Start;
204 R.End = End;
205 R.StartPtr = SI->getPointerOperand();
206 R.Alignment = SI->getAlignment();
207 R.TheStores.push_back(SI);
208 return;
209 }
210
211 // This store overlaps with I, add it.
212 I->TheStores.push_back(SI);
213
214 // At this point, we may have an interval that completely contains our store.
215 // If so, just add it to the interval and return.
216 if (I->Start <= Start && I->End >= End)
217 return;
218
219 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
220 // but is not entirely contained within the range.
221
222 // See if the range extends the start of the range. In this case, it couldn't
223 // possibly cause it to join the prior range, because otherwise we would have
224 // stopped on *it*.
225 if (Start < I->Start) {
226 I->Start = Start;
227 I->StartPtr = SI->getPointerOperand();
Dan Gohman264d2452009-09-14 23:39:10 +0000228 I->Alignment = SI->getAlignment();
Owen Andersona723d1e2008-04-09 08:23:16 +0000229 }
230
231 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
232 // is in or right at the end of I), and that End >= I->Start. Extend I out to
233 // End.
234 if (End > I->End) {
235 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000236 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000237 while (++NextI != E && End >= NextI->Start) {
238 // Merge the range in.
239 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
240 if (NextI->End > I->End)
241 I->End = NextI->End;
242 Ranges.erase(NextI);
243 NextI = I;
244 }
245 }
246}
247
248//===----------------------------------------------------------------------===//
249// MemCpyOpt Pass
250//===----------------------------------------------------------------------===//
251
252namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000253 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000254 MemoryDependenceAnalysis *MD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000255 bool runOnFunction(Function &F);
256 public:
257 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000258 MemCpyOpt() : FunctionPass(ID) {
259 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000260 MD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000261 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000262
263 private:
264 // This transformation requires dominator postdominator info
265 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
266 AU.setPreservesCFG();
267 AU.addRequired<DominatorTree>();
268 AU.addRequired<MemoryDependenceAnalysis>();
269 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000270 AU.addPreserved<AliasAnalysis>();
271 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000272 }
273
274 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000275 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
276 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000277 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000278 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
279 uint64_t cpyLen, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000280 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
281 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000282 bool processByValArgument(CallSite CS, unsigned ArgNo);
Owen Andersona723d1e2008-04-09 08:23:16 +0000283 bool iterateOnFunction(Function &F);
284 };
285
286 char MemCpyOpt::ID = 0;
287}
288
289// createMemCpyOptPass - The public interface to this file...
290FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
291
Owen Anderson2ab36d32010-10-12 19:48:12 +0000292INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
293 false, false)
294INITIALIZE_PASS_DEPENDENCY(DominatorTree)
295INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
296INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
297INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
298 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000299
Owen Andersona723d1e2008-04-09 08:23:16 +0000300/// processStore - When GVN is scanning forward over instructions, we look for
301/// some other patterns to fold away. In particular, this looks for stores to
302/// neighboring locations of memory. If it sees enough consequtive ones
303/// (currently 4) it attempts to merge them together into a memcpy/memset.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000304bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000305 if (SI->isVolatile()) return false;
306
Owen Anderson65491212010-10-15 22:52:12 +0000307 TargetData *TD = getAnalysisIfAvailable<TargetData>();
308 if (!TD) return false;
309
310 // Detect cases where we're performing call slot forwarding, but
311 // happen to be using a load-store pair to implement it, rather than
312 // a memcpy.
313 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
314 if (!LI->isVolatile() && LI->hasOneUse()) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000315 MemDepResult dep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000316 CallInst *C = 0;
317 if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
318 C = dyn_cast<CallInst>(dep.getInst());
319
320 if (C) {
321 bool changed = performCallSlotOptzn(LI,
322 SI->getPointerOperand()->stripPointerCasts(),
323 LI->getPointerOperand()->stripPointerCasts(),
324 TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
325 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000326 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000327 SI->eraseFromParent();
328 LI->eraseFromParent();
329 ++NumMemCpyInstr;
330 return true;
331 }
332 }
333 }
334 }
335
Owen Andersona723d1e2008-04-09 08:23:16 +0000336 // There are two cases that are interesting for this code to handle: memcpy
337 // and memset. Right now we only handle memset.
338
339 // Ensure that the value being stored is something that can be memset'able a
340 // byte at a time like "0" or "-1" or any width, as well as things like
341 // 0xA0A0A0A0 and 0.0.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000342 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
Owen Andersona723d1e2008-04-09 08:23:16 +0000343 if (!ByteVal)
344 return false;
345
Owen Andersona723d1e2008-04-09 08:23:16 +0000346 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
347
348 // Okay, so we now have a single store that can be splatable. Scan to find
349 // all subsequent stores of the same value to offset from the same pointer.
350 // Join these together into ranges, so we can decide whether contiguous blocks
351 // are stored.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000352 MemsetRanges Ranges(*TD);
Owen Andersona723d1e2008-04-09 08:23:16 +0000353
354 Value *StartPtr = SI->getPointerOperand();
355
356 BasicBlock::iterator BI = SI;
357 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
358 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
359 // If the call is readnone, ignore it, otherwise bail out. We don't even
360 // allow readonly here because we don't want something like:
361 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Gabor Greifa292b2f2010-07-27 16:44:23 +0000362 if (AA.getModRefBehavior(CallSite(BI)) ==
Owen Andersona723d1e2008-04-09 08:23:16 +0000363 AliasAnalysis::DoesNotAccessMemory)
364 continue;
365
366 // TODO: If this is a memset, try to join it in.
367
368 break;
369 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
370 break;
371
372 // If this is a non-store instruction it is fine, ignore it.
373 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
374 if (NextStore == 0) continue;
375
376 // If this is a store, see if we can merge it in.
377 if (NextStore->isVolatile()) break;
378
379 // Check to see if this stored value is of the same byte-splattable value.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000380 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
Owen Andersona723d1e2008-04-09 08:23:16 +0000381 break;
382
383 // Check to see if this store is to a constant offset from the start ptr.
384 int64_t Offset;
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000385 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000386 break;
387
388 Ranges.addStore(Offset, NextStore);
389 }
390
391 // If we have no ranges, then we just had a single store with nothing that
392 // could be merged in. This is a very common case of course.
393 if (Ranges.empty())
394 return false;
395
396 // If we had at least one store that could be merged in, add the starting
397 // store as well. We try to avoid this unless there is at least something
398 // interesting as a small compile-time optimization.
399 Ranges.addStore(0, SI);
Owen Andersona723d1e2008-04-09 08:23:16 +0000400
Owen Andersona723d1e2008-04-09 08:23:16 +0000401
402 // Now that we have full information about ranges, loop over the ranges and
403 // emit memset's for anything big enough to be worthwhile.
404 bool MadeChange = false;
405 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
406 I != E; ++I) {
407 const MemsetRange &Range = *I;
408
409 if (Range.TheStores.size() == 1) continue;
410
411 // If it is profitable to lower this range to memset, do so now.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000412 if (!Range.isProfitableToUseMemset(*TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000413 continue;
414
415 // Otherwise, we do want to transform this! Create a new memset. We put
416 // the memset right before the first instruction that isn't part of this
417 // memset block. This ensure that the memset is dominated by any addressing
418 // instruction needed by the start of the block.
419 BasicBlock::iterator InsertPt = BI;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000420
Owen Andersona723d1e2008-04-09 08:23:16 +0000421 // Get the starting pointer of the block.
422 StartPtr = Range.StartPtr;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000423
424 // Determine alignment
425 unsigned Alignment = Range.Alignment;
426 if (Alignment == 0) {
427 const Type *EltType =
428 cast<PointerType>(StartPtr->getType())->getElementType();
429 Alignment = TD->getABITypeAlignment(EltType);
430 }
431
Chris Lattner61db1f52010-12-26 22:57:41 +0000432 IRBuilder<> Builder(InsertPt);
433 Value *C =
434 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
435
David Greenecb33fd12010-01-05 01:27:47 +0000436 DEBUG(dbgs() << "Replace stores:\n";
Owen Andersona723d1e2008-04-09 08:23:16 +0000437 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000438 dbgs() << *Range.TheStores[i] << '\n';
Jeffrey Yasskin8e68c382010-12-23 00:58:24 +0000439 dbgs() << "With: " << *C << '\n'); (void)C;
Owen Andersona723d1e2008-04-09 08:23:16 +0000440
Owen Andersona8bd6582008-04-21 07:45:10 +0000441 // Don't invalidate the iterator
442 BBI = BI;
443
Owen Andersona723d1e2008-04-09 08:23:16 +0000444 // Zap all the stores.
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000445 for (SmallVector<StoreInst*, 16>::const_iterator
446 SI = Range.TheStores.begin(),
Owen Andersona8bd6582008-04-21 07:45:10 +0000447 SE = Range.TheStores.end(); SI != SE; ++SI)
448 (*SI)->eraseFromParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000449 ++NumMemSetInfer;
450 MadeChange = true;
451 }
452
453 return MadeChange;
454}
455
456
457/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
458/// and checks for the possibility of a call slot optimization by having
459/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000460bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
461 Value *cpyDest, Value *cpySrc,
462 uint64_t cpyLen, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000463 // The general transformation to keep in mind is
464 //
465 // call @func(..., src, ...)
466 // memcpy(dest, src, ...)
467 //
468 // ->
469 //
470 // memcpy(dest, src, ...)
471 // call @func(..., dest, ...)
472 //
473 // Since moving the memcpy is technically awkward, we additionally check that
474 // src only holds uninitialized values at the moment of the call, meaning that
475 // the memcpy can be discarded rather than moved.
476
477 // Deliberately get the source and destination with bitcasts stripped away,
478 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000479 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000480
Owen Andersona723d1e2008-04-09 08:23:16 +0000481 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000482 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000483 if (!srcAlloca)
484 return false;
485
486 // Check that all of src is copied to dest.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000487 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000488 if (!TD) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000489
Chris Lattner61c6ba82009-09-01 17:09:55 +0000490 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000491 if (!srcArraySize)
492 return false;
493
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000494 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000495 srcArraySize->getZExtValue();
496
Owen Anderson65491212010-10-15 22:52:12 +0000497 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000498 return false;
499
500 // Check that accessing the first srcSize bytes of dest will not cause a
501 // trap. Otherwise the transform is invalid since it might cause a trap
502 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000503 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000504 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000505 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000506 if (!destArraySize)
507 return false;
508
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000509 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000510 destArraySize->getZExtValue();
511
512 if (destSize < srcSize)
513 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000514 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000515 // If the destination is an sret parameter then only accesses that are
516 // outside of the returned struct type can trap.
517 if (!A->hasStructRetAttr())
518 return false;
519
Chris Lattner61c6ba82009-09-01 17:09:55 +0000520 const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000521 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000522
523 if (destSize < srcSize)
524 return false;
525 } else {
526 return false;
527 }
528
529 // Check that src is not accessed except via the call and the memcpy. This
530 // guarantees that it holds only undefined values when passed in (so the final
531 // memcpy can be dropped), that it is not read or written between the call and
532 // the memcpy, and that writing beyond the end of it is undefined.
533 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
534 srcAlloca->use_end());
535 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000536 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000537
Owen Anderson009e4f72008-06-01 22:26:26 +0000538 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000539 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
540 I != E; ++I)
541 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000542 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000543 if (G->hasAllZeroIndices())
544 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
545 I != E; ++I)
546 srcUseList.push_back(*I);
547 else
548 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000549 } else if (UI != C && UI != cpy) {
550 return false;
551 }
552 }
553
554 // Since we're changing the parameter to the callsite, we need to make sure
555 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000556 DominatorTree &DT = getAnalysis<DominatorTree>();
557 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000558 if (!DT.dominates(cpyDestInst, C))
559 return false;
560
561 // In addition to knowing that the call does not access src in some
562 // unexpected manner, for example via a global, which we deduce from
563 // the use analysis, we also need to know that it does not sneakily
564 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000565 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson65491212010-10-15 22:52:12 +0000566 if (AA.getModRefInfo(C, cpyDest, srcSize) !=
Owen Andersona723d1e2008-04-09 08:23:16 +0000567 AliasAnalysis::NoModRef)
568 return false;
569
570 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000571 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000572 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000573 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000574 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000575 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000576 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000577 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000578 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000579 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000580 else
581 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
582 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000583 }
584
Owen Anderson12cb36c2008-06-01 21:52:16 +0000585 if (!changedArgument)
586 return false;
587
Owen Andersona723d1e2008-04-09 08:23:16 +0000588 // Drop any cached information about the call, because we may have changed
589 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000590 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000591
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000592 // Remove the memcpy.
593 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000594 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000595
596 return true;
597}
598
Chris Lattner43f8e432010-11-18 07:02:37 +0000599/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
600/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
601/// copy from MDep's input if we can. MSize is the size of M's copy.
602///
603bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
604 uint64_t MSize) {
605 // We can only transforms memcpy's where the dest of one is the source of the
606 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000607 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000608 return false;
609
Chris Lattnerf7f35462010-12-09 07:39:50 +0000610 // If dep instruction is reading from our current input, then it is a noop
611 // transfer and substituting the input won't change this instruction. Just
612 // ignore the input and let someone else zap MDep. This handles cases like:
613 // memcpy(a <- a)
614 // memcpy(b <- a)
615 if (M->getSource() == MDep->getSource())
616 return false;
617
Chris Lattner43f8e432010-11-18 07:02:37 +0000618 // Second, the length of the memcpy's must be the same, or the preceeding one
619 // must be larger than the following one.
620 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
621 if (!C1) return false;
622
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000623 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000624
625 // Verify that the copied-from memory doesn't change in between the two
626 // transfers. For example, in:
627 // memcpy(a <- b)
628 // *b = 42;
629 // memcpy(c <- a)
630 // It would be invalid to transform the second memcpy into memcpy(c <- b).
631 //
632 // TODO: If the code between M and MDep is transparent to the destination "c",
633 // then we could still perform the xform by moving M up to the first memcpy.
634 //
635 // NOTE: This is conservative, it will stop on any read from the source loc,
636 // not just the defining memcpy.
637 MemDepResult SourceDep =
638 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
639 false, M, M->getParent());
640 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
641 return false;
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000642
643 // If the dest of the second might alias the source of the first, then the
644 // source and dest might overlap. We still want to eliminate the intermediate
645 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000646 bool UseMemMove = false;
647 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
648 UseMemMove = true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000649
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000650 // If all checks passed, then we can transform M.
Chris Lattner43f8e432010-11-18 07:02:37 +0000651
652 // Make sure to use the lesser of the alignment of the source and the dest
653 // since we're changing where we're reading from, but don't want to increase
654 // the alignment past what can be read from or written to.
655 // TODO: Is this worth it if we're creating a less aligned memcpy? For
656 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000657 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Chris Lattner61db1f52010-12-26 22:57:41 +0000658
659 IRBuilder<> Builder(M);
660 if (UseMemMove)
661 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
662 Align, M->isVolatile());
663 else
664 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
665 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000666
Chris Lattner604f6fe2010-11-21 08:06:10 +0000667 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000668 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000669 M->eraseFromParent();
670 ++NumMemCpyInstr;
671 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000672}
673
674
Gabor Greif7d3056b2010-07-28 22:50:26 +0000675/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
676/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
677/// B to be a memcpy from X to Z (or potentially a memmove, depending on
678/// circumstances). This allows later passes to remove the first memcpy
679/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000680bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000681 // We can only optimize statically-sized memcpy's that are non-volatile.
682 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
683 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000684
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000685 // If the source and destination of the memcpy are the same, then zap it.
686 if (M->getSource() == M->getDest()) {
687 MD->removeInstruction(M);
688 M->eraseFromParent();
689 return false;
690 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000691
692 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000693 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000694 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000695 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000696 IRBuilder<> Builder(M);
697 Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
698 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000699 MD->removeInstruction(M);
700 M->eraseFromParent();
701 ++NumCpyToSet;
702 return true;
703 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000704
Owen Andersona8bd6582008-04-21 07:45:10 +0000705 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000706 // a) memcpy-memcpy xform which exposes redundance for DSE.
707 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000708 MemDepResult DepInfo = MD->getDependency(M);
709 if (!DepInfo.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000710 return false;
Owen Andersona8bd6582008-04-21 07:45:10 +0000711
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000712 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()))
713 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Owen Andersona723d1e2008-04-09 08:23:16 +0000714
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000715 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000716 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
717 CopySize->getZExtValue(), C)) {
718 M->eraseFromParent();
719 return true;
720 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000721 }
Owen Anderson02e99882008-04-29 21:51:00 +0000722 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000723}
724
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000725/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
726/// are guaranteed not to alias.
727bool MemCpyOpt::processMemMove(MemMoveInst *M) {
728 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
729
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000730 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000731 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000732 return false;
733
David Greenecb33fd12010-01-05 01:27:47 +0000734 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000735
736 // If not, then we know we can transform this.
737 Module *Mod = M->getParent()->getParent()->getParent();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000738 const Type *ArgTys[3] = { M->getRawDest()->getType(),
739 M->getRawSource()->getType(),
740 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000741 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
742 ArgTys, 3));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000743
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000744 // MemDep may have over conservative information about this instruction, just
745 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000746 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000747
748 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000749 return true;
750}
751
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000752/// processByValArgument - This is called on every byval argument in call sites.
753bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
754 TargetData *TD = getAnalysisIfAvailable<TargetData>();
755 if (!TD) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000756
Chris Lattner604f6fe2010-11-21 08:06:10 +0000757 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000758 Value *ByValArg = CS.getArgument(ArgNo);
Chris Lattnerb5a31962010-12-01 01:24:55 +0000759 const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType();
760 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000761 MemDepResult DepInfo =
762 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
763 true, CS.getInstruction(),
764 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000765 if (!DepInfo.isClobber())
766 return false;
767
768 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
769 // a memcpy, see if we can byval from the source of the memcpy instead of the
770 // result.
771 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
772 if (MDep == 0 || MDep->isVolatile() ||
773 ByValArg->stripPointerCasts() != MDep->getDest())
774 return false;
775
776 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000777 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000778 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000779 return false;
780
781 // Get the alignment of the byval. If it is greater than the memcpy, then we
782 // can't do the substitution. If the call doesn't specify the alignment, then
783 // it is some target specific value that we can't know.
784 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
785 if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign)
786 return false;
787
788 // Verify that the copied-from memory doesn't change in between the memcpy and
789 // the byval call.
790 // memcpy(a <- b)
791 // *b = 42;
792 // foo(*a)
793 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000794 //
795 // NOTE: This is conservative, it will stop on any read from the source loc,
796 // not just the defining memcpy.
797 MemDepResult SourceDep =
798 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
799 false, CS.getInstruction(), MDep->getParent());
800 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
801 return false;
802
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000803 Value *TmpCast = MDep->getSource();
804 if (MDep->getSource()->getType() != ByValArg->getType())
805 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
806 "tmpcast", CS.getInstruction());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000807
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000808 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
809 << " " << *MDep << "\n"
810 << " " << *CS.getInstruction() << "\n");
811
812 // Otherwise we're good! Update the byval argument.
813 CS.setArgument(ArgNo, TmpCast);
814 ++NumMemCpyInstr;
815 return true;
816}
817
818/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000819bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000820 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000821
Chris Lattner61c6ba82009-09-01 17:09:55 +0000822 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000823 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000824 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000825 // Avoid invalidating the iterator.
826 Instruction *I = BI++;
Owen Andersona8bd6582008-04-21 07:45:10 +0000827
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000828 bool RepeatInstruction = false;
829
Owen Andersona8bd6582008-04-21 07:45:10 +0000830 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000831 MadeChange |= processStore(SI, BI);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000832 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) {
833 RepeatInstruction = processMemCpy(M);
834 } else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) {
835 RepeatInstruction = processMemMove(M);
836 } else if (CallSite CS = (Value*)I) {
837 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
838 if (CS.paramHasAttr(i+1, Attribute::ByVal))
839 MadeChange |= processByValArgument(CS, i);
840 }
841
842 // Reprocess the instruction if desired.
843 if (RepeatInstruction) {
844 --BI;
845 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000846 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000847 }
848 }
849
Chris Lattner61c6ba82009-09-01 17:09:55 +0000850 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000851}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000852
853// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
854// function.
855//
856bool MemCpyOpt::runOnFunction(Function &F) {
857 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000858 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000859 while (1) {
860 if (!iterateOnFunction(F))
861 break;
862 MadeChange = true;
863 }
864
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000865 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000866 return MadeChange;
867}