blob: b6bc79228824839eec03c17bf516d6d822daaaae [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
Owen Andersona723d1e2008-04-09 08:23:16 +000015#include "llvm/Transforms/Scalar.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000016#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/Statistic.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattnerbb897102010-12-26 20:15:01 +000020#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Stephen Hines36b56882014-04-23 16:57:46 -070022#include "llvm/IR/Dominators.h"
23#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000024#include "llvm/IR/GlobalVariable.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000028#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner149f5282011-05-01 18:27:11 +000030#include "llvm/Target/TargetLibraryInfo.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000031#include "llvm/Transforms/Utils/Local.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000032#include <list>
33using namespace llvm;
34
Stephen Hinesdce4a402014-05-29 02:49:00 -070035#define DEBUG_TYPE "memcpyopt"
36
Owen Andersona723d1e2008-04-09 08:23:16 +000037STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
38STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000039STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000040STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000041
Benjamin Kramer39acdb02012-09-13 16:29:49 +000042static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Micah Villmow3574eca2012-10-08 16:38:25 +000043 bool &VariableIdxFound, const DataLayout &TD){
Owen Andersona723d1e2008-04-09 08:23:16 +000044 // Skip over the first indices.
45 gep_type_iterator GTI = gep_type_begin(GEP);
46 for (unsigned i = 1; i != Idx; ++i, ++GTI)
47 /*skip along*/;
Nadav Rotema94d6e82012-07-24 10:51:42 +000048
Owen Andersona723d1e2008-04-09 08:23:16 +000049 // Compute the offset implied by the rest of the indices.
50 int64_t Offset = 0;
51 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
52 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
Stephen Hinesdce4a402014-05-29 02:49:00 -070053 if (!OpC)
Owen Andersona723d1e2008-04-09 08:23:16 +000054 return VariableIdxFound = true;
55 if (OpC->isZero()) continue; // No offset.
56
57 // Handle struct indices, which add their field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000058 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +000059 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
60 continue;
61 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000062
Owen Andersona723d1e2008-04-09 08:23:16 +000063 // Otherwise, we have a sequential type like an array or vector. Multiply
64 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +000065 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +000066 Offset += Size*OpC->getSExtValue();
67 }
68
69 return Offset;
70}
71
72/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
73/// constant offset, and return that constant offset. For example, Ptr1 might
74/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
75static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Micah Villmow3574eca2012-10-08 16:38:25 +000076 const DataLayout &TD) {
Chris Lattner2d5c0cd2011-01-12 01:43:46 +000077 Ptr1 = Ptr1->stripPointerCasts();
78 Ptr2 = Ptr2->stripPointerCasts();
Stephen Hines36b56882014-04-23 16:57:46 -070079
80 // Handle the trivial case first.
81 if (Ptr1 == Ptr2) {
82 Offset = 0;
83 return true;
84 }
85
Benjamin Kramer39acdb02012-09-13 16:29:49 +000086 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
87 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotema94d6e82012-07-24 10:51:42 +000088
Chris Lattner9fa11e92011-01-08 21:07:56 +000089 bool VariableIdxFound = false;
90
91 // If one pointer is a GEP and the other isn't, then see if the GEP is a
92 // constant offset from the base, as in "P" and "gep P, 1".
Stephen Hinesdce4a402014-05-29 02:49:00 -070093 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Chris Lattner9fa11e92011-01-08 21:07:56 +000094 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
95 return !VariableIdxFound;
96 }
97
Stephen Hinesdce4a402014-05-29 02:49:00 -070098 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Chris Lattner9fa11e92011-01-08 21:07:56 +000099 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
100 return !VariableIdxFound;
101 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000102
Owen Andersona723d1e2008-04-09 08:23:16 +0000103 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
104 // base. After that base, they may have some number of common (and
105 // potentially variable) indices. After that they handle some constant
106 // offset, which determines their offset from each other. At this point, we
107 // handle no other case.
Owen Andersona723d1e2008-04-09 08:23:16 +0000108 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
109 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000110
Owen Andersona723d1e2008-04-09 08:23:16 +0000111 // Skip any common indices and track the GEP types.
112 unsigned Idx = 1;
113 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
114 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
115 break;
116
Owen Andersona723d1e2008-04-09 08:23:16 +0000117 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
118 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
119 if (VariableIdxFound) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000120
Owen Andersona723d1e2008-04-09 08:23:16 +0000121 Offset = Offset2-Offset1;
122 return true;
123}
124
125
126/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
127/// This allows us to analyze stores like:
128/// store 0 -> P+1
129/// store 0 -> P+0
130/// store 0 -> P+3
131/// store 0 -> P+2
132/// which sometimes happens with stores to arrays of structs etc. When we see
133/// the first store, we make a range [1, 2). The second store extends the range
134/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
135/// two ranges into [0, 3) which is memset'able.
136namespace {
137struct MemsetRange {
138 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000139 // The range is closed at the start and open at the end: [Start, End).
Owen Andersona723d1e2008-04-09 08:23:16 +0000140 int64_t Start, End;
141
142 /// StartPtr - The getelementptr instruction that points to the start of the
143 /// range.
144 Value *StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000145
Owen Andersona723d1e2008-04-09 08:23:16 +0000146 /// Alignment - The known alignment of the first store.
147 unsigned Alignment;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000148
Owen Andersona723d1e2008-04-09 08:23:16 +0000149 /// TheStores - The actual stores that make up this range.
Chris Lattner06511262011-01-08 20:54:51 +0000150 SmallVector<Instruction*, 16> TheStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000151
Micah Villmow3574eca2012-10-08 16:38:25 +0000152 bool isProfitableToUseMemset(const DataLayout &TD) const;
Owen Andersona723d1e2008-04-09 08:23:16 +0000153
154};
155} // end anon namespace
156
Micah Villmow3574eca2012-10-08 16:38:25 +0000157bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
Chad Rosiera4b6fd52011-12-05 22:53:09 +0000158 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosierd8bd26e2011-12-05 22:37:00 +0000159 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner06511262011-01-08 20:54:51 +0000160
161 // If there is nothing to merge, don't do anything.
162 if (TheStores.size() < 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000163
Chris Lattner06511262011-01-08 20:54:51 +0000164 // If any of the stores are a memset, then it is always good to extend the
165 // memset.
166 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
167 if (!isa<StoreInst>(TheStores[i]))
168 return true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000169
Owen Andersona723d1e2008-04-09 08:23:16 +0000170 // Assume that the code generator is capable of merging pairs of stores
171 // together if it wants to.
Chris Lattner06511262011-01-08 20:54:51 +0000172 if (TheStores.size() == 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000173
Owen Andersona723d1e2008-04-09 08:23:16 +0000174 // If we have fewer than 8 stores, it can still be worthwhile to do this.
175 // For example, merging 4 i8 stores into an i32 store is useful almost always.
176 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
177 // memset will be split into 2 32-bit stores anyway) and doing so can
178 // pessimize the llvm optimizer.
179 //
180 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault4b28ee22013-09-16 22:43:16 +0000181 // the maximum GPR width is the same size as the largest legal integer
182 // size. If so, check to see whether we will end up actually reducing the
183 // number of stores used.
Owen Andersona723d1e2008-04-09 08:23:16 +0000184 unsigned Bytes = unsigned(End-Start);
Matt Arsenault4b28ee22013-09-16 22:43:16 +0000185 unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
186 if (MaxIntSize == 0)
187 MaxIntSize = 1;
188 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000189
Owen Andersona723d1e2008-04-09 08:23:16 +0000190 // Assume the remaining bytes if any are done a byte at a time.
Matt Arsenault4b28ee22013-09-16 22:43:16 +0000191 unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000192
Owen Andersona723d1e2008-04-09 08:23:16 +0000193 // If we will reduce the # stores (according to this heuristic), do the
194 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
195 // etc.
196 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000197}
Owen Andersona723d1e2008-04-09 08:23:16 +0000198
199
200namespace {
201class MemsetRanges {
202 /// Ranges - A sorted list of the memset ranges. We use std::list here
203 /// because each element is relatively large and expensive to copy.
204 std::list<MemsetRange> Ranges;
205 typedef std::list<MemsetRange>::iterator range_iterator;
Stephen Hines36b56882014-04-23 16:57:46 -0700206 const DataLayout &DL;
Owen Andersona723d1e2008-04-09 08:23:16 +0000207public:
Stephen Hines36b56882014-04-23 16:57:46 -0700208 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000209
Owen Andersona723d1e2008-04-09 08:23:16 +0000210 typedef std::list<MemsetRange>::const_iterator const_iterator;
211 const_iterator begin() const { return Ranges.begin(); }
212 const_iterator end() const { return Ranges.end(); }
213 bool empty() const { return Ranges.empty(); }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000214
Chris Lattner67a716a2011-01-08 20:24:01 +0000215 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner06511262011-01-08 20:54:51 +0000216 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
217 addStore(OffsetFromFirst, SI);
218 else
219 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattner67a716a2011-01-08 20:24:01 +0000220 }
Chris Lattner06511262011-01-08 20:54:51 +0000221
222 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Stephen Hines36b56882014-04-23 16:57:46 -0700223 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000224
Chris Lattner06511262011-01-08 20:54:51 +0000225 addRange(OffsetFromFirst, StoreSize,
226 SI->getPointerOperand(), SI->getAlignment(), SI);
227 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000228
Chris Lattner06511262011-01-08 20:54:51 +0000229 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
230 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
231 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
232 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000233
Chris Lattner06511262011-01-08 20:54:51 +0000234 void addRange(int64_t Start, int64_t Size, Value *Ptr,
235 unsigned Alignment, Instruction *Inst);
236
Owen Andersona723d1e2008-04-09 08:23:16 +0000237};
Nadav Rotema94d6e82012-07-24 10:51:42 +0000238
Owen Andersona723d1e2008-04-09 08:23:16 +0000239} // end anon namespace
240
241
Chris Lattner06511262011-01-08 20:54:51 +0000242/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersona723d1e2008-04-09 08:23:16 +0000243/// new range for the specified store at the specified offset, merging into
244/// existing ranges as appropriate.
Chris Lattner06511262011-01-08 20:54:51 +0000245///
246/// Do a linear search of the ranges to see if this can be joined and/or to
247/// find the insertion point in the list. We keep the ranges sorted for
248/// simplicity here. This is a linear search of a linked list, which is ugly,
249/// however the number of ranges is limited, so this won't get crazy slow.
250void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
251 unsigned Alignment, Instruction *Inst) {
252 int64_t End = Start+Size;
Owen Andersona723d1e2008-04-09 08:23:16 +0000253 range_iterator I = Ranges.begin(), E = Ranges.end();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000254
Owen Andersona723d1e2008-04-09 08:23:16 +0000255 while (I != E && Start > I->End)
256 ++I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000257
Owen Andersona723d1e2008-04-09 08:23:16 +0000258 // We now know that I == E, in which case we didn't find anything to merge
259 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
260 // to insert a new range. Handle this now.
261 if (I == E || End < I->Start) {
262 MemsetRange &R = *Ranges.insert(I, MemsetRange());
263 R.Start = Start;
264 R.End = End;
Chris Lattner06511262011-01-08 20:54:51 +0000265 R.StartPtr = Ptr;
266 R.Alignment = Alignment;
267 R.TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000268 return;
269 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000270
Owen Andersona723d1e2008-04-09 08:23:16 +0000271 // This store overlaps with I, add it.
Chris Lattner06511262011-01-08 20:54:51 +0000272 I->TheStores.push_back(Inst);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000273
Owen Andersona723d1e2008-04-09 08:23:16 +0000274 // At this point, we may have an interval that completely contains our store.
275 // If so, just add it to the interval and return.
276 if (I->Start <= Start && I->End >= End)
277 return;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000278
Owen Andersona723d1e2008-04-09 08:23:16 +0000279 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
280 // but is not entirely contained within the range.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000281
Owen Andersona723d1e2008-04-09 08:23:16 +0000282 // See if the range extends the start of the range. In this case, it couldn't
283 // possibly cause it to join the prior range, because otherwise we would have
284 // stopped on *it*.
285 if (Start < I->Start) {
286 I->Start = Start;
Chris Lattner06511262011-01-08 20:54:51 +0000287 I->StartPtr = Ptr;
288 I->Alignment = Alignment;
Owen Andersona723d1e2008-04-09 08:23:16 +0000289 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000290
Owen Andersona723d1e2008-04-09 08:23:16 +0000291 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
292 // is in or right at the end of I), and that End >= I->Start. Extend I out to
293 // End.
294 if (End > I->End) {
295 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000296 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000297 while (++NextI != E && End >= NextI->Start) {
298 // Merge the range in.
299 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
300 if (NextI->End > I->End)
301 I->End = NextI->End;
302 Ranges.erase(NextI);
303 NextI = I;
304 }
305 }
306}
307
308//===----------------------------------------------------------------------===//
309// MemCpyOpt Pass
310//===----------------------------------------------------------------------===//
311
312namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000313 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000314 MemoryDependenceAnalysis *MD;
Chris Lattner149f5282011-05-01 18:27:11 +0000315 TargetLibraryInfo *TLI;
Stephen Hines36b56882014-04-23 16:57:46 -0700316 const DataLayout *DL;
Owen Andersona723d1e2008-04-09 08:23:16 +0000317 public:
318 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000319 MemCpyOpt() : FunctionPass(ID) {
320 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700321 MD = nullptr;
322 TLI = nullptr;
323 DL = nullptr;
Owen Anderson081c34b2010-10-19 17:21:58 +0000324 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000325
Stephen Hines36b56882014-04-23 16:57:46 -0700326 bool runOnFunction(Function &F) override;
Chris Lattner67a716a2011-01-08 20:24:01 +0000327
Owen Andersona723d1e2008-04-09 08:23:16 +0000328 private:
329 // This transformation requires dominator postdominator info
Stephen Hines36b56882014-04-23 16:57:46 -0700330 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersona723d1e2008-04-09 08:23:16 +0000331 AU.setPreservesCFG();
Stephen Hines36b56882014-04-23 16:57:46 -0700332 AU.addRequired<DominatorTreeWrapperPass>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000333 AU.addRequired<MemoryDependenceAnalysis>();
334 AU.addRequired<AliasAnalysis>();
Chris Lattner149f5282011-05-01 18:27:11 +0000335 AU.addRequired<TargetLibraryInfo>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000336 AU.addPreserved<AliasAnalysis>();
337 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000338 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000339
Owen Andersona723d1e2008-04-09 08:23:16 +0000340 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000341 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000342 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000343 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000344 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000345 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000346 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000347 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
348 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000349 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattner67a716a2011-01-08 20:24:01 +0000350 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
351 Value *ByteVal);
352
Owen Andersona723d1e2008-04-09 08:23:16 +0000353 bool iterateOnFunction(Function &F);
354 };
Nadav Rotema94d6e82012-07-24 10:51:42 +0000355
Owen Andersona723d1e2008-04-09 08:23:16 +0000356 char MemCpyOpt::ID = 0;
357}
358
359// createMemCpyOptPass - The public interface to this file...
360FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
361
Owen Anderson2ab36d32010-10-12 19:48:12 +0000362INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
363 false, false)
Stephen Hines36b56882014-04-23 16:57:46 -0700364INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000365INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chris Lattner149f5282011-05-01 18:27:11 +0000366INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000367INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
368INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
369 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000370
Chris Lattner67a716a2011-01-08 20:24:01 +0000371/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersona723d1e2008-04-09 08:23:16 +0000372/// some other patterns to fold away. In particular, this looks for stores to
Duncan Sandsab4c3662011-02-15 09:23:02 +0000373/// neighboring locations of memory. If it sees enough consecutive ones, it
Chris Lattner67a716a2011-01-08 20:24:01 +0000374/// attempts to merge them together into a memcpy/memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000375Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattner67a716a2011-01-08 20:24:01 +0000376 Value *StartPtr, Value *ByteVal) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700377 if (!DL) return nullptr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000378
Chris Lattner67a716a2011-01-08 20:24:01 +0000379 // Okay, so we now have a single store that can be splatable. Scan to find
380 // all subsequent stores of the same value to offset from the same pointer.
381 // Join these together into ranges, so we can decide whether contiguous blocks
382 // are stored.
Stephen Hines36b56882014-04-23 16:57:46 -0700383 MemsetRanges Ranges(*DL);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000384
Chris Lattner67a716a2011-01-08 20:24:01 +0000385 BasicBlock::iterator BI = StartInst;
386 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner06511262011-01-08 20:54:51 +0000387 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
388 // If the instruction is readnone, ignore it, otherwise bail out. We
389 // don't even allow readonly here because we don't want something like:
Chris Lattner67a716a2011-01-08 20:24:01 +0000390 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner06511262011-01-08 20:54:51 +0000391 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
392 break;
393 continue;
394 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000395
Chris Lattner06511262011-01-08 20:54:51 +0000396 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
397 // If this is a store, see if we can merge it in.
Eli Friedman56efe242011-08-17 22:22:24 +0000398 if (!NextStore->isSimple()) break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000399
Chris Lattner06511262011-01-08 20:54:51 +0000400 // Check to see if this stored value is of the same byte-splattable value.
401 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
402 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000403
Chris Lattner06511262011-01-08 20:54:51 +0000404 // Check to see if this store is to a constant offset from the start ptr.
405 int64_t Offset;
Chris Lattnerf4268502011-01-09 19:26:10 +0000406 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
Stephen Hines36b56882014-04-23 16:57:46 -0700407 Offset, *DL))
Chris Lattner06511262011-01-08 20:54:51 +0000408 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000409
Chris Lattner06511262011-01-08 20:54:51 +0000410 Ranges.addStore(Offset, NextStore);
411 } else {
412 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000413
Chris Lattner06511262011-01-08 20:54:51 +0000414 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
415 !isa<ConstantInt>(MSI->getLength()))
416 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000417
Chris Lattner06511262011-01-08 20:54:51 +0000418 // Check to see if this store is to a constant offset from the start ptr.
419 int64_t Offset;
Stephen Hines36b56882014-04-23 16:57:46 -0700420 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
Chris Lattner06511262011-01-08 20:54:51 +0000421 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000422
Chris Lattner06511262011-01-08 20:54:51 +0000423 Ranges.addMemSet(Offset, MSI);
424 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000425 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000426
Chris Lattner67a716a2011-01-08 20:24:01 +0000427 // If we have no ranges, then we just had a single store with nothing that
428 // could be merged in. This is a very common case of course.
429 if (Ranges.empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700430 return nullptr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000431
Chris Lattner67a716a2011-01-08 20:24:01 +0000432 // If we had at least one store that could be merged in, add the starting
433 // store as well. We try to avoid this unless there is at least something
434 // interesting as a small compile-time optimization.
435 Ranges.addInst(0, StartInst);
436
437 // If we create any memsets, we put it right before the first instruction that
438 // isn't part of the memset block. This ensure that the memset is dominated
439 // by any addressing instruction needed by the start of the block.
440 IRBuilder<> Builder(BI);
441
442 // Now that we have full information about ranges, loop over the ranges and
443 // emit memset's for anything big enough to be worthwhile.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700444 Instruction *AMemSet = nullptr;
Chris Lattner67a716a2011-01-08 20:24:01 +0000445 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
446 I != E; ++I) {
447 const MemsetRange &Range = *I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000448
Chris Lattner67a716a2011-01-08 20:24:01 +0000449 if (Range.TheStores.size() == 1) continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000450
Chris Lattner67a716a2011-01-08 20:24:01 +0000451 // If it is profitable to lower this range to memset, do so now.
Stephen Hines36b56882014-04-23 16:57:46 -0700452 if (!Range.isProfitableToUseMemset(*DL))
Chris Lattner67a716a2011-01-08 20:24:01 +0000453 continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000454
Chris Lattner67a716a2011-01-08 20:24:01 +0000455 // Otherwise, we do want to transform this! Create a new memset.
456 // Get the starting pointer of the block.
457 StartPtr = Range.StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000458
Chris Lattner67a716a2011-01-08 20:24:01 +0000459 // Determine alignment
460 unsigned Alignment = Range.Alignment;
461 if (Alignment == 0) {
Nadav Rotema94d6e82012-07-24 10:51:42 +0000462 Type *EltType =
Chris Lattner67a716a2011-01-08 20:24:01 +0000463 cast<PointerType>(StartPtr->getType())->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700464 Alignment = DL->getABITypeAlignment(EltType);
Chris Lattner67a716a2011-01-08 20:24:01 +0000465 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000466
467 AMemSet =
Chris Lattner67a716a2011-01-08 20:24:01 +0000468 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000469
Chris Lattner67a716a2011-01-08 20:24:01 +0000470 DEBUG(dbgs() << "Replace stores:\n";
471 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
472 dbgs() << *Range.TheStores[i] << '\n';
473 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelb90584a2011-05-04 21:58:58 +0000474
475 if (!Range.TheStores.empty())
476 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
477
Chris Lattner67a716a2011-01-08 20:24:01 +0000478 // Zap all the stores.
Craig Topper365ef0b2013-07-03 15:07:05 +0000479 for (SmallVectorImpl<Instruction *>::const_iterator
Chris Lattner67a716a2011-01-08 20:24:01 +0000480 SI = Range.TheStores.begin(),
Chris Lattner8a629572011-01-08 22:19:21 +0000481 SE = Range.TheStores.end(); SI != SE; ++SI) {
482 MD->removeInstruction(*SI);
Chris Lattner67a716a2011-01-08 20:24:01 +0000483 (*SI)->eraseFromParent();
Chris Lattner8a629572011-01-08 22:19:21 +0000484 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000485 ++NumMemSetInfer;
486 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000487
Chris Lattner67a716a2011-01-08 20:24:01 +0000488 return AMemSet;
489}
490
491
Chris Lattner61c6ba82009-09-01 17:09:55 +0000492bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman56efe242011-08-17 22:22:24 +0000493 if (!SI->isSimple()) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000494
Stephen Hinesdce4a402014-05-29 02:49:00 -0700495 if (!DL) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000496
497 // Detect cases where we're performing call slot forwarding, but
498 // happen to be using a load-store pair to implement it, rather than
499 // a memcpy.
500 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman56efe242011-08-17 22:22:24 +0000501 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedman5d40ef22011-06-15 01:25:56 +0000502 LI->getParent() == SI->getParent()) {
Eli Friedman70d893e2011-06-02 21:24:42 +0000503 MemDepResult ldep = MD->getDependency(LI);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700504 CallInst *C = nullptr;
Eli Friedman70d893e2011-06-02 21:24:42 +0000505 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
506 C = dyn_cast<CallInst>(ldep.getInst());
507
508 if (C) {
509 // Check that nothing touches the dest of the "copy" between
510 // the call and the store.
Eli Friedman5d40ef22011-06-15 01:25:56 +0000511 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
512 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
513 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
514 E = C; I != E; --I) {
515 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700516 C = nullptr;
Eli Friedman5d40ef22011-06-15 01:25:56 +0000517 break;
518 }
Eli Friedman70d893e2011-06-02 21:24:42 +0000519 }
520 }
521
Owen Anderson65491212010-10-15 22:52:12 +0000522 if (C) {
Duncan Sandsf5874752012-10-04 10:54:40 +0000523 unsigned storeAlign = SI->getAlignment();
524 if (!storeAlign)
Stephen Hines36b56882014-04-23 16:57:46 -0700525 storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
Duncan Sandsf5874752012-10-04 10:54:40 +0000526 unsigned loadAlign = LI->getAlignment();
527 if (!loadAlign)
Stephen Hines36b56882014-04-23 16:57:46 -0700528 loadAlign = DL->getABITypeAlignment(LI->getType());
Duncan Sandsf5874752012-10-04 10:54:40 +0000529
Owen Anderson65491212010-10-15 22:52:12 +0000530 bool changed = performCallSlotOptzn(LI,
Nadav Rotema94d6e82012-07-24 10:51:42 +0000531 SI->getPointerOperand()->stripPointerCasts(),
Owen Anderson65491212010-10-15 22:52:12 +0000532 LI->getPointerOperand()->stripPointerCasts(),
Stephen Hines36b56882014-04-23 16:57:46 -0700533 DL->getTypeStoreSize(SI->getOperand(0)->getType()),
Duncan Sandsf5874752012-10-04 10:54:40 +0000534 std::min(storeAlign, loadAlign), C);
Owen Anderson65491212010-10-15 22:52:12 +0000535 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000536 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000537 SI->eraseFromParent();
Chris Lattnerf4268502011-01-09 19:26:10 +0000538 MD->removeInstruction(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000539 LI->eraseFromParent();
540 ++NumMemCpyInstr;
541 return true;
542 }
543 }
544 }
545 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000546
Owen Andersona723d1e2008-04-09 08:23:16 +0000547 // There are two cases that are interesting for this code to handle: memcpy
548 // and memset. Right now we only handle memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000549
Owen Andersona723d1e2008-04-09 08:23:16 +0000550 // Ensure that the value being stored is something that can be memset'able a
551 // byte at a time like "0" or "-1" or any width, as well as things like
552 // 0xA0A0A0A0 and 0.0.
Chris Lattner67a716a2011-01-08 20:24:01 +0000553 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
554 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
555 ByteVal)) {
556 BBI = I; // Don't invalidate iterator.
557 return true;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000558 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000559
Chris Lattner67a716a2011-01-08 20:24:01 +0000560 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000561}
562
Chris Lattnerd90a1922011-01-08 21:19:19 +0000563bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
564 // See if there is another memset or store neighboring this memset which
565 // allows us to widen out the memset to do a single larger store.
Chris Lattner0468e3e2011-01-08 22:11:56 +0000566 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
567 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
568 MSI->getValue())) {
569 BBI = I; // Don't invalidate iterator.
570 return true;
571 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000572 return false;
573}
574
Owen Andersona723d1e2008-04-09 08:23:16 +0000575
576/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
577/// and checks for the possibility of a call slot optimization by having
578/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000579bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
580 Value *cpyDest, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000581 uint64_t cpyLen, unsigned cpyAlign,
582 CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000583 // The general transformation to keep in mind is
584 //
585 // call @func(..., src, ...)
586 // memcpy(dest, src, ...)
587 //
588 // ->
589 //
590 // memcpy(dest, src, ...)
591 // call @func(..., dest, ...)
592 //
593 // Since moving the memcpy is technically awkward, we additionally check that
594 // src only holds uninitialized values at the moment of the call, meaning that
595 // the memcpy can be discarded rather than moved.
596
597 // Deliberately get the source and destination with bitcasts stripped away,
598 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000599 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000600
Owen Andersona723d1e2008-04-09 08:23:16 +0000601 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000602 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000603 if (!srcAlloca)
604 return false;
605
606 // Check that all of src is copied to dest.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700607 if (!DL) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000608
Chris Lattner61c6ba82009-09-01 17:09:55 +0000609 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000610 if (!srcArraySize)
611 return false;
612
Stephen Hines36b56882014-04-23 16:57:46 -0700613 uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000614 srcArraySize->getZExtValue();
615
Owen Anderson65491212010-10-15 22:52:12 +0000616 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000617 return false;
618
619 // Check that accessing the first srcSize bytes of dest will not cause a
620 // trap. Otherwise the transform is invalid since it might cause a trap
621 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000622 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000623 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000624 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000625 if (!destArraySize)
626 return false;
627
Stephen Hines36b56882014-04-23 16:57:46 -0700628 uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000629 destArraySize->getZExtValue();
630
631 if (destSize < srcSize)
632 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000633 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000634 // If the destination is an sret parameter then only accesses that are
635 // outside of the returned struct type can trap.
636 if (!A->hasStructRetAttr())
637 return false;
638
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000639 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Shuxin Yang9792b642013-06-08 04:56:05 +0000640 if (!StructTy->isSized()) {
641 // The call may never return and hence the copy-instruction may never
642 // be executed, and therefore it's not safe to say "the destination
643 // has at least <cpyLen> bytes, as implied by the copy-instruction",
644 return false;
645 }
646
Stephen Hines36b56882014-04-23 16:57:46 -0700647 uint64_t destSize = DL->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000648 if (destSize < srcSize)
649 return false;
650 } else {
651 return false;
652 }
653
Duncan Sands3372c5a2012-10-05 07:29:46 +0000654 // Check that dest points to memory that is at least as aligned as src.
655 unsigned srcAlign = srcAlloca->getAlignment();
656 if (!srcAlign)
Stephen Hines36b56882014-04-23 16:57:46 -0700657 srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands3372c5a2012-10-05 07:29:46 +0000658 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
659 // If dest is not aligned enough and we can't increase its alignment then
660 // bail out.
661 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
662 return false;
663
Owen Andersona723d1e2008-04-09 08:23:16 +0000664 // Check that src is not accessed except via the call and the memcpy. This
665 // guarantees that it holds only undefined values when passed in (so the final
666 // memcpy can be dropped), that it is not read or written between the call and
667 // the memcpy, and that writing beyond the end of it is undefined.
Stephen Hines36b56882014-04-23 16:57:46 -0700668 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
669 srcAlloca->user_end());
Owen Andersona723d1e2008-04-09 08:23:16 +0000670 while (!srcUseList.empty()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700671 User *U = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000672
Stephen Hines36b56882014-04-23 16:57:46 -0700673 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
674 for (User *UU : U->users())
675 srcUseList.push_back(UU);
676 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000677 if (G->hasAllZeroIndices())
Stephen Hines36b56882014-04-23 16:57:46 -0700678 for (User *UU : U->users())
679 srcUseList.push_back(UU);
Owen Anderson009e4f72008-06-01 22:26:26 +0000680 else
681 return false;
Stephen Hines36b56882014-04-23 16:57:46 -0700682 } else if (U != C && U != cpy) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000683 return false;
684 }
685 }
686
687 // Since we're changing the parameter to the callsite, we need to make sure
688 // that what would be the new parameter dominates the callsite.
Stephen Hines36b56882014-04-23 16:57:46 -0700689 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000690 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000691 if (!DT.dominates(cpyDestInst, C))
692 return false;
693
694 // In addition to knowing that the call does not access src in some
695 // unexpected manner, for example via a global, which we deduce from
696 // the use analysis, we also need to know that it does not sneakily
697 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000698 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chad Rosier3a884f52012-05-14 20:35:04 +0000699 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
700 // If necessary, perform additional analysis.
701 if (MR != AliasAnalysis::NoModRef)
702 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
703 if (MR != AliasAnalysis::NoModRef)
Owen Andersona723d1e2008-04-09 08:23:16 +0000704 return false;
705
706 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000707 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000708 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000709 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sands7508f942012-10-04 13:53:21 +0000710 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
711 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
712 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000713 changedArgument = true;
Duncan Sands7508f942012-10-04 13:53:21 +0000714 if (CS.getArgument(i)->getType() == Dest->getType())
715 CS.setArgument(i, Dest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000716 else
Duncan Sands7508f942012-10-04 13:53:21 +0000717 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
718 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000719 }
720
Owen Anderson12cb36c2008-06-01 21:52:16 +0000721 if (!changedArgument)
722 return false;
723
Duncan Sandsf5874752012-10-04 10:54:40 +0000724 // If the destination wasn't sufficiently aligned then increase its alignment.
725 if (!isDestSufficientlyAligned) {
726 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
727 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
728 }
729
Owen Andersona723d1e2008-04-09 08:23:16 +0000730 // Drop any cached information about the call, because we may have changed
731 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000732 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000733
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000734 // Remove the memcpy.
735 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000736 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000737
738 return true;
739}
740
Chris Lattner43f8e432010-11-18 07:02:37 +0000741/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
742/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
743/// copy from MDep's input if we can. MSize is the size of M's copy.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000744///
Chris Lattner43f8e432010-11-18 07:02:37 +0000745bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
746 uint64_t MSize) {
747 // We can only transforms memcpy's where the dest of one is the source of the
748 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000749 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000750 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000751
Chris Lattnerf7f35462010-12-09 07:39:50 +0000752 // If dep instruction is reading from our current input, then it is a noop
753 // transfer and substituting the input won't change this instruction. Just
754 // ignore the input and let someone else zap MDep. This handles cases like:
755 // memcpy(a <- a)
756 // memcpy(b <- a)
757 if (M->getSource() == MDep->getSource())
758 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000759
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000760 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner43f8e432010-11-18 07:02:37 +0000761 // must be larger than the following one.
Dan Gohman8fb25c52011-01-21 22:07:57 +0000762 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
763 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
764 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
765 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000766
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000767 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000768
769 // Verify that the copied-from memory doesn't change in between the two
770 // transfers. For example, in:
771 // memcpy(a <- b)
772 // *b = 42;
773 // memcpy(c <- a)
774 // It would be invalid to transform the second memcpy into memcpy(c <- b).
775 //
776 // TODO: If the code between M and MDep is transparent to the destination "c",
777 // then we could still perform the xform by moving M up to the first memcpy.
778 //
779 // NOTE: This is conservative, it will stop on any read from the source loc,
780 // not just the defining memcpy.
781 MemDepResult SourceDep =
782 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
783 false, M, M->getParent());
784 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
785 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000786
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000787 // If the dest of the second might alias the source of the first, then the
788 // source and dest might overlap. We still want to eliminate the intermediate
789 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000790 bool UseMemMove = false;
791 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
792 UseMemMove = true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000793
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000794 // If all checks passed, then we can transform M.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000795
Chris Lattner43f8e432010-11-18 07:02:37 +0000796 // Make sure to use the lesser of the alignment of the source and the dest
797 // since we're changing where we're reading from, but don't want to increase
798 // the alignment past what can be read from or written to.
799 // TODO: Is this worth it if we're creating a less aligned memcpy? For
800 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000801 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000802
Chris Lattner61db1f52010-12-26 22:57:41 +0000803 IRBuilder<> Builder(M);
804 if (UseMemMove)
805 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
806 Align, M->isVolatile());
807 else
808 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
809 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000810
Chris Lattner604f6fe2010-11-21 08:06:10 +0000811 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000812 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000813 M->eraseFromParent();
814 ++NumMemCpyInstr;
815 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000816}
817
818
Gabor Greif7d3056b2010-07-28 22:50:26 +0000819/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
820/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
821/// B to be a memcpy from X to Z (or potentially a memmove, depending on
822/// circumstances). This allows later passes to remove the first memcpy
823/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000824bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Stephen Hines36b56882014-04-23 16:57:46 -0700825 // We can only optimize non-volatile memcpy's.
826 if (M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000827
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000828 // If the source and destination of the memcpy are the same, then zap it.
829 if (M->getSource() == M->getDest()) {
830 MD->removeInstruction(M);
831 M->eraseFromParent();
832 return false;
833 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000834
835 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000836 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000837 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000838 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000839 IRBuilder<> Builder(M);
Stephen Hines36b56882014-04-23 16:57:46 -0700840 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Chris Lattner61db1f52010-12-26 22:57:41 +0000841 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000842 MD->removeInstruction(M);
843 M->eraseFromParent();
844 ++NumCpyToSet;
845 return true;
846 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000847
Stephen Hines36b56882014-04-23 16:57:46 -0700848 // The optimizations after this point require the memcpy size.
849 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700850 if (!CopySize) return false;
Stephen Hines36b56882014-04-23 16:57:46 -0700851
852 // The are three possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000853 // a) memcpy-memcpy xform which exposes redundance for DSE.
854 // b) call-memcpy xform for return slot optimization.
Stephen Hines36b56882014-04-23 16:57:46 -0700855 // c) memcpy from freshly alloca'd space or space that has just started its
856 // lifetime copies undefined data, and we can therefore eliminate the
857 // memcpy in favor of the data that was already at the destination.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000858 MemDepResult DepInfo = MD->getDependency(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000859 if (DepInfo.isClobber()) {
860 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
861 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Duncan Sandsf5874752012-10-04 10:54:40 +0000862 CopySize->getZExtValue(), M->getAlignment(),
863 C)) {
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000864 MD->removeInstruction(M);
865 M->eraseFromParent();
866 return true;
867 }
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000868 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000869 }
Ahmed Charlesb83a67e2012-02-13 06:30:56 +0000870
871 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000872 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
873 M, M->getParent());
874 if (SrcDepInfo.isClobber()) {
875 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
876 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Stephen Hines36b56882014-04-23 16:57:46 -0700877 } else if (SrcDepInfo.isDef()) {
878 Instruction *I = SrcDepInfo.getInst();
879 bool hasUndefContents = false;
880
881 if (isa<AllocaInst>(I)) {
882 hasUndefContents = true;
883 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
884 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
885 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
886 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
887 hasUndefContents = true;
888 }
889
890 if (hasUndefContents) {
891 MD->removeInstruction(M);
892 M->eraseFromParent();
893 ++NumMemCpyInstr;
894 return true;
895 }
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000896 }
897
Owen Anderson02e99882008-04-29 21:51:00 +0000898 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000899}
900
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000901/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
902/// are guaranteed not to alias.
903bool MemCpyOpt::processMemMove(MemMoveInst *M) {
904 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
905
Chris Lattner149f5282011-05-01 18:27:11 +0000906 if (!TLI->has(LibFunc::memmove))
907 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000908
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000909 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000910 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000911 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000912
David Greenecb33fd12010-01-05 01:27:47 +0000913 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000914
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000915 // If not, then we know we can transform this.
916 Module *Mod = M->getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +0000917 Type *ArgTys[3] = { M->getRawDest()->getType(),
918 M->getRawSource()->getType(),
919 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000920 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000921 ArgTys));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000922
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000923 // MemDep may have over conservative information about this instruction, just
924 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000925 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000926
927 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000928 return true;
929}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000930
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000931/// processByValArgument - This is called on every byval argument in call sites.
932bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700933 if (!DL) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000934
Chris Lattner604f6fe2010-11-21 08:06:10 +0000935 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000936 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewycky865703e2011-10-12 00:14:31 +0000937 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700938 uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000939 MemDepResult DepInfo =
940 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
941 true, CS.getInstruction(),
942 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000943 if (!DepInfo.isClobber())
944 return false;
945
946 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
947 // a memcpy, see if we can byval from the source of the memcpy instead of the
948 // result.
949 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700950 if (!MDep || MDep->isVolatile() ||
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000951 ByValArg->stripPointerCasts() != MDep->getDest())
952 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000953
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000954 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000955 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700956 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000957 return false;
958
Chris Lattnerb3f06732011-05-23 00:03:39 +0000959 // Get the alignment of the byval. If the call doesn't specify the alignment,
960 // then it is some target specific value that we can't know.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000961 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattnerb3f06732011-05-23 00:03:39 +0000962 if (ByValAlign == 0) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000963
Chris Lattnerb3f06732011-05-23 00:03:39 +0000964 // If it is greater than the memcpy, then we check to see if we can force the
965 // source of the memcpy to the alignment we need. If we fail, we bail out.
966 if (MDep->getAlignment() < ByValAlign &&
Stephen Hines36b56882014-04-23 16:57:46 -0700967 getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, DL) < ByValAlign)
Chris Lattnerb3f06732011-05-23 00:03:39 +0000968 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000969
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000970 // Verify that the copied-from memory doesn't change in between the memcpy and
971 // the byval call.
972 // memcpy(a <- b)
973 // *b = 42;
974 // foo(*a)
975 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000976 //
977 // NOTE: This is conservative, it will stop on any read from the source loc,
978 // not just the defining memcpy.
979 MemDepResult SourceDep =
980 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
981 false, CS.getInstruction(), MDep->getParent());
982 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
983 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000984
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000985 Value *TmpCast = MDep->getSource();
986 if (MDep->getSource()->getType() != ByValArg->getType())
987 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
988 "tmpcast", CS.getInstruction());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000989
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000990 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
991 << " " << *MDep << "\n"
992 << " " << *CS.getInstruction() << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000993
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000994 // Otherwise we're good! Update the byval argument.
995 CS.setArgument(ArgNo, TmpCast);
996 ++NumMemCpyInstr;
997 return true;
998}
999
1000/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +00001001bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +00001002 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +00001003
Chris Lattner61c6ba82009-09-01 17:09:55 +00001004 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +00001005 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001006 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +00001007 // Avoid invalidating the iterator.
1008 Instruction *I = BI++;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001009
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001010 bool RepeatInstruction = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001011
Owen Andersona8bd6582008-04-21 07:45:10 +00001012 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +00001013 MadeChange |= processStore(SI, BI);
Chris Lattnerd90a1922011-01-08 21:19:19 +00001014 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1015 RepeatInstruction = processMemSet(M, BI);
1016 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001017 RepeatInstruction = processMemCpy(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +00001018 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001019 RepeatInstruction = processMemMove(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +00001020 else if (CallSite CS = (Value*)I) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001021 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky173862e2011-11-20 19:09:04 +00001022 if (CS.isByValArgument(i))
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001023 MadeChange |= processByValArgument(CS, i);
1024 }
1025
1026 // Reprocess the instruction if desired.
1027 if (RepeatInstruction) {
Chris Lattner8a629572011-01-08 22:19:21 +00001028 if (BI != BB->begin()) --BI;
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001029 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +00001030 }
Owen Andersona723d1e2008-04-09 08:23:16 +00001031 }
1032 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001033
Chris Lattner61c6ba82009-09-01 17:09:55 +00001034 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +00001035}
Chris Lattner61c6ba82009-09-01 17:09:55 +00001036
1037// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1038// function.
1039//
1040bool MemCpyOpt::runOnFunction(Function &F) {
Stephen Hines36b56882014-04-23 16:57:46 -07001041 if (skipOptnoneFunction(F))
1042 return false;
1043
Chris Lattner61c6ba82009-09-01 17:09:55 +00001044 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001045 MD = &getAnalysis<MemoryDependenceAnalysis>();
Stephen Hines36b56882014-04-23 16:57:46 -07001046 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001047 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chris Lattner149f5282011-05-01 18:27:11 +00001048 TLI = &getAnalysis<TargetLibraryInfo>();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001049
Chris Lattner149f5282011-05-01 18:27:11 +00001050 // If we don't have at least memset and memcpy, there is little point of doing
1051 // anything here. These are required by a freestanding implementation, so if
1052 // even they are disabled, there is no point in trying hard.
1053 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1054 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001055
Chris Lattner61c6ba82009-09-01 17:09:55 +00001056 while (1) {
1057 if (!iterateOnFunction(F))
1058 break;
1059 MadeChange = true;
1060 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001061
Stephen Hinesdce4a402014-05-29 02:49:00 -07001062 MD = nullptr;
Chris Lattner61c6ba82009-09-01 17:09:55 +00001063 return MadeChange;
1064}