blob: 2603c969c5acf6333d8517de533b9d66c0cf979d [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"
Owen Andersona723d1e2008-04-09 08:23:16 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000019#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattnerbb897102010-12-26 20:15:01 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Stephen Hines36b56882014-04-23 16:57:46 -070023#include "llvm/IR/Dominators.h"
24#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/GlobalVariable.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000029#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner149f5282011-05-01 18:27:11 +000031#include "llvm/Target/TargetLibraryInfo.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Transforms/Utils/Local.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000033#include <list>
34using namespace llvm;
35
36STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
37STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000038STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000039STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000040
Benjamin Kramer39acdb02012-09-13 16:29:49 +000041static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Micah Villmow3574eca2012-10-08 16:38:25 +000042 bool &VariableIdxFound, const DataLayout &TD){
Owen Andersona723d1e2008-04-09 08:23:16 +000043 // Skip over the first indices.
44 gep_type_iterator GTI = gep_type_begin(GEP);
45 for (unsigned i = 1; i != Idx; ++i, ++GTI)
46 /*skip along*/;
Nadav Rotema94d6e82012-07-24 10:51:42 +000047
Owen Andersona723d1e2008-04-09 08:23:16 +000048 // Compute the offset implied by the rest of the indices.
49 int64_t Offset = 0;
50 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
51 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
52 if (OpC == 0)
53 return VariableIdxFound = true;
54 if (OpC->isZero()) continue; // No offset.
55
56 // Handle struct indices, which add their field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000057 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +000058 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
59 continue;
60 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000061
Owen Andersona723d1e2008-04-09 08:23:16 +000062 // Otherwise, we have a sequential type like an array or vector. Multiply
63 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +000064 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +000065 Offset += Size*OpC->getSExtValue();
66 }
67
68 return Offset;
69}
70
71/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
72/// constant offset, and return that constant offset. For example, Ptr1 might
73/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
74static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Micah Villmow3574eca2012-10-08 16:38:25 +000075 const DataLayout &TD) {
Chris Lattner2d5c0cd2011-01-12 01:43:46 +000076 Ptr1 = Ptr1->stripPointerCasts();
77 Ptr2 = Ptr2->stripPointerCasts();
Stephen Hines36b56882014-04-23 16:57:46 -070078
79 // Handle the trivial case first.
80 if (Ptr1 == Ptr2) {
81 Offset = 0;
82 return true;
83 }
84
Benjamin Kramer39acdb02012-09-13 16:29:49 +000085 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
86 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotema94d6e82012-07-24 10:51:42 +000087
Chris Lattner9fa11e92011-01-08 21:07:56 +000088 bool VariableIdxFound = false;
89
90 // If one pointer is a GEP and the other isn't, then see if the GEP is a
91 // constant offset from the base, as in "P" and "gep P, 1".
92 if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
93 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
94 return !VariableIdxFound;
95 }
96
97 if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
98 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
99 return !VariableIdxFound;
100 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000101
Owen Andersona723d1e2008-04-09 08:23:16 +0000102 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
103 // base. After that base, they may have some number of common (and
104 // potentially variable) indices. After that they handle some constant
105 // offset, which determines their offset from each other. At this point, we
106 // handle no other case.
Owen Andersona723d1e2008-04-09 08:23:16 +0000107 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
108 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000109
Owen Andersona723d1e2008-04-09 08:23:16 +0000110 // Skip any common indices and track the GEP types.
111 unsigned Idx = 1;
112 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
113 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
114 break;
115
Owen Andersona723d1e2008-04-09 08:23:16 +0000116 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
117 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
118 if (VariableIdxFound) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000119
Owen Andersona723d1e2008-04-09 08:23:16 +0000120 Offset = Offset2-Offset1;
121 return true;
122}
123
124
125/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
126/// This allows us to analyze stores like:
127/// store 0 -> P+1
128/// store 0 -> P+0
129/// store 0 -> P+3
130/// store 0 -> P+2
131/// which sometimes happens with stores to arrays of structs etc. When we see
132/// the first store, we make a range [1, 2). The second store extends the range
133/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
134/// two ranges into [0, 3) which is memset'able.
135namespace {
136struct MemsetRange {
137 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000138 // The range is closed at the start and open at the end: [Start, End).
Owen Andersona723d1e2008-04-09 08:23:16 +0000139 int64_t Start, End;
140
141 /// StartPtr - The getelementptr instruction that points to the start of the
142 /// range.
143 Value *StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000144
Owen Andersona723d1e2008-04-09 08:23:16 +0000145 /// Alignment - The known alignment of the first store.
146 unsigned Alignment;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000147
Owen Andersona723d1e2008-04-09 08:23:16 +0000148 /// TheStores - The actual stores that make up this range.
Chris Lattner06511262011-01-08 20:54:51 +0000149 SmallVector<Instruction*, 16> TheStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000150
Micah Villmow3574eca2012-10-08 16:38:25 +0000151 bool isProfitableToUseMemset(const DataLayout &TD) const;
Owen Andersona723d1e2008-04-09 08:23:16 +0000152
153};
154} // end anon namespace
155
Micah Villmow3574eca2012-10-08 16:38:25 +0000156bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
Chad Rosiera4b6fd52011-12-05 22:53:09 +0000157 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosierd8bd26e2011-12-05 22:37:00 +0000158 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner06511262011-01-08 20:54:51 +0000159
160 // If there is nothing to merge, don't do anything.
161 if (TheStores.size() < 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000162
Chris Lattner06511262011-01-08 20:54:51 +0000163 // If any of the stores are a memset, then it is always good to extend the
164 // memset.
165 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
166 if (!isa<StoreInst>(TheStores[i]))
167 return true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000168
Owen Andersona723d1e2008-04-09 08:23:16 +0000169 // Assume that the code generator is capable of merging pairs of stores
170 // together if it wants to.
Chris Lattner06511262011-01-08 20:54:51 +0000171 if (TheStores.size() == 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000172
Owen Andersona723d1e2008-04-09 08:23:16 +0000173 // If we have fewer than 8 stores, it can still be worthwhile to do this.
174 // For example, merging 4 i8 stores into an i32 store is useful almost always.
175 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
176 // memset will be split into 2 32-bit stores anyway) and doing so can
177 // pessimize the llvm optimizer.
178 //
179 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault4b28ee22013-09-16 22:43:16 +0000180 // the maximum GPR width is the same size as the largest legal integer
181 // size. If so, check to see whether we will end up actually reducing the
182 // number of stores used.
Owen Andersona723d1e2008-04-09 08:23:16 +0000183 unsigned Bytes = unsigned(End-Start);
Matt Arsenault4b28ee22013-09-16 22:43:16 +0000184 unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
185 if (MaxIntSize == 0)
186 MaxIntSize = 1;
187 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000188
Owen Andersona723d1e2008-04-09 08:23:16 +0000189 // Assume the remaining bytes if any are done a byte at a time.
Matt Arsenault4b28ee22013-09-16 22:43:16 +0000190 unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000191
Owen Andersona723d1e2008-04-09 08:23:16 +0000192 // If we will reduce the # stores (according to this heuristic), do the
193 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
194 // etc.
195 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000196}
Owen Andersona723d1e2008-04-09 08:23:16 +0000197
198
199namespace {
200class MemsetRanges {
201 /// Ranges - A sorted list of the memset ranges. We use std::list here
202 /// because each element is relatively large and expensive to copy.
203 std::list<MemsetRange> Ranges;
204 typedef std::list<MemsetRange>::iterator range_iterator;
Stephen Hines36b56882014-04-23 16:57:46 -0700205 const DataLayout &DL;
Owen Andersona723d1e2008-04-09 08:23:16 +0000206public:
Stephen Hines36b56882014-04-23 16:57:46 -0700207 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000208
Owen Andersona723d1e2008-04-09 08:23:16 +0000209 typedef std::list<MemsetRange>::const_iterator const_iterator;
210 const_iterator begin() const { return Ranges.begin(); }
211 const_iterator end() const { return Ranges.end(); }
212 bool empty() const { return Ranges.empty(); }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000213
Chris Lattner67a716a2011-01-08 20:24:01 +0000214 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner06511262011-01-08 20:54:51 +0000215 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
216 addStore(OffsetFromFirst, SI);
217 else
218 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattner67a716a2011-01-08 20:24:01 +0000219 }
Chris Lattner06511262011-01-08 20:54:51 +0000220
221 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Stephen Hines36b56882014-04-23 16:57:46 -0700222 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000223
Chris Lattner06511262011-01-08 20:54:51 +0000224 addRange(OffsetFromFirst, StoreSize,
225 SI->getPointerOperand(), SI->getAlignment(), SI);
226 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000227
Chris Lattner06511262011-01-08 20:54:51 +0000228 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
229 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
230 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
231 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000232
Chris Lattner06511262011-01-08 20:54:51 +0000233 void addRange(int64_t Start, int64_t Size, Value *Ptr,
234 unsigned Alignment, Instruction *Inst);
235
Owen Andersona723d1e2008-04-09 08:23:16 +0000236};
Nadav Rotema94d6e82012-07-24 10:51:42 +0000237
Owen Andersona723d1e2008-04-09 08:23:16 +0000238} // end anon namespace
239
240
Chris Lattner06511262011-01-08 20:54:51 +0000241/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersona723d1e2008-04-09 08:23:16 +0000242/// new range for the specified store at the specified offset, merging into
243/// existing ranges as appropriate.
Chris Lattner06511262011-01-08 20:54:51 +0000244///
245/// Do a linear search of the ranges to see if this can be joined and/or to
246/// find the insertion point in the list. We keep the ranges sorted for
247/// simplicity here. This is a linear search of a linked list, which is ugly,
248/// however the number of ranges is limited, so this won't get crazy slow.
249void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
250 unsigned Alignment, Instruction *Inst) {
251 int64_t End = Start+Size;
Owen Andersona723d1e2008-04-09 08:23:16 +0000252 range_iterator I = Ranges.begin(), E = Ranges.end();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000253
Owen Andersona723d1e2008-04-09 08:23:16 +0000254 while (I != E && Start > I->End)
255 ++I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000256
Owen Andersona723d1e2008-04-09 08:23:16 +0000257 // We now know that I == E, in which case we didn't find anything to merge
258 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
259 // to insert a new range. Handle this now.
260 if (I == E || End < I->Start) {
261 MemsetRange &R = *Ranges.insert(I, MemsetRange());
262 R.Start = Start;
263 R.End = End;
Chris Lattner06511262011-01-08 20:54:51 +0000264 R.StartPtr = Ptr;
265 R.Alignment = Alignment;
266 R.TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000267 return;
268 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000269
Owen Andersona723d1e2008-04-09 08:23:16 +0000270 // This store overlaps with I, add it.
Chris Lattner06511262011-01-08 20:54:51 +0000271 I->TheStores.push_back(Inst);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000272
Owen Andersona723d1e2008-04-09 08:23:16 +0000273 // At this point, we may have an interval that completely contains our store.
274 // If so, just add it to the interval and return.
275 if (I->Start <= Start && I->End >= End)
276 return;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000277
Owen Andersona723d1e2008-04-09 08:23:16 +0000278 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
279 // but is not entirely contained within the range.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000280
Owen Andersona723d1e2008-04-09 08:23:16 +0000281 // See if the range extends the start of the range. In this case, it couldn't
282 // possibly cause it to join the prior range, because otherwise we would have
283 // stopped on *it*.
284 if (Start < I->Start) {
285 I->Start = Start;
Chris Lattner06511262011-01-08 20:54:51 +0000286 I->StartPtr = Ptr;
287 I->Alignment = Alignment;
Owen Andersona723d1e2008-04-09 08:23:16 +0000288 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000289
Owen Andersona723d1e2008-04-09 08:23:16 +0000290 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
291 // is in or right at the end of I), and that End >= I->Start. Extend I out to
292 // End.
293 if (End > I->End) {
294 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000295 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000296 while (++NextI != E && End >= NextI->Start) {
297 // Merge the range in.
298 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
299 if (NextI->End > I->End)
300 I->End = NextI->End;
301 Ranges.erase(NextI);
302 NextI = I;
303 }
304 }
305}
306
307//===----------------------------------------------------------------------===//
308// MemCpyOpt Pass
309//===----------------------------------------------------------------------===//
310
311namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000312 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000313 MemoryDependenceAnalysis *MD;
Chris Lattner149f5282011-05-01 18:27:11 +0000314 TargetLibraryInfo *TLI;
Stephen Hines36b56882014-04-23 16:57:46 -0700315 const DataLayout *DL;
Owen Andersona723d1e2008-04-09 08:23:16 +0000316 public:
317 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000318 MemCpyOpt() : FunctionPass(ID) {
319 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000320 MD = 0;
Chris Lattner149f5282011-05-01 18:27:11 +0000321 TLI = 0;
Stephen Hines36b56882014-04-23 16:57:46 -0700322 DL = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000323 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000324
Stephen Hines36b56882014-04-23 16:57:46 -0700325 bool runOnFunction(Function &F) override;
Chris Lattner67a716a2011-01-08 20:24:01 +0000326
Owen Andersona723d1e2008-04-09 08:23:16 +0000327 private:
328 // This transformation requires dominator postdominator info
Stephen Hines36b56882014-04-23 16:57:46 -0700329 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersona723d1e2008-04-09 08:23:16 +0000330 AU.setPreservesCFG();
Stephen Hines36b56882014-04-23 16:57:46 -0700331 AU.addRequired<DominatorTreeWrapperPass>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000332 AU.addRequired<MemoryDependenceAnalysis>();
333 AU.addRequired<AliasAnalysis>();
Chris Lattner149f5282011-05-01 18:27:11 +0000334 AU.addRequired<TargetLibraryInfo>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000335 AU.addPreserved<AliasAnalysis>();
336 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000337 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000338
Owen Andersona723d1e2008-04-09 08:23:16 +0000339 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000340 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000341 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000342 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000343 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000344 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000345 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000346 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
347 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000348 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattner67a716a2011-01-08 20:24:01 +0000349 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
350 Value *ByteVal);
351
Owen Andersona723d1e2008-04-09 08:23:16 +0000352 bool iterateOnFunction(Function &F);
353 };
Nadav Rotema94d6e82012-07-24 10:51:42 +0000354
Owen Andersona723d1e2008-04-09 08:23:16 +0000355 char MemCpyOpt::ID = 0;
356}
357
358// createMemCpyOptPass - The public interface to this file...
359FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
360
Owen Anderson2ab36d32010-10-12 19:48:12 +0000361INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
362 false, false)
Stephen Hines36b56882014-04-23 16:57:46 -0700363INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000364INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chris Lattner149f5282011-05-01 18:27:11 +0000365INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000366INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
367INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
368 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000369
Chris Lattner67a716a2011-01-08 20:24:01 +0000370/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersona723d1e2008-04-09 08:23:16 +0000371/// some other patterns to fold away. In particular, this looks for stores to
Duncan Sandsab4c3662011-02-15 09:23:02 +0000372/// neighboring locations of memory. If it sees enough consecutive ones, it
Chris Lattner67a716a2011-01-08 20:24:01 +0000373/// attempts to merge them together into a memcpy/memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000374Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattner67a716a2011-01-08 20:24:01 +0000375 Value *StartPtr, Value *ByteVal) {
Stephen Hines36b56882014-04-23 16:57:46 -0700376 if (DL == 0) return 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000377
Chris Lattner67a716a2011-01-08 20:24:01 +0000378 // Okay, so we now have a single store that can be splatable. Scan to find
379 // all subsequent stores of the same value to offset from the same pointer.
380 // Join these together into ranges, so we can decide whether contiguous blocks
381 // are stored.
Stephen Hines36b56882014-04-23 16:57:46 -0700382 MemsetRanges Ranges(*DL);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000383
Chris Lattner67a716a2011-01-08 20:24:01 +0000384 BasicBlock::iterator BI = StartInst;
385 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner06511262011-01-08 20:54:51 +0000386 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
387 // If the instruction is readnone, ignore it, otherwise bail out. We
388 // don't even allow readonly here because we don't want something like:
Chris Lattner67a716a2011-01-08 20:24:01 +0000389 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner06511262011-01-08 20:54:51 +0000390 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
391 break;
392 continue;
393 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000394
Chris Lattner06511262011-01-08 20:54:51 +0000395 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
396 // If this is a store, see if we can merge it in.
Eli Friedman56efe242011-08-17 22:22:24 +0000397 if (!NextStore->isSimple()) break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000398
Chris Lattner06511262011-01-08 20:54:51 +0000399 // Check to see if this stored value is of the same byte-splattable value.
400 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
401 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000402
Chris Lattner06511262011-01-08 20:54:51 +0000403 // Check to see if this store is to a constant offset from the start ptr.
404 int64_t Offset;
Chris Lattnerf4268502011-01-09 19:26:10 +0000405 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
Stephen Hines36b56882014-04-23 16:57:46 -0700406 Offset, *DL))
Chris Lattner06511262011-01-08 20:54:51 +0000407 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000408
Chris Lattner06511262011-01-08 20:54:51 +0000409 Ranges.addStore(Offset, NextStore);
410 } else {
411 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000412
Chris Lattner06511262011-01-08 20:54:51 +0000413 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
414 !isa<ConstantInt>(MSI->getLength()))
415 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000416
Chris Lattner06511262011-01-08 20:54:51 +0000417 // Check to see if this store is to a constant offset from the start ptr.
418 int64_t Offset;
Stephen Hines36b56882014-04-23 16:57:46 -0700419 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
Chris Lattner06511262011-01-08 20:54:51 +0000420 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000421
Chris Lattner06511262011-01-08 20:54:51 +0000422 Ranges.addMemSet(Offset, MSI);
423 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000424 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000425
Chris Lattner67a716a2011-01-08 20:24:01 +0000426 // If we have no ranges, then we just had a single store with nothing that
427 // could be merged in. This is a very common case of course.
428 if (Ranges.empty())
429 return 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000430
Chris Lattner67a716a2011-01-08 20:24:01 +0000431 // If we had at least one store that could be merged in, add the starting
432 // store as well. We try to avoid this unless there is at least something
433 // interesting as a small compile-time optimization.
434 Ranges.addInst(0, StartInst);
435
436 // If we create any memsets, we put it right before the first instruction that
437 // isn't part of the memset block. This ensure that the memset is dominated
438 // by any addressing instruction needed by the start of the block.
439 IRBuilder<> Builder(BI);
440
441 // Now that we have full information about ranges, loop over the ranges and
442 // emit memset's for anything big enough to be worthwhile.
443 Instruction *AMemSet = 0;
444 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
445 I != E; ++I) {
446 const MemsetRange &Range = *I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000447
Chris Lattner67a716a2011-01-08 20:24:01 +0000448 if (Range.TheStores.size() == 1) continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000449
Chris Lattner67a716a2011-01-08 20:24:01 +0000450 // If it is profitable to lower this range to memset, do so now.
Stephen Hines36b56882014-04-23 16:57:46 -0700451 if (!Range.isProfitableToUseMemset(*DL))
Chris Lattner67a716a2011-01-08 20:24:01 +0000452 continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000453
Chris Lattner67a716a2011-01-08 20:24:01 +0000454 // Otherwise, we do want to transform this! Create a new memset.
455 // Get the starting pointer of the block.
456 StartPtr = Range.StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000457
Chris Lattner67a716a2011-01-08 20:24:01 +0000458 // Determine alignment
459 unsigned Alignment = Range.Alignment;
460 if (Alignment == 0) {
Nadav Rotema94d6e82012-07-24 10:51:42 +0000461 Type *EltType =
Chris Lattner67a716a2011-01-08 20:24:01 +0000462 cast<PointerType>(StartPtr->getType())->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700463 Alignment = DL->getABITypeAlignment(EltType);
Chris Lattner67a716a2011-01-08 20:24:01 +0000464 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000465
466 AMemSet =
Chris Lattner67a716a2011-01-08 20:24:01 +0000467 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000468
Chris Lattner67a716a2011-01-08 20:24:01 +0000469 DEBUG(dbgs() << "Replace stores:\n";
470 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
471 dbgs() << *Range.TheStores[i] << '\n';
472 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelb90584a2011-05-04 21:58:58 +0000473
474 if (!Range.TheStores.empty())
475 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
476
Chris Lattner67a716a2011-01-08 20:24:01 +0000477 // Zap all the stores.
Craig Topper365ef0b2013-07-03 15:07:05 +0000478 for (SmallVectorImpl<Instruction *>::const_iterator
Chris Lattner67a716a2011-01-08 20:24:01 +0000479 SI = Range.TheStores.begin(),
Chris Lattner8a629572011-01-08 22:19:21 +0000480 SE = Range.TheStores.end(); SI != SE; ++SI) {
481 MD->removeInstruction(*SI);
Chris Lattner67a716a2011-01-08 20:24:01 +0000482 (*SI)->eraseFromParent();
Chris Lattner8a629572011-01-08 22:19:21 +0000483 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000484 ++NumMemSetInfer;
485 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000486
Chris Lattner67a716a2011-01-08 20:24:01 +0000487 return AMemSet;
488}
489
490
Chris Lattner61c6ba82009-09-01 17:09:55 +0000491bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman56efe242011-08-17 22:22:24 +0000492 if (!SI->isSimple()) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000493
Stephen Hines36b56882014-04-23 16:57:46 -0700494 if (DL == 0) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000495
496 // Detect cases where we're performing call slot forwarding, but
497 // happen to be using a load-store pair to implement it, rather than
498 // a memcpy.
499 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman56efe242011-08-17 22:22:24 +0000500 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedman5d40ef22011-06-15 01:25:56 +0000501 LI->getParent() == SI->getParent()) {
Eli Friedman70d893e2011-06-02 21:24:42 +0000502 MemDepResult ldep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000503 CallInst *C = 0;
Eli Friedman70d893e2011-06-02 21:24:42 +0000504 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
505 C = dyn_cast<CallInst>(ldep.getInst());
506
507 if (C) {
508 // Check that nothing touches the dest of the "copy" between
509 // the call and the store.
Eli Friedman5d40ef22011-06-15 01:25:56 +0000510 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
511 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
512 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
513 E = C; I != E; --I) {
514 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
Eli Friedman70d893e2011-06-02 21:24:42 +0000515 C = 0;
Eli Friedman5d40ef22011-06-15 01:25:56 +0000516 break;
517 }
Eli Friedman70d893e2011-06-02 21:24:42 +0000518 }
519 }
520
Owen Anderson65491212010-10-15 22:52:12 +0000521 if (C) {
Duncan Sandsf5874752012-10-04 10:54:40 +0000522 unsigned storeAlign = SI->getAlignment();
523 if (!storeAlign)
Stephen Hines36b56882014-04-23 16:57:46 -0700524 storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
Duncan Sandsf5874752012-10-04 10:54:40 +0000525 unsigned loadAlign = LI->getAlignment();
526 if (!loadAlign)
Stephen Hines36b56882014-04-23 16:57:46 -0700527 loadAlign = DL->getABITypeAlignment(LI->getType());
Duncan Sandsf5874752012-10-04 10:54:40 +0000528
Owen Anderson65491212010-10-15 22:52:12 +0000529 bool changed = performCallSlotOptzn(LI,
Nadav Rotema94d6e82012-07-24 10:51:42 +0000530 SI->getPointerOperand()->stripPointerCasts(),
Owen Anderson65491212010-10-15 22:52:12 +0000531 LI->getPointerOperand()->stripPointerCasts(),
Stephen Hines36b56882014-04-23 16:57:46 -0700532 DL->getTypeStoreSize(SI->getOperand(0)->getType()),
Duncan Sandsf5874752012-10-04 10:54:40 +0000533 std::min(storeAlign, loadAlign), C);
Owen Anderson65491212010-10-15 22:52:12 +0000534 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000535 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000536 SI->eraseFromParent();
Chris Lattnerf4268502011-01-09 19:26:10 +0000537 MD->removeInstruction(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000538 LI->eraseFromParent();
539 ++NumMemCpyInstr;
540 return true;
541 }
542 }
543 }
544 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000545
Owen Andersona723d1e2008-04-09 08:23:16 +0000546 // There are two cases that are interesting for this code to handle: memcpy
547 // and memset. Right now we only handle memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000548
Owen Andersona723d1e2008-04-09 08:23:16 +0000549 // Ensure that the value being stored is something that can be memset'able a
550 // byte at a time like "0" or "-1" or any width, as well as things like
551 // 0xA0A0A0A0 and 0.0.
Chris Lattner67a716a2011-01-08 20:24:01 +0000552 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
553 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
554 ByteVal)) {
555 BBI = I; // Don't invalidate iterator.
556 return true;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000557 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000558
Chris Lattner67a716a2011-01-08 20:24:01 +0000559 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000560}
561
Chris Lattnerd90a1922011-01-08 21:19:19 +0000562bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
563 // See if there is another memset or store neighboring this memset which
564 // allows us to widen out the memset to do a single larger store.
Chris Lattner0468e3e2011-01-08 22:11:56 +0000565 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
566 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
567 MSI->getValue())) {
568 BBI = I; // Don't invalidate iterator.
569 return true;
570 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000571 return false;
572}
573
Owen Andersona723d1e2008-04-09 08:23:16 +0000574
575/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
576/// and checks for the possibility of a call slot optimization by having
577/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000578bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
579 Value *cpyDest, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000580 uint64_t cpyLen, unsigned cpyAlign,
581 CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000582 // The general transformation to keep in mind is
583 //
584 // call @func(..., src, ...)
585 // memcpy(dest, src, ...)
586 //
587 // ->
588 //
589 // memcpy(dest, src, ...)
590 // call @func(..., dest, ...)
591 //
592 // Since moving the memcpy is technically awkward, we additionally check that
593 // src only holds uninitialized values at the moment of the call, meaning that
594 // the memcpy can be discarded rather than moved.
595
596 // Deliberately get the source and destination with bitcasts stripped away,
597 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000598 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000599
Owen Andersona723d1e2008-04-09 08:23:16 +0000600 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000601 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000602 if (!srcAlloca)
603 return false;
604
605 // Check that all of src is copied to dest.
Stephen Hines36b56882014-04-23 16:57:46 -0700606 if (DL == 0) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000607
Chris Lattner61c6ba82009-09-01 17:09:55 +0000608 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000609 if (!srcArraySize)
610 return false;
611
Stephen Hines36b56882014-04-23 16:57:46 -0700612 uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000613 srcArraySize->getZExtValue();
614
Owen Anderson65491212010-10-15 22:52:12 +0000615 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000616 return false;
617
618 // Check that accessing the first srcSize bytes of dest will not cause a
619 // trap. Otherwise the transform is invalid since it might cause a trap
620 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000621 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000622 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000623 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000624 if (!destArraySize)
625 return false;
626
Stephen Hines36b56882014-04-23 16:57:46 -0700627 uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000628 destArraySize->getZExtValue();
629
630 if (destSize < srcSize)
631 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000632 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000633 // If the destination is an sret parameter then only accesses that are
634 // outside of the returned struct type can trap.
635 if (!A->hasStructRetAttr())
636 return false;
637
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000638 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Shuxin Yang9792b642013-06-08 04:56:05 +0000639 if (!StructTy->isSized()) {
640 // The call may never return and hence the copy-instruction may never
641 // be executed, and therefore it's not safe to say "the destination
642 // has at least <cpyLen> bytes, as implied by the copy-instruction",
643 return false;
644 }
645
Stephen Hines36b56882014-04-23 16:57:46 -0700646 uint64_t destSize = DL->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000647 if (destSize < srcSize)
648 return false;
649 } else {
650 return false;
651 }
652
Duncan Sands3372c5a2012-10-05 07:29:46 +0000653 // Check that dest points to memory that is at least as aligned as src.
654 unsigned srcAlign = srcAlloca->getAlignment();
655 if (!srcAlign)
Stephen Hines36b56882014-04-23 16:57:46 -0700656 srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands3372c5a2012-10-05 07:29:46 +0000657 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
658 // If dest is not aligned enough and we can't increase its alignment then
659 // bail out.
660 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
661 return false;
662
Owen Andersona723d1e2008-04-09 08:23:16 +0000663 // Check that src is not accessed except via the call and the memcpy. This
664 // guarantees that it holds only undefined values when passed in (so the final
665 // memcpy can be dropped), that it is not read or written between the call and
666 // the memcpy, and that writing beyond the end of it is undefined.
Stephen Hines36b56882014-04-23 16:57:46 -0700667 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
668 srcAlloca->user_end());
Owen Andersona723d1e2008-04-09 08:23:16 +0000669 while (!srcUseList.empty()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700670 User *U = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000671
Stephen Hines36b56882014-04-23 16:57:46 -0700672 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
673 for (User *UU : U->users())
674 srcUseList.push_back(UU);
675 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000676 if (G->hasAllZeroIndices())
Stephen Hines36b56882014-04-23 16:57:46 -0700677 for (User *UU : U->users())
678 srcUseList.push_back(UU);
Owen Anderson009e4f72008-06-01 22:26:26 +0000679 else
680 return false;
Stephen Hines36b56882014-04-23 16:57:46 -0700681 } else if (U != C && U != cpy) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000682 return false;
683 }
684 }
685
686 // Since we're changing the parameter to the callsite, we need to make sure
687 // that what would be the new parameter dominates the callsite.
Stephen Hines36b56882014-04-23 16:57:46 -0700688 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000689 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000690 if (!DT.dominates(cpyDestInst, C))
691 return false;
692
693 // In addition to knowing that the call does not access src in some
694 // unexpected manner, for example via a global, which we deduce from
695 // the use analysis, we also need to know that it does not sneakily
696 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000697 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chad Rosier3a884f52012-05-14 20:35:04 +0000698 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
699 // If necessary, perform additional analysis.
700 if (MR != AliasAnalysis::NoModRef)
701 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
702 if (MR != AliasAnalysis::NoModRef)
Owen Andersona723d1e2008-04-09 08:23:16 +0000703 return false;
704
705 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000706 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000707 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000708 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sands7508f942012-10-04 13:53:21 +0000709 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
710 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
711 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000712 changedArgument = true;
Duncan Sands7508f942012-10-04 13:53:21 +0000713 if (CS.getArgument(i)->getType() == Dest->getType())
714 CS.setArgument(i, Dest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000715 else
Duncan Sands7508f942012-10-04 13:53:21 +0000716 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
717 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000718 }
719
Owen Anderson12cb36c2008-06-01 21:52:16 +0000720 if (!changedArgument)
721 return false;
722
Duncan Sandsf5874752012-10-04 10:54:40 +0000723 // If the destination wasn't sufficiently aligned then increase its alignment.
724 if (!isDestSufficientlyAligned) {
725 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
726 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
727 }
728
Owen Andersona723d1e2008-04-09 08:23:16 +0000729 // Drop any cached information about the call, because we may have changed
730 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000731 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000732
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000733 // Remove the memcpy.
734 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000735 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000736
737 return true;
738}
739
Chris Lattner43f8e432010-11-18 07:02:37 +0000740/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
741/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
742/// copy from MDep's input if we can. MSize is the size of M's copy.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000743///
Chris Lattner43f8e432010-11-18 07:02:37 +0000744bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
745 uint64_t MSize) {
746 // We can only transforms memcpy's where the dest of one is the source of the
747 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000748 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000749 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000750
Chris Lattnerf7f35462010-12-09 07:39:50 +0000751 // If dep instruction is reading from our current input, then it is a noop
752 // transfer and substituting the input won't change this instruction. Just
753 // ignore the input and let someone else zap MDep. This handles cases like:
754 // memcpy(a <- a)
755 // memcpy(b <- a)
756 if (M->getSource() == MDep->getSource())
757 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000758
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000759 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner43f8e432010-11-18 07:02:37 +0000760 // must be larger than the following one.
Dan Gohman8fb25c52011-01-21 22:07:57 +0000761 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
762 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
763 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
764 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000765
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000766 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000767
768 // Verify that the copied-from memory doesn't change in between the two
769 // transfers. For example, in:
770 // memcpy(a <- b)
771 // *b = 42;
772 // memcpy(c <- a)
773 // It would be invalid to transform the second memcpy into memcpy(c <- b).
774 //
775 // TODO: If the code between M and MDep is transparent to the destination "c",
776 // then we could still perform the xform by moving M up to the first memcpy.
777 //
778 // NOTE: This is conservative, it will stop on any read from the source loc,
779 // not just the defining memcpy.
780 MemDepResult SourceDep =
781 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
782 false, M, M->getParent());
783 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
784 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000785
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000786 // If the dest of the second might alias the source of the first, then the
787 // source and dest might overlap. We still want to eliminate the intermediate
788 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000789 bool UseMemMove = false;
790 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
791 UseMemMove = true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000792
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000793 // If all checks passed, then we can transform M.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000794
Chris Lattner43f8e432010-11-18 07:02:37 +0000795 // Make sure to use the lesser of the alignment of the source and the dest
796 // since we're changing where we're reading from, but don't want to increase
797 // the alignment past what can be read from or written to.
798 // TODO: Is this worth it if we're creating a less aligned memcpy? For
799 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000800 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000801
Chris Lattner61db1f52010-12-26 22:57:41 +0000802 IRBuilder<> Builder(M);
803 if (UseMemMove)
804 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
805 Align, M->isVolatile());
806 else
807 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
808 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000809
Chris Lattner604f6fe2010-11-21 08:06:10 +0000810 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000811 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000812 M->eraseFromParent();
813 ++NumMemCpyInstr;
814 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000815}
816
817
Gabor Greif7d3056b2010-07-28 22:50:26 +0000818/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
819/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
820/// B to be a memcpy from X to Z (or potentially a memmove, depending on
821/// circumstances). This allows later passes to remove the first memcpy
822/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000823bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Stephen Hines36b56882014-04-23 16:57:46 -0700824 // We can only optimize non-volatile memcpy's.
825 if (M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000826
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000827 // If the source and destination of the memcpy are the same, then zap it.
828 if (M->getSource() == M->getDest()) {
829 MD->removeInstruction(M);
830 M->eraseFromParent();
831 return false;
832 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000833
834 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000835 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000836 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000837 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000838 IRBuilder<> Builder(M);
Stephen Hines36b56882014-04-23 16:57:46 -0700839 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Chris Lattner61db1f52010-12-26 22:57:41 +0000840 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000841 MD->removeInstruction(M);
842 M->eraseFromParent();
843 ++NumCpyToSet;
844 return true;
845 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000846
Stephen Hines36b56882014-04-23 16:57:46 -0700847 // The optimizations after this point require the memcpy size.
848 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
849 if (CopySize == 0) return false;
850
851 // The are three possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000852 // a) memcpy-memcpy xform which exposes redundance for DSE.
853 // b) call-memcpy xform for return slot optimization.
Stephen Hines36b56882014-04-23 16:57:46 -0700854 // c) memcpy from freshly alloca'd space or space that has just started its
855 // lifetime copies undefined data, and we can therefore eliminate the
856 // memcpy in favor of the data that was already at the destination.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000857 MemDepResult DepInfo = MD->getDependency(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000858 if (DepInfo.isClobber()) {
859 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
860 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Duncan Sandsf5874752012-10-04 10:54:40 +0000861 CopySize->getZExtValue(), M->getAlignment(),
862 C)) {
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000863 MD->removeInstruction(M);
864 M->eraseFromParent();
865 return true;
866 }
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000867 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000868 }
Ahmed Charlesb83a67e2012-02-13 06:30:56 +0000869
870 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000871 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
872 M, M->getParent());
873 if (SrcDepInfo.isClobber()) {
874 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
875 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Stephen Hines36b56882014-04-23 16:57:46 -0700876 } else if (SrcDepInfo.isDef()) {
877 Instruction *I = SrcDepInfo.getInst();
878 bool hasUndefContents = false;
879
880 if (isa<AllocaInst>(I)) {
881 hasUndefContents = true;
882 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
883 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
884 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
885 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
886 hasUndefContents = true;
887 }
888
889 if (hasUndefContents) {
890 MD->removeInstruction(M);
891 M->eraseFromParent();
892 ++NumMemCpyInstr;
893 return true;
894 }
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000895 }
896
Owen Anderson02e99882008-04-29 21:51:00 +0000897 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000898}
899
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000900/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
901/// are guaranteed not to alias.
902bool MemCpyOpt::processMemMove(MemMoveInst *M) {
903 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
904
Chris Lattner149f5282011-05-01 18:27:11 +0000905 if (!TLI->has(LibFunc::memmove))
906 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000907
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000908 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000909 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000910 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000911
David Greenecb33fd12010-01-05 01:27:47 +0000912 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000913
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000914 // If not, then we know we can transform this.
915 Module *Mod = M->getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +0000916 Type *ArgTys[3] = { M->getRawDest()->getType(),
917 M->getRawSource()->getType(),
918 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000919 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000920 ArgTys));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000921
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000922 // MemDep may have over conservative information about this instruction, just
923 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000924 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000925
926 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000927 return true;
928}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000929
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000930/// processByValArgument - This is called on every byval argument in call sites.
931bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Stephen Hines36b56882014-04-23 16:57:46 -0700932 if (DL == 0) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000933
Chris Lattner604f6fe2010-11-21 08:06:10 +0000934 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000935 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewycky865703e2011-10-12 00:14:31 +0000936 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700937 uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000938 MemDepResult DepInfo =
939 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
940 true, CS.getInstruction(),
941 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000942 if (!DepInfo.isClobber())
943 return false;
944
945 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
946 // a memcpy, see if we can byval from the source of the memcpy instead of the
947 // result.
948 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
949 if (MDep == 0 || MDep->isVolatile() ||
950 ByValArg->stripPointerCasts() != MDep->getDest())
951 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000952
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000953 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000954 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000955 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000956 return false;
957
Chris Lattnerb3f06732011-05-23 00:03:39 +0000958 // Get the alignment of the byval. If the call doesn't specify the alignment,
959 // then it is some target specific value that we can't know.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000960 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattnerb3f06732011-05-23 00:03:39 +0000961 if (ByValAlign == 0) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000962
Chris Lattnerb3f06732011-05-23 00:03:39 +0000963 // If it is greater than the memcpy, then we check to see if we can force the
964 // source of the memcpy to the alignment we need. If we fail, we bail out.
965 if (MDep->getAlignment() < ByValAlign &&
Stephen Hines36b56882014-04-23 16:57:46 -0700966 getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, DL) < ByValAlign)
Chris Lattnerb3f06732011-05-23 00:03:39 +0000967 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000968
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000969 // Verify that the copied-from memory doesn't change in between the memcpy and
970 // the byval call.
971 // memcpy(a <- b)
972 // *b = 42;
973 // foo(*a)
974 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000975 //
976 // NOTE: This is conservative, it will stop on any read from the source loc,
977 // not just the defining memcpy.
978 MemDepResult SourceDep =
979 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
980 false, CS.getInstruction(), MDep->getParent());
981 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
982 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000983
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000984 Value *TmpCast = MDep->getSource();
985 if (MDep->getSource()->getType() != ByValArg->getType())
986 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
987 "tmpcast", CS.getInstruction());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000988
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000989 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
990 << " " << *MDep << "\n"
991 << " " << *CS.getInstruction() << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000992
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000993 // Otherwise we're good! Update the byval argument.
994 CS.setArgument(ArgNo, TmpCast);
995 ++NumMemCpyInstr;
996 return true;
997}
998
999/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +00001000bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +00001001 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +00001002
Chris Lattner61c6ba82009-09-01 17:09:55 +00001003 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +00001004 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001005 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +00001006 // Avoid invalidating the iterator.
1007 Instruction *I = BI++;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001008
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001009 bool RepeatInstruction = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001010
Owen Andersona8bd6582008-04-21 07:45:10 +00001011 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +00001012 MadeChange |= processStore(SI, BI);
Chris Lattnerd90a1922011-01-08 21:19:19 +00001013 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1014 RepeatInstruction = processMemSet(M, BI);
1015 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001016 RepeatInstruction = processMemCpy(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +00001017 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001018 RepeatInstruction = processMemMove(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +00001019 else if (CallSite CS = (Value*)I) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001020 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky173862e2011-11-20 19:09:04 +00001021 if (CS.isByValArgument(i))
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001022 MadeChange |= processByValArgument(CS, i);
1023 }
1024
1025 // Reprocess the instruction if desired.
1026 if (RepeatInstruction) {
Chris Lattner8a629572011-01-08 22:19:21 +00001027 if (BI != BB->begin()) --BI;
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001028 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +00001029 }
Owen Andersona723d1e2008-04-09 08:23:16 +00001030 }
1031 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001032
Chris Lattner61c6ba82009-09-01 17:09:55 +00001033 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +00001034}
Chris Lattner61c6ba82009-09-01 17:09:55 +00001035
1036// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1037// function.
1038//
1039bool MemCpyOpt::runOnFunction(Function &F) {
Stephen Hines36b56882014-04-23 16:57:46 -07001040 if (skipOptnoneFunction(F))
1041 return false;
1042
Chris Lattner61c6ba82009-09-01 17:09:55 +00001043 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001044 MD = &getAnalysis<MemoryDependenceAnalysis>();
Stephen Hines36b56882014-04-23 16:57:46 -07001045 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1046 DL = DLP ? &DLP->getDataLayout() : 0;
Chris Lattner149f5282011-05-01 18:27:11 +00001047 TLI = &getAnalysis<TargetLibraryInfo>();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001048
Chris Lattner149f5282011-05-01 18:27:11 +00001049 // If we don't have at least memset and memcpy, there is little point of doing
1050 // anything here. These are required by a freestanding implementation, so if
1051 // even they are disabled, there is no point in trying hard.
1052 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1053 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001054
Chris Lattner61c6ba82009-09-01 17:09:55 +00001055 while (1) {
1056 if (!iterateOnFunction(F))
1057 break;
1058 MadeChange = true;
1059 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001060
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001061 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +00001062 return MadeChange;
1063}