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.addRequired<MemoryDependenceWrapperPass>(); 275 AU.addRequired<AAResultsWrapperPass>(); 276 AU.addRequired<TargetLibraryInfoWrapperPass>(); 277 AU.addPreserved<GlobalsAAWrapperPass>(); 278 AU.addPreserved<MemoryDependenceWrapperPass>(); 279 } 280 }; 281 282 } // end anonymous namespace 283 284 char MemCpyOptLegacyPass::ID = 0; 285 286 /// The public interface to this file... 287 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); } 288 289 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization", 290 false, false) 291 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 292 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 293 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 294 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 295 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 296 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 297 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization", 298 false, false) 299 300 /// When scanning forward over instructions, we look for some other patterns to 301 /// fold away. In particular, this looks for stores to neighboring locations of 302 /// memory. If it sees enough consecutive ones, it attempts to merge them 303 /// together into a memcpy/memset. 304 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst, 305 Value *StartPtr, 306 Value *ByteVal) { 307 const DataLayout &DL = StartInst->getModule()->getDataLayout(); 308 309 // Okay, so we now have a single store that can be splatable. Scan to find 310 // all subsequent stores of the same value to offset from the same pointer. 311 // Join these together into ranges, so we can decide whether contiguous blocks 312 // are stored. 313 MemsetRanges Ranges(DL); 314 315 BasicBlock::iterator BI(StartInst); 316 for (++BI; !BI->isTerminator(); ++BI) { 317 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) { 318 // If the instruction is readnone, ignore it, otherwise bail out. We 319 // don't even allow readonly here because we don't want something like: 320 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A). 321 if (BI->mayWriteToMemory() || BI->mayReadFromMemory()) 322 break; 323 continue; 324 } 325 326 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) { 327 // If this is a store, see if we can merge it in. 328 if (!NextStore->isSimple()) break; 329 330 // Check to see if this stored value is of the same byte-splattable value. 331 Value *StoredByte = isBytewiseValue(NextStore->getOperand(0), DL); 332 if (isa<UndefValue>(ByteVal) && StoredByte) 333 ByteVal = StoredByte; 334 if (ByteVal != StoredByte) 335 break; 336 337 // Check to see if this store is to a constant offset from the start ptr. 338 Optional<int64_t> Offset = 339 isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL); 340 if (!Offset) 341 break; 342 343 Ranges.addStore(*Offset, NextStore); 344 } else { 345 MemSetInst *MSI = cast<MemSetInst>(BI); 346 347 if (MSI->isVolatile() || ByteVal != MSI->getValue() || 348 !isa<ConstantInt>(MSI->getLength())) 349 break; 350 351 // Check to see if this store is to a constant offset from the start ptr. 352 Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL); 353 if (!Offset) 354 break; 355 356 Ranges.addMemSet(*Offset, MSI); 357 } 358 } 359 360 // If we have no ranges, then we just had a single store with nothing that 361 // could be merged in. This is a very common case of course. 362 if (Ranges.empty()) 363 return nullptr; 364 365 // If we had at least one store that could be merged in, add the starting 366 // store as well. We try to avoid this unless there is at least something 367 // interesting as a small compile-time optimization. 368 Ranges.addInst(0, StartInst); 369 370 // If we create any memsets, we put it right before the first instruction that 371 // isn't part of the memset block. This ensure that the memset is dominated 372 // by any addressing instruction needed by the start of the block. 373 IRBuilder<> Builder(&*BI); 374 375 // Now that we have full information about ranges, loop over the ranges and 376 // emit memset's for anything big enough to be worthwhile. 377 Instruction *AMemSet = nullptr; 378 for (const MemsetRange &Range : Ranges) { 379 if (Range.TheStores.size() == 1) continue; 380 381 // If it is profitable to lower this range to memset, do so now. 382 if (!Range.isProfitableToUseMemset(DL)) 383 continue; 384 385 // Otherwise, we do want to transform this! Create a new memset. 386 // Get the starting pointer of the block. 387 StartPtr = Range.StartPtr; 388 389 AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start, 390 MaybeAlign(Range.Alignment)); 391 LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI 392 : Range.TheStores) dbgs() 393 << *SI << '\n'; 394 dbgs() << "With: " << *AMemSet << '\n'); 395 396 if (!Range.TheStores.empty()) 397 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc()); 398 399 // Zap all the stores. 400 for (Instruction *SI : Range.TheStores) { 401 MD->removeInstruction(SI); 402 SI->eraseFromParent(); 403 } 404 ++NumMemSetInfer; 405 } 406 407 return AMemSet; 408 } 409 410 // This method try to lift a store instruction before position P. 411 // It will lift the store and its argument + that anything that 412 // may alias with these. 413 // The method returns true if it was successful. 414 static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P, 415 const LoadInst *LI) { 416 // If the store alias this position, early bail out. 417 MemoryLocation StoreLoc = MemoryLocation::get(SI); 418 if (isModOrRefSet(AA.getModRefInfo(P, StoreLoc))) 419 return false; 420 421 // Keep track of the arguments of all instruction we plan to lift 422 // so we can make sure to lift them as well if appropriate. 423 DenseSet<Instruction*> Args; 424 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) 425 if (Ptr->getParent() == SI->getParent()) 426 Args.insert(Ptr); 427 428 // Instruction to lift before P. 429 SmallVector<Instruction*, 8> ToLift; 430 431 // Memory locations of lifted instructions. 432 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc}; 433 434 // Lifted calls. 435 SmallVector<const CallBase *, 8> Calls; 436 437 const MemoryLocation LoadLoc = MemoryLocation::get(LI); 438 439 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) { 440 auto *C = &*I; 441 442 bool MayAlias = isModOrRefSet(AA.getModRefInfo(C, None)); 443 444 bool NeedLift = false; 445 if (Args.erase(C)) 446 NeedLift = true; 447 else if (MayAlias) { 448 NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) { 449 return isModOrRefSet(AA.getModRefInfo(C, ML)); 450 }); 451 452 if (!NeedLift) 453 NeedLift = llvm::any_of(Calls, [C, &AA](const CallBase *Call) { 454 return isModOrRefSet(AA.getModRefInfo(C, Call)); 455 }); 456 } 457 458 if (!NeedLift) 459 continue; 460 461 if (MayAlias) { 462 // Since LI is implicitly moved downwards past the lifted instructions, 463 // none of them may modify its source. 464 if (isModSet(AA.getModRefInfo(C, LoadLoc))) 465 return false; 466 else if (const auto *Call = dyn_cast<CallBase>(C)) { 467 // If we can't lift this before P, it's game over. 468 if (isModOrRefSet(AA.getModRefInfo(P, Call))) 469 return false; 470 471 Calls.push_back(Call); 472 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) { 473 // If we can't lift this before P, it's game over. 474 auto ML = MemoryLocation::get(C); 475 if (isModOrRefSet(AA.getModRefInfo(P, ML))) 476 return false; 477 478 MemLocs.push_back(ML); 479 } else 480 // We don't know how to lift this instruction. 481 return false; 482 } 483 484 ToLift.push_back(C); 485 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k) 486 if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) { 487 if (A->getParent() == SI->getParent()) { 488 // Cannot hoist user of P above P 489 if(A == P) return false; 490 Args.insert(A); 491 } 492 } 493 } 494 495 // We made it, we need to lift 496 for (auto *I : llvm::reverse(ToLift)) { 497 LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n"); 498 I->moveBefore(P); 499 } 500 501 return true; 502 } 503 504 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) { 505 if (!SI->isSimple()) return false; 506 507 // Avoid merging nontemporal stores since the resulting 508 // memcpy/memset would not be able to preserve the nontemporal hint. 509 // In theory we could teach how to propagate the !nontemporal metadata to 510 // memset calls. However, that change would force the backend to 511 // conservatively expand !nontemporal memset calls back to sequences of 512 // store instructions (effectively undoing the merging). 513 if (SI->getMetadata(LLVMContext::MD_nontemporal)) 514 return false; 515 516 const DataLayout &DL = SI->getModule()->getDataLayout(); 517 518 // Load to store forwarding can be interpreted as memcpy. 519 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) { 520 if (LI->isSimple() && LI->hasOneUse() && 521 LI->getParent() == SI->getParent()) { 522 523 auto *T = LI->getType(); 524 if (T->isAggregateType()) { 525 AliasAnalysis &AA = LookupAliasAnalysis(); 526 MemoryLocation LoadLoc = MemoryLocation::get(LI); 527 528 // We use alias analysis to check if an instruction may store to 529 // the memory we load from in between the load and the store. If 530 // such an instruction is found, we try to promote there instead 531 // of at the store position. 532 Instruction *P = SI; 533 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) { 534 if (isModSet(AA.getModRefInfo(&I, LoadLoc))) { 535 P = &I; 536 break; 537 } 538 } 539 540 // We found an instruction that may write to the loaded memory. 541 // We can try to promote at this position instead of the store 542 // position if nothing alias the store memory after this and the store 543 // destination is not in the range. 544 if (P && P != SI) { 545 if (!moveUp(AA, SI, P, LI)) 546 P = nullptr; 547 } 548 549 // If a valid insertion position is found, then we can promote 550 // the load/store pair to a memcpy. 551 if (P) { 552 // If we load from memory that may alias the memory we store to, 553 // memmove must be used to preserve semantic. If not, memcpy can 554 // be used. 555 bool UseMemMove = false; 556 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc)) 557 UseMemMove = true; 558 559 uint64_t Size = DL.getTypeStoreSize(T); 560 561 IRBuilder<> Builder(P); 562 Instruction *M; 563 if (UseMemMove) 564 M = Builder.CreateMemMove( 565 SI->getPointerOperand(), SI->getAlign(), 566 LI->getPointerOperand(), LI->getAlign(), Size); 567 else 568 M = Builder.CreateMemCpy( 569 SI->getPointerOperand(), SI->getAlign(), 570 LI->getPointerOperand(), LI->getAlign(), Size); 571 572 LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => " 573 << *M << "\n"); 574 575 MD->removeInstruction(SI); 576 SI->eraseFromParent(); 577 MD->removeInstruction(LI); 578 LI->eraseFromParent(); 579 ++NumMemCpyInstr; 580 581 // Make sure we do not invalidate the iterator. 582 BBI = M->getIterator(); 583 return true; 584 } 585 } 586 587 // Detect cases where we're performing call slot forwarding, but 588 // happen to be using a load-store pair to implement it, rather than 589 // a memcpy. 590 MemDepResult ldep = MD->getDependency(LI); 591 CallInst *C = nullptr; 592 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst())) 593 C = dyn_cast<CallInst>(ldep.getInst()); 594 595 if (C) { 596 // Check that nothing touches the dest of the "copy" between 597 // the call and the store. 598 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts(); 599 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest); 600 AliasAnalysis &AA = LookupAliasAnalysis(); 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 DominatorTree &DT = LookupDomTree(); 815 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest)) 816 if (!DT.dominates(cpyDestInst, C)) 817 return false; 818 819 // In addition to knowing that the call does not access src in some 820 // unexpected manner, for example via a global, which we deduce from 821 // the use analysis, we also need to know that it does not sneakily 822 // access dest. We rely on AA to figure this out for us. 823 AliasAnalysis &AA = LookupAliasAnalysis(); 824 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, LocationSize::precise(srcSize)); 825 // If necessary, perform additional analysis. 826 if (isModOrRefSet(MR)) 827 MR = AA.callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), &DT); 828 if (isModOrRefSet(MR)) 829 return false; 830 831 // We can't create address space casts here because we don't know if they're 832 // safe for the target. 833 if (cpySrc->getType()->getPointerAddressSpace() != 834 cpyDest->getType()->getPointerAddressSpace()) 835 return false; 836 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI) 837 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc && 838 cpySrc->getType()->getPointerAddressSpace() != 839 C->getArgOperand(ArgI)->getType()->getPointerAddressSpace()) 840 return false; 841 842 // All the checks have passed, so do the transformation. 843 bool changedArgument = false; 844 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI) 845 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) { 846 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest 847 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(), 848 cpyDest->getName(), C); 849 changedArgument = true; 850 if (C->getArgOperand(ArgI)->getType() == Dest->getType()) 851 C->setArgOperand(ArgI, Dest); 852 else 853 C->setArgOperand(ArgI, CastInst::CreatePointerCast( 854 Dest, C->getArgOperand(ArgI)->getType(), 855 Dest->getName(), C)); 856 } 857 858 if (!changedArgument) 859 return false; 860 861 // If the destination wasn't sufficiently aligned then increase its alignment. 862 if (!isDestSufficientlyAligned) { 863 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!"); 864 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign); 865 } 866 867 // Drop any cached information about the call, because we may have changed 868 // its dependence information by changing its parameter. 869 MD->removeInstruction(C); 870 871 // Update AA metadata 872 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be 873 // handled here, but combineMetadata doesn't support them yet 874 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 875 LLVMContext::MD_noalias, 876 LLVMContext::MD_invariant_group, 877 LLVMContext::MD_access_group}; 878 combineMetadata(C, cpy, KnownIDs, true); 879 880 // Remove the memcpy. 881 MD->removeInstruction(cpy); 882 ++NumMemCpyInstr; 883 884 return true; 885 } 886 887 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is 888 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can. 889 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M, 890 MemCpyInst *MDep) { 891 // We can only transforms memcpy's where the dest of one is the source of the 892 // other. 893 if (M->getSource() != MDep->getDest() || MDep->isVolatile()) 894 return false; 895 896 // If dep instruction is reading from our current input, then it is a noop 897 // transfer and substituting the input won't change this instruction. Just 898 // ignore the input and let someone else zap MDep. This handles cases like: 899 // memcpy(a <- a) 900 // memcpy(b <- a) 901 if (M->getSource() == MDep->getSource()) 902 return false; 903 904 // Second, the length of the memcpy's must be the same, or the preceding one 905 // must be larger than the following one. 906 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength()); 907 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength()); 908 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue()) 909 return false; 910 911 AliasAnalysis &AA = LookupAliasAnalysis(); 912 913 // Verify that the copied-from memory doesn't change in between the two 914 // transfers. For example, in: 915 // memcpy(a <- b) 916 // *b = 42; 917 // memcpy(c <- a) 918 // It would be invalid to transform the second memcpy into memcpy(c <- b). 919 // 920 // TODO: If the code between M and MDep is transparent to the destination "c", 921 // then we could still perform the xform by moving M up to the first memcpy. 922 // 923 // NOTE: This is conservative, it will stop on any read from the source loc, 924 // not just the defining memcpy. 925 MemDepResult SourceDep = 926 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false, 927 M->getIterator(), M->getParent()); 928 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) 929 return false; 930 931 // If the dest of the second might alias the source of the first, then the 932 // source and dest might overlap. We still want to eliminate the intermediate 933 // value, but we have to generate a memmove instead of memcpy. 934 bool UseMemMove = false; 935 if (!AA.isNoAlias(MemoryLocation::getForDest(M), 936 MemoryLocation::getForSource(MDep))) 937 UseMemMove = true; 938 939 // If all checks passed, then we can transform M. 940 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n" 941 << *MDep << '\n' << *M << '\n'); 942 943 // TODO: Is this worth it if we're creating a less aligned memcpy? For 944 // example we could be moving from movaps -> movq on x86. 945 IRBuilder<> Builder(M); 946 if (UseMemMove) 947 Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(), 948 MDep->getRawSource(), MDep->getSourceAlign(), 949 M->getLength(), M->isVolatile()); 950 else 951 Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(), 952 MDep->getRawSource(), MDep->getSourceAlign(), 953 M->getLength(), M->isVolatile()); 954 955 // Remove the instruction we're replacing. 956 MD->removeInstruction(M); 957 M->eraseFromParent(); 958 ++NumMemCpyInstr; 959 return true; 960 } 961 962 /// We've found that the (upward scanning) memory dependence of \p MemCpy is 963 /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that 964 /// weren't copied over by \p MemCpy. 965 /// 966 /// In other words, transform: 967 /// \code 968 /// memset(dst, c, dst_size); 969 /// memcpy(dst, src, src_size); 970 /// \endcode 971 /// into: 972 /// \code 973 /// memcpy(dst, src, src_size); 974 /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size); 975 /// \endcode 976 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy, 977 MemSetInst *MemSet) { 978 // We can only transform memset/memcpy with the same destination. 979 if (MemSet->getDest() != MemCpy->getDest()) 980 return false; 981 982 // Check that there are no other dependencies on the memset destination. 983 MemDepResult DstDepInfo = 984 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false, 985 MemCpy->getIterator(), MemCpy->getParent()); 986 if (DstDepInfo.getInst() != MemSet) 987 return false; 988 989 // Use the same i8* dest as the memcpy, killing the memset dest if different. 990 Value *Dest = MemCpy->getRawDest(); 991 Value *DestSize = MemSet->getLength(); 992 Value *SrcSize = MemCpy->getLength(); 993 994 // By default, create an unaligned memset. 995 unsigned Align = 1; 996 // If Dest is aligned, and SrcSize is constant, use the minimum alignment 997 // of the sum. 998 const unsigned DestAlign = 999 std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment()); 1000 if (DestAlign > 1) 1001 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize)) 1002 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign); 1003 1004 IRBuilder<> Builder(MemCpy); 1005 1006 // If the sizes have different types, zext the smaller one. 1007 if (DestSize->getType() != SrcSize->getType()) { 1008 if (DestSize->getType()->getIntegerBitWidth() > 1009 SrcSize->getType()->getIntegerBitWidth()) 1010 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType()); 1011 else 1012 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType()); 1013 } 1014 1015 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize); 1016 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize); 1017 Value *MemsetLen = Builder.CreateSelect( 1018 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff); 1019 Builder.CreateMemSet( 1020 Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest, 1021 SrcSize), 1022 MemSet->getOperand(1), MemsetLen, MaybeAlign(Align)); 1023 1024 MD->removeInstruction(MemSet); 1025 MemSet->eraseFromParent(); 1026 return true; 1027 } 1028 1029 /// Determine whether the instruction has undefined content for the given Size, 1030 /// either because it was freshly alloca'd or started its lifetime. 1031 static bool hasUndefContents(Instruction *I, ConstantInt *Size) { 1032 if (isa<AllocaInst>(I)) 1033 return true; 1034 1035 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 1036 if (II->getIntrinsicID() == Intrinsic::lifetime_start) 1037 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0))) 1038 if (LTSize->getZExtValue() >= Size->getZExtValue()) 1039 return true; 1040 1041 return false; 1042 } 1043 1044 /// Transform memcpy to memset when its source was just memset. 1045 /// In other words, turn: 1046 /// \code 1047 /// memset(dst1, c, dst1_size); 1048 /// memcpy(dst2, dst1, dst2_size); 1049 /// \endcode 1050 /// into: 1051 /// \code 1052 /// memset(dst1, c, dst1_size); 1053 /// memset(dst2, c, dst2_size); 1054 /// \endcode 1055 /// When dst2_size <= dst1_size. 1056 /// 1057 /// The \p MemCpy must have a Constant length. 1058 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy, 1059 MemSetInst *MemSet) { 1060 AliasAnalysis &AA = LookupAliasAnalysis(); 1061 1062 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and 1063 // memcpying from the same address. Otherwise it is hard to reason about. 1064 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource())) 1065 return false; 1066 1067 // A known memset size is required. 1068 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength()); 1069 if (!MemSetSize) 1070 return false; 1071 1072 // Make sure the memcpy doesn't read any more than what the memset wrote. 1073 // Don't worry about sizes larger than i64. 1074 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength()); 1075 if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) { 1076 // If the memcpy is larger than the memset, but the memory was undef prior 1077 // to the memset, we can just ignore the tail. Technically we're only 1078 // interested in the bytes from MemSetSize..CopySize here, but as we can't 1079 // easily represent this location, we use the full 0..CopySize range. 1080 MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy); 1081 MemDepResult DepInfo = MD->getPointerDependencyFrom( 1082 MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent()); 1083 if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize)) 1084 CopySize = MemSetSize; 1085 else 1086 return false; 1087 } 1088 1089 IRBuilder<> Builder(MemCpy); 1090 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1), CopySize, 1091 MaybeAlign(MemCpy->getDestAlignment())); 1092 return true; 1093 } 1094 1095 /// Perform simplification of memcpy's. If we have memcpy A 1096 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite 1097 /// B to be a memcpy from X to Z (or potentially a memmove, depending on 1098 /// circumstances). This allows later passes to remove the first memcpy 1099 /// altogether. 1100 bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) { 1101 // We can only optimize non-volatile memcpy's. 1102 if (M->isVolatile()) return false; 1103 1104 // If the source and destination of the memcpy are the same, then zap it. 1105 if (M->getSource() == M->getDest()) { 1106 ++BBI; 1107 MD->removeInstruction(M); 1108 M->eraseFromParent(); 1109 return true; 1110 } 1111 1112 // If copying from a constant, try to turn the memcpy into a memset. 1113 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource())) 1114 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 1115 if (Value *ByteVal = isBytewiseValue(GV->getInitializer(), 1116 M->getModule()->getDataLayout())) { 1117 IRBuilder<> Builder(M); 1118 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(), 1119 MaybeAlign(M->getDestAlignment()), false); 1120 MD->removeInstruction(M); 1121 M->eraseFromParent(); 1122 ++NumCpyToSet; 1123 return true; 1124 } 1125 1126 MemDepResult DepInfo = MD->getDependency(M); 1127 1128 // Try to turn a partially redundant memset + memcpy into 1129 // memcpy + smaller memset. We don't need the memcpy size for this. 1130 if (DepInfo.isClobber()) 1131 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst())) 1132 if (processMemSetMemCpyDependence(M, MDep)) 1133 return true; 1134 1135 // The optimizations after this point require the memcpy size. 1136 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength()); 1137 if (!CopySize) return false; 1138 1139 // There are four possible optimizations we can do for memcpy: 1140 // a) memcpy-memcpy xform which exposes redundance for DSE. 1141 // b) call-memcpy xform for return slot optimization. 1142 // c) memcpy from freshly alloca'd space or space that has just started its 1143 // lifetime copies undefined data, and we can therefore eliminate the 1144 // memcpy in favor of the data that was already at the destination. 1145 // d) memcpy from a just-memset'd source can be turned into memset. 1146 if (DepInfo.isClobber()) { 1147 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) { 1148 // FIXME: Can we pass in either of dest/src alignment here instead 1149 // of conservatively taking the minimum? 1150 Align Alignment = std::min(M->getDestAlign().valueOrOne(), 1151 M->getSourceAlign().valueOrOne()); 1152 if (performCallSlotOptzn(M, M->getDest(), M->getSource(), 1153 CopySize->getZExtValue(), Alignment, C)) { 1154 MD->removeInstruction(M); 1155 M->eraseFromParent(); 1156 return true; 1157 } 1158 } 1159 } 1160 1161 MemoryLocation SrcLoc = MemoryLocation::getForSource(M); 1162 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom( 1163 SrcLoc, true, M->getIterator(), M->getParent()); 1164 1165 if (SrcDepInfo.isClobber()) { 1166 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst())) 1167 return processMemCpyMemCpyDependence(M, MDep); 1168 } else if (SrcDepInfo.isDef()) { 1169 if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) { 1170 MD->removeInstruction(M); 1171 M->eraseFromParent(); 1172 ++NumMemCpyInstr; 1173 return true; 1174 } 1175 } 1176 1177 if (SrcDepInfo.isClobber()) 1178 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst())) 1179 if (performMemCpyToMemSetOptzn(M, MDep)) { 1180 MD->removeInstruction(M); 1181 M->eraseFromParent(); 1182 ++NumCpyToSet; 1183 return true; 1184 } 1185 1186 return false; 1187 } 1188 1189 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed 1190 /// not to alias. 1191 bool MemCpyOptPass::processMemMove(MemMoveInst *M) { 1192 AliasAnalysis &AA = LookupAliasAnalysis(); 1193 1194 if (!TLI->has(LibFunc_memmove)) 1195 return false; 1196 1197 // See if the pointers alias. 1198 if (!AA.isNoAlias(MemoryLocation::getForDest(M), 1199 MemoryLocation::getForSource(M))) 1200 return false; 1201 1202 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M 1203 << "\n"); 1204 1205 // If not, then we know we can transform this. 1206 Type *ArgTys[3] = { M->getRawDest()->getType(), 1207 M->getRawSource()->getType(), 1208 M->getLength()->getType() }; 1209 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(), 1210 Intrinsic::memcpy, ArgTys)); 1211 1212 // MemDep may have over conservative information about this instruction, just 1213 // conservatively flush it from the cache. 1214 MD->removeInstruction(M); 1215 1216 ++NumMoveToCpy; 1217 return true; 1218 } 1219 1220 /// This is called on every byval argument in call sites. 1221 bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) { 1222 const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout(); 1223 // Find out what feeds this byval argument. 1224 Value *ByValArg = CB.getArgOperand(ArgNo); 1225 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType(); 1226 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy); 1227 MemDepResult DepInfo = MD->getPointerDependencyFrom( 1228 MemoryLocation(ByValArg, LocationSize::precise(ByValSize)), true, 1229 CB.getIterator(), CB.getParent()); 1230 if (!DepInfo.isClobber()) 1231 return false; 1232 1233 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by 1234 // a memcpy, see if we can byval from the source of the memcpy instead of the 1235 // result. 1236 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()); 1237 if (!MDep || MDep->isVolatile() || 1238 ByValArg->stripPointerCasts() != MDep->getDest()) 1239 return false; 1240 1241 // The length of the memcpy must be larger or equal to the size of the byval. 1242 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); 1243 if (!C1 || C1->getValue().getZExtValue() < ByValSize) 1244 return false; 1245 1246 // Get the alignment of the byval. If the call doesn't specify the alignment, 1247 // then it is some target specific value that we can't know. 1248 MaybeAlign ByValAlign = CB.getParamAlign(ArgNo); 1249 if (!ByValAlign) return false; 1250 1251 // If it is greater than the memcpy, then we check to see if we can force the 1252 // source of the memcpy to the alignment we need. If we fail, we bail out. 1253 AssumptionCache &AC = LookupAssumptionCache(); 1254 DominatorTree &DT = LookupDomTree(); 1255 MaybeAlign MemDepAlign = MDep->getSourceAlign(); 1256 if ((!MemDepAlign || *MemDepAlign < *ByValAlign) && 1257 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, &AC, 1258 &DT) < *ByValAlign) 1259 return false; 1260 1261 // The address space of the memcpy source must match the byval argument 1262 if (MDep->getSource()->getType()->getPointerAddressSpace() != 1263 ByValArg->getType()->getPointerAddressSpace()) 1264 return false; 1265 1266 // Verify that the copied-from memory doesn't change in between the memcpy and 1267 // the byval call. 1268 // memcpy(a <- b) 1269 // *b = 42; 1270 // foo(*a) 1271 // It would be invalid to transform the second memcpy into foo(*b). 1272 // 1273 // NOTE: This is conservative, it will stop on any read from the source loc, 1274 // not just the defining memcpy. 1275 MemDepResult SourceDep = MD->getPointerDependencyFrom( 1276 MemoryLocation::getForSource(MDep), false, 1277 CB.getIterator(), MDep->getParent()); 1278 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) 1279 return false; 1280 1281 Value *TmpCast = MDep->getSource(); 1282 if (MDep->getSource()->getType() != ByValArg->getType()) { 1283 BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(), 1284 "tmpcast", &CB); 1285 // Set the tmpcast's DebugLoc to MDep's 1286 TmpBitCast->setDebugLoc(MDep->getDebugLoc()); 1287 TmpCast = TmpBitCast; 1288 } 1289 1290 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n" 1291 << " " << *MDep << "\n" 1292 << " " << CB << "\n"); 1293 1294 // Otherwise we're good! Update the byval argument. 1295 CB.setArgOperand(ArgNo, TmpCast); 1296 ++NumMemCpyInstr; 1297 return true; 1298 } 1299 1300 /// Executes one iteration of MemCpyOptPass. 1301 bool MemCpyOptPass::iterateOnFunction(Function &F) { 1302 bool MadeChange = false; 1303 1304 DominatorTree &DT = LookupDomTree(); 1305 1306 // Walk all instruction in the function. 1307 for (BasicBlock &BB : F) { 1308 // Skip unreachable blocks. For example processStore assumes that an 1309 // instruction in a BB can't be dominated by a later instruction in the 1310 // same BB (which is a scenario that can happen for an unreachable BB that 1311 // has itself as a predecessor). 1312 if (!DT.isReachableFromEntry(&BB)) 1313 continue; 1314 1315 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { 1316 // Avoid invalidating the iterator. 1317 Instruction *I = &*BI++; 1318 1319 bool RepeatInstruction = false; 1320 1321 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 1322 MadeChange |= processStore(SI, BI); 1323 else if (MemSetInst *M = dyn_cast<MemSetInst>(I)) 1324 RepeatInstruction = processMemSet(M, BI); 1325 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) 1326 RepeatInstruction = processMemCpy(M, BI); 1327 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) 1328 RepeatInstruction = processMemMove(M); 1329 else if (auto *CB = dyn_cast<CallBase>(I)) { 1330 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) 1331 if (CB->isByValArgument(i)) 1332 MadeChange |= processByValArgument(*CB, i); 1333 } 1334 1335 // Reprocess the instruction if desired. 1336 if (RepeatInstruction) { 1337 if (BI != BB.begin()) 1338 --BI; 1339 MadeChange = true; 1340 } 1341 } 1342 } 1343 1344 return MadeChange; 1345 } 1346 1347 PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) { 1348 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F); 1349 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1350 1351 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & { 1352 return AM.getResult<AAManager>(F); 1353 }; 1354 auto LookupAssumptionCache = [&]() -> AssumptionCache & { 1355 return AM.getResult<AssumptionAnalysis>(F); 1356 }; 1357 auto LookupDomTree = [&]() -> DominatorTree & { 1358 return AM.getResult<DominatorTreeAnalysis>(F); 1359 }; 1360 1361 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis, 1362 LookupAssumptionCache, LookupDomTree); 1363 if (!MadeChange) 1364 return PreservedAnalyses::all(); 1365 1366 PreservedAnalyses PA; 1367 PA.preserveSet<CFGAnalyses>(); 1368 PA.preserve<GlobalsAA>(); 1369 PA.preserve<MemoryDependenceAnalysis>(); 1370 return PA; 1371 } 1372 1373 bool MemCpyOptPass::runImpl( 1374 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_, 1375 std::function<AliasAnalysis &()> LookupAliasAnalysis_, 1376 std::function<AssumptionCache &()> LookupAssumptionCache_, 1377 std::function<DominatorTree &()> LookupDomTree_) { 1378 bool MadeChange = false; 1379 MD = MD_; 1380 TLI = TLI_; 1381 LookupAliasAnalysis = std::move(LookupAliasAnalysis_); 1382 LookupAssumptionCache = std::move(LookupAssumptionCache_); 1383 LookupDomTree = std::move(LookupDomTree_); 1384 1385 // If we don't have at least memset and memcpy, there is little point of doing 1386 // anything here. These are required by a freestanding implementation, so if 1387 // even they are disabled, there is no point in trying hard. 1388 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy)) 1389 return false; 1390 1391 while (true) { 1392 if (!iterateOnFunction(F)) 1393 break; 1394 MadeChange = true; 1395 } 1396 1397 MD = nullptr; 1398 return MadeChange; 1399 } 1400 1401 /// This is the main transformation entry point for a function. 1402 bool MemCpyOptLegacyPass::runOnFunction(Function &F) { 1403 if (skipFunction(F)) 1404 return false; 1405 1406 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 1407 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1408 1409 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & { 1410 return getAnalysis<AAResultsWrapperPass>().getAAResults(); 1411 }; 1412 auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & { 1413 return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1414 }; 1415 auto LookupDomTree = [this]() -> DominatorTree & { 1416 return getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1417 }; 1418 1419 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache, 1420 LookupDomTree); 1421 } 1422