Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1 | //===- 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 Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 17 | #include "llvm/IntrinsicInst.h" |
| 18 | #include "llvm/Instructions.h" |
Owen Anderson | fa5cbd6 | 2009-07-03 19:42:02 +0000 | [diff] [blame] | 19 | #include "llvm/LLVMContext.h" |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/SmallVector.h" |
| 21 | #include "llvm/ADT/Statistic.h" |
| 22 | #include "llvm/Analysis/Dominators.h" |
| 23 | #include "llvm/Analysis/AliasAnalysis.h" |
| 24 | #include "llvm/Analysis/MemoryDependenceAnalysis.h" |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 25 | #include "llvm/Support/Debug.h" |
| 26 | #include "llvm/Support/GetElementPtrTypeIterator.h" |
Chris Lattner | bdff548 | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 27 | #include "llvm/Support/raw_ostream.h" |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 28 | #include "llvm/Target/TargetData.h" |
| 29 | #include <list> |
| 30 | using namespace llvm; |
| 31 | |
| 32 | STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted"); |
| 33 | STATISTIC(NumMemSetInfer, "Number of memsets inferred"); |
Duncan Sands | 05cd03b | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 34 | STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy"); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 35 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 36 | /// isBytewiseValue - If the specified value can be set by repeating the same |
| 37 | /// byte in memory, return the i8 value that it is represented with. This is |
| 38 | /// true for all i8 values obviously, but is also true for i32 0, i32 -1, |
| 39 | /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated |
| 40 | /// byte store (e.g. i16 0x1234), return null. |
Chris Lattner | cf0fe8d | 2009-10-05 05:54:46 +0000 | [diff] [blame] | 41 | static Value *isBytewiseValue(Value *V) { |
| 42 | LLVMContext &Context = V->getContext(); |
| 43 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 44 | // All byte-wide stores are splatable, even of arbitrary variables. |
Duncan Sands | b0bc6c3 | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 45 | if (V->getType()->isIntegerTy(8)) return V; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 46 | |
| 47 | // Constant float and double values can be handled as integer values if the |
| 48 | // corresponding integer value is "byteable". An important case is 0.0. |
| 49 | if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { |
Chris Lattner | cf0fe8d | 2009-10-05 05:54:46 +0000 | [diff] [blame] | 50 | if (CFP->getType()->isFloatTy()) |
Owen Anderson | 1d0be15 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 51 | V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(Context)); |
Chris Lattner | cf0fe8d | 2009-10-05 05:54:46 +0000 | [diff] [blame] | 52 | if (CFP->getType()->isDoubleTy()) |
Owen Anderson | 1d0be15 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 53 | V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(Context)); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 54 | // Don't handle long double formats, which have strange constraints. |
| 55 | } |
| 56 | |
| 57 | // We can handle constant integers that are power of two in size and a |
| 58 | // multiple of 8 bits. |
| 59 | if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { |
| 60 | unsigned Width = CI->getBitWidth(); |
| 61 | if (isPowerOf2_32(Width) && Width > 8) { |
| 62 | // We can handle this value if the recursive binary decomposition is the |
| 63 | // same at all levels. |
| 64 | APInt Val = CI->getValue(); |
| 65 | APInt Val2; |
| 66 | while (Val.getBitWidth() != 8) { |
| 67 | unsigned NextWidth = Val.getBitWidth()/2; |
| 68 | Val2 = Val.lshr(NextWidth); |
| 69 | Val2.trunc(Val.getBitWidth()/2); |
| 70 | Val.trunc(Val.getBitWidth()/2); |
| 71 | |
| 72 | // If the top/bottom halves aren't the same, reject it. |
| 73 | if (Val != Val2) |
| 74 | return 0; |
| 75 | } |
Owen Anderson | eed707b | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 76 | return ConstantInt::get(Context, Val); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 77 | } |
| 78 | } |
| 79 | |
| 80 | // Conceptually, we could handle things like: |
| 81 | // %a = zext i8 %X to i16 |
| 82 | // %b = shl i16 %a, 8 |
| 83 | // %c = or i16 %a, %b |
| 84 | // but until there is an example that actually needs this, it doesn't seem |
| 85 | // worth worrying about. |
| 86 | return 0; |
| 87 | } |
| 88 | |
| 89 | static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx, |
| 90 | bool &VariableIdxFound, TargetData &TD) { |
| 91 | // Skip over the first indices. |
| 92 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 93 | for (unsigned i = 1; i != Idx; ++i, ++GTI) |
| 94 | /*skip along*/; |
| 95 | |
| 96 | // Compute the offset implied by the rest of the indices. |
| 97 | int64_t Offset = 0; |
| 98 | for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) { |
| 99 | ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 100 | if (OpC == 0) |
| 101 | return VariableIdxFound = true; |
| 102 | if (OpC->isZero()) continue; // No offset. |
| 103 | |
| 104 | // Handle struct indices, which add their field offset to the pointer. |
| 105 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 106 | Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue()); |
| 107 | continue; |
| 108 | } |
| 109 | |
| 110 | // Otherwise, we have a sequential type like an array or vector. Multiply |
| 111 | // the index by the ElementSize. |
Duncan Sands | 777d230 | 2009-05-09 07:06:46 +0000 | [diff] [blame] | 112 | uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 113 | Offset += Size*OpC->getSExtValue(); |
| 114 | } |
| 115 | |
| 116 | return Offset; |
| 117 | } |
| 118 | |
| 119 | /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a |
| 120 | /// constant offset, and return that constant offset. For example, Ptr1 might |
| 121 | /// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8. |
| 122 | static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset, |
| 123 | TargetData &TD) { |
| 124 | // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical |
| 125 | // base. After that base, they may have some number of common (and |
| 126 | // potentially variable) indices. After that they handle some constant |
| 127 | // offset, which determines their offset from each other. At this point, we |
| 128 | // handle no other case. |
| 129 | GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1); |
| 130 | GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2); |
| 131 | if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0)) |
| 132 | return false; |
| 133 | |
| 134 | // Skip any common indices and track the GEP types. |
| 135 | unsigned Idx = 1; |
| 136 | for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx) |
| 137 | if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx)) |
| 138 | break; |
| 139 | |
| 140 | bool VariableIdxFound = false; |
| 141 | int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD); |
| 142 | int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD); |
| 143 | if (VariableIdxFound) return false; |
| 144 | |
| 145 | Offset = Offset2-Offset1; |
| 146 | return true; |
| 147 | } |
| 148 | |
| 149 | |
| 150 | /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value. |
| 151 | /// This allows us to analyze stores like: |
| 152 | /// store 0 -> P+1 |
| 153 | /// store 0 -> P+0 |
| 154 | /// store 0 -> P+3 |
| 155 | /// store 0 -> P+2 |
| 156 | /// which sometimes happens with stores to arrays of structs etc. When we see |
| 157 | /// the first store, we make a range [1, 2). The second store extends the range |
| 158 | /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the |
| 159 | /// two ranges into [0, 3) which is memset'able. |
| 160 | namespace { |
| 161 | struct MemsetRange { |
| 162 | // Start/End - A semi range that describes the span that this range covers. |
| 163 | // The range is closed at the start and open at the end: [Start, End). |
| 164 | int64_t Start, End; |
| 165 | |
| 166 | /// StartPtr - The getelementptr instruction that points to the start of the |
| 167 | /// range. |
| 168 | Value *StartPtr; |
| 169 | |
| 170 | /// Alignment - The known alignment of the first store. |
| 171 | unsigned Alignment; |
| 172 | |
| 173 | /// TheStores - The actual stores that make up this range. |
| 174 | SmallVector<StoreInst*, 16> TheStores; |
| 175 | |
| 176 | bool isProfitableToUseMemset(const TargetData &TD) const; |
| 177 | |
| 178 | }; |
| 179 | } // end anon namespace |
| 180 | |
| 181 | bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const { |
| 182 | // If we found more than 8 stores to merge or 64 bytes, use memset. |
| 183 | if (TheStores.size() >= 8 || End-Start >= 64) return true; |
| 184 | |
| 185 | // Assume that the code generator is capable of merging pairs of stores |
| 186 | // together if it wants to. |
| 187 | if (TheStores.size() <= 2) return false; |
| 188 | |
| 189 | // If we have fewer than 8 stores, it can still be worthwhile to do this. |
| 190 | // For example, merging 4 i8 stores into an i32 store is useful almost always. |
| 191 | // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the |
| 192 | // memset will be split into 2 32-bit stores anyway) and doing so can |
| 193 | // pessimize the llvm optimizer. |
| 194 | // |
| 195 | // Since we don't have perfect knowledge here, make some assumptions: assume |
| 196 | // the maximum GPR width is the same size as the pointer size and assume that |
| 197 | // this width can be stored. If so, check to see whether we will end up |
| 198 | // actually reducing the number of stores used. |
| 199 | unsigned Bytes = unsigned(End-Start); |
| 200 | unsigned NumPointerStores = Bytes/TD.getPointerSize(); |
| 201 | |
| 202 | // Assume the remaining bytes if any are done a byte at a time. |
| 203 | unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize(); |
| 204 | |
| 205 | // If we will reduce the # stores (according to this heuristic), do the |
| 206 | // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32 |
| 207 | // etc. |
| 208 | return TheStores.size() > NumPointerStores+NumByteStores; |
| 209 | } |
| 210 | |
| 211 | |
| 212 | namespace { |
| 213 | class MemsetRanges { |
| 214 | /// Ranges - A sorted list of the memset ranges. We use std::list here |
| 215 | /// because each element is relatively large and expensive to copy. |
| 216 | std::list<MemsetRange> Ranges; |
| 217 | typedef std::list<MemsetRange>::iterator range_iterator; |
| 218 | TargetData &TD; |
| 219 | public: |
| 220 | MemsetRanges(TargetData &td) : TD(td) {} |
| 221 | |
| 222 | typedef std::list<MemsetRange>::const_iterator const_iterator; |
| 223 | const_iterator begin() const { return Ranges.begin(); } |
| 224 | const_iterator end() const { return Ranges.end(); } |
| 225 | bool empty() const { return Ranges.empty(); } |
| 226 | |
| 227 | void addStore(int64_t OffsetFromFirst, StoreInst *SI); |
| 228 | }; |
| 229 | |
| 230 | } // end anon namespace |
| 231 | |
| 232 | |
| 233 | /// addStore - Add a new store to the MemsetRanges data structure. This adds a |
| 234 | /// new range for the specified store at the specified offset, merging into |
| 235 | /// existing ranges as appropriate. |
| 236 | void MemsetRanges::addStore(int64_t Start, StoreInst *SI) { |
| 237 | int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType()); |
| 238 | |
| 239 | // Do a linear search of the ranges to see if this can be joined and/or to |
| 240 | // find the insertion point in the list. We keep the ranges sorted for |
| 241 | // simplicity here. This is a linear search of a linked list, which is ugly, |
| 242 | // however the number of ranges is limited, so this won't get crazy slow. |
| 243 | range_iterator I = Ranges.begin(), E = Ranges.end(); |
| 244 | |
| 245 | while (I != E && Start > I->End) |
| 246 | ++I; |
| 247 | |
| 248 | // We now know that I == E, in which case we didn't find anything to merge |
| 249 | // with, or that Start <= I->End. If End < I->Start or I == E, then we need |
| 250 | // to insert a new range. Handle this now. |
| 251 | if (I == E || End < I->Start) { |
| 252 | MemsetRange &R = *Ranges.insert(I, MemsetRange()); |
| 253 | R.Start = Start; |
| 254 | R.End = End; |
| 255 | R.StartPtr = SI->getPointerOperand(); |
| 256 | R.Alignment = SI->getAlignment(); |
| 257 | R.TheStores.push_back(SI); |
| 258 | return; |
| 259 | } |
| 260 | |
| 261 | // This store overlaps with I, add it. |
| 262 | I->TheStores.push_back(SI); |
| 263 | |
| 264 | // At this point, we may have an interval that completely contains our store. |
| 265 | // If so, just add it to the interval and return. |
| 266 | if (I->Start <= Start && I->End >= End) |
| 267 | return; |
| 268 | |
| 269 | // Now we know that Start <= I->End and End >= I->Start so the range overlaps |
| 270 | // but is not entirely contained within the range. |
| 271 | |
| 272 | // See if the range extends the start of the range. In this case, it couldn't |
| 273 | // possibly cause it to join the prior range, because otherwise we would have |
| 274 | // stopped on *it*. |
| 275 | if (Start < I->Start) { |
| 276 | I->Start = Start; |
| 277 | I->StartPtr = SI->getPointerOperand(); |
Dan Gohman | 264d245 | 2009-09-14 23:39:10 +0000 | [diff] [blame] | 278 | I->Alignment = SI->getAlignment(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 279 | } |
| 280 | |
| 281 | // Now we know that Start <= I->End and Start >= I->Start (so the startpoint |
| 282 | // is in or right at the end of I), and that End >= I->Start. Extend I out to |
| 283 | // End. |
| 284 | if (End > I->End) { |
| 285 | I->End = End; |
Nick Lewycky | 9c0f146 | 2009-03-19 05:51:39 +0000 | [diff] [blame] | 286 | range_iterator NextI = I; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 287 | while (++NextI != E && End >= NextI->Start) { |
| 288 | // Merge the range in. |
| 289 | I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end()); |
| 290 | if (NextI->End > I->End) |
| 291 | I->End = NextI->End; |
| 292 | Ranges.erase(NextI); |
| 293 | NextI = I; |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | //===----------------------------------------------------------------------===// |
| 299 | // MemCpyOpt Pass |
| 300 | //===----------------------------------------------------------------------===// |
| 301 | |
| 302 | namespace { |
Chris Lattner | 3e8b663 | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 303 | class MemCpyOpt : public FunctionPass { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 304 | MemoryDependenceAnalysis *MD; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 305 | bool runOnFunction(Function &F); |
| 306 | public: |
| 307 | static char ID; // Pass identification, replacement for typeid |
Owen Anderson | 081c34b | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 308 | MemCpyOpt() : FunctionPass(ID) { |
| 309 | initializeMemCpyOptPass(*PassRegistry::getPassRegistry()); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 310 | MD = 0; |
Owen Anderson | 081c34b | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 311 | } |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 312 | |
| 313 | private: |
| 314 | // This transformation requires dominator postdominator info |
| 315 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 316 | AU.setPreservesCFG(); |
| 317 | AU.addRequired<DominatorTree>(); |
| 318 | AU.addRequired<MemoryDependenceAnalysis>(); |
| 319 | AU.addRequired<AliasAnalysis>(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 320 | AU.addPreserved<AliasAnalysis>(); |
| 321 | AU.addPreserved<MemoryDependenceAnalysis>(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 322 | } |
| 323 | |
| 324 | // Helper fuctions |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 325 | bool processStore(StoreInst *SI, BasicBlock::iterator &BBI); |
| 326 | bool processMemCpy(MemCpyInst *M); |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 327 | bool processMemMove(MemMoveInst *M); |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 328 | bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc, |
| 329 | uint64_t cpyLen, CallInst *C); |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 330 | bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep, |
| 331 | uint64_t MSize); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 332 | bool processByValArgument(CallSite CS, unsigned ArgNo); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 333 | bool iterateOnFunction(Function &F); |
| 334 | }; |
| 335 | |
| 336 | char MemCpyOpt::ID = 0; |
| 337 | } |
| 338 | |
| 339 | // createMemCpyOptPass - The public interface to this file... |
| 340 | FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); } |
| 341 | |
Owen Anderson | 2ab36d3 | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 342 | INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization", |
| 343 | false, false) |
| 344 | INITIALIZE_PASS_DEPENDENCY(DominatorTree) |
| 345 | INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis) |
| 346 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
| 347 | INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization", |
| 348 | false, false) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 349 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 350 | /// processStore - When GVN is scanning forward over instructions, we look for |
| 351 | /// some other patterns to fold away. In particular, this looks for stores to |
| 352 | /// neighboring locations of memory. If it sees enough consequtive ones |
| 353 | /// (currently 4) it attempts to merge them together into a memcpy/memset. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 354 | bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 355 | if (SI->isVolatile()) return false; |
| 356 | |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 357 | TargetData *TD = getAnalysisIfAvailable<TargetData>(); |
| 358 | if (!TD) return false; |
| 359 | |
| 360 | // Detect cases where we're performing call slot forwarding, but |
| 361 | // happen to be using a load-store pair to implement it, rather than |
| 362 | // a memcpy. |
| 363 | if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) { |
| 364 | if (!LI->isVolatile() && LI->hasOneUse()) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 365 | MemDepResult dep = MD->getDependency(LI); |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 366 | CallInst *C = 0; |
| 367 | if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst())) |
| 368 | C = dyn_cast<CallInst>(dep.getInst()); |
| 369 | |
| 370 | if (C) { |
| 371 | bool changed = performCallSlotOptzn(LI, |
| 372 | SI->getPointerOperand()->stripPointerCasts(), |
| 373 | LI->getPointerOperand()->stripPointerCasts(), |
| 374 | TD->getTypeStoreSize(SI->getOperand(0)->getType()), C); |
| 375 | if (changed) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 376 | MD->removeInstruction(SI); |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 377 | SI->eraseFromParent(); |
| 378 | LI->eraseFromParent(); |
| 379 | ++NumMemCpyInstr; |
| 380 | return true; |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | |
Chris Lattner | ff1e98c | 2009-09-08 00:27:14 +0000 | [diff] [blame] | 386 | LLVMContext &Context = SI->getContext(); |
| 387 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 388 | // There are two cases that are interesting for this code to handle: memcpy |
| 389 | // and memset. Right now we only handle memset. |
| 390 | |
| 391 | // Ensure that the value being stored is something that can be memset'able a |
| 392 | // byte at a time like "0" or "-1" or any width, as well as things like |
| 393 | // 0xA0A0A0A0 and 0.0. |
Chris Lattner | cf0fe8d | 2009-10-05 05:54:46 +0000 | [diff] [blame] | 394 | Value *ByteVal = isBytewiseValue(SI->getOperand(0)); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 395 | if (!ByteVal) |
| 396 | return false; |
| 397 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 398 | AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); |
Dan Gohman | a195b7f | 2009-07-28 00:37:06 +0000 | [diff] [blame] | 399 | Module *M = SI->getParent()->getParent()->getParent(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 400 | |
| 401 | // Okay, so we now have a single store that can be splatable. Scan to find |
| 402 | // all subsequent stores of the same value to offset from the same pointer. |
| 403 | // Join these together into ranges, so we can decide whether contiguous blocks |
| 404 | // are stored. |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 405 | MemsetRanges Ranges(*TD); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 406 | |
| 407 | Value *StartPtr = SI->getPointerOperand(); |
| 408 | |
| 409 | BasicBlock::iterator BI = SI; |
| 410 | for (++BI; !isa<TerminatorInst>(BI); ++BI) { |
| 411 | if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) { |
| 412 | // If the call is readnone, ignore it, otherwise bail out. We don't even |
| 413 | // allow readonly here because we don't want something like: |
| 414 | // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A). |
Gabor Greif | a292b2f | 2010-07-27 16:44:23 +0000 | [diff] [blame] | 415 | if (AA.getModRefBehavior(CallSite(BI)) == |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 416 | AliasAnalysis::DoesNotAccessMemory) |
| 417 | continue; |
| 418 | |
| 419 | // TODO: If this is a memset, try to join it in. |
| 420 | |
| 421 | break; |
| 422 | } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI)) |
| 423 | break; |
| 424 | |
| 425 | // If this is a non-store instruction it is fine, ignore it. |
| 426 | StoreInst *NextStore = dyn_cast<StoreInst>(BI); |
| 427 | if (NextStore == 0) continue; |
| 428 | |
| 429 | // If this is a store, see if we can merge it in. |
| 430 | if (NextStore->isVolatile()) break; |
| 431 | |
| 432 | // Check to see if this stored value is of the same byte-splattable value. |
Chris Lattner | cf0fe8d | 2009-10-05 05:54:46 +0000 | [diff] [blame] | 433 | if (ByteVal != isBytewiseValue(NextStore->getOperand(0))) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 434 | break; |
| 435 | |
| 436 | // Check to see if this store is to a constant offset from the start ptr. |
| 437 | int64_t Offset; |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 438 | if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD)) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 439 | break; |
| 440 | |
| 441 | Ranges.addStore(Offset, NextStore); |
| 442 | } |
| 443 | |
| 444 | // If we have no ranges, then we just had a single store with nothing that |
| 445 | // could be merged in. This is a very common case of course. |
| 446 | if (Ranges.empty()) |
| 447 | return false; |
| 448 | |
| 449 | // If we had at least one store that could be merged in, add the starting |
| 450 | // store as well. We try to avoid this unless there is at least something |
| 451 | // interesting as a small compile-time optimization. |
| 452 | Ranges.addStore(0, SI); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 453 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 454 | |
| 455 | // Now that we have full information about ranges, loop over the ranges and |
| 456 | // emit memset's for anything big enough to be worthwhile. |
| 457 | bool MadeChange = false; |
| 458 | for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end(); |
| 459 | I != E; ++I) { |
| 460 | const MemsetRange &Range = *I; |
| 461 | |
| 462 | if (Range.TheStores.size() == 1) continue; |
| 463 | |
| 464 | // If it is profitable to lower this range to memset, do so now. |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 465 | if (!Range.isProfitableToUseMemset(*TD)) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 466 | continue; |
| 467 | |
| 468 | // Otherwise, we do want to transform this! Create a new memset. We put |
| 469 | // the memset right before the first instruction that isn't part of this |
| 470 | // memset block. This ensure that the memset is dominated by any addressing |
| 471 | // instruction needed by the start of the block. |
| 472 | BasicBlock::iterator InsertPt = BI; |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 473 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 474 | // Get the starting pointer of the block. |
| 475 | StartPtr = Range.StartPtr; |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 476 | |
| 477 | // Determine alignment |
| 478 | unsigned Alignment = Range.Alignment; |
| 479 | if (Alignment == 0) { |
| 480 | const Type *EltType = |
| 481 | cast<PointerType>(StartPtr->getType())->getElementType(); |
| 482 | Alignment = TD->getABITypeAlignment(EltType); |
| 483 | } |
| 484 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 485 | // Cast the start ptr to be i8* as memset requires. |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 486 | const PointerType* StartPTy = cast<PointerType>(StartPtr->getType()); |
| 487 | const PointerType *i8Ptr = Type::getInt8PtrTy(Context, |
| 488 | StartPTy->getAddressSpace()); |
| 489 | if (StartPTy!= i8Ptr) |
Daniel Dunbar | 460f656 | 2009-07-26 09:48:23 +0000 | [diff] [blame] | 490 | StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getName(), |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 491 | InsertPt); |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 492 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 493 | Value *Ops[] = { |
| 494 | StartPtr, ByteVal, // Start, value |
Owen Anderson | e922c02 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 495 | // size |
Chris Lattner | ff1e98c | 2009-09-08 00:27:14 +0000 | [diff] [blame] | 496 | ConstantInt::get(Type::getInt64Ty(Context), Range.End-Range.Start), |
Owen Anderson | e922c02 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 497 | // align |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 498 | ConstantInt::get(Type::getInt32Ty(Context), Alignment), |
| 499 | // volatile |
Benjamin Kramer | f601d6d | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 500 | ConstantInt::getFalse(Context), |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 501 | }; |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 502 | const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() }; |
| 503 | |
| 504 | Function *MemSetF = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2); |
| 505 | |
| 506 | Value *C = CallInst::Create(MemSetF, Ops, Ops+5, "", InsertPt); |
David Greene | cb33fd1 | 2010-01-05 01:27:47 +0000 | [diff] [blame] | 507 | DEBUG(dbgs() << "Replace stores:\n"; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 508 | for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i) |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 509 | dbgs() << *Range.TheStores[i] << '\n'; |
| 510 | dbgs() << "With: " << *C << '\n'); C=C; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 511 | |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 512 | // Don't invalidate the iterator |
| 513 | BBI = BI; |
| 514 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 515 | // Zap all the stores. |
Chris Lattner | ff1e98c | 2009-09-08 00:27:14 +0000 | [diff] [blame] | 516 | for (SmallVector<StoreInst*, 16>::const_iterator |
| 517 | SI = Range.TheStores.begin(), |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 518 | SE = Range.TheStores.end(); SI != SE; ++SI) |
| 519 | (*SI)->eraseFromParent(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 520 | ++NumMemSetInfer; |
| 521 | MadeChange = true; |
| 522 | } |
| 523 | |
| 524 | return MadeChange; |
| 525 | } |
| 526 | |
| 527 | |
| 528 | /// performCallSlotOptzn - takes a memcpy and a call that it depends on, |
| 529 | /// and checks for the possibility of a call slot optimization by having |
| 530 | /// the call write its result directly into the destination of the memcpy. |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 531 | bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy, |
| 532 | Value *cpyDest, Value *cpySrc, |
| 533 | uint64_t cpyLen, CallInst *C) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 534 | // The general transformation to keep in mind is |
| 535 | // |
| 536 | // call @func(..., src, ...) |
| 537 | // memcpy(dest, src, ...) |
| 538 | // |
| 539 | // -> |
| 540 | // |
| 541 | // memcpy(dest, src, ...) |
| 542 | // call @func(..., dest, ...) |
| 543 | // |
| 544 | // Since moving the memcpy is technically awkward, we additionally check that |
| 545 | // src only holds uninitialized values at the moment of the call, meaning that |
| 546 | // the memcpy can be discarded rather than moved. |
| 547 | |
| 548 | // Deliberately get the source and destination with bitcasts stripped away, |
| 549 | // because we'll need to do type comparisons based on the underlying type. |
Gabor Greif | 7d3056b | 2010-07-28 22:50:26 +0000 | [diff] [blame] | 550 | CallSite CS(C); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 551 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 552 | // Require that src be an alloca. This simplifies the reasoning considerably. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 553 | AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 554 | if (!srcAlloca) |
| 555 | return false; |
| 556 | |
| 557 | // Check that all of src is copied to dest. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 558 | TargetData *TD = getAnalysisIfAvailable<TargetData>(); |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 559 | if (!TD) return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 560 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 561 | ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 562 | if (!srcArraySize) |
| 563 | return false; |
| 564 | |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 565 | uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) * |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 566 | srcArraySize->getZExtValue(); |
| 567 | |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 568 | if (cpyLen < srcSize) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 569 | return false; |
| 570 | |
| 571 | // Check that accessing the first srcSize bytes of dest will not cause a |
| 572 | // trap. Otherwise the transform is invalid since it might cause a trap |
| 573 | // to occur earlier than it otherwise would. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 574 | if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 575 | // The destination is an alloca. Check it is larger than srcSize. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 576 | ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 577 | if (!destArraySize) |
| 578 | return false; |
| 579 | |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 580 | uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) * |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 581 | destArraySize->getZExtValue(); |
| 582 | |
| 583 | if (destSize < srcSize) |
| 584 | return false; |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 585 | } else if (Argument *A = dyn_cast<Argument>(cpyDest)) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 586 | // If the destination is an sret parameter then only accesses that are |
| 587 | // outside of the returned struct type can trap. |
| 588 | if (!A->hasStructRetAttr()) |
| 589 | return false; |
| 590 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 591 | const Type *StructTy = cast<PointerType>(A->getType())->getElementType(); |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 592 | uint64_t destSize = TD->getTypeAllocSize(StructTy); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 593 | |
| 594 | if (destSize < srcSize) |
| 595 | return false; |
| 596 | } else { |
| 597 | return false; |
| 598 | } |
| 599 | |
| 600 | // Check that src is not accessed except via the call and the memcpy. This |
| 601 | // guarantees that it holds only undefined values when passed in (so the final |
| 602 | // memcpy can be dropped), that it is not read or written between the call and |
| 603 | // the memcpy, and that writing beyond the end of it is undefined. |
| 604 | SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(), |
| 605 | srcAlloca->use_end()); |
| 606 | while (!srcUseList.empty()) { |
Dan Gohman | 321a813 | 2010-01-05 16:27:25 +0000 | [diff] [blame] | 607 | User *UI = srcUseList.pop_back_val(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 608 | |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 609 | if (isa<BitCastInst>(UI)) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 610 | for (User::use_iterator I = UI->use_begin(), E = UI->use_end(); |
| 611 | I != E; ++I) |
| 612 | srcUseList.push_back(*I); |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 613 | } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) { |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 614 | if (G->hasAllZeroIndices()) |
| 615 | for (User::use_iterator I = UI->use_begin(), E = UI->use_end(); |
| 616 | I != E; ++I) |
| 617 | srcUseList.push_back(*I); |
| 618 | else |
| 619 | return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 620 | } else if (UI != C && UI != cpy) { |
| 621 | return false; |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | // Since we're changing the parameter to the callsite, we need to make sure |
| 626 | // that what would be the new parameter dominates the callsite. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 627 | DominatorTree &DT = getAnalysis<DominatorTree>(); |
| 628 | if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest)) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 629 | if (!DT.dominates(cpyDestInst, C)) |
| 630 | return false; |
| 631 | |
| 632 | // In addition to knowing that the call does not access src in some |
| 633 | // unexpected manner, for example via a global, which we deduce from |
| 634 | // the use analysis, we also need to know that it does not sneakily |
| 635 | // access dest. We rely on AA to figure this out for us. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 636 | AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 637 | if (AA.getModRefInfo(C, cpyDest, srcSize) != |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 638 | AliasAnalysis::NoModRef) |
| 639 | return false; |
| 640 | |
| 641 | // All the checks have passed, so do the transformation. |
Owen Anderson | 12cb36c | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 642 | bool changedArgument = false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 643 | for (unsigned i = 0; i < CS.arg_size(); ++i) |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 644 | if (CS.getArgument(i)->stripPointerCasts() == cpySrc) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 645 | if (cpySrc->getType() != cpyDest->getType()) |
Gabor Greif | 7cbd8a3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 646 | cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(), |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 647 | cpyDest->getName(), C); |
Owen Anderson | 12cb36c | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 648 | changedArgument = true; |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 649 | if (CS.getArgument(i)->getType() == cpyDest->getType()) |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 650 | CS.setArgument(i, cpyDest); |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 651 | else |
| 652 | CS.setArgument(i, CastInst::CreatePointerCast(cpyDest, |
| 653 | CS.getArgument(i)->getType(), cpyDest->getName(), C)); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 654 | } |
| 655 | |
Owen Anderson | 12cb36c | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 656 | if (!changedArgument) |
| 657 | return false; |
| 658 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 659 | // Drop any cached information about the call, because we may have changed |
| 660 | // its dependence information by changing its parameter. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 661 | MD->removeInstruction(C); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 662 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 663 | // Remove the memcpy. |
| 664 | MD->removeInstruction(cpy); |
Dan Gohman | fe60104 | 2010-06-22 15:08:57 +0000 | [diff] [blame] | 665 | ++NumMemCpyInstr; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 666 | |
| 667 | return true; |
| 668 | } |
| 669 | |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 670 | /// processMemCpyMemCpyDependence - We've found that the (upward scanning) |
| 671 | /// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to |
| 672 | /// copy from MDep's input if we can. MSize is the size of M's copy. |
| 673 | /// |
| 674 | bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep, |
| 675 | uint64_t MSize) { |
| 676 | // We can only transforms memcpy's where the dest of one is the source of the |
| 677 | // other. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 678 | if (M->getSource() != MDep->getDest() || MDep->isVolatile()) |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 679 | return false; |
| 680 | |
| 681 | // Second, the length of the memcpy's must be the same, or the preceeding one |
| 682 | // must be larger than the following one. |
| 683 | ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); |
| 684 | if (!C1) return false; |
| 685 | |
| 686 | uint64_t DepSize = C1->getValue().getZExtValue(); |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 687 | if (DepSize < MSize) |
| 688 | return false; |
| 689 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 690 | AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame^] | 691 | |
| 692 | // Verify that the copied-from memory doesn't change in between the two |
| 693 | // transfers. For example, in: |
| 694 | // memcpy(a <- b) |
| 695 | // *b = 42; |
| 696 | // memcpy(c <- a) |
| 697 | // It would be invalid to transform the second memcpy into memcpy(c <- b). |
| 698 | // |
| 699 | // TODO: If the code between M and MDep is transparent to the destination "c", |
| 700 | // then we could still perform the xform by moving M up to the first memcpy. |
| 701 | // |
| 702 | // NOTE: This is conservative, it will stop on any read from the source loc, |
| 703 | // not just the defining memcpy. |
| 704 | MemDepResult SourceDep = |
| 705 | MD->getPointerDependencyFrom(AA.getLocationForSource(MDep), |
| 706 | false, M, M->getParent()); |
| 707 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) |
| 708 | return false; |
Chris Lattner | 5a7aeaa | 2010-11-18 08:00:57 +0000 | [diff] [blame] | 709 | |
| 710 | // If the dest of the second might alias the source of the first, then the |
| 711 | // source and dest might overlap. We still want to eliminate the intermediate |
| 712 | // value, but we have to generate a memmove instead of memcpy. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 713 | Intrinsic::ID ResultFn = Intrinsic::memcpy; |
Chris Lattner | 12f7085 | 2010-11-18 07:39:57 +0000 | [diff] [blame] | 714 | if (!AA.isNoAlias(M->getRawDest(), MSize, MDep->getRawSource(), DepSize)) |
Chris Lattner | 5a7aeaa | 2010-11-18 08:00:57 +0000 | [diff] [blame] | 715 | ResultFn = Intrinsic::memmove; |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 716 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 717 | // If all checks passed, then we can transform M. |
Chris Lattner | 245b7f6 | 2010-11-18 07:38:43 +0000 | [diff] [blame] | 718 | const Type *ArgTys[3] = { |
| 719 | M->getRawDest()->getType(), |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 720 | MDep->getRawSource()->getType(), |
Chris Lattner | 245b7f6 | 2010-11-18 07:38:43 +0000 | [diff] [blame] | 721 | M->getLength()->getType() |
| 722 | }; |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 723 | Function *MemCpyFun = |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 724 | Intrinsic::getDeclaration(MDep->getParent()->getParent()->getParent(), |
Chris Lattner | 5a7aeaa | 2010-11-18 08:00:57 +0000 | [diff] [blame] | 725 | ResultFn, ArgTys, 3); |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 726 | |
| 727 | // Make sure to use the lesser of the alignment of the source and the dest |
| 728 | // since we're changing where we're reading from, but don't want to increase |
| 729 | // the alignment past what can be read from or written to. |
| 730 | // TODO: Is this worth it if we're creating a less aligned memcpy? For |
| 731 | // example we could be moving from movaps -> movq on x86. |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 732 | unsigned Align = std::min(MDep->getAlignment(), M->getAlignment()); |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 733 | Value *Args[5] = { |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 734 | M->getRawDest(), |
| 735 | MDep->getRawSource(), |
| 736 | M->getLength(), |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 737 | ConstantInt::get(Type::getInt32Ty(MemCpyFun->getContext()), Align), |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 738 | M->getVolatileCst() |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 739 | }; |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame^] | 740 | CallInst::Create(MemCpyFun, Args, Args+5, "", M); |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 741 | |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame^] | 742 | // Remove the instruction we're replacing. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 743 | MD->removeInstruction(M); |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 744 | M->eraseFromParent(); |
| 745 | ++NumMemCpyInstr; |
| 746 | return true; |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 747 | } |
| 748 | |
| 749 | |
Gabor Greif | 7d3056b | 2010-07-28 22:50:26 +0000 | [diff] [blame] | 750 | /// processMemCpy - perform simplification of memcpy's. If we have memcpy A |
| 751 | /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite |
| 752 | /// B to be a memcpy from X to Z (or potentially a memmove, depending on |
| 753 | /// circumstances). This allows later passes to remove the first memcpy |
| 754 | /// altogether. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 755 | bool MemCpyOpt::processMemCpy(MemCpyInst *M) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 756 | // We can only optimize statically-sized memcpy's that are non-volatile. |
| 757 | ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength()); |
| 758 | if (CopySize == 0 || M->isVolatile()) return false; |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 759 | |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 760 | // The are two possible optimizations we can do for memcpy: |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 761 | // a) memcpy-memcpy xform which exposes redundance for DSE. |
| 762 | // b) call-memcpy xform for return slot optimization. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 763 | MemDepResult DepInfo = MD->getDependency(M); |
| 764 | if (!DepInfo.isClobber()) |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 765 | return false; |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 766 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 767 | if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst())) |
| 768 | return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 769 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 770 | if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) { |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 771 | bool changed = performCallSlotOptzn(M, M->getDest(), M->getSource(), |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 772 | CopySize->getZExtValue(), C); |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 773 | if (changed) M->eraseFromParent(); |
| 774 | return changed; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 775 | } |
Owen Anderson | 02e9988 | 2008-04-29 21:51:00 +0000 | [diff] [blame] | 776 | return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 777 | } |
| 778 | |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 779 | /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst |
| 780 | /// are guaranteed not to alias. |
| 781 | bool MemCpyOpt::processMemMove(MemMoveInst *M) { |
| 782 | AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); |
| 783 | |
| 784 | // If the memmove is a constant size, use it for the alias query, this allows |
| 785 | // us to optimize things like: memmove(P, P+64, 64); |
Dan Gohman | 3da848b | 2010-10-19 22:54:46 +0000 | [diff] [blame] | 786 | uint64_t MemMoveSize = AliasAnalysis::UnknownSize; |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 787 | if (ConstantInt *Len = dyn_cast<ConstantInt>(M->getLength())) |
| 788 | MemMoveSize = Len->getZExtValue(); |
| 789 | |
| 790 | // See if the pointers alias. |
| 791 | if (AA.alias(M->getRawDest(), MemMoveSize, M->getRawSource(), MemMoveSize) != |
| 792 | AliasAnalysis::NoAlias) |
| 793 | return false; |
| 794 | |
David Greene | cb33fd1 | 2010-01-05 01:27:47 +0000 | [diff] [blame] | 795 | DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n"); |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 796 | |
| 797 | // If not, then we know we can transform this. |
| 798 | Module *Mod = M->getParent()->getParent()->getParent(); |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 799 | const Type *ArgTys[3] = { M->getRawDest()->getType(), |
| 800 | M->getRawSource()->getType(), |
| 801 | M->getLength()->getType() }; |
Gabor Greif | a399781 | 2010-07-22 10:37:47 +0000 | [diff] [blame] | 802 | M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy, |
| 803 | ArgTys, 3)); |
Duncan Sands | 05cd03b | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 804 | |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 805 | // MemDep may have over conservative information about this instruction, just |
| 806 | // conservatively flush it from the cache. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 807 | MD->removeInstruction(M); |
Duncan Sands | 05cd03b | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 808 | |
| 809 | ++NumMoveToCpy; |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 810 | return true; |
| 811 | } |
| 812 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 813 | /// processByValArgument - This is called on every byval argument in call sites. |
| 814 | bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) { |
| 815 | TargetData *TD = getAnalysisIfAvailable<TargetData>(); |
| 816 | if (!TD) return false; |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 817 | |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame^] | 818 | // Find out what feeds this byval argument. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 819 | Value *ByValArg = CS.getArgument(ArgNo); |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame^] | 820 | uint64_t ByValSize = TD->getTypeAllocSize(ByValArg->getType()); |
| 821 | MemDepResult DepInfo = |
| 822 | MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize), |
| 823 | true, CS.getInstruction(), |
| 824 | CS.getInstruction()->getParent()); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 825 | if (!DepInfo.isClobber()) |
| 826 | return false; |
| 827 | |
| 828 | // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by |
| 829 | // a memcpy, see if we can byval from the source of the memcpy instead of the |
| 830 | // result. |
| 831 | MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()); |
| 832 | if (MDep == 0 || MDep->isVolatile() || |
| 833 | ByValArg->stripPointerCasts() != MDep->getDest()) |
| 834 | return false; |
| 835 | |
| 836 | // The length of the memcpy must be larger or equal to the size of the byval. |
| 837 | // must be larger than the following one. |
| 838 | ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame^] | 839 | if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize) |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 840 | return false; |
| 841 | |
| 842 | // Get the alignment of the byval. If it is greater than the memcpy, then we |
| 843 | // can't do the substitution. If the call doesn't specify the alignment, then |
| 844 | // it is some target specific value that we can't know. |
| 845 | unsigned ByValAlign = CS.getParamAlignment(ArgNo+1); |
| 846 | if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign) |
| 847 | return false; |
| 848 | |
| 849 | // Verify that the copied-from memory doesn't change in between the memcpy and |
| 850 | // the byval call. |
| 851 | // memcpy(a <- b) |
| 852 | // *b = 42; |
| 853 | // foo(*a) |
| 854 | // It would be invalid to transform the second memcpy into foo(*b). |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame^] | 855 | // |
| 856 | // NOTE: This is conservative, it will stop on any read from the source loc, |
| 857 | // not just the defining memcpy. |
| 858 | MemDepResult SourceDep = |
| 859 | MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep), |
| 860 | false, CS.getInstruction(), MDep->getParent()); |
| 861 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) |
| 862 | return false; |
| 863 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 864 | Value *TmpCast = MDep->getSource(); |
| 865 | if (MDep->getSource()->getType() != ByValArg->getType()) |
| 866 | TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(), |
| 867 | "tmpcast", CS.getInstruction()); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 868 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 869 | DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n" |
| 870 | << " " << *MDep << "\n" |
| 871 | << " " << *CS.getInstruction() << "\n"); |
| 872 | |
| 873 | // Otherwise we're good! Update the byval argument. |
| 874 | CS.setArgument(ArgNo, TmpCast); |
| 875 | ++NumMemCpyInstr; |
| 876 | return true; |
| 877 | } |
| 878 | |
| 879 | /// iterateOnFunction - Executes one iteration of MemCpyOpt. |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 880 | bool MemCpyOpt::iterateOnFunction(Function &F) { |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 881 | bool MadeChange = false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 882 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 883 | // Walk all instruction in the function. |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 884 | for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 885 | for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 886 | // Avoid invalidating the iterator. |
| 887 | Instruction *I = BI++; |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 888 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 889 | bool RepeatInstruction = false; |
| 890 | |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 891 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 892 | MadeChange |= processStore(SI, BI); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 893 | else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) { |
| 894 | RepeatInstruction = processMemCpy(M); |
| 895 | } else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) { |
| 896 | RepeatInstruction = processMemMove(M); |
| 897 | } else if (CallSite CS = (Value*)I) { |
| 898 | for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) |
| 899 | if (CS.paramHasAttr(i+1, Attribute::ByVal)) |
| 900 | MadeChange |= processByValArgument(CS, i); |
| 901 | } |
| 902 | |
| 903 | // Reprocess the instruction if desired. |
| 904 | if (RepeatInstruction) { |
| 905 | --BI; |
| 906 | MadeChange = true; |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 907 | } |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 908 | } |
| 909 | } |
| 910 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 911 | return MadeChange; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 912 | } |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 913 | |
| 914 | // MemCpyOpt::runOnFunction - This is the main transformation entry point for a |
| 915 | // function. |
| 916 | // |
| 917 | bool MemCpyOpt::runOnFunction(Function &F) { |
| 918 | bool MadeChange = false; |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 919 | MD = &getAnalysis<MemoryDependenceAnalysis>(); |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 920 | while (1) { |
| 921 | if (!iterateOnFunction(F)) |
| 922 | break; |
| 923 | MadeChange = true; |
| 924 | } |
| 925 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 926 | MD = 0; |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 927 | return MadeChange; |
| 928 | } |
| 929 | |
| 930 | |
| 931 | |