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