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