blob: c6381205c897c6f9e9e442edbbec54cc4b4de45a [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"
Owen Andersona723d1e2008-04-09 08:23:16 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000027#include "llvm/Support/raw_ostream.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000028#include "llvm/Target/TargetData.h"
29#include <list>
30using namespace llvm;
31
32STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
33STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000034STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000035STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000036
Owen Andersona723d1e2008-04-09 08:23:16 +000037/// isBytewiseValue - If the specified value can be set by repeating the same
38/// byte in memory, return the i8 value that it is represented with. This is
39/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
40/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
41/// byte store (e.g. i16 0x1234), return null.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +000042static Value *isBytewiseValue(Value *V) {
Benjamin Kramera1120872010-12-24 21:17:12 +000043 // Look through constant globals.
44 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
45 if (GV->mayBeOverridden() || !GV->isConstant() || !GV->hasInitializer())
46 return 0;
47 V = GV->getInitializer();
48 }
49
Owen Andersona723d1e2008-04-09 08:23:16 +000050 // All byte-wide stores are splatable, even of arbitrary variables.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000051 if (V->getType()->isIntegerTy(8)) return V;
Owen Andersona723d1e2008-04-09 08:23:16 +000052
53 // Constant float and double values can be handled as integer values if the
54 // corresponding integer value is "byteable". An important case is 0.0.
55 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +000056 if (CFP->getType()->isFloatTy())
Chris Lattner7a0b4fd2010-11-29 23:35:33 +000057 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +000058 if (CFP->getType()->isDoubleTy())
Chris Lattner7a0b4fd2010-11-29 23:35:33 +000059 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
Owen Andersona723d1e2008-04-09 08:23:16 +000060 // Don't handle long double formats, which have strange constraints.
61 }
62
63 // We can handle constant integers that are power of two in size and a
64 // multiple of 8 bits.
65 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
66 unsigned Width = CI->getBitWidth();
67 if (isPowerOf2_32(Width) && Width > 8) {
68 // We can handle this value if the recursive binary decomposition is the
69 // same at all levels.
70 APInt Val = CI->getValue();
71 APInt Val2;
72 while (Val.getBitWidth() != 8) {
73 unsigned NextWidth = Val.getBitWidth()/2;
74 Val2 = Val.lshr(NextWidth);
Jay Foad40f8f622010-12-07 08:25:19 +000075 Val2 = Val2.trunc(Val.getBitWidth()/2);
76 Val = Val.trunc(Val.getBitWidth()/2);
Owen Andersona723d1e2008-04-09 08:23:16 +000077
78 // If the top/bottom halves aren't the same, reject it.
79 if (Val != Val2)
80 return 0;
81 }
Chris Lattner7a0b4fd2010-11-29 23:35:33 +000082 return ConstantInt::get(V->getContext(), Val);
Owen Andersona723d1e2008-04-09 08:23:16 +000083 }
84 }
Benjamin Kramera1120872010-12-24 21:17:12 +000085
86 // A ConstantArray is splatable if all its members are equal and also
87 // splatable.
88 if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
89 if (CA->getNumOperands() == 0)
90 return 0;
91
92 Value *Val = isBytewiseValue(CA->getOperand(0));
93 if (!Val)
94 return 0;
95
96 for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I)
97 if (CA->getOperand(I-1) != CA->getOperand(I))
98 return 0;
99
100 return Val;
101 }
102
Owen Andersona723d1e2008-04-09 08:23:16 +0000103 // Conceptually, we could handle things like:
104 // %a = zext i8 %X to i16
105 // %b = shl i16 %a, 8
106 // %c = or i16 %a, %b
107 // but until there is an example that actually needs this, it doesn't seem
108 // worth worrying about.
109 return 0;
110}
111
112static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
113 bool &VariableIdxFound, TargetData &TD) {
114 // Skip over the first indices.
115 gep_type_iterator GTI = gep_type_begin(GEP);
116 for (unsigned i = 1; i != Idx; ++i, ++GTI)
117 /*skip along*/;
118
119 // Compute the offset implied by the rest of the indices.
120 int64_t Offset = 0;
121 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
122 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
123 if (OpC == 0)
124 return VariableIdxFound = true;
125 if (OpC->isZero()) continue; // No offset.
126
127 // Handle struct indices, which add their field offset to the pointer.
128 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
129 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
130 continue;
131 }
132
133 // Otherwise, we have a sequential type like an array or vector. Multiply
134 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +0000135 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +0000136 Offset += Size*OpC->getSExtValue();
137 }
138
139 return Offset;
140}
141
142/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
143/// constant offset, and return that constant offset. For example, Ptr1 might
144/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
145static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
146 TargetData &TD) {
147 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
148 // base. After that base, they may have some number of common (and
149 // potentially variable) indices. After that they handle some constant
150 // offset, which determines their offset from each other. At this point, we
151 // handle no other case.
152 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
153 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
154 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
155 return false;
156
157 // Skip any common indices and track the GEP types.
158 unsigned Idx = 1;
159 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
160 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
161 break;
162
163 bool VariableIdxFound = false;
164 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
165 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
166 if (VariableIdxFound) return false;
167
168 Offset = Offset2-Offset1;
169 return true;
170}
171
172
173/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
174/// This allows us to analyze stores like:
175/// store 0 -> P+1
176/// store 0 -> P+0
177/// store 0 -> P+3
178/// store 0 -> P+2
179/// which sometimes happens with stores to arrays of structs etc. When we see
180/// the first store, we make a range [1, 2). The second store extends the range
181/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
182/// two ranges into [0, 3) which is memset'able.
183namespace {
184struct MemsetRange {
185 // Start/End - A semi range that describes the span that this range covers.
186 // The range is closed at the start and open at the end: [Start, End).
187 int64_t Start, End;
188
189 /// StartPtr - The getelementptr instruction that points to the start of the
190 /// range.
191 Value *StartPtr;
192
193 /// Alignment - The known alignment of the first store.
194 unsigned Alignment;
195
196 /// TheStores - The actual stores that make up this range.
197 SmallVector<StoreInst*, 16> TheStores;
198
199 bool isProfitableToUseMemset(const TargetData &TD) const;
200
201};
202} // end anon namespace
203
204bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
205 // If we found more than 8 stores to merge or 64 bytes, use memset.
206 if (TheStores.size() >= 8 || End-Start >= 64) return true;
207
208 // Assume that the code generator is capable of merging pairs of stores
209 // together if it wants to.
210 if (TheStores.size() <= 2) return false;
211
212 // If we have fewer than 8 stores, it can still be worthwhile to do this.
213 // For example, merging 4 i8 stores into an i32 store is useful almost always.
214 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
215 // memset will be split into 2 32-bit stores anyway) and doing so can
216 // pessimize the llvm optimizer.
217 //
218 // Since we don't have perfect knowledge here, make some assumptions: assume
219 // the maximum GPR width is the same size as the pointer size and assume that
220 // this width can be stored. If so, check to see whether we will end up
221 // actually reducing the number of stores used.
222 unsigned Bytes = unsigned(End-Start);
223 unsigned NumPointerStores = Bytes/TD.getPointerSize();
224
225 // Assume the remaining bytes if any are done a byte at a time.
226 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
227
228 // If we will reduce the # stores (according to this heuristic), do the
229 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
230 // etc.
231 return TheStores.size() > NumPointerStores+NumByteStores;
232}
233
234
235namespace {
236class MemsetRanges {
237 /// Ranges - A sorted list of the memset ranges. We use std::list here
238 /// because each element is relatively large and expensive to copy.
239 std::list<MemsetRange> Ranges;
240 typedef std::list<MemsetRange>::iterator range_iterator;
241 TargetData &TD;
242public:
243 MemsetRanges(TargetData &td) : TD(td) {}
244
245 typedef std::list<MemsetRange>::const_iterator const_iterator;
246 const_iterator begin() const { return Ranges.begin(); }
247 const_iterator end() const { return Ranges.end(); }
248 bool empty() const { return Ranges.empty(); }
249
250 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
251};
252
253} // end anon namespace
254
255
256/// addStore - Add a new store to the MemsetRanges data structure. This adds a
257/// new range for the specified store at the specified offset, merging into
258/// existing ranges as appropriate.
259void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
260 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
261
262 // Do a linear search of the ranges to see if this can be joined and/or to
263 // find the insertion point in the list. We keep the ranges sorted for
264 // simplicity here. This is a linear search of a linked list, which is ugly,
265 // however the number of ranges is limited, so this won't get crazy slow.
266 range_iterator I = Ranges.begin(), E = Ranges.end();
267
268 while (I != E && Start > I->End)
269 ++I;
270
271 // We now know that I == E, in which case we didn't find anything to merge
272 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
273 // to insert a new range. Handle this now.
274 if (I == E || End < I->Start) {
275 MemsetRange &R = *Ranges.insert(I, MemsetRange());
276 R.Start = Start;
277 R.End = End;
278 R.StartPtr = SI->getPointerOperand();
279 R.Alignment = SI->getAlignment();
280 R.TheStores.push_back(SI);
281 return;
282 }
283
284 // This store overlaps with I, add it.
285 I->TheStores.push_back(SI);
286
287 // At this point, we may have an interval that completely contains our store.
288 // If so, just add it to the interval and return.
289 if (I->Start <= Start && I->End >= End)
290 return;
291
292 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
293 // but is not entirely contained within the range.
294
295 // See if the range extends the start of the range. In this case, it couldn't
296 // possibly cause it to join the prior range, because otherwise we would have
297 // stopped on *it*.
298 if (Start < I->Start) {
299 I->Start = Start;
300 I->StartPtr = SI->getPointerOperand();
Dan Gohman264d2452009-09-14 23:39:10 +0000301 I->Alignment = SI->getAlignment();
Owen Andersona723d1e2008-04-09 08:23:16 +0000302 }
303
304 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
305 // is in or right at the end of I), and that End >= I->Start. Extend I out to
306 // End.
307 if (End > I->End) {
308 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000309 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000310 while (++NextI != E && End >= NextI->Start) {
311 // Merge the range in.
312 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
313 if (NextI->End > I->End)
314 I->End = NextI->End;
315 Ranges.erase(NextI);
316 NextI = I;
317 }
318 }
319}
320
321//===----------------------------------------------------------------------===//
322// MemCpyOpt Pass
323//===----------------------------------------------------------------------===//
324
325namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000326 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000327 MemoryDependenceAnalysis *MD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000328 bool runOnFunction(Function &F);
329 public:
330 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000331 MemCpyOpt() : FunctionPass(ID) {
332 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000333 MD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000334 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000335
336 private:
337 // This transformation requires dominator postdominator info
338 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
339 AU.setPreservesCFG();
340 AU.addRequired<DominatorTree>();
341 AU.addRequired<MemoryDependenceAnalysis>();
342 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000343 AU.addPreserved<AliasAnalysis>();
344 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000345 }
346
347 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000348 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
349 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000350 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000351 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
352 uint64_t cpyLen, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000353 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
354 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000355 bool processByValArgument(CallSite CS, unsigned ArgNo);
Owen Andersona723d1e2008-04-09 08:23:16 +0000356 bool iterateOnFunction(Function &F);
357 };
358
359 char MemCpyOpt::ID = 0;
360}
361
362// createMemCpyOptPass - The public interface to this file...
363FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
364
Owen Anderson2ab36d32010-10-12 19:48:12 +0000365INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
366 false, false)
367INITIALIZE_PASS_DEPENDENCY(DominatorTree)
368INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
369INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
370INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
371 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000372
Owen Andersona723d1e2008-04-09 08:23:16 +0000373/// processStore - When GVN is scanning forward over instructions, we look for
374/// some other patterns to fold away. In particular, this looks for stores to
375/// neighboring locations of memory. If it sees enough consequtive ones
376/// (currently 4) it attempts to merge them together into a memcpy/memset.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000377bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000378 if (SI->isVolatile()) return false;
379
Owen Anderson65491212010-10-15 22:52:12 +0000380 TargetData *TD = getAnalysisIfAvailable<TargetData>();
381 if (!TD) return false;
382
383 // Detect cases where we're performing call slot forwarding, but
384 // happen to be using a load-store pair to implement it, rather than
385 // a memcpy.
386 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
387 if (!LI->isVolatile() && LI->hasOneUse()) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000388 MemDepResult dep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000389 CallInst *C = 0;
390 if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
391 C = dyn_cast<CallInst>(dep.getInst());
392
393 if (C) {
394 bool changed = performCallSlotOptzn(LI,
395 SI->getPointerOperand()->stripPointerCasts(),
396 LI->getPointerOperand()->stripPointerCasts(),
397 TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
398 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000399 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000400 SI->eraseFromParent();
401 LI->eraseFromParent();
402 ++NumMemCpyInstr;
403 return true;
404 }
405 }
406 }
407 }
408
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000409 LLVMContext &Context = SI->getContext();
410
Owen Andersona723d1e2008-04-09 08:23:16 +0000411 // There are two cases that are interesting for this code to handle: memcpy
412 // and memset. Right now we only handle memset.
413
414 // Ensure that the value being stored is something that can be memset'able a
415 // byte at a time like "0" or "-1" or any width, as well as things like
416 // 0xA0A0A0A0 and 0.0.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000417 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
Owen Andersona723d1e2008-04-09 08:23:16 +0000418 if (!ByteVal)
419 return false;
420
Owen Andersona723d1e2008-04-09 08:23:16 +0000421 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohmana195b7f2009-07-28 00:37:06 +0000422 Module *M = SI->getParent()->getParent()->getParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000423
424 // Okay, so we now have a single store that can be splatable. Scan to find
425 // all subsequent stores of the same value to offset from the same pointer.
426 // Join these together into ranges, so we can decide whether contiguous blocks
427 // are stored.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000428 MemsetRanges Ranges(*TD);
Owen Andersona723d1e2008-04-09 08:23:16 +0000429
430 Value *StartPtr = SI->getPointerOperand();
431
432 BasicBlock::iterator BI = SI;
433 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
434 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
435 // If the call is readnone, ignore it, otherwise bail out. We don't even
436 // allow readonly here because we don't want something like:
437 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Gabor Greifa292b2f2010-07-27 16:44:23 +0000438 if (AA.getModRefBehavior(CallSite(BI)) ==
Owen Andersona723d1e2008-04-09 08:23:16 +0000439 AliasAnalysis::DoesNotAccessMemory)
440 continue;
441
442 // TODO: If this is a memset, try to join it in.
443
444 break;
445 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
446 break;
447
448 // If this is a non-store instruction it is fine, ignore it.
449 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
450 if (NextStore == 0) continue;
451
452 // If this is a store, see if we can merge it in.
453 if (NextStore->isVolatile()) break;
454
455 // Check to see if this stored value is of the same byte-splattable value.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000456 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
Owen Andersona723d1e2008-04-09 08:23:16 +0000457 break;
458
459 // Check to see if this store is to a constant offset from the start ptr.
460 int64_t Offset;
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000461 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000462 break;
463
464 Ranges.addStore(Offset, NextStore);
465 }
466
467 // If we have no ranges, then we just had a single store with nothing that
468 // could be merged in. This is a very common case of course.
469 if (Ranges.empty())
470 return false;
471
472 // If we had at least one store that could be merged in, add the starting
473 // store as well. We try to avoid this unless there is at least something
474 // interesting as a small compile-time optimization.
475 Ranges.addStore(0, SI);
Owen Andersona723d1e2008-04-09 08:23:16 +0000476
Owen Andersona723d1e2008-04-09 08:23:16 +0000477
478 // Now that we have full information about ranges, loop over the ranges and
479 // emit memset's for anything big enough to be worthwhile.
480 bool MadeChange = false;
481 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
482 I != E; ++I) {
483 const MemsetRange &Range = *I;
484
485 if (Range.TheStores.size() == 1) continue;
486
487 // If it is profitable to lower this range to memset, do so now.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000488 if (!Range.isProfitableToUseMemset(*TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000489 continue;
490
491 // Otherwise, we do want to transform this! Create a new memset. We put
492 // the memset right before the first instruction that isn't part of this
493 // memset block. This ensure that the memset is dominated by any addressing
494 // instruction needed by the start of the block.
495 BasicBlock::iterator InsertPt = BI;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000496
Owen Andersona723d1e2008-04-09 08:23:16 +0000497 // Get the starting pointer of the block.
498 StartPtr = Range.StartPtr;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000499
500 // Determine alignment
501 unsigned Alignment = Range.Alignment;
502 if (Alignment == 0) {
503 const Type *EltType =
504 cast<PointerType>(StartPtr->getType())->getElementType();
505 Alignment = TD->getABITypeAlignment(EltType);
506 }
507
Owen Andersona723d1e2008-04-09 08:23:16 +0000508 // Cast the start ptr to be i8* as memset requires.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000509 const PointerType* StartPTy = cast<PointerType>(StartPtr->getType());
510 const PointerType *i8Ptr = Type::getInt8PtrTy(Context,
511 StartPTy->getAddressSpace());
512 if (StartPTy!= i8Ptr)
Daniel Dunbar460f6562009-07-26 09:48:23 +0000513 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getName(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000514 InsertPt);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000515
Owen Andersona723d1e2008-04-09 08:23:16 +0000516 Value *Ops[] = {
517 StartPtr, ByteVal, // Start, value
Owen Andersone922c022009-07-22 00:24:57 +0000518 // size
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000519 ConstantInt::get(Type::getInt64Ty(Context), Range.End-Range.Start),
Owen Andersone922c022009-07-22 00:24:57 +0000520 // align
Mon P Wang20adc9d2010-04-04 03:10:48 +0000521 ConstantInt::get(Type::getInt32Ty(Context), Alignment),
522 // volatile
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000523 ConstantInt::getFalse(Context),
Owen Andersona723d1e2008-04-09 08:23:16 +0000524 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000525 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
526
527 Function *MemSetF = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
528
529 Value *C = CallInst::Create(MemSetF, Ops, Ops+5, "", InsertPt);
David Greenecb33fd12010-01-05 01:27:47 +0000530 DEBUG(dbgs() << "Replace stores:\n";
Owen Andersona723d1e2008-04-09 08:23:16 +0000531 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000532 dbgs() << *Range.TheStores[i] << '\n';
Jeffrey Yasskin8e68c382010-12-23 00:58:24 +0000533 dbgs() << "With: " << *C << '\n'); (void)C;
Owen Andersona723d1e2008-04-09 08:23:16 +0000534
Owen Andersona8bd6582008-04-21 07:45:10 +0000535 // Don't invalidate the iterator
536 BBI = BI;
537
Owen Andersona723d1e2008-04-09 08:23:16 +0000538 // Zap all the stores.
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000539 for (SmallVector<StoreInst*, 16>::const_iterator
540 SI = Range.TheStores.begin(),
Owen Andersona8bd6582008-04-21 07:45:10 +0000541 SE = Range.TheStores.end(); SI != SE; ++SI)
542 (*SI)->eraseFromParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000543 ++NumMemSetInfer;
544 MadeChange = true;
545 }
546
547 return MadeChange;
548}
549
550
551/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
552/// and checks for the possibility of a call slot optimization by having
553/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000554bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
555 Value *cpyDest, Value *cpySrc,
556 uint64_t cpyLen, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000557 // The general transformation to keep in mind is
558 //
559 // call @func(..., src, ...)
560 // memcpy(dest, src, ...)
561 //
562 // ->
563 //
564 // memcpy(dest, src, ...)
565 // call @func(..., dest, ...)
566 //
567 // Since moving the memcpy is technically awkward, we additionally check that
568 // src only holds uninitialized values at the moment of the call, meaning that
569 // the memcpy can be discarded rather than moved.
570
571 // Deliberately get the source and destination with bitcasts stripped away,
572 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000573 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000574
Owen Andersona723d1e2008-04-09 08:23:16 +0000575 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000576 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000577 if (!srcAlloca)
578 return false;
579
580 // Check that all of src is copied to dest.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000581 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000582 if (!TD) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000583
Chris Lattner61c6ba82009-09-01 17:09:55 +0000584 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000585 if (!srcArraySize)
586 return false;
587
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000588 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000589 srcArraySize->getZExtValue();
590
Owen Anderson65491212010-10-15 22:52:12 +0000591 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000592 return false;
593
594 // Check that accessing the first srcSize bytes of dest will not cause a
595 // trap. Otherwise the transform is invalid since it might cause a trap
596 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000597 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000598 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000599 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000600 if (!destArraySize)
601 return false;
602
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000603 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000604 destArraySize->getZExtValue();
605
606 if (destSize < srcSize)
607 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000608 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000609 // If the destination is an sret parameter then only accesses that are
610 // outside of the returned struct type can trap.
611 if (!A->hasStructRetAttr())
612 return false;
613
Chris Lattner61c6ba82009-09-01 17:09:55 +0000614 const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000615 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000616
617 if (destSize < srcSize)
618 return false;
619 } else {
620 return false;
621 }
622
623 // Check that src is not accessed except via the call and the memcpy. This
624 // guarantees that it holds only undefined values when passed in (so the final
625 // memcpy can be dropped), that it is not read or written between the call and
626 // the memcpy, and that writing beyond the end of it is undefined.
627 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
628 srcAlloca->use_end());
629 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000630 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000631
Owen Anderson009e4f72008-06-01 22:26:26 +0000632 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000633 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
634 I != E; ++I)
635 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000636 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000637 if (G->hasAllZeroIndices())
638 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
639 I != E; ++I)
640 srcUseList.push_back(*I);
641 else
642 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000643 } else if (UI != C && UI != cpy) {
644 return false;
645 }
646 }
647
648 // Since we're changing the parameter to the callsite, we need to make sure
649 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000650 DominatorTree &DT = getAnalysis<DominatorTree>();
651 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000652 if (!DT.dominates(cpyDestInst, C))
653 return false;
654
655 // In addition to knowing that the call does not access src in some
656 // unexpected manner, for example via a global, which we deduce from
657 // the use analysis, we also need to know that it does not sneakily
658 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000659 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson65491212010-10-15 22:52:12 +0000660 if (AA.getModRefInfo(C, cpyDest, srcSize) !=
Owen Andersona723d1e2008-04-09 08:23:16 +0000661 AliasAnalysis::NoModRef)
662 return false;
663
664 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000665 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000666 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000667 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000668 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000669 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000670 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000671 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000672 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000673 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000674 else
675 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
676 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000677 }
678
Owen Anderson12cb36c2008-06-01 21:52:16 +0000679 if (!changedArgument)
680 return false;
681
Owen Andersona723d1e2008-04-09 08:23:16 +0000682 // Drop any cached information about the call, because we may have changed
683 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000684 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000685
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000686 // Remove the memcpy.
687 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000688 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000689
690 return true;
691}
692
Chris Lattner43f8e432010-11-18 07:02:37 +0000693/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
694/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
695/// copy from MDep's input if we can. MSize is the size of M's copy.
696///
697bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
698 uint64_t MSize) {
699 // We can only transforms memcpy's where the dest of one is the source of the
700 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000701 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000702 return false;
703
Chris Lattnerf7f35462010-12-09 07:39:50 +0000704 // If dep instruction is reading from our current input, then it is a noop
705 // transfer and substituting the input won't change this instruction. Just
706 // ignore the input and let someone else zap MDep. This handles cases like:
707 // memcpy(a <- a)
708 // memcpy(b <- a)
709 if (M->getSource() == MDep->getSource())
710 return false;
711
Chris Lattner43f8e432010-11-18 07:02:37 +0000712 // Second, the length of the memcpy's must be the same, or the preceeding one
713 // must be larger than the following one.
714 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
715 if (!C1) return false;
716
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000717 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000718
719 // Verify that the copied-from memory doesn't change in between the two
720 // transfers. For example, in:
721 // memcpy(a <- b)
722 // *b = 42;
723 // memcpy(c <- a)
724 // It would be invalid to transform the second memcpy into memcpy(c <- b).
725 //
726 // TODO: If the code between M and MDep is transparent to the destination "c",
727 // then we could still perform the xform by moving M up to the first memcpy.
728 //
729 // NOTE: This is conservative, it will stop on any read from the source loc,
730 // not just the defining memcpy.
731 MemDepResult SourceDep =
732 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
733 false, M, M->getParent());
734 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
735 return false;
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000736
737 // If the dest of the second might alias the source of the first, then the
738 // source and dest might overlap. We still want to eliminate the intermediate
739 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000740 Intrinsic::ID ResultFn = Intrinsic::memcpy;
Dan Gohman387f28a2010-12-16 02:51:19 +0000741 if (AA.alias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)) !=
742 AliasAnalysis::NoAlias)
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000743 ResultFn = Intrinsic::memmove;
Chris Lattner43f8e432010-11-18 07:02:37 +0000744
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000745 // If all checks passed, then we can transform M.
Chris Lattner245b7f62010-11-18 07:38:43 +0000746 const Type *ArgTys[3] = {
747 M->getRawDest()->getType(),
Chris Lattner43f8e432010-11-18 07:02:37 +0000748 MDep->getRawSource()->getType(),
Chris Lattner245b7f62010-11-18 07:38:43 +0000749 M->getLength()->getType()
750 };
Chris Lattner43f8e432010-11-18 07:02:37 +0000751 Function *MemCpyFun =
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000752 Intrinsic::getDeclaration(MDep->getParent()->getParent()->getParent(),
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000753 ResultFn, ArgTys, 3);
Chris Lattner43f8e432010-11-18 07:02:37 +0000754
755 // Make sure to use the lesser of the alignment of the source and the dest
756 // since we're changing where we're reading from, but don't want to increase
757 // the alignment past what can be read from or written to.
758 // TODO: Is this worth it if we're creating a less aligned memcpy? For
759 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000760 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Chris Lattner43f8e432010-11-18 07:02:37 +0000761 Value *Args[5] = {
Chris Lattnerd528be62010-11-18 08:07:09 +0000762 M->getRawDest(),
763 MDep->getRawSource(),
764 M->getLength(),
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000765 ConstantInt::get(Type::getInt32Ty(MemCpyFun->getContext()), Align),
Chris Lattnerd528be62010-11-18 08:07:09 +0000766 M->getVolatileCst()
Chris Lattner43f8e432010-11-18 07:02:37 +0000767 };
Chris Lattner604f6fe2010-11-21 08:06:10 +0000768 CallInst::Create(MemCpyFun, Args, Args+5, "", M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000769
Chris Lattner604f6fe2010-11-21 08:06:10 +0000770 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000771 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000772 M->eraseFromParent();
773 ++NumMemCpyInstr;
774 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000775}
776
777
Gabor Greif7d3056b2010-07-28 22:50:26 +0000778/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
779/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
780/// B to be a memcpy from X to Z (or potentially a memmove, depending on
781/// circumstances). This allows later passes to remove the first memcpy
782/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000783bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000784 // We can only optimize statically-sized memcpy's that are non-volatile.
785 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
786 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000787
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000788 // If the source and destination of the memcpy are the same, then zap it.
789 if (M->getSource() == M->getDest()) {
790 MD->removeInstruction(M);
791 M->eraseFromParent();
792 return false;
793 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000794
795 // If copying from a constant, try to turn the memcpy into a memset.
796 if (Value *ByteVal = isBytewiseValue(M->getSource())) {
797 Value *Ops[] = {
798 M->getRawDest(), ByteVal, // Start, value
799 CopySize, // Size
800 M->getAlignmentCst(), // Alignment
801 ConstantInt::getFalse(M->getContext()), // volatile
802 };
803 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
804 Module *Mod = M->getParent()->getParent()->getParent();
805 Function *MemSetF = Intrinsic::getDeclaration(Mod, Intrinsic::memset, Tys, 2);
806 CallInst::Create(MemSetF, Ops, Ops+5, "", M);
807 M->eraseFromParent();
808 ++NumCpyToSet;
809 return true;
810 }
811
Owen Andersona8bd6582008-04-21 07:45:10 +0000812 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000813 // a) memcpy-memcpy xform which exposes redundance for DSE.
814 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000815 MemDepResult DepInfo = MD->getDependency(M);
816 if (!DepInfo.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000817 return false;
Owen Andersona8bd6582008-04-21 07:45:10 +0000818
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000819 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()))
820 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Owen Andersona723d1e2008-04-09 08:23:16 +0000821
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000822 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000823 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
824 CopySize->getZExtValue(), C)) {
825 M->eraseFromParent();
826 return true;
827 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000828 }
Owen Anderson02e99882008-04-29 21:51:00 +0000829 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000830}
831
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000832/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
833/// are guaranteed not to alias.
834bool MemCpyOpt::processMemMove(MemMoveInst *M) {
835 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
836
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000837 // See if the pointers alias.
Dan Gohman387f28a2010-12-16 02:51:19 +0000838 if (AA.alias(AA.getLocationForDest(M),
839 AA.getLocationForSource(M)) !=
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000840 AliasAnalysis::NoAlias)
841 return false;
842
David Greenecb33fd12010-01-05 01:27:47 +0000843 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000844
845 // If not, then we know we can transform this.
846 Module *Mod = M->getParent()->getParent()->getParent();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000847 const Type *ArgTys[3] = { M->getRawDest()->getType(),
848 M->getRawSource()->getType(),
849 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000850 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
851 ArgTys, 3));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000852
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000853 // MemDep may have over conservative information about this instruction, just
854 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000855 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000856
857 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000858 return true;
859}
860
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000861/// processByValArgument - This is called on every byval argument in call sites.
862bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
863 TargetData *TD = getAnalysisIfAvailable<TargetData>();
864 if (!TD) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000865
Chris Lattner604f6fe2010-11-21 08:06:10 +0000866 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000867 Value *ByValArg = CS.getArgument(ArgNo);
Chris Lattnerb5a31962010-12-01 01:24:55 +0000868 const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType();
869 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000870 MemDepResult DepInfo =
871 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
872 true, CS.getInstruction(),
873 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000874 if (!DepInfo.isClobber())
875 return false;
876
877 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
878 // a memcpy, see if we can byval from the source of the memcpy instead of the
879 // result.
880 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
881 if (MDep == 0 || MDep->isVolatile() ||
882 ByValArg->stripPointerCasts() != MDep->getDest())
883 return false;
884
885 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000886 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000887 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000888 return false;
889
890 // Get the alignment of the byval. If it is greater than the memcpy, then we
891 // can't do the substitution. If the call doesn't specify the alignment, then
892 // it is some target specific value that we can't know.
893 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
894 if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign)
895 return false;
896
897 // Verify that the copied-from memory doesn't change in between the memcpy and
898 // the byval call.
899 // memcpy(a <- b)
900 // *b = 42;
901 // foo(*a)
902 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000903 //
904 // NOTE: This is conservative, it will stop on any read from the source loc,
905 // not just the defining memcpy.
906 MemDepResult SourceDep =
907 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
908 false, CS.getInstruction(), MDep->getParent());
909 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
910 return false;
911
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000912 Value *TmpCast = MDep->getSource();
913 if (MDep->getSource()->getType() != ByValArg->getType())
914 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
915 "tmpcast", CS.getInstruction());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000916
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000917 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
918 << " " << *MDep << "\n"
919 << " " << *CS.getInstruction() << "\n");
920
921 // Otherwise we're good! Update the byval argument.
922 CS.setArgument(ArgNo, TmpCast);
923 ++NumMemCpyInstr;
924 return true;
925}
926
927/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000928bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000929 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000930
Chris Lattner61c6ba82009-09-01 17:09:55 +0000931 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000932 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000933 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000934 // Avoid invalidating the iterator.
935 Instruction *I = BI++;
Owen Andersona8bd6582008-04-21 07:45:10 +0000936
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000937 bool RepeatInstruction = false;
938
Owen Andersona8bd6582008-04-21 07:45:10 +0000939 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000940 MadeChange |= processStore(SI, BI);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000941 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) {
942 RepeatInstruction = processMemCpy(M);
943 } else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) {
944 RepeatInstruction = processMemMove(M);
945 } else if (CallSite CS = (Value*)I) {
946 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
947 if (CS.paramHasAttr(i+1, Attribute::ByVal))
948 MadeChange |= processByValArgument(CS, i);
949 }
950
951 // Reprocess the instruction if desired.
952 if (RepeatInstruction) {
953 --BI;
954 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000955 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000956 }
957 }
958
Chris Lattner61c6ba82009-09-01 17:09:55 +0000959 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000960}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000961
962// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
963// function.
964//
965bool MemCpyOpt::runOnFunction(Function &F) {
966 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000967 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000968 while (1) {
969 if (!iterateOnFunction(F))
970 break;
971 MadeChange = true;
972 }
973
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000974 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000975 return MadeChange;
976}