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 #include "llvm/ADT/DenseSet.h" 16 #include "llvm/ADT/iterator_range.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/Analysis/AssumptionCache.h" 21 #include "llvm/Analysis/GlobalsModRef.h" 22 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/Analysis/TargetLibraryInfo.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/IR/Argument.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GetElementPtrTypeIterator.h" 33 #include "llvm/IR/GlobalVariable.h" 34 #include "llvm/IR/InstrTypes.h" 35 #include "llvm/IR/Instruction.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Intrinsics.h" 39 #include "llvm/IR/IRBuilder.h" 40 #include "llvm/IR/LLVMContext.h" 41 #include "llvm/IR/Module.h" 42 #include "llvm/IR/Operator.h" 43 #include "llvm/IR/Type.h" 44 #include "llvm/IR/User.h" 45 #include "llvm/IR/Value.h" 46 #include "llvm/Pass.h" 47 #include "llvm/Support/Casting.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/MathExtras.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include "llvm/Transforms/Scalar.h" 52 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" 53 #include "llvm/Transforms/Utils/Local.h" 54 #include <algorithm> 55 #include <cassert> 56 #include <cstdint> 57 58 using namespace llvm; 59 60 #define DEBUG_TYPE "memcpyopt" 61 62 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted"); 63 STATISTIC(NumMemSetInfer, "Number of memsets inferred"); 64 STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy"); 65 STATISTIC(NumCpyToSet, "Number of memcpys converted to memset"); 66 67 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, 68 bool &VariableIdxFound, 69 const DataLayout &DL) { 70 // Skip over the first indices. 71 gep_type_iterator GTI = gep_type_begin(GEP); 72 for (unsigned i = 1; i != Idx; ++i, ++GTI) 73 /*skip along*/; 74 75 // Compute the offset implied by the rest of the indices. 76 int64_t Offset = 0; 77 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) { 78 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i)); 79 if (!OpC) 80 return VariableIdxFound = true; 81 if (OpC->isZero()) continue; // No offset. 82 83 // Handle struct indices, which add their field offset to the pointer. 84 if (StructType *STy = GTI.getStructTypeOrNull()) { 85 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue()); 86 continue; 87 } 88 89 // Otherwise, we have a sequential type like an array or vector. Multiply 90 // the index by the ElementSize. 91 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); 92 Offset += Size*OpC->getSExtValue(); 93 } 94 95 return Offset; 96 } 97 98 /// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and 99 /// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2 100 /// might be &A[40]. In this case offset would be -8. 101 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset, 102 const DataLayout &DL) { 103 Ptr1 = Ptr1->stripPointerCasts(); 104 Ptr2 = Ptr2->stripPointerCasts(); 105 106 // Handle the trivial case first. 107 if (Ptr1 == Ptr2) { 108 Offset = 0; 109 return true; 110 } 111 112 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1); 113 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2); 114 115 bool VariableIdxFound = false; 116 117 // If one pointer is a GEP and the other isn't, then see if the GEP is a 118 // constant offset from the base, as in "P" and "gep P, 1". 119 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) { 120 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL); 121 return !VariableIdxFound; 122 } 123 124 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) { 125 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL); 126 return !VariableIdxFound; 127 } 128 129 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical 130 // base. After that base, they may have some number of common (and 131 // potentially variable) indices. After that they handle some constant 132 // offset, which determines their offset from each other. At this point, we 133 // handle no other case. 134 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0)) 135 return false; 136 137 // Skip any common indices and track the GEP types. 138 unsigned Idx = 1; 139 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx) 140 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx)) 141 break; 142 143 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL); 144 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL); 145 if (VariableIdxFound) return false; 146 147 Offset = Offset2-Offset1; 148 return true; 149 } 150 151 namespace { 152 153 /// Represents a range of memset'd bytes with the ByteVal value. 154 /// This allows us to analyze stores like: 155 /// store 0 -> P+1 156 /// store 0 -> P+0 157 /// store 0 -> P+3 158 /// store 0 -> P+2 159 /// which sometimes happens with stores to arrays of structs etc. When we see 160 /// the first store, we make a range [1, 2). The second store extends the range 161 /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the 162 /// two ranges into [0, 3) which is memset'able. 163 struct MemsetRange { 164 // Start/End - A semi range that describes the span that this range covers. 165 // The range is closed at the start and open at the end: [Start, End). 166 int64_t Start, End; 167 168 /// StartPtr - The getelementptr instruction that points to the start of the 169 /// range. 170 Value *StartPtr; 171 172 /// Alignment - The known alignment of the first store. 173 unsigned Alignment; 174 175 /// TheStores - The actual stores that make up this range. 176 SmallVector<Instruction*, 16> TheStores; 177 178 bool isProfitableToUseMemset(const DataLayout &DL) const; 179 }; 180 181 } // end anonymous namespace 182 183 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const { 184 // If we found more than 4 stores to merge or 16 bytes, use memset. 185 if (TheStores.size() >= 4 || End-Start >= 16) return true; 186 187 // If there is nothing to merge, don't do anything. 188 if (TheStores.size() < 2) return false; 189 190 // If any of the stores are a memset, then it is always good to extend the 191 // memset. 192 for (Instruction *SI : TheStores) 193 if (!isa<StoreInst>(SI)) 194 return true; 195 196 // Assume that the code generator is capable of merging pairs of stores 197 // together if it wants to. 198 if (TheStores.size() == 2) return false; 199 200 // If we have fewer than 8 stores, it can still be worthwhile to do this. 201 // For example, merging 4 i8 stores into an i32 store is useful almost always. 202 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the 203 // memset will be split into 2 32-bit stores anyway) and doing so can 204 // pessimize the llvm optimizer. 205 // 206 // Since we don't have perfect knowledge here, make some assumptions: assume 207 // the maximum GPR width is the same size as the largest legal integer 208 // size. If so, check to see whether we will end up actually reducing the 209 // number of stores used. 210 unsigned Bytes = unsigned(End-Start); 211 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8; 212 if (MaxIntSize == 0) 213 MaxIntSize = 1; 214 unsigned NumPointerStores = Bytes / MaxIntSize; 215 216 // Assume the remaining bytes if any are done a byte at a time. 217 unsigned NumByteStores = Bytes % MaxIntSize; 218 219 // If we will reduce the # stores (according to this heuristic), do the 220 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32 221 // etc. 222 return TheStores.size() > NumPointerStores+NumByteStores; 223 } 224 225 namespace { 226 227 class MemsetRanges { 228 /// A sorted list of the memset ranges. 229 SmallVector<MemsetRange, 8> Ranges; 230 typedef SmallVectorImpl<MemsetRange>::iterator range_iterator; 231 const DataLayout &DL; 232 233 public: 234 MemsetRanges(const DataLayout &DL) : DL(DL) {} 235 236 typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator; 237 const_iterator begin() const { return Ranges.begin(); } 238 const_iterator end() const { return Ranges.end(); } 239 bool empty() const { return Ranges.empty(); } 240 241 void addInst(int64_t OffsetFromFirst, Instruction *Inst) { 242 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 243 addStore(OffsetFromFirst, SI); 244 else 245 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst)); 246 } 247 248 void addStore(int64_t OffsetFromFirst, StoreInst *SI) { 249 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType()); 250 251 addRange(OffsetFromFirst, StoreSize, 252 SI->getPointerOperand(), SI->getAlignment(), SI); 253 } 254 255 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) { 256 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 257 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI); 258 } 259 260 void addRange(int64_t Start, int64_t Size, Value *Ptr, 261 unsigned Alignment, Instruction *Inst); 262 263 }; 264 265 } // end anonymous namespace 266 267 /// Add a new store to the MemsetRanges data structure. This adds a 268 /// new range for the specified store at the specified offset, merging into 269 /// existing ranges as appropriate. 270 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr, 271 unsigned Alignment, Instruction *Inst) { 272 int64_t End = Start+Size; 273 274 range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start, 275 [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; }); 276 277 // We now know that I == E, in which case we didn't find anything to merge 278 // with, or that Start <= I->End. If End < I->Start or I == E, then we need 279 // to insert a new range. Handle this now. 280 if (I == Ranges.end() || End < I->Start) { 281 MemsetRange &R = *Ranges.insert(I, MemsetRange()); 282 R.Start = Start; 283 R.End = End; 284 R.StartPtr = Ptr; 285 R.Alignment = Alignment; 286 R.TheStores.push_back(Inst); 287 return; 288 } 289 290 // This store overlaps with I, add it. 291 I->TheStores.push_back(Inst); 292 293 // At this point, we may have an interval that completely contains our store. 294 // If so, just add it to the interval and return. 295 if (I->Start <= Start && I->End >= End) 296 return; 297 298 // Now we know that Start <= I->End and End >= I->Start so the range overlaps 299 // but is not entirely contained within the range. 300 301 // See if the range extends the start of the range. In this case, it couldn't 302 // possibly cause it to join the prior range, because otherwise we would have 303 // stopped on *it*. 304 if (Start < I->Start) { 305 I->Start = Start; 306 I->StartPtr = Ptr; 307 I->Alignment = Alignment; 308 } 309 310 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint 311 // is in or right at the end of I), and that End >= I->Start. Extend I out to 312 // End. 313 if (End > I->End) { 314 I->End = End; 315 range_iterator NextI = I; 316 while (++NextI != Ranges.end() && End >= NextI->Start) { 317 // Merge the range in. 318 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end()); 319 if (NextI->End > I->End) 320 I->End = NextI->End; 321 Ranges.erase(NextI); 322 NextI = I; 323 } 324 } 325 } 326 327 //===----------------------------------------------------------------------===// 328 // MemCpyOptLegacyPass Pass 329 //===----------------------------------------------------------------------===// 330 331 namespace { 332 333 class MemCpyOptLegacyPass : public FunctionPass { 334 MemCpyOptPass Impl; 335 336 public: 337 static char ID; // Pass identification, replacement for typeid 338 339 MemCpyOptLegacyPass() : FunctionPass(ID) { 340 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry()); 341 } 342 343 bool runOnFunction(Function &F) override; 344 345 private: 346 // This transformation requires dominator postdominator info 347 void getAnalysisUsage(AnalysisUsage &AU) const override { 348 AU.setPreservesCFG(); 349 AU.addRequired<AssumptionCacheTracker>(); 350 AU.addRequired<DominatorTreeWrapperPass>(); 351 AU.addRequired<MemoryDependenceWrapperPass>(); 352 AU.addRequired<AAResultsWrapperPass>(); 353 AU.addRequired<TargetLibraryInfoWrapperPass>(); 354 AU.addPreserved<GlobalsAAWrapperPass>(); 355 AU.addPreserved<MemoryDependenceWrapperPass>(); 356 } 357 358 // Helper functions 359 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI); 360 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI); 361 bool processMemCpy(MemCpyInst *M); 362 bool processMemMove(MemMoveInst *M); 363 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc, 364 uint64_t cpyLen, unsigned cpyAlign, CallInst *C); 365 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep); 366 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep); 367 bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep); 368 bool processByValArgument(CallSite CS, unsigned ArgNo); 369 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr, 370 Value *ByteVal); 371 372 bool iterateOnFunction(Function &F); 373 }; 374 375 char MemCpyOptLegacyPass::ID = 0; 376 377 } // end anonymous namespace 378 379 /// The public interface to this file... 380 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); } 381 382 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization", 383 false, false) 384 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 385 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 386 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 387 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 388 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 389 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 390 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization", 391 false, false) 392 393 /// When scanning forward over instructions, we look for some other patterns to 394 /// fold away. In particular, this looks for stores to neighboring locations of 395 /// memory. If it sees enough consecutive ones, it attempts to merge them 396 /// together into a memcpy/memset. 397 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst, 398 Value *StartPtr, 399 Value *ByteVal) { 400 const DataLayout &DL = StartInst->getModule()->getDataLayout(); 401 402 // Okay, so we now have a single store that can be splatable. Scan to find 403 // all subsequent stores of the same value to offset from the same pointer. 404 // Join these together into ranges, so we can decide whether contiguous blocks 405 // are stored. 406 MemsetRanges Ranges(DL); 407 408 BasicBlock::iterator BI(StartInst); 409 for (++BI; !isa<TerminatorInst>(BI); ++BI) { 410 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) { 411 // If the instruction is readnone, ignore it, otherwise bail out. We 412 // don't even allow readonly here because we don't want something like: 413 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A). 414 if (BI->mayWriteToMemory() || BI->mayReadFromMemory()) 415 break; 416 continue; 417 } 418 419 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) { 420 // If this is a store, see if we can merge it in. 421 if (!NextStore->isSimple()) break; 422 423 // Check to see if this stored value is of the same byte-splattable value. 424 if (ByteVal != isBytewiseValue(NextStore->getOperand(0))) 425 break; 426 427 // Check to see if this store is to a constant offset from the start ptr. 428 int64_t Offset; 429 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, 430 DL)) 431 break; 432 433 Ranges.addStore(Offset, NextStore); 434 } else { 435 MemSetInst *MSI = cast<MemSetInst>(BI); 436 437 if (MSI->isVolatile() || ByteVal != MSI->getValue() || 438 !isa<ConstantInt>(MSI->getLength())) 439 break; 440 441 // Check to see if this store is to a constant offset from the start ptr. 442 int64_t Offset; 443 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL)) 444 break; 445 446 Ranges.addMemSet(Offset, MSI); 447 } 448 } 449 450 // If we have no ranges, then we just had a single store with nothing that 451 // could be merged in. This is a very common case of course. 452 if (Ranges.empty()) 453 return nullptr; 454 455 // If we had at least one store that could be merged in, add the starting 456 // store as well. We try to avoid this unless there is at least something 457 // interesting as a small compile-time optimization. 458 Ranges.addInst(0, StartInst); 459 460 // If we create any memsets, we put it right before the first instruction that 461 // isn't part of the memset block. This ensure that the memset is dominated 462 // by any addressing instruction needed by the start of the block. 463 IRBuilder<> Builder(&*BI); 464 465 // Now that we have full information about ranges, loop over the ranges and 466 // emit memset's for anything big enough to be worthwhile. 467 Instruction *AMemSet = nullptr; 468 for (const MemsetRange &Range : Ranges) { 469 470 if (Range.TheStores.size() == 1) continue; 471 472 // If it is profitable to lower this range to memset, do so now. 473 if (!Range.isProfitableToUseMemset(DL)) 474 continue; 475 476 // Otherwise, we do want to transform this! Create a new memset. 477 // Get the starting pointer of the block. 478 StartPtr = Range.StartPtr; 479 480 // Determine alignment 481 unsigned Alignment = Range.Alignment; 482 if (Alignment == 0) { 483 Type *EltType = 484 cast<PointerType>(StartPtr->getType())->getElementType(); 485 Alignment = DL.getABITypeAlignment(EltType); 486 } 487 488 AMemSet = 489 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment); 490 491 DEBUG(dbgs() << "Replace stores:\n"; 492 for (Instruction *SI : Range.TheStores) 493 dbgs() << *SI << '\n'; 494 dbgs() << "With: " << *AMemSet << '\n'); 495 496 if (!Range.TheStores.empty()) 497 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc()); 498 499 // Zap all the stores. 500 for (Instruction *SI : Range.TheStores) { 501 MD->removeInstruction(SI); 502 SI->eraseFromParent(); 503 } 504 ++NumMemSetInfer; 505 } 506 507 return AMemSet; 508 } 509 510 static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI, 511 const LoadInst *LI) { 512 unsigned StoreAlign = SI->getAlignment(); 513 if (!StoreAlign) 514 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType()); 515 unsigned LoadAlign = LI->getAlignment(); 516 if (!LoadAlign) 517 LoadAlign = DL.getABITypeAlignment(LI->getType()); 518 519 return std::min(StoreAlign, LoadAlign); 520 } 521 522 // This method try to lift a store instruction before position P. 523 // It will lift the store and its argument + that anything that 524 // may alias with these. 525 // The method returns true if it was successful. 526 static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P, 527 const LoadInst *LI) { 528 // If the store alias this position, early bail out. 529 MemoryLocation StoreLoc = MemoryLocation::get(SI); 530 if (AA.getModRefInfo(P, StoreLoc) != MRI_NoModRef) 531 return false; 532 533 // Keep track of the arguments of all instruction we plan to lift 534 // so we can make sure to lift them as well if apropriate. 535 DenseSet<Instruction*> Args; 536 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) 537 if (Ptr->getParent() == SI->getParent()) 538 Args.insert(Ptr); 539 540 // Instruction to lift before P. 541 SmallVector<Instruction*, 8> ToLift; 542 543 // Memory locations of lifted instructions. 544 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc}; 545 546 // Lifted callsites. 547 SmallVector<ImmutableCallSite, 8> CallSites; 548 549 const MemoryLocation LoadLoc = MemoryLocation::get(LI); 550 551 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) { 552 auto *C = &*I; 553 554 bool MayAlias = AA.getModRefInfo(C) != MRI_NoModRef; 555 556 bool NeedLift = false; 557 if (Args.erase(C)) 558 NeedLift = true; 559 else if (MayAlias) { 560 NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) { 561 return AA.getModRefInfo(C, ML); 562 }); 563 564 if (!NeedLift) 565 NeedLift = 566 llvm::any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) { 567 return AA.getModRefInfo(C, CS); 568 }); 569 } 570 571 if (!NeedLift) 572 continue; 573 574 if (MayAlias) { 575 // Since LI is implicitly moved downwards past the lifted instructions, 576 // none of them may modify its source. 577 if (AA.getModRefInfo(C, LoadLoc) & MRI_Mod) 578 return false; 579 else if (auto CS = ImmutableCallSite(C)) { 580 // If we can't lift this before P, it's game over. 581 if (AA.getModRefInfo(P, CS) != MRI_NoModRef) 582 return false; 583 584 CallSites.push_back(CS); 585 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) { 586 // If we can't lift this before P, it's game over. 587 auto ML = MemoryLocation::get(C); 588 if (AA.getModRefInfo(P, ML) != MRI_NoModRef) 589 return false; 590 591 MemLocs.push_back(ML); 592 } else 593 // We don't know how to lift this instruction. 594 return false; 595 } 596 597 ToLift.push_back(C); 598 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k) 599 if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) 600 if (A->getParent() == SI->getParent()) 601 Args.insert(A); 602 } 603 604 // We made it, we need to lift 605 for (auto *I : llvm::reverse(ToLift)) { 606 DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n"); 607 I->moveBefore(P); 608 } 609 610 return true; 611 } 612 613 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) { 614 if (!SI->isSimple()) return false; 615 616 // Avoid merging nontemporal stores since the resulting 617 // memcpy/memset would not be able to preserve the nontemporal hint. 618 // In theory we could teach how to propagate the !nontemporal metadata to 619 // memset calls. However, that change would force the backend to 620 // conservatively expand !nontemporal memset calls back to sequences of 621 // store instructions (effectively undoing the merging). 622 if (SI->getMetadata(LLVMContext::MD_nontemporal)) 623 return false; 624 625 const DataLayout &DL = SI->getModule()->getDataLayout(); 626 627 // Load to store forwarding can be interpreted as memcpy. 628 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) { 629 if (LI->isSimple() && LI->hasOneUse() && 630 LI->getParent() == SI->getParent()) { 631 632 auto *T = LI->getType(); 633 if (T->isAggregateType()) { 634 AliasAnalysis &AA = LookupAliasAnalysis(); 635 MemoryLocation LoadLoc = MemoryLocation::get(LI); 636 637 // We use alias analysis to check if an instruction may store to 638 // the memory we load from in between the load and the store. If 639 // such an instruction is found, we try to promote there instead 640 // of at the store position. 641 Instruction *P = SI; 642 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) { 643 if (AA.getModRefInfo(&I, LoadLoc) & MRI_Mod) { 644 P = &I; 645 break; 646 } 647 } 648 649 // We found an instruction that may write to the loaded memory. 650 // We can try to promote at this position instead of the store 651 // position if nothing alias the store memory after this and the store 652 // destination is not in the range. 653 if (P && P != SI) { 654 if (!moveUp(AA, SI, P, LI)) 655 P = nullptr; 656 } 657 658 // If a valid insertion position is found, then we can promote 659 // the load/store pair to a memcpy. 660 if (P) { 661 // If we load from memory that may alias the memory we store to, 662 // memmove must be used to preserve semantic. If not, memcpy can 663 // be used. 664 bool UseMemMove = false; 665 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc)) 666 UseMemMove = true; 667 668 unsigned Align = findCommonAlignment(DL, SI, LI); 669 uint64_t Size = DL.getTypeStoreSize(T); 670 671 IRBuilder<> Builder(P); 672 Instruction *M; 673 if (UseMemMove) 674 M = Builder.CreateMemMove(SI->getPointerOperand(), 675 LI->getPointerOperand(), Size, 676 Align, SI->isVolatile()); 677 else 678 M = Builder.CreateMemCpy(SI->getPointerOperand(), 679 LI->getPointerOperand(), Size, 680 Align, SI->isVolatile()); 681 682 DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI 683 << " => " << *M << "\n"); 684 685 MD->removeInstruction(SI); 686 SI->eraseFromParent(); 687 MD->removeInstruction(LI); 688 LI->eraseFromParent(); 689 ++NumMemCpyInstr; 690 691 // Make sure we do not invalidate the iterator. 692 BBI = M->getIterator(); 693 return true; 694 } 695 } 696 697 // Detect cases where we're performing call slot forwarding, but 698 // happen to be using a load-store pair to implement it, rather than 699 // a memcpy. 700 MemDepResult ldep = MD->getDependency(LI); 701 CallInst *C = nullptr; 702 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst())) 703 C = dyn_cast<CallInst>(ldep.getInst()); 704 705 if (C) { 706 // Check that nothing touches the dest of the "copy" between 707 // the call and the store. 708 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts(); 709 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest); 710 AliasAnalysis &AA = LookupAliasAnalysis(); 711 MemoryLocation StoreLoc = MemoryLocation::get(SI); 712 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator(); 713 I != E; --I) { 714 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) { 715 C = nullptr; 716 break; 717 } 718 // The store to dest may never happen if an exception can be thrown 719 // between the load and the store. 720 if (I->mayThrow() && !CpyDestIsLocal) { 721 C = nullptr; 722 break; 723 } 724 } 725 } 726 727 if (C) { 728 bool changed = performCallSlotOptzn( 729 LI, SI->getPointerOperand()->stripPointerCasts(), 730 LI->getPointerOperand()->stripPointerCasts(), 731 DL.getTypeStoreSize(SI->getOperand(0)->getType()), 732 findCommonAlignment(DL, SI, LI), C); 733 if (changed) { 734 MD->removeInstruction(SI); 735 SI->eraseFromParent(); 736 MD->removeInstruction(LI); 737 LI->eraseFromParent(); 738 ++NumMemCpyInstr; 739 return true; 740 } 741 } 742 } 743 } 744 745 // There are two cases that are interesting for this code to handle: memcpy 746 // and memset. Right now we only handle memset. 747 748 // Ensure that the value being stored is something that can be memset'able a 749 // byte at a time like "0" or "-1" or any width, as well as things like 750 // 0xA0A0A0A0 and 0.0. 751 auto *V = SI->getOperand(0); 752 if (Value *ByteVal = isBytewiseValue(V)) { 753 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(), 754 ByteVal)) { 755 BBI = I->getIterator(); // Don't invalidate iterator. 756 return true; 757 } 758 759 // If we have an aggregate, we try to promote it to memset regardless 760 // of opportunity for merging as it can expose optimization opportunities 761 // in subsequent passes. 762 auto *T = V->getType(); 763 if (T->isAggregateType()) { 764 uint64_t Size = DL.getTypeStoreSize(T); 765 unsigned Align = SI->getAlignment(); 766 if (!Align) 767 Align = DL.getABITypeAlignment(T); 768 IRBuilder<> Builder(SI); 769 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, 770 Size, Align, SI->isVolatile()); 771 772 DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n"); 773 774 MD->removeInstruction(SI); 775 SI->eraseFromParent(); 776 NumMemSetInfer++; 777 778 // Make sure we do not invalidate the iterator. 779 BBI = M->getIterator(); 780 return true; 781 } 782 } 783 784 return false; 785 } 786 787 bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) { 788 // See if there is another memset or store neighboring this memset which 789 // allows us to widen out the memset to do a single larger store. 790 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile()) 791 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(), 792 MSI->getValue())) { 793 BBI = I->getIterator(); // Don't invalidate iterator. 794 return true; 795 } 796 return false; 797 } 798 799 /// Takes a memcpy and a call that it depends on, 800 /// and checks for the possibility of a call slot optimization by having 801 /// the call write its result directly into the destination of the memcpy. 802 bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest, 803 Value *cpySrc, uint64_t cpyLen, 804 unsigned cpyAlign, CallInst *C) { 805 // The general transformation to keep in mind is 806 // 807 // call @func(..., src, ...) 808 // memcpy(dest, src, ...) 809 // 810 // -> 811 // 812 // memcpy(dest, src, ...) 813 // call @func(..., dest, ...) 814 // 815 // Since moving the memcpy is technically awkward, we additionally check that 816 // src only holds uninitialized values at the moment of the call, meaning that 817 // the memcpy can be discarded rather than moved. 818 819 // Lifetime marks shouldn't be operated on. 820 if (Function *F = C->getCalledFunction()) 821 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start) 822 return false; 823 824 // Deliberately get the source and destination with bitcasts stripped away, 825 // because we'll need to do type comparisons based on the underlying type. 826 CallSite CS(C); 827 828 // Require that src be an alloca. This simplifies the reasoning considerably. 829 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc); 830 if (!srcAlloca) 831 return false; 832 833 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize()); 834 if (!srcArraySize) 835 return false; 836 837 const DataLayout &DL = cpy->getModule()->getDataLayout(); 838 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) * 839 srcArraySize->getZExtValue(); 840 841 if (cpyLen < srcSize) 842 return false; 843 844 // Check that accessing the first srcSize bytes of dest will not cause a 845 // trap. Otherwise the transform is invalid since it might cause a trap 846 // to occur earlier than it otherwise would. 847 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) { 848 // The destination is an alloca. Check it is larger than srcSize. 849 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize()); 850 if (!destArraySize) 851 return false; 852 853 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) * 854 destArraySize->getZExtValue(); 855 856 if (destSize < srcSize) 857 return false; 858 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) { 859 // The store to dest may never happen if the call can throw. 860 if (C->mayThrow()) 861 return false; 862 863 if (A->getDereferenceableBytes() < srcSize) { 864 // If the destination is an sret parameter then only accesses that are 865 // outside of the returned struct type can trap. 866 if (!A->hasStructRetAttr()) 867 return false; 868 869 Type *StructTy = cast<PointerType>(A->getType())->getElementType(); 870 if (!StructTy->isSized()) { 871 // The call may never return and hence the copy-instruction may never 872 // be executed, and therefore it's not safe to say "the destination 873 // has at least <cpyLen> bytes, as implied by the copy-instruction", 874 return false; 875 } 876 877 uint64_t destSize = DL.getTypeAllocSize(StructTy); 878 if (destSize < srcSize) 879 return false; 880 } 881 } else { 882 return false; 883 } 884 885 // Check that dest points to memory that is at least as aligned as src. 886 unsigned srcAlign = srcAlloca->getAlignment(); 887 if (!srcAlign) 888 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType()); 889 bool isDestSufficientlyAligned = srcAlign <= cpyAlign; 890 // If dest is not aligned enough and we can't increase its alignment then 891 // bail out. 892 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest)) 893 return false; 894 895 // Check that src is not accessed except via the call and the memcpy. This 896 // guarantees that it holds only undefined values when passed in (so the final 897 // memcpy can be dropped), that it is not read or written between the call and 898 // the memcpy, and that writing beyond the end of it is undefined. 899 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(), 900 srcAlloca->user_end()); 901 while (!srcUseList.empty()) { 902 User *U = srcUseList.pop_back_val(); 903 904 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) { 905 for (User *UU : U->users()) 906 srcUseList.push_back(UU); 907 continue; 908 } 909 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) { 910 if (!G->hasAllZeroIndices()) 911 return false; 912 913 for (User *UU : U->users()) 914 srcUseList.push_back(UU); 915 continue; 916 } 917 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U)) 918 if (IT->getIntrinsicID() == Intrinsic::lifetime_start || 919 IT->getIntrinsicID() == Intrinsic::lifetime_end) 920 continue; 921 922 if (U != C && U != cpy) 923 return false; 924 } 925 926 // Check that src isn't captured by the called function since the 927 // transformation can cause aliasing issues in that case. 928 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) 929 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i)) 930 return false; 931 932 // Since we're changing the parameter to the callsite, we need to make sure 933 // that what would be the new parameter dominates the callsite. 934 DominatorTree &DT = LookupDomTree(); 935 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest)) 936 if (!DT.dominates(cpyDestInst, C)) 937 return false; 938 939 // In addition to knowing that the call does not access src in some 940 // unexpected manner, for example via a global, which we deduce from 941 // the use analysis, we also need to know that it does not sneakily 942 // access dest. We rely on AA to figure this out for us. 943 AliasAnalysis &AA = LookupAliasAnalysis(); 944 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize); 945 // If necessary, perform additional analysis. 946 if (MR != MRI_NoModRef) 947 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT); 948 if (MR != MRI_NoModRef) 949 return false; 950 951 // All the checks have passed, so do the transformation. 952 bool changedArgument = false; 953 for (unsigned i = 0; i < CS.arg_size(); ++i) 954 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) { 955 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest 956 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(), 957 cpyDest->getName(), C); 958 changedArgument = true; 959 if (CS.getArgument(i)->getType() == Dest->getType()) 960 CS.setArgument(i, Dest); 961 else 962 CS.setArgument(i, CastInst::CreatePointerCast(Dest, 963 CS.getArgument(i)->getType(), Dest->getName(), C)); 964 } 965 966 if (!changedArgument) 967 return false; 968 969 // If the destination wasn't sufficiently aligned then increase its alignment. 970 if (!isDestSufficientlyAligned) { 971 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!"); 972 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign); 973 } 974 975 // Drop any cached information about the call, because we may have changed 976 // its dependence information by changing its parameter. 977 MD->removeInstruction(C); 978 979 // Update AA metadata 980 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be 981 // handled here, but combineMetadata doesn't support them yet 982 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 983 LLVMContext::MD_noalias, 984 LLVMContext::MD_invariant_group}; 985 combineMetadata(C, cpy, KnownIDs); 986 987 // Remove the memcpy. 988 MD->removeInstruction(cpy); 989 ++NumMemCpyInstr; 990 991 return true; 992 } 993 994 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is 995 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can. 996 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M, 997 MemCpyInst *MDep) { 998 // We can only transforms memcpy's where the dest of one is the source of the 999 // other. 1000 if (M->getSource() != MDep->getDest() || MDep->isVolatile()) 1001 return false; 1002 1003 // If dep instruction is reading from our current input, then it is a noop 1004 // transfer and substituting the input won't change this instruction. Just 1005 // ignore the input and let someone else zap MDep. This handles cases like: 1006 // memcpy(a <- a) 1007 // memcpy(b <- a) 1008 if (M->getSource() == MDep->getSource()) 1009 return false; 1010 1011 // Second, the length of the memcpy's must be the same, or the preceding one 1012 // must be larger than the following one. 1013 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength()); 1014 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength()); 1015 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue()) 1016 return false; 1017 1018 AliasAnalysis &AA = LookupAliasAnalysis(); 1019 1020 // Verify that the copied-from memory doesn't change in between the two 1021 // transfers. For example, in: 1022 // memcpy(a <- b) 1023 // *b = 42; 1024 // memcpy(c <- a) 1025 // It would be invalid to transform the second memcpy into memcpy(c <- b). 1026 // 1027 // TODO: If the code between M and MDep is transparent to the destination "c", 1028 // then we could still perform the xform by moving M up to the first memcpy. 1029 // 1030 // NOTE: This is conservative, it will stop on any read from the source loc, 1031 // not just the defining memcpy. 1032 MemDepResult SourceDep = 1033 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false, 1034 M->getIterator(), M->getParent()); 1035 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) 1036 return false; 1037 1038 // If the dest of the second might alias the source of the first, then the 1039 // source and dest might overlap. We still want to eliminate the intermediate 1040 // value, but we have to generate a memmove instead of memcpy. 1041 bool UseMemMove = false; 1042 if (!AA.isNoAlias(MemoryLocation::getForDest(M), 1043 MemoryLocation::getForSource(MDep))) 1044 UseMemMove = true; 1045 1046 // If all checks passed, then we can transform M. 1047 1048 // Make sure to use the lesser of the alignment of the source and the dest 1049 // since we're changing where we're reading from, but don't want to increase 1050 // the alignment past what can be read from or written to. 1051 // TODO: Is this worth it if we're creating a less aligned memcpy? For 1052 // example we could be moving from movaps -> movq on x86. 1053 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment()); 1054 1055 IRBuilder<> Builder(M); 1056 if (UseMemMove) 1057 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(), 1058 Align, M->isVolatile()); 1059 else 1060 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(), 1061 Align, M->isVolatile()); 1062 1063 // Remove the instruction we're replacing. 1064 MD->removeInstruction(M); 1065 M->eraseFromParent(); 1066 ++NumMemCpyInstr; 1067 return true; 1068 } 1069 1070 /// We've found that the (upward scanning) memory dependence of \p MemCpy is 1071 /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that 1072 /// weren't copied over by \p MemCpy. 1073 /// 1074 /// In other words, transform: 1075 /// \code 1076 /// memset(dst, c, dst_size); 1077 /// memcpy(dst, src, src_size); 1078 /// \endcode 1079 /// into: 1080 /// \code 1081 /// memcpy(dst, src, src_size); 1082 /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size); 1083 /// \endcode 1084 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy, 1085 MemSetInst *MemSet) { 1086 // We can only transform memset/memcpy with the same destination. 1087 if (MemSet->getDest() != MemCpy->getDest()) 1088 return false; 1089 1090 // Check that there are no other dependencies on the memset destination. 1091 MemDepResult DstDepInfo = 1092 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false, 1093 MemCpy->getIterator(), MemCpy->getParent()); 1094 if (DstDepInfo.getInst() != MemSet) 1095 return false; 1096 1097 // Use the same i8* dest as the memcpy, killing the memset dest if different. 1098 Value *Dest = MemCpy->getRawDest(); 1099 Value *DestSize = MemSet->getLength(); 1100 Value *SrcSize = MemCpy->getLength(); 1101 1102 // By default, create an unaligned memset. 1103 unsigned Align = 1; 1104 // If Dest is aligned, and SrcSize is constant, use the minimum alignment 1105 // of the sum. 1106 const unsigned DestAlign = 1107 std::max(MemSet->getAlignment(), MemCpy->getAlignment()); 1108 if (DestAlign > 1) 1109 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize)) 1110 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign); 1111 1112 IRBuilder<> Builder(MemCpy); 1113 1114 // If the sizes have different types, zext the smaller one. 1115 if (DestSize->getType() != SrcSize->getType()) { 1116 if (DestSize->getType()->getIntegerBitWidth() > 1117 SrcSize->getType()->getIntegerBitWidth()) 1118 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType()); 1119 else 1120 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType()); 1121 } 1122 1123 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize); 1124 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize); 1125 Value *MemsetLen = Builder.CreateSelect( 1126 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff); 1127 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1), 1128 MemsetLen, Align); 1129 1130 MD->removeInstruction(MemSet); 1131 MemSet->eraseFromParent(); 1132 return true; 1133 } 1134 1135 /// Transform memcpy to memset when its source was just memset. 1136 /// In other words, turn: 1137 /// \code 1138 /// memset(dst1, c, dst1_size); 1139 /// memcpy(dst2, dst1, dst2_size); 1140 /// \endcode 1141 /// into: 1142 /// \code 1143 /// memset(dst1, c, dst1_size); 1144 /// memset(dst2, c, dst2_size); 1145 /// \endcode 1146 /// When dst2_size <= dst1_size. 1147 /// 1148 /// The \p MemCpy must have a Constant length. 1149 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy, 1150 MemSetInst *MemSet) { 1151 AliasAnalysis &AA = LookupAliasAnalysis(); 1152 1153 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and 1154 // memcpying from the same address. Otherwise it is hard to reason about. 1155 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource())) 1156 return false; 1157 1158 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength()); 1159 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength()); 1160 // Make sure the memcpy doesn't read any more than what the memset wrote. 1161 // Don't worry about sizes larger than i64. 1162 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue()) 1163 return false; 1164 1165 IRBuilder<> Builder(MemCpy); 1166 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1), 1167 CopySize, MemCpy->getAlignment()); 1168 return true; 1169 } 1170 1171 /// Perform simplification of memcpy's. If we have memcpy A 1172 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite 1173 /// B to be a memcpy from X to Z (or potentially a memmove, depending on 1174 /// circumstances). This allows later passes to remove the first memcpy 1175 /// altogether. 1176 bool MemCpyOptPass::processMemCpy(MemCpyInst *M) { 1177 // We can only optimize non-volatile memcpy's. 1178 if (M->isVolatile()) return false; 1179 1180 // If the source and destination of the memcpy are the same, then zap it. 1181 if (M->getSource() == M->getDest()) { 1182 MD->removeInstruction(M); 1183 M->eraseFromParent(); 1184 return false; 1185 } 1186 1187 // If copying from a constant, try to turn the memcpy into a memset. 1188 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource())) 1189 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 1190 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) { 1191 IRBuilder<> Builder(M); 1192 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(), 1193 M->getAlignment(), false); 1194 MD->removeInstruction(M); 1195 M->eraseFromParent(); 1196 ++NumCpyToSet; 1197 return true; 1198 } 1199 1200 MemDepResult DepInfo = MD->getDependency(M); 1201 1202 // Try to turn a partially redundant memset + memcpy into 1203 // memcpy + smaller memset. We don't need the memcpy size for this. 1204 if (DepInfo.isClobber()) 1205 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst())) 1206 if (processMemSetMemCpyDependence(M, MDep)) 1207 return true; 1208 1209 // The optimizations after this point require the memcpy size. 1210 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength()); 1211 if (!CopySize) return false; 1212 1213 // There are four possible optimizations we can do for memcpy: 1214 // a) memcpy-memcpy xform which exposes redundance for DSE. 1215 // b) call-memcpy xform for return slot optimization. 1216 // c) memcpy from freshly alloca'd space or space that has just started its 1217 // lifetime copies undefined data, and we can therefore eliminate the 1218 // memcpy in favor of the data that was already at the destination. 1219 // d) memcpy from a just-memset'd source can be turned into memset. 1220 if (DepInfo.isClobber()) { 1221 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) { 1222 if (performCallSlotOptzn(M, M->getDest(), M->getSource(), 1223 CopySize->getZExtValue(), M->getAlignment(), 1224 C)) { 1225 MD->removeInstruction(M); 1226 M->eraseFromParent(); 1227 return true; 1228 } 1229 } 1230 } 1231 1232 MemoryLocation SrcLoc = MemoryLocation::getForSource(M); 1233 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom( 1234 SrcLoc, true, M->getIterator(), M->getParent()); 1235 1236 if (SrcDepInfo.isClobber()) { 1237 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst())) 1238 return processMemCpyMemCpyDependence(M, MDep); 1239 } else if (SrcDepInfo.isDef()) { 1240 Instruction *I = SrcDepInfo.getInst(); 1241 bool hasUndefContents = false; 1242 1243 if (isa<AllocaInst>(I)) { 1244 hasUndefContents = true; 1245 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 1246 if (II->getIntrinsicID() == Intrinsic::lifetime_start) 1247 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0))) 1248 if (LTSize->getZExtValue() >= CopySize->getZExtValue()) 1249 hasUndefContents = true; 1250 } 1251 1252 if (hasUndefContents) { 1253 MD->removeInstruction(M); 1254 M->eraseFromParent(); 1255 ++NumMemCpyInstr; 1256 return true; 1257 } 1258 } 1259 1260 if (SrcDepInfo.isClobber()) 1261 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst())) 1262 if (performMemCpyToMemSetOptzn(M, MDep)) { 1263 MD->removeInstruction(M); 1264 M->eraseFromParent(); 1265 ++NumCpyToSet; 1266 return true; 1267 } 1268 1269 return false; 1270 } 1271 1272 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed 1273 /// not to alias. 1274 bool MemCpyOptPass::processMemMove(MemMoveInst *M) { 1275 AliasAnalysis &AA = LookupAliasAnalysis(); 1276 1277 if (!TLI->has(LibFunc_memmove)) 1278 return false; 1279 1280 // See if the pointers alias. 1281 if (!AA.isNoAlias(MemoryLocation::getForDest(M), 1282 MemoryLocation::getForSource(M))) 1283 return false; 1284 1285 DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M 1286 << "\n"); 1287 1288 // If not, then we know we can transform this. 1289 Type *ArgTys[3] = { M->getRawDest()->getType(), 1290 M->getRawSource()->getType(), 1291 M->getLength()->getType() }; 1292 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(), 1293 Intrinsic::memcpy, ArgTys)); 1294 1295 // MemDep may have over conservative information about this instruction, just 1296 // conservatively flush it from the cache. 1297 MD->removeInstruction(M); 1298 1299 ++NumMoveToCpy; 1300 return true; 1301 } 1302 1303 /// This is called on every byval argument in call sites. 1304 bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) { 1305 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout(); 1306 // Find out what feeds this byval argument. 1307 Value *ByValArg = CS.getArgument(ArgNo); 1308 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType(); 1309 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy); 1310 MemDepResult DepInfo = MD->getPointerDependencyFrom( 1311 MemoryLocation(ByValArg, ByValSize), true, 1312 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent()); 1313 if (!DepInfo.isClobber()) 1314 return false; 1315 1316 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by 1317 // a memcpy, see if we can byval from the source of the memcpy instead of the 1318 // result. 1319 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()); 1320 if (!MDep || MDep->isVolatile() || 1321 ByValArg->stripPointerCasts() != MDep->getDest()) 1322 return false; 1323 1324 // The length of the memcpy must be larger or equal to the size of the byval. 1325 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); 1326 if (!C1 || C1->getValue().getZExtValue() < ByValSize) 1327 return false; 1328 1329 // Get the alignment of the byval. If the call doesn't specify the alignment, 1330 // then it is some target specific value that we can't know. 1331 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1); 1332 if (ByValAlign == 0) return false; 1333 1334 // If it is greater than the memcpy, then we check to see if we can force the 1335 // source of the memcpy to the alignment we need. If we fail, we bail out. 1336 AssumptionCache &AC = LookupAssumptionCache(); 1337 DominatorTree &DT = LookupDomTree(); 1338 if (MDep->getAlignment() < ByValAlign && 1339 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, 1340 CS.getInstruction(), &AC, &DT) < ByValAlign) 1341 return false; 1342 1343 // Verify that the copied-from memory doesn't change in between the memcpy and 1344 // the byval call. 1345 // memcpy(a <- b) 1346 // *b = 42; 1347 // foo(*a) 1348 // It would be invalid to transform the second memcpy into foo(*b). 1349 // 1350 // NOTE: This is conservative, it will stop on any read from the source loc, 1351 // not just the defining memcpy. 1352 MemDepResult SourceDep = MD->getPointerDependencyFrom( 1353 MemoryLocation::getForSource(MDep), false, 1354 CS.getInstruction()->getIterator(), MDep->getParent()); 1355 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) 1356 return false; 1357 1358 Value *TmpCast = MDep->getSource(); 1359 if (MDep->getSource()->getType() != ByValArg->getType()) 1360 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(), 1361 "tmpcast", CS.getInstruction()); 1362 1363 DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n" 1364 << " " << *MDep << "\n" 1365 << " " << *CS.getInstruction() << "\n"); 1366 1367 // Otherwise we're good! Update the byval argument. 1368 CS.setArgument(ArgNo, TmpCast); 1369 ++NumMemCpyInstr; 1370 return true; 1371 } 1372 1373 /// Executes one iteration of MemCpyOptPass. 1374 bool MemCpyOptPass::iterateOnFunction(Function &F) { 1375 bool MadeChange = false; 1376 1377 // Walk all instruction in the function. 1378 for (BasicBlock &BB : F) { 1379 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { 1380 // Avoid invalidating the iterator. 1381 Instruction *I = &*BI++; 1382 1383 bool RepeatInstruction = false; 1384 1385 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 1386 MadeChange |= processStore(SI, BI); 1387 else if (MemSetInst *M = dyn_cast<MemSetInst>(I)) 1388 RepeatInstruction = processMemSet(M, BI); 1389 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) 1390 RepeatInstruction = processMemCpy(M); 1391 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) 1392 RepeatInstruction = processMemMove(M); 1393 else if (auto CS = CallSite(I)) { 1394 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) 1395 if (CS.isByValArgument(i)) 1396 MadeChange |= processByValArgument(CS, i); 1397 } 1398 1399 // Reprocess the instruction if desired. 1400 if (RepeatInstruction) { 1401 if (BI != BB.begin()) 1402 --BI; 1403 MadeChange = true; 1404 } 1405 } 1406 } 1407 1408 return MadeChange; 1409 } 1410 1411 PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) { 1412 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F); 1413 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1414 1415 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & { 1416 return AM.getResult<AAManager>(F); 1417 }; 1418 auto LookupAssumptionCache = [&]() -> AssumptionCache & { 1419 return AM.getResult<AssumptionAnalysis>(F); 1420 }; 1421 auto LookupDomTree = [&]() -> DominatorTree & { 1422 return AM.getResult<DominatorTreeAnalysis>(F); 1423 }; 1424 1425 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis, 1426 LookupAssumptionCache, LookupDomTree); 1427 if (!MadeChange) 1428 return PreservedAnalyses::all(); 1429 1430 PreservedAnalyses PA; 1431 PA.preserveSet<CFGAnalyses>(); 1432 PA.preserve<GlobalsAA>(); 1433 PA.preserve<MemoryDependenceAnalysis>(); 1434 return PA; 1435 } 1436 1437 bool MemCpyOptPass::runImpl( 1438 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_, 1439 std::function<AliasAnalysis &()> LookupAliasAnalysis_, 1440 std::function<AssumptionCache &()> LookupAssumptionCache_, 1441 std::function<DominatorTree &()> LookupDomTree_) { 1442 bool MadeChange = false; 1443 MD = MD_; 1444 TLI = TLI_; 1445 LookupAliasAnalysis = std::move(LookupAliasAnalysis_); 1446 LookupAssumptionCache = std::move(LookupAssumptionCache_); 1447 LookupDomTree = std::move(LookupDomTree_); 1448 1449 // If we don't have at least memset and memcpy, there is little point of doing 1450 // anything here. These are required by a freestanding implementation, so if 1451 // even they are disabled, there is no point in trying hard. 1452 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy)) 1453 return false; 1454 1455 while (true) { 1456 if (!iterateOnFunction(F)) 1457 break; 1458 MadeChange = true; 1459 } 1460 1461 MD = nullptr; 1462 return MadeChange; 1463 } 1464 1465 /// This is the main transformation entry point for a function. 1466 bool MemCpyOptLegacyPass::runOnFunction(Function &F) { 1467 if (skipFunction(F)) 1468 return false; 1469 1470 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 1471 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1472 1473 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & { 1474 return getAnalysis<AAResultsWrapperPass>().getAAResults(); 1475 }; 1476 auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & { 1477 return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1478 }; 1479 auto LookupDomTree = [this]() -> DominatorTree & { 1480 return getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1481 }; 1482 1483 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache, 1484 LookupDomTree); 1485 } 1486