1 //===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===// 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 implements an idiom recognizer that transforms simple loops into a 10 // non-loop form. In cases that this kicks in, it can be a significant 11 // performance win. 12 // 13 // If compiling for code size we avoid idiom recognition if the resulting 14 // code could be larger than the code for the original loop. One way this could 15 // happen is if the loop is not removable after idiom recognition due to the 16 // presence of non-idiom instructions. The initial implementation of the 17 // heuristics applies to idioms in multi-block loops. 18 // 19 //===----------------------------------------------------------------------===// 20 // 21 // TODO List: 22 // 23 // Future loop memory idioms to recognize: 24 // memcmp, memmove, strlen, etc. 25 // Future floating point idioms to recognize in -ffast-math mode: 26 // fpowi 27 // Future integer operation idioms to recognize: 28 // ctpop 29 // 30 // Beware that isel's default lowering for ctpop is highly inefficient for 31 // i64 and larger types when i64 is legal and the value has few bits set. It 32 // would be good to enhance isel to emit a loop for ctpop in this case. 33 // 34 // This could recognize common matrix multiplies and dot product idioms and 35 // replace them with calls to BLAS (if linked in??). 36 // 37 //===----------------------------------------------------------------------===// 38 39 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" 40 #include "llvm/ADT/APInt.h" 41 #include "llvm/ADT/ArrayRef.h" 42 #include "llvm/ADT/DenseMap.h" 43 #include "llvm/ADT/MapVector.h" 44 #include "llvm/ADT/SetVector.h" 45 #include "llvm/ADT/SmallPtrSet.h" 46 #include "llvm/ADT/SmallVector.h" 47 #include "llvm/ADT/Statistic.h" 48 #include "llvm/ADT/StringRef.h" 49 #include "llvm/Analysis/AliasAnalysis.h" 50 #include "llvm/Analysis/LoopAccessAnalysis.h" 51 #include "llvm/Analysis/LoopInfo.h" 52 #include "llvm/Analysis/LoopPass.h" 53 #include "llvm/Analysis/MemoryLocation.h" 54 #include "llvm/Analysis/MemorySSA.h" 55 #include "llvm/Analysis/MemorySSAUpdater.h" 56 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 57 #include "llvm/Analysis/ScalarEvolution.h" 58 #include "llvm/Analysis/ScalarEvolutionExpander.h" 59 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 60 #include "llvm/Analysis/TargetLibraryInfo.h" 61 #include "llvm/Analysis/TargetTransformInfo.h" 62 #include "llvm/Analysis/ValueTracking.h" 63 #include "llvm/IR/Attributes.h" 64 #include "llvm/IR/BasicBlock.h" 65 #include "llvm/IR/Constant.h" 66 #include "llvm/IR/Constants.h" 67 #include "llvm/IR/DataLayout.h" 68 #include "llvm/IR/DebugLoc.h" 69 #include "llvm/IR/DerivedTypes.h" 70 #include "llvm/IR/Dominators.h" 71 #include "llvm/IR/GlobalValue.h" 72 #include "llvm/IR/GlobalVariable.h" 73 #include "llvm/IR/IRBuilder.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instruction.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Module.h" 81 #include "llvm/IR/PassManager.h" 82 #include "llvm/IR/Type.h" 83 #include "llvm/IR/User.h" 84 #include "llvm/IR/Value.h" 85 #include "llvm/IR/ValueHandle.h" 86 #include "llvm/InitializePasses.h" 87 #include "llvm/Pass.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Transforms/Scalar.h" 93 #include "llvm/Transforms/Utils/BuildLibCalls.h" 94 #include "llvm/Transforms/Utils/Local.h" 95 #include "llvm/Transforms/Utils/LoopUtils.h" 96 #include <algorithm> 97 #include <cassert> 98 #include <cstdint> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "loop-idiom" 105 106 STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); 107 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); 108 109 static cl::opt<bool> UseLIRCodeSizeHeurs( 110 "use-lir-code-size-heurs", 111 cl::desc("Use loop idiom recognition code size heuristics when compiling" 112 "with -Os/-Oz"), 113 cl::init(true), cl::Hidden); 114 115 namespace { 116 117 class LoopIdiomRecognize { 118 Loop *CurLoop = nullptr; 119 AliasAnalysis *AA; 120 DominatorTree *DT; 121 LoopInfo *LI; 122 ScalarEvolution *SE; 123 TargetLibraryInfo *TLI; 124 const TargetTransformInfo *TTI; 125 const DataLayout *DL; 126 OptimizationRemarkEmitter &ORE; 127 bool ApplyCodeSizeHeuristics; 128 std::unique_ptr<MemorySSAUpdater> MSSAU; 129 130 public: 131 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, 132 LoopInfo *LI, ScalarEvolution *SE, 133 TargetLibraryInfo *TLI, 134 const TargetTransformInfo *TTI, MemorySSA *MSSA, 135 const DataLayout *DL, 136 OptimizationRemarkEmitter &ORE) 137 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) { 138 if (MSSA) 139 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 140 } 141 142 bool runOnLoop(Loop *L); 143 144 private: 145 using StoreList = SmallVector<StoreInst *, 8>; 146 using StoreListMap = MapVector<Value *, StoreList>; 147 148 StoreListMap StoreRefsForMemset; 149 StoreListMap StoreRefsForMemsetPattern; 150 StoreList StoreRefsForMemcpy; 151 bool HasMemset; 152 bool HasMemsetPattern; 153 bool HasMemcpy; 154 155 /// Return code for isLegalStore() 156 enum LegalStoreKind { 157 None = 0, 158 Memset, 159 MemsetPattern, 160 Memcpy, 161 UnorderedAtomicMemcpy, 162 DontUse // Dummy retval never to be used. Allows catching errors in retval 163 // handling. 164 }; 165 166 /// \name Countable Loop Idiom Handling 167 /// @{ 168 169 bool runOnCountableLoop(); 170 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, 171 SmallVectorImpl<BasicBlock *> &ExitBlocks); 172 173 void collectStores(BasicBlock *BB); 174 LegalStoreKind isLegalStore(StoreInst *SI); 175 enum class ForMemset { No, Yes }; 176 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, 177 ForMemset For); 178 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); 179 180 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, 181 MaybeAlign StoreAlignment, Value *StoredVal, 182 Instruction *TheStore, 183 SmallPtrSetImpl<Instruction *> &Stores, 184 const SCEVAddRecExpr *Ev, const SCEV *BECount, 185 bool NegStride, bool IsLoopMemset = false); 186 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); 187 bool avoidLIRForMultiBlockLoop(bool IsMemset = false, 188 bool IsLoopMemset = false); 189 190 /// @} 191 /// \name Noncountable Loop Idiom Handling 192 /// @{ 193 194 bool runOnNoncountableLoop(); 195 196 bool recognizePopcount(); 197 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, 198 PHINode *CntPhi, Value *Var); 199 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz 200 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB, 201 Instruction *CntInst, PHINode *CntPhi, 202 Value *Var, Instruction *DefX, 203 const DebugLoc &DL, bool ZeroCheck, 204 bool IsCntPhiUsedOutsideLoop); 205 206 /// @} 207 }; 208 209 class LoopIdiomRecognizeLegacyPass : public LoopPass { 210 public: 211 static char ID; 212 213 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) { 214 initializeLoopIdiomRecognizeLegacyPassPass( 215 *PassRegistry::getPassRegistry()); 216 } 217 218 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 219 if (skipLoop(L)) 220 return false; 221 222 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 223 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 224 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 225 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 226 TargetLibraryInfo *TLI = 227 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 228 *L->getHeader()->getParent()); 229 const TargetTransformInfo *TTI = 230 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 231 *L->getHeader()->getParent()); 232 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout(); 233 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 234 MemorySSA *MSSA = nullptr; 235 if (MSSAAnalysis) 236 MSSA = &MSSAAnalysis->getMSSA(); 237 238 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 239 // pass. Function analyses need to be preserved across loop transformations 240 // but ORE cannot be preserved (see comment before the pass definition). 241 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 242 243 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, MSSA, DL, ORE); 244 return LIR.runOnLoop(L); 245 } 246 247 /// This transformation requires natural loop information & requires that 248 /// loop preheaders be inserted into the CFG. 249 void getAnalysisUsage(AnalysisUsage &AU) const override { 250 AU.addRequired<TargetLibraryInfoWrapperPass>(); 251 AU.addRequired<TargetTransformInfoWrapperPass>(); 252 AU.addPreserved<MemorySSAWrapperPass>(); 253 getLoopAnalysisUsage(AU); 254 } 255 }; 256 257 } // end anonymous namespace 258 259 char LoopIdiomRecognizeLegacyPass::ID = 0; 260 261 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM, 262 LoopStandardAnalysisResults &AR, 263 LPMUpdater &) { 264 const auto *DL = &L.getHeader()->getModule()->getDataLayout(); 265 266 const auto &FAM = 267 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 268 Function *F = L.getHeader()->getParent(); 269 270 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F); 271 // FIXME: This should probably be optional rather than required. 272 if (!ORE) 273 report_fatal_error( 274 "LoopIdiomRecognizePass: OptimizationRemarkEmitterAnalysis not cached " 275 "at a higher level"); 276 277 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, 278 AR.MSSA, DL, *ORE); 279 if (!LIR.runOnLoop(&L)) 280 return PreservedAnalyses::all(); 281 282 auto PA = getLoopPassPreservedAnalyses(); 283 if (AR.MSSA) 284 PA.preserve<MemorySSAAnalysis>(); 285 return PA; 286 } 287 288 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", 289 "Recognize loop idioms", false, false) 290 INITIALIZE_PASS_DEPENDENCY(LoopPass) 291 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 292 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 293 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom", 294 "Recognize loop idioms", false, false) 295 296 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); } 297 298 static void deleteDeadInstruction(Instruction *I) { 299 I->replaceAllUsesWith(UndefValue::get(I->getType())); 300 I->eraseFromParent(); 301 } 302 303 //===----------------------------------------------------------------------===// 304 // 305 // Implementation of LoopIdiomRecognize 306 // 307 //===----------------------------------------------------------------------===// 308 309 bool LoopIdiomRecognize::runOnLoop(Loop *L) { 310 CurLoop = L; 311 // If the loop could not be converted to canonical form, it must have an 312 // indirectbr in it, just give up. 313 if (!L->getLoopPreheader()) 314 return false; 315 316 // Disable loop idiom recognition if the function's name is a common idiom. 317 StringRef Name = L->getHeader()->getParent()->getName(); 318 if (Name == "memset" || Name == "memcpy") 319 return false; 320 321 // Determine if code size heuristics need to be applied. 322 ApplyCodeSizeHeuristics = 323 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs; 324 325 HasMemset = TLI->has(LibFunc_memset); 326 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16); 327 HasMemcpy = TLI->has(LibFunc_memcpy); 328 329 if (HasMemset || HasMemsetPattern || HasMemcpy) 330 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 331 return runOnCountableLoop(); 332 333 return runOnNoncountableLoop(); 334 } 335 336 bool LoopIdiomRecognize::runOnCountableLoop() { 337 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); 338 assert(!isa<SCEVCouldNotCompute>(BECount) && 339 "runOnCountableLoop() called on a loop without a predictable" 340 "backedge-taken count"); 341 342 // If this loop executes exactly one time, then it should be peeled, not 343 // optimized by this pass. 344 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 345 if (BECst->getAPInt() == 0) 346 return false; 347 348 SmallVector<BasicBlock *, 8> ExitBlocks; 349 CurLoop->getUniqueExitBlocks(ExitBlocks); 350 351 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 352 << CurLoop->getHeader()->getParent()->getName() 353 << "] Countable Loop %" << CurLoop->getHeader()->getName() 354 << "\n"); 355 356 // The following transforms hoist stores/memsets into the loop pre-header. 357 // Give up if the loop has instructions that may throw. 358 SimpleLoopSafetyInfo SafetyInfo; 359 SafetyInfo.computeLoopSafetyInfo(CurLoop); 360 if (SafetyInfo.anyBlockMayThrow()) 361 return false; 362 363 bool MadeChange = false; 364 365 // Scan all the blocks in the loop that are not in subloops. 366 for (auto *BB : CurLoop->getBlocks()) { 367 // Ignore blocks in subloops. 368 if (LI->getLoopFor(BB) != CurLoop) 369 continue; 370 371 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); 372 } 373 return MadeChange; 374 } 375 376 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { 377 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); 378 return ConstStride->getAPInt(); 379 } 380 381 /// getMemSetPatternValue - If a strided store of the specified value is safe to 382 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should 383 /// be passed in. Otherwise, return null. 384 /// 385 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these 386 /// just replicate their input array and then pass on to memset_pattern16. 387 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { 388 // FIXME: This could check for UndefValue because it can be merged into any 389 // other valid pattern. 390 391 // If the value isn't a constant, we can't promote it to being in a constant 392 // array. We could theoretically do a store to an alloca or something, but 393 // that doesn't seem worthwhile. 394 Constant *C = dyn_cast<Constant>(V); 395 if (!C) 396 return nullptr; 397 398 // Only handle simple values that are a power of two bytes in size. 399 uint64_t Size = DL->getTypeSizeInBits(V->getType()); 400 if (Size == 0 || (Size & 7) || (Size & (Size - 1))) 401 return nullptr; 402 403 // Don't care enough about darwin/ppc to implement this. 404 if (DL->isBigEndian()) 405 return nullptr; 406 407 // Convert to size in bytes. 408 Size /= 8; 409 410 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see 411 // if the top and bottom are the same (e.g. for vectors and large integers). 412 if (Size > 16) 413 return nullptr; 414 415 // If the constant is exactly 16 bytes, just use it. 416 if (Size == 16) 417 return C; 418 419 // Otherwise, we'll use an array of the constants. 420 unsigned ArraySize = 16 / Size; 421 ArrayType *AT = ArrayType::get(V->getType(), ArraySize); 422 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); 423 } 424 425 LoopIdiomRecognize::LegalStoreKind 426 LoopIdiomRecognize::isLegalStore(StoreInst *SI) { 427 // Don't touch volatile stores. 428 if (SI->isVolatile()) 429 return LegalStoreKind::None; 430 // We only want simple or unordered-atomic stores. 431 if (!SI->isUnordered()) 432 return LegalStoreKind::None; 433 434 // Don't convert stores of non-integral pointer types to memsets (which stores 435 // integers). 436 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType())) 437 return LegalStoreKind::None; 438 439 // Avoid merging nontemporal stores. 440 if (SI->getMetadata(LLVMContext::MD_nontemporal)) 441 return LegalStoreKind::None; 442 443 Value *StoredVal = SI->getValueOperand(); 444 Value *StorePtr = SI->getPointerOperand(); 445 446 // Reject stores that are so large that they overflow an unsigned. 447 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); 448 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) 449 return LegalStoreKind::None; 450 451 // See if the pointer expression is an AddRec like {base,+,1} on the current 452 // loop, which indicates a strided store. If we have something else, it's a 453 // random store we can't handle. 454 const SCEVAddRecExpr *StoreEv = 455 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 456 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 457 return LegalStoreKind::None; 458 459 // Check to see if we have a constant stride. 460 if (!isa<SCEVConstant>(StoreEv->getOperand(1))) 461 return LegalStoreKind::None; 462 463 // See if the store can be turned into a memset. 464 465 // If the stored value is a byte-wise value (like i32 -1), then it may be 466 // turned into a memset of i8 -1, assuming that all the consecutive bytes 467 // are stored. A store of i32 0x01020304 can never be turned into a memset, 468 // but it can be turned into memset_pattern if the target supports it. 469 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 470 Constant *PatternValue = nullptr; 471 472 // Note: memset and memset_pattern on unordered-atomic is yet not supported 473 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple(); 474 475 // If we're allowed to form a memset, and the stored value would be 476 // acceptable for memset, use it. 477 if (!UnorderedAtomic && HasMemset && SplatValue && 478 // Verify that the stored value is loop invariant. If not, we can't 479 // promote the memset. 480 CurLoop->isLoopInvariant(SplatValue)) { 481 // It looks like we can use SplatValue. 482 return LegalStoreKind::Memset; 483 } else if (!UnorderedAtomic && HasMemsetPattern && 484 // Don't create memset_pattern16s with address spaces. 485 StorePtr->getType()->getPointerAddressSpace() == 0 && 486 (PatternValue = getMemSetPatternValue(StoredVal, DL))) { 487 // It looks like we can use PatternValue! 488 return LegalStoreKind::MemsetPattern; 489 } 490 491 // Otherwise, see if the store can be turned into a memcpy. 492 if (HasMemcpy) { 493 // Check to see if the stride matches the size of the store. If so, then we 494 // know that every byte is touched in the loop. 495 APInt Stride = getStoreStride(StoreEv); 496 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 497 if (StoreSize != Stride && StoreSize != -Stride) 498 return LegalStoreKind::None; 499 500 // The store must be feeding a non-volatile load. 501 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); 502 503 // Only allow non-volatile loads 504 if (!LI || LI->isVolatile()) 505 return LegalStoreKind::None; 506 // Only allow simple or unordered-atomic loads 507 if (!LI->isUnordered()) 508 return LegalStoreKind::None; 509 510 // See if the pointer expression is an AddRec like {base,+,1} on the current 511 // loop, which indicates a strided load. If we have something else, it's a 512 // random load we can't handle. 513 const SCEVAddRecExpr *LoadEv = 514 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 515 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 516 return LegalStoreKind::None; 517 518 // The store and load must share the same stride. 519 if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) 520 return LegalStoreKind::None; 521 522 // Success. This store can be converted into a memcpy. 523 UnorderedAtomic = UnorderedAtomic || LI->isAtomic(); 524 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy 525 : LegalStoreKind::Memcpy; 526 } 527 // This store can't be transformed into a memset/memcpy. 528 return LegalStoreKind::None; 529 } 530 531 void LoopIdiomRecognize::collectStores(BasicBlock *BB) { 532 StoreRefsForMemset.clear(); 533 StoreRefsForMemsetPattern.clear(); 534 StoreRefsForMemcpy.clear(); 535 for (Instruction &I : *BB) { 536 StoreInst *SI = dyn_cast<StoreInst>(&I); 537 if (!SI) 538 continue; 539 540 // Make sure this is a strided store with a constant stride. 541 switch (isLegalStore(SI)) { 542 case LegalStoreKind::None: 543 // Nothing to do 544 break; 545 case LegalStoreKind::Memset: { 546 // Find the base pointer. 547 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); 548 StoreRefsForMemset[Ptr].push_back(SI); 549 } break; 550 case LegalStoreKind::MemsetPattern: { 551 // Find the base pointer. 552 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); 553 StoreRefsForMemsetPattern[Ptr].push_back(SI); 554 } break; 555 case LegalStoreKind::Memcpy: 556 case LegalStoreKind::UnorderedAtomicMemcpy: 557 StoreRefsForMemcpy.push_back(SI); 558 break; 559 default: 560 assert(false && "unhandled return value"); 561 break; 562 } 563 } 564 } 565 566 /// runOnLoopBlock - Process the specified block, which lives in a counted loop 567 /// with the specified backedge count. This block is known to be in the current 568 /// loop and not in any subloops. 569 bool LoopIdiomRecognize::runOnLoopBlock( 570 BasicBlock *BB, const SCEV *BECount, 571 SmallVectorImpl<BasicBlock *> &ExitBlocks) { 572 // We can only promote stores in this block if they are unconditionally 573 // executed in the loop. For a block to be unconditionally executed, it has 574 // to dominate all the exit blocks of the loop. Verify this now. 575 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 576 if (!DT->dominates(BB, ExitBlocks[i])) 577 return false; 578 579 bool MadeChange = false; 580 // Look for store instructions, which may be optimized to memset/memcpy. 581 collectStores(BB); 582 583 // Look for a single store or sets of stores with a common base, which can be 584 // optimized into a memset (memset_pattern). The latter most commonly happens 585 // with structs and handunrolled loops. 586 for (auto &SL : StoreRefsForMemset) 587 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes); 588 589 for (auto &SL : StoreRefsForMemsetPattern) 590 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No); 591 592 // Optimize the store into a memcpy, if it feeds an similarly strided load. 593 for (auto &SI : StoreRefsForMemcpy) 594 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); 595 596 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 597 Instruction *Inst = &*I++; 598 // Look for memset instructions, which may be optimized to a larger memset. 599 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { 600 WeakTrackingVH InstPtr(&*I); 601 if (!processLoopMemSet(MSI, BECount)) 602 continue; 603 MadeChange = true; 604 605 // If processing the memset invalidated our iterator, start over from the 606 // top of the block. 607 if (!InstPtr) 608 I = BB->begin(); 609 continue; 610 } 611 } 612 613 return MadeChange; 614 } 615 616 /// See if this store(s) can be promoted to a memset. 617 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, 618 const SCEV *BECount, ForMemset For) { 619 // Try to find consecutive stores that can be transformed into memsets. 620 SetVector<StoreInst *> Heads, Tails; 621 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; 622 623 // Do a quadratic search on all of the given stores and find 624 // all of the pairs of stores that follow each other. 625 SmallVector<unsigned, 16> IndexQueue; 626 for (unsigned i = 0, e = SL.size(); i < e; ++i) { 627 assert(SL[i]->isSimple() && "Expected only non-volatile stores."); 628 629 Value *FirstStoredVal = SL[i]->getValueOperand(); 630 Value *FirstStorePtr = SL[i]->getPointerOperand(); 631 const SCEVAddRecExpr *FirstStoreEv = 632 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); 633 APInt FirstStride = getStoreStride(FirstStoreEv); 634 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType()); 635 636 // See if we can optimize just this store in isolation. 637 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { 638 Heads.insert(SL[i]); 639 continue; 640 } 641 642 Value *FirstSplatValue = nullptr; 643 Constant *FirstPatternValue = nullptr; 644 645 if (For == ForMemset::Yes) 646 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL); 647 else 648 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); 649 650 assert((FirstSplatValue || FirstPatternValue) && 651 "Expected either splat value or pattern value."); 652 653 IndexQueue.clear(); 654 // If a store has multiple consecutive store candidates, search Stores 655 // array according to the sequence: from i+1 to e, then from i-1 to 0. 656 // This is because usually pairing with immediate succeeding or preceding 657 // candidate create the best chance to find memset opportunity. 658 unsigned j = 0; 659 for (j = i + 1; j < e; ++j) 660 IndexQueue.push_back(j); 661 for (j = i; j > 0; --j) 662 IndexQueue.push_back(j - 1); 663 664 for (auto &k : IndexQueue) { 665 assert(SL[k]->isSimple() && "Expected only non-volatile stores."); 666 Value *SecondStorePtr = SL[k]->getPointerOperand(); 667 const SCEVAddRecExpr *SecondStoreEv = 668 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); 669 APInt SecondStride = getStoreStride(SecondStoreEv); 670 671 if (FirstStride != SecondStride) 672 continue; 673 674 Value *SecondStoredVal = SL[k]->getValueOperand(); 675 Value *SecondSplatValue = nullptr; 676 Constant *SecondPatternValue = nullptr; 677 678 if (For == ForMemset::Yes) 679 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL); 680 else 681 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); 682 683 assert((SecondSplatValue || SecondPatternValue) && 684 "Expected either splat value or pattern value."); 685 686 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { 687 if (For == ForMemset::Yes) { 688 if (isa<UndefValue>(FirstSplatValue)) 689 FirstSplatValue = SecondSplatValue; 690 if (FirstSplatValue != SecondSplatValue) 691 continue; 692 } else { 693 if (isa<UndefValue>(FirstPatternValue)) 694 FirstPatternValue = SecondPatternValue; 695 if (FirstPatternValue != SecondPatternValue) 696 continue; 697 } 698 Tails.insert(SL[k]); 699 Heads.insert(SL[i]); 700 ConsecutiveChain[SL[i]] = SL[k]; 701 break; 702 } 703 } 704 } 705 706 // We may run into multiple chains that merge into a single chain. We mark the 707 // stores that we transformed so that we don't visit the same store twice. 708 SmallPtrSet<Value *, 16> TransformedStores; 709 bool Changed = false; 710 711 // For stores that start but don't end a link in the chain: 712 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); 713 it != e; ++it) { 714 if (Tails.count(*it)) 715 continue; 716 717 // We found a store instr that starts a chain. Now follow the chain and try 718 // to transform it. 719 SmallPtrSet<Instruction *, 8> AdjacentStores; 720 StoreInst *I = *it; 721 722 StoreInst *HeadStore = I; 723 unsigned StoreSize = 0; 724 725 // Collect the chain into a list. 726 while (Tails.count(I) || Heads.count(I)) { 727 if (TransformedStores.count(I)) 728 break; 729 AdjacentStores.insert(I); 730 731 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType()); 732 // Move to the next value in the chain. 733 I = ConsecutiveChain[I]; 734 } 735 736 Value *StoredVal = HeadStore->getValueOperand(); 737 Value *StorePtr = HeadStore->getPointerOperand(); 738 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 739 APInt Stride = getStoreStride(StoreEv); 740 741 // Check to see if the stride matches the size of the stores. If so, then 742 // we know that every byte is touched in the loop. 743 if (StoreSize != Stride && StoreSize != -Stride) 744 continue; 745 746 bool NegStride = StoreSize == -Stride; 747 748 if (processLoopStridedStore(StorePtr, StoreSize, 749 MaybeAlign(HeadStore->getAlignment()), 750 StoredVal, HeadStore, AdjacentStores, StoreEv, 751 BECount, NegStride)) { 752 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); 753 Changed = true; 754 } 755 } 756 757 return Changed; 758 } 759 760 /// processLoopMemSet - See if this memset can be promoted to a large memset. 761 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, 762 const SCEV *BECount) { 763 // We can only handle non-volatile memsets with a constant size. 764 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) 765 return false; 766 767 // If we're not allowed to hack on memset, we fail. 768 if (!HasMemset) 769 return false; 770 771 Value *Pointer = MSI->getDest(); 772 773 // See if the pointer expression is an AddRec like {base,+,1} on the current 774 // loop, which indicates a strided store. If we have something else, it's a 775 // random store we can't handle. 776 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); 777 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) 778 return false; 779 780 // Reject memsets that are so large that they overflow an unsigned. 781 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 782 if ((SizeInBytes >> 32) != 0) 783 return false; 784 785 // Check to see if the stride matches the size of the memset. If so, then we 786 // know that every byte is touched in the loop. 787 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); 788 if (!ConstStride) 789 return false; 790 791 APInt Stride = ConstStride->getAPInt(); 792 if (SizeInBytes != Stride && SizeInBytes != -Stride) 793 return false; 794 795 // Verify that the memset value is loop invariant. If not, we can't promote 796 // the memset. 797 Value *SplatValue = MSI->getValue(); 798 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) 799 return false; 800 801 SmallPtrSet<Instruction *, 1> MSIs; 802 MSIs.insert(MSI); 803 bool NegStride = SizeInBytes == -Stride; 804 return processLoopStridedStore( 805 Pointer, (unsigned)SizeInBytes, MaybeAlign(MSI->getDestAlignment()), 806 SplatValue, MSI, MSIs, Ev, BECount, NegStride, /*IsLoopMemset=*/true); 807 } 808 809 /// mayLoopAccessLocation - Return true if the specified loop might access the 810 /// specified pointer location, which is a loop-strided access. The 'Access' 811 /// argument specifies what the verboten forms of access are (read or write). 812 static bool 813 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, 814 const SCEV *BECount, unsigned StoreSize, 815 AliasAnalysis &AA, 816 SmallPtrSetImpl<Instruction *> &IgnoredStores) { 817 // Get the location that may be stored across the loop. Since the access is 818 // strided positively through memory, we say that the modified location starts 819 // at the pointer and has infinite size. 820 LocationSize AccessSize = LocationSize::unknown(); 821 822 // If the loop iterates a fixed number of times, we can refine the access size 823 // to be exactly the size of the memset, which is (BECount+1)*StoreSize 824 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 825 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) * 826 StoreSize); 827 828 // TODO: For this to be really effective, we have to dive into the pointer 829 // operand in the store. Store to &A[i] of 100 will always return may alias 830 // with store of &A[100], we need to StoreLoc to be "A" with size of 100, 831 // which will then no-alias a store to &A[100]. 832 MemoryLocation StoreLoc(Ptr, AccessSize); 833 834 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; 835 ++BI) 836 for (Instruction &I : **BI) 837 if (IgnoredStores.count(&I) == 0 && 838 isModOrRefSet( 839 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access))) 840 return true; 841 842 return false; 843 } 844 845 // If we have a negative stride, Start refers to the end of the memory location 846 // we're trying to memset. Therefore, we need to recompute the base pointer, 847 // which is just Start - BECount*Size. 848 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, 849 Type *IntPtr, unsigned StoreSize, 850 ScalarEvolution *SE) { 851 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); 852 if (StoreSize != 1) 853 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), 854 SCEV::FlagNUW); 855 return SE->getMinusSCEV(Start, Index); 856 } 857 858 /// Compute the number of bytes as a SCEV from the backedge taken count. 859 /// 860 /// This also maps the SCEV into the provided type and tries to handle the 861 /// computation in a way that will fold cleanly. 862 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr, 863 unsigned StoreSize, Loop *CurLoop, 864 const DataLayout *DL, ScalarEvolution *SE) { 865 const SCEV *NumBytesS; 866 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to 867 // pointer size if it isn't already. 868 // 869 // If we're going to need to zero extend the BE count, check if we can add 870 // one to it prior to zero extending without overflow. Provided this is safe, 871 // it allows better simplification of the +1. 872 if (DL->getTypeSizeInBits(BECount->getType()) < 873 DL->getTypeSizeInBits(IntPtr) && 874 SE->isLoopEntryGuardedByCond( 875 CurLoop, ICmpInst::ICMP_NE, BECount, 876 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) { 877 NumBytesS = SE->getZeroExtendExpr( 878 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW), 879 IntPtr); 880 } else { 881 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr), 882 SE->getOne(IntPtr), SCEV::FlagNUW); 883 } 884 885 // And scale it based on the store size. 886 if (StoreSize != 1) { 887 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), 888 SCEV::FlagNUW); 889 } 890 return NumBytesS; 891 } 892 893 /// processLoopStridedStore - We see a strided store of some value. If we can 894 /// transform this into a memset or memset_pattern in the loop preheader, do so. 895 bool LoopIdiomRecognize::processLoopStridedStore( 896 Value *DestPtr, unsigned StoreSize, MaybeAlign StoreAlignment, 897 Value *StoredVal, Instruction *TheStore, 898 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, 899 const SCEV *BECount, bool NegStride, bool IsLoopMemset) { 900 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 901 Constant *PatternValue = nullptr; 902 903 if (!SplatValue) 904 PatternValue = getMemSetPatternValue(StoredVal, DL); 905 906 assert((SplatValue || PatternValue) && 907 "Expected either splat value or pattern value."); 908 909 // The trip count of the loop and the base pointer of the addrec SCEV is 910 // guaranteed to be loop invariant, which means that it should dominate the 911 // header. This allows us to insert code for it in the preheader. 912 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); 913 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 914 IRBuilder<> Builder(Preheader->getTerminator()); 915 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 916 917 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); 918 Type *IntIdxTy = DL->getIndexType(DestPtr->getType()); 919 920 const SCEV *Start = Ev->getStart(); 921 // Handle negative strided loops. 922 if (NegStride) 923 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSize, SE); 924 925 // TODO: ideally we should still be able to generate memset if SCEV expander 926 // is taught to generate the dependencies at the latest point. 927 if (!isSafeToExpand(Start, *SE)) 928 return false; 929 930 // Okay, we have a strided store "p[i]" of a splattable value. We can turn 931 // this into a memset in the loop preheader now if we want. However, this 932 // would be unsafe to do if there is anything else in the loop that may read 933 // or write to the aliased location. Check for any overlap by generating the 934 // base pointer and checking the region. 935 Value *BasePtr = 936 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); 937 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount, 938 StoreSize, *AA, Stores)) { 939 Expander.clear(); 940 // If we generated new code for the base pointer, clean up. 941 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); 942 return false; 943 } 944 945 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset)) 946 return false; 947 948 // Okay, everything looks good, insert the memset. 949 950 const SCEV *NumBytesS = 951 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE); 952 953 // TODO: ideally we should still be able to generate memset if SCEV expander 954 // is taught to generate the dependencies at the latest point. 955 if (!isSafeToExpand(NumBytesS, *SE)) 956 return false; 957 958 Value *NumBytes = 959 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 960 961 CallInst *NewCall; 962 if (SplatValue) { 963 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, 964 MaybeAlign(StoreAlignment)); 965 } else { 966 // Everything is emitted in default address space 967 Type *Int8PtrTy = DestInt8PtrTy; 968 969 Module *M = TheStore->getModule(); 970 StringRef FuncName = "memset_pattern16"; 971 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(), 972 Int8PtrTy, Int8PtrTy, IntIdxTy); 973 inferLibFuncAttributes(M, FuncName, *TLI); 974 975 // Otherwise we should form a memset_pattern16. PatternValue is known to be 976 // an constant array of 16-bytes. Plop the value into a mergable global. 977 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, 978 GlobalValue::PrivateLinkage, 979 PatternValue, ".memset_pattern"); 980 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. 981 GV->setAlignment(Align(16)); 982 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); 983 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); 984 } 985 NewCall->setDebugLoc(TheStore->getDebugLoc()); 986 987 if (MSSAU) { 988 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 989 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 990 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 991 } 992 993 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" 994 << " from store to: " << *Ev << " at: " << *TheStore 995 << "\n"); 996 997 ORE.emit([&]() { 998 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStridedStore", 999 NewCall->getDebugLoc(), Preheader) 1000 << "Transformed loop-strided store into a call to " 1001 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1002 << "() function"; 1003 }); 1004 1005 // Okay, the memset has been formed. Zap the original store and anything that 1006 // feeds into it. 1007 for (auto *I : Stores) { 1008 if (MSSAU) 1009 MSSAU->removeMemoryAccess(I, true); 1010 deleteDeadInstruction(I); 1011 } 1012 if (MSSAU && VerifyMemorySSA) 1013 MSSAU->getMemorySSA()->verifyMemorySSA(); 1014 ++NumMemSet; 1015 return true; 1016 } 1017 1018 /// If the stored value is a strided load in the same loop with the same stride 1019 /// this may be transformable into a memcpy. This kicks in for stuff like 1020 /// for (i) A[i] = B[i]; 1021 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, 1022 const SCEV *BECount) { 1023 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores."); 1024 1025 Value *StorePtr = SI->getPointerOperand(); 1026 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 1027 APInt Stride = getStoreStride(StoreEv); 1028 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 1029 bool NegStride = StoreSize == -Stride; 1030 1031 // The store must be feeding a non-volatile load. 1032 LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); 1033 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads."); 1034 1035 // See if the pointer expression is an AddRec like {base,+,1} on the current 1036 // loop, which indicates a strided load. If we have something else, it's a 1037 // random load we can't handle. 1038 const SCEVAddRecExpr *LoadEv = 1039 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 1040 1041 // The trip count of the loop and the base pointer of the addrec SCEV is 1042 // guaranteed to be loop invariant, which means that it should dominate the 1043 // header. This allows us to insert code for it in the preheader. 1044 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1045 IRBuilder<> Builder(Preheader->getTerminator()); 1046 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 1047 1048 const SCEV *StrStart = StoreEv->getStart(); 1049 unsigned StrAS = SI->getPointerAddressSpace(); 1050 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS)); 1051 1052 // Handle negative strided loops. 1053 if (NegStride) 1054 StrStart = getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSize, SE); 1055 1056 // Okay, we have a strided store "p[i]" of a loaded value. We can turn 1057 // this into a memcpy in the loop preheader now if we want. However, this 1058 // would be unsafe to do if there is anything else in the loop that may read 1059 // or write the memory region we're storing to. This includes the load that 1060 // feeds the stores. Check for an alias by generating the base address and 1061 // checking everything. 1062 Value *StoreBasePtr = Expander.expandCodeFor( 1063 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); 1064 1065 SmallPtrSet<Instruction *, 1> Stores; 1066 Stores.insert(SI); 1067 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount, 1068 StoreSize, *AA, Stores)) { 1069 Expander.clear(); 1070 // If we generated new code for the base pointer, clean up. 1071 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 1072 return false; 1073 } 1074 1075 const SCEV *LdStart = LoadEv->getStart(); 1076 unsigned LdAS = LI->getPointerAddressSpace(); 1077 1078 // Handle negative strided loops. 1079 if (NegStride) 1080 LdStart = getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSize, SE); 1081 1082 // For a memcpy, we have to make sure that the input array is not being 1083 // mutated by the loop. 1084 Value *LoadBasePtr = Expander.expandCodeFor( 1085 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); 1086 1087 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount, 1088 StoreSize, *AA, Stores)) { 1089 Expander.clear(); 1090 // If we generated new code for the base pointer, clean up. 1091 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); 1092 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 1093 return false; 1094 } 1095 1096 if (avoidLIRForMultiBlockLoop()) 1097 return false; 1098 1099 // Okay, everything is safe, we can transform this! 1100 1101 const SCEV *NumBytesS = 1102 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE); 1103 1104 Value *NumBytes = 1105 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 1106 1107 CallInst *NewCall = nullptr; 1108 // Check whether to generate an unordered atomic memcpy: 1109 // If the load or store are atomic, then they must necessarily be unordered 1110 // by previous checks. 1111 if (!SI->isAtomic() && !LI->isAtomic()) 1112 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlign(), LoadBasePtr, 1113 LI->getAlign(), NumBytes); 1114 else { 1115 // We cannot allow unaligned ops for unordered load/store, so reject 1116 // anything where the alignment isn't at least the element size. 1117 const MaybeAlign StoreAlign = SI->getAlign(); 1118 const MaybeAlign LoadAlign = LI->getAlign(); 1119 if (StoreAlign == None || LoadAlign == None) 1120 return false; 1121 if (*StoreAlign < StoreSize || *LoadAlign < StoreSize) 1122 return false; 1123 1124 // If the element.atomic memcpy is not lowered into explicit 1125 // loads/stores later, then it will be lowered into an element-size 1126 // specific lib call. If the lib call doesn't exist for our store size, then 1127 // we shouldn't generate the memcpy. 1128 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize()) 1129 return false; 1130 1131 // Create the call. 1132 // Note that unordered atomic loads/stores are *required* by the spec to 1133 // have an alignment but non-atomic loads/stores may not. 1134 NewCall = Builder.CreateElementUnorderedAtomicMemCpy( 1135 StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, 1136 StoreSize); 1137 } 1138 NewCall->setDebugLoc(SI->getDebugLoc()); 1139 1140 if (MSSAU) { 1141 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1142 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 1143 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1144 } 1145 1146 LLVM_DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" 1147 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" 1148 << " from store ptr=" << *StoreEv << " at: " << *SI 1149 << "\n"); 1150 1151 ORE.emit([&]() { 1152 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad", 1153 NewCall->getDebugLoc(), Preheader) 1154 << "Formed a call to " 1155 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1156 << "() function"; 1157 }); 1158 1159 // Okay, the memcpy has been formed. Zap the original store and anything that 1160 // feeds into it. 1161 if (MSSAU) 1162 MSSAU->removeMemoryAccess(SI, true); 1163 deleteDeadInstruction(SI); 1164 if (MSSAU && VerifyMemorySSA) 1165 MSSAU->getMemorySSA()->verifyMemorySSA(); 1166 ++NumMemCpy; 1167 return true; 1168 } 1169 1170 // When compiling for codesize we avoid idiom recognition for a multi-block loop 1171 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop. 1172 // 1173 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, 1174 bool IsLoopMemset) { 1175 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) { 1176 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) { 1177 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName() 1178 << " : LIR " << (IsMemset ? "Memset" : "Memcpy") 1179 << " avoided: multi-block top-level loop\n"); 1180 return true; 1181 } 1182 } 1183 1184 return false; 1185 } 1186 1187 bool LoopIdiomRecognize::runOnNoncountableLoop() { 1188 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 1189 << CurLoop->getHeader()->getParent()->getName() 1190 << "] Noncountable Loop %" 1191 << CurLoop->getHeader()->getName() << "\n"); 1192 1193 return recognizePopcount() || recognizeAndInsertFFS(); 1194 } 1195 1196 /// Check if the given conditional branch is based on the comparison between 1197 /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is 1198 /// true), the control yields to the loop entry. If the branch matches the 1199 /// behavior, the variable involved in the comparison is returned. This function 1200 /// will be called to see if the precondition and postcondition of the loop are 1201 /// in desirable form. 1202 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry, 1203 bool JmpOnZero = false) { 1204 if (!BI || !BI->isConditional()) 1205 return nullptr; 1206 1207 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 1208 if (!Cond) 1209 return nullptr; 1210 1211 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); 1212 if (!CmpZero || !CmpZero->isZero()) 1213 return nullptr; 1214 1215 BasicBlock *TrueSucc = BI->getSuccessor(0); 1216 BasicBlock *FalseSucc = BI->getSuccessor(1); 1217 if (JmpOnZero) 1218 std::swap(TrueSucc, FalseSucc); 1219 1220 ICmpInst::Predicate Pred = Cond->getPredicate(); 1221 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) || 1222 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry)) 1223 return Cond->getOperand(0); 1224 1225 return nullptr; 1226 } 1227 1228 // Check if the recurrence variable `VarX` is in the right form to create 1229 // the idiom. Returns the value coerced to a PHINode if so. 1230 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX, 1231 BasicBlock *LoopEntry) { 1232 auto *PhiX = dyn_cast<PHINode>(VarX); 1233 if (PhiX && PhiX->getParent() == LoopEntry && 1234 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX)) 1235 return PhiX; 1236 return nullptr; 1237 } 1238 1239 /// Return true iff the idiom is detected in the loop. 1240 /// 1241 /// Additionally: 1242 /// 1) \p CntInst is set to the instruction counting the population bit. 1243 /// 2) \p CntPhi is set to the corresponding phi node. 1244 /// 3) \p Var is set to the value whose population bits are being counted. 1245 /// 1246 /// The core idiom we are trying to detect is: 1247 /// \code 1248 /// if (x0 != 0) 1249 /// goto loop-exit // the precondition of the loop 1250 /// cnt0 = init-val; 1251 /// do { 1252 /// x1 = phi (x0, x2); 1253 /// cnt1 = phi(cnt0, cnt2); 1254 /// 1255 /// cnt2 = cnt1 + 1; 1256 /// ... 1257 /// x2 = x1 & (x1 - 1); 1258 /// ... 1259 /// } while(x != 0); 1260 /// 1261 /// loop-exit: 1262 /// \endcode 1263 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, 1264 Instruction *&CntInst, PHINode *&CntPhi, 1265 Value *&Var) { 1266 // step 1: Check to see if the look-back branch match this pattern: 1267 // "if (a!=0) goto loop-entry". 1268 BasicBlock *LoopEntry; 1269 Instruction *DefX2, *CountInst; 1270 Value *VarX1, *VarX0; 1271 PHINode *PhiX, *CountPhi; 1272 1273 DefX2 = CountInst = nullptr; 1274 VarX1 = VarX0 = nullptr; 1275 PhiX = CountPhi = nullptr; 1276 LoopEntry = *(CurLoop->block_begin()); 1277 1278 // step 1: Check if the loop-back branch is in desirable form. 1279 { 1280 if (Value *T = matchCondition( 1281 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1282 DefX2 = dyn_cast<Instruction>(T); 1283 else 1284 return false; 1285 } 1286 1287 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" 1288 { 1289 if (!DefX2 || DefX2->getOpcode() != Instruction::And) 1290 return false; 1291 1292 BinaryOperator *SubOneOp; 1293 1294 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) 1295 VarX1 = DefX2->getOperand(1); 1296 else { 1297 VarX1 = DefX2->getOperand(0); 1298 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); 1299 } 1300 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1) 1301 return false; 1302 1303 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1)); 1304 if (!Dec || 1305 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) || 1306 (SubOneOp->getOpcode() == Instruction::Add && 1307 Dec->isMinusOne()))) { 1308 return false; 1309 } 1310 } 1311 1312 // step 3: Check the recurrence of variable X 1313 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry); 1314 if (!PhiX) 1315 return false; 1316 1317 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 1318 { 1319 CountInst = nullptr; 1320 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1321 IterE = LoopEntry->end(); 1322 Iter != IterE; Iter++) { 1323 Instruction *Inst = &*Iter; 1324 if (Inst->getOpcode() != Instruction::Add) 1325 continue; 1326 1327 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1328 if (!Inc || !Inc->isOne()) 1329 continue; 1330 1331 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1332 if (!Phi) 1333 continue; 1334 1335 // Check if the result of the instruction is live of the loop. 1336 bool LiveOutLoop = false; 1337 for (User *U : Inst->users()) { 1338 if ((cast<Instruction>(U))->getParent() != LoopEntry) { 1339 LiveOutLoop = true; 1340 break; 1341 } 1342 } 1343 1344 if (LiveOutLoop) { 1345 CountInst = Inst; 1346 CountPhi = Phi; 1347 break; 1348 } 1349 } 1350 1351 if (!CountInst) 1352 return false; 1353 } 1354 1355 // step 5: check if the precondition is in this form: 1356 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" 1357 { 1358 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1359 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); 1360 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) 1361 return false; 1362 1363 CntInst = CountInst; 1364 CntPhi = CountPhi; 1365 Var = T; 1366 } 1367 1368 return true; 1369 } 1370 1371 /// Return true if the idiom is detected in the loop. 1372 /// 1373 /// Additionally: 1374 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ) 1375 /// or nullptr if there is no such. 1376 /// 2) \p CntPhi is set to the corresponding phi node 1377 /// or nullptr if there is no such. 1378 /// 3) \p Var is set to the value whose CTLZ could be used. 1379 /// 4) \p DefX is set to the instruction calculating Loop exit condition. 1380 /// 1381 /// The core idiom we are trying to detect is: 1382 /// \code 1383 /// if (x0 == 0) 1384 /// goto loop-exit // the precondition of the loop 1385 /// cnt0 = init-val; 1386 /// do { 1387 /// x = phi (x0, x.next); //PhiX 1388 /// cnt = phi(cnt0, cnt.next); 1389 /// 1390 /// cnt.next = cnt + 1; 1391 /// ... 1392 /// x.next = x >> 1; // DefX 1393 /// ... 1394 /// } while(x.next != 0); 1395 /// 1396 /// loop-exit: 1397 /// \endcode 1398 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, 1399 Intrinsic::ID &IntrinID, Value *&InitX, 1400 Instruction *&CntInst, PHINode *&CntPhi, 1401 Instruction *&DefX) { 1402 BasicBlock *LoopEntry; 1403 Value *VarX = nullptr; 1404 1405 DefX = nullptr; 1406 CntInst = nullptr; 1407 CntPhi = nullptr; 1408 LoopEntry = *(CurLoop->block_begin()); 1409 1410 // step 1: Check if the loop-back branch is in desirable form. 1411 if (Value *T = matchCondition( 1412 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1413 DefX = dyn_cast<Instruction>(T); 1414 else 1415 return false; 1416 1417 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1" 1418 if (!DefX || !DefX->isShift()) 1419 return false; 1420 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz : 1421 Intrinsic::ctlz; 1422 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)); 1423 if (!Shft || !Shft->isOne()) 1424 return false; 1425 VarX = DefX->getOperand(0); 1426 1427 // step 3: Check the recurrence of variable X 1428 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry); 1429 if (!PhiX) 1430 return false; 1431 1432 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader()); 1433 1434 // Make sure the initial value can't be negative otherwise the ashr in the 1435 // loop might never reach zero which would make the loop infinite. 1436 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL)) 1437 return false; 1438 1439 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1 1440 // TODO: We can skip the step. If loop trip count is known (CTLZ), 1441 // then all uses of "cnt.next" could be optimized to the trip count 1442 // plus "cnt0". Currently it is not optimized. 1443 // This step could be used to detect POPCNT instruction: 1444 // cnt.next = cnt + (x.next & 1) 1445 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1446 IterE = LoopEntry->end(); 1447 Iter != IterE; Iter++) { 1448 Instruction *Inst = &*Iter; 1449 if (Inst->getOpcode() != Instruction::Add) 1450 continue; 1451 1452 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1453 if (!Inc || !Inc->isOne()) 1454 continue; 1455 1456 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1457 if (!Phi) 1458 continue; 1459 1460 CntInst = Inst; 1461 CntPhi = Phi; 1462 break; 1463 } 1464 if (!CntInst) 1465 return false; 1466 1467 return true; 1468 } 1469 1470 /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop 1471 /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new 1472 /// trip count returns true; otherwise, returns false. 1473 bool LoopIdiomRecognize::recognizeAndInsertFFS() { 1474 // Give up if the loop has multiple blocks or multiple backedges. 1475 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1476 return false; 1477 1478 Intrinsic::ID IntrinID; 1479 Value *InitX; 1480 Instruction *DefX = nullptr; 1481 PHINode *CntPhi = nullptr; 1482 Instruction *CntInst = nullptr; 1483 // Help decide if transformation is profitable. For ShiftUntilZero idiom, 1484 // this is always 6. 1485 size_t IdiomCanonicalSize = 6; 1486 1487 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, 1488 CntInst, CntPhi, DefX)) 1489 return false; 1490 1491 bool IsCntPhiUsedOutsideLoop = false; 1492 for (User *U : CntPhi->users()) 1493 if (!CurLoop->contains(cast<Instruction>(U))) { 1494 IsCntPhiUsedOutsideLoop = true; 1495 break; 1496 } 1497 bool IsCntInstUsedOutsideLoop = false; 1498 for (User *U : CntInst->users()) 1499 if (!CurLoop->contains(cast<Instruction>(U))) { 1500 IsCntInstUsedOutsideLoop = true; 1501 break; 1502 } 1503 // If both CntInst and CntPhi are used outside the loop the profitability 1504 // is questionable. 1505 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop) 1506 return false; 1507 1508 // For some CPUs result of CTLZ(X) intrinsic is undefined 1509 // when X is 0. If we can not guarantee X != 0, we need to check this 1510 // when expand. 1511 bool ZeroCheck = false; 1512 // It is safe to assume Preheader exist as it was checked in 1513 // parent function RunOnLoop. 1514 BasicBlock *PH = CurLoop->getLoopPreheader(); 1515 1516 // If we are using the count instruction outside the loop, make sure we 1517 // have a zero check as a precondition. Without the check the loop would run 1518 // one iteration for before any check of the input value. This means 0 and 1 1519 // would have identical behavior in the original loop and thus 1520 if (!IsCntPhiUsedOutsideLoop) { 1521 auto *PreCondBB = PH->getSinglePredecessor(); 1522 if (!PreCondBB) 1523 return false; 1524 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1525 if (!PreCondBI) 1526 return false; 1527 if (matchCondition(PreCondBI, PH) != InitX) 1528 return false; 1529 ZeroCheck = true; 1530 } 1531 1532 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always 1533 // profitable if we delete the loop. 1534 1535 // the loop has only 6 instructions: 1536 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ] 1537 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ] 1538 // %shr = ashr %n.addr.0, 1 1539 // %tobool = icmp eq %shr, 0 1540 // %inc = add nsw %i.0, 1 1541 // br i1 %tobool 1542 1543 const Value *Args[] = 1544 {InitX, ZeroCheck ? ConstantInt::getTrue(InitX->getContext()) 1545 : ConstantInt::getFalse(InitX->getContext())}; 1546 1547 // @llvm.dbg doesn't count as they have no semantic effect. 1548 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug(); 1549 uint32_t HeaderSize = 1550 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end()); 1551 1552 if (HeaderSize != IdiomCanonicalSize && 1553 TTI->getIntrinsicCost(IntrinID, InitX->getType(), Args) > 1554 TargetTransformInfo::TCC_Basic) 1555 return false; 1556 1557 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX, 1558 DefX->getDebugLoc(), ZeroCheck, 1559 IsCntPhiUsedOutsideLoop); 1560 return true; 1561 } 1562 1563 /// Recognizes a population count idiom in a non-countable loop. 1564 /// 1565 /// If detected, transforms the relevant code to issue the popcount intrinsic 1566 /// function call, and returns true; otherwise, returns false. 1567 bool LoopIdiomRecognize::recognizePopcount() { 1568 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) 1569 return false; 1570 1571 // Counting population are usually conducted by few arithmetic instructions. 1572 // Such instructions can be easily "absorbed" by vacant slots in a 1573 // non-compact loop. Therefore, recognizing popcount idiom only makes sense 1574 // in a compact loop. 1575 1576 // Give up if the loop has multiple blocks or multiple backedges. 1577 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1578 return false; 1579 1580 BasicBlock *LoopBody = *(CurLoop->block_begin()); 1581 if (LoopBody->size() >= 20) { 1582 // The loop is too big, bail out. 1583 return false; 1584 } 1585 1586 // It should have a preheader containing nothing but an unconditional branch. 1587 BasicBlock *PH = CurLoop->getLoopPreheader(); 1588 if (!PH || &PH->front() != PH->getTerminator()) 1589 return false; 1590 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); 1591 if (!EntryBI || EntryBI->isConditional()) 1592 return false; 1593 1594 // It should have a precondition block where the generated popcount intrinsic 1595 // function can be inserted. 1596 auto *PreCondBB = PH->getSinglePredecessor(); 1597 if (!PreCondBB) 1598 return false; 1599 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1600 if (!PreCondBI || PreCondBI->isUnconditional()) 1601 return false; 1602 1603 Instruction *CntInst; 1604 PHINode *CntPhi; 1605 Value *Val; 1606 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) 1607 return false; 1608 1609 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); 1610 return true; 1611 } 1612 1613 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1614 const DebugLoc &DL) { 1615 Value *Ops[] = {Val}; 1616 Type *Tys[] = {Val->getType()}; 1617 1618 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1619 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); 1620 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1621 CI->setDebugLoc(DL); 1622 1623 return CI; 1624 } 1625 1626 static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1627 const DebugLoc &DL, bool ZeroCheck, 1628 Intrinsic::ID IID) { 1629 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()}; 1630 Type *Tys[] = {Val->getType()}; 1631 1632 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1633 Function *Func = Intrinsic::getDeclaration(M, IID, Tys); 1634 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1635 CI->setDebugLoc(DL); 1636 1637 return CI; 1638 } 1639 1640 /// Transform the following loop (Using CTLZ, CTTZ is similar): 1641 /// loop: 1642 /// CntPhi = PHI [Cnt0, CntInst] 1643 /// PhiX = PHI [InitX, DefX] 1644 /// CntInst = CntPhi + 1 1645 /// DefX = PhiX >> 1 1646 /// LOOP_BODY 1647 /// Br: loop if (DefX != 0) 1648 /// Use(CntPhi) or Use(CntInst) 1649 /// 1650 /// Into: 1651 /// If CntPhi used outside the loop: 1652 /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1) 1653 /// Count = CountPrev + 1 1654 /// else 1655 /// Count = BitWidth(InitX) - CTLZ(InitX) 1656 /// loop: 1657 /// CntPhi = PHI [Cnt0, CntInst] 1658 /// PhiX = PHI [InitX, DefX] 1659 /// PhiCount = PHI [Count, Dec] 1660 /// CntInst = CntPhi + 1 1661 /// DefX = PhiX >> 1 1662 /// Dec = PhiCount - 1 1663 /// LOOP_BODY 1664 /// Br: loop if (Dec != 0) 1665 /// Use(CountPrev + Cnt0) // Use(CntPhi) 1666 /// or 1667 /// Use(Count + Cnt0) // Use(CntInst) 1668 /// 1669 /// If LOOP_BODY is empty the loop will be deleted. 1670 /// If CntInst and DefX are not used in LOOP_BODY they will be removed. 1671 void LoopIdiomRecognize::transformLoopToCountable( 1672 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst, 1673 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL, 1674 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) { 1675 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator()); 1676 1677 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block 1678 IRBuilder<> Builder(PreheaderBr); 1679 Builder.SetCurrentDebugLocation(DL); 1680 Value *FFS, *Count, *CountPrev, *NewCount, *InitXNext; 1681 1682 // Count = BitWidth - CTLZ(InitX); 1683 // If there are uses of CntPhi create: 1684 // CountPrev = BitWidth - CTLZ(InitX >> 1); 1685 if (IsCntPhiUsedOutsideLoop) { 1686 if (DefX->getOpcode() == Instruction::AShr) 1687 InitXNext = 1688 Builder.CreateAShr(InitX, ConstantInt::get(InitX->getType(), 1)); 1689 else if (DefX->getOpcode() == Instruction::LShr) 1690 InitXNext = 1691 Builder.CreateLShr(InitX, ConstantInt::get(InitX->getType(), 1)); 1692 else if (DefX->getOpcode() == Instruction::Shl) // cttz 1693 InitXNext = 1694 Builder.CreateShl(InitX, ConstantInt::get(InitX->getType(), 1)); 1695 else 1696 llvm_unreachable("Unexpected opcode!"); 1697 } else 1698 InitXNext = InitX; 1699 FFS = createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID); 1700 Count = Builder.CreateSub( 1701 ConstantInt::get(FFS->getType(), 1702 FFS->getType()->getIntegerBitWidth()), 1703 FFS); 1704 if (IsCntPhiUsedOutsideLoop) { 1705 CountPrev = Count; 1706 Count = Builder.CreateAdd( 1707 CountPrev, 1708 ConstantInt::get(CountPrev->getType(), 1)); 1709 } 1710 1711 NewCount = Builder.CreateZExtOrTrunc( 1712 IsCntPhiUsedOutsideLoop ? CountPrev : Count, 1713 cast<IntegerType>(CntInst->getType())); 1714 1715 // If the counter's initial value is not zero, insert Add Inst. 1716 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader); 1717 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 1718 if (!InitConst || !InitConst->isZero()) 1719 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 1720 1721 // Step 2: Insert new IV and loop condition: 1722 // loop: 1723 // ... 1724 // PhiCount = PHI [Count, Dec] 1725 // ... 1726 // Dec = PhiCount - 1 1727 // ... 1728 // Br: loop if (Dec != 0) 1729 BasicBlock *Body = *(CurLoop->block_begin()); 1730 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 1731 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 1732 Type *Ty = Count->getType(); 1733 1734 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 1735 1736 Builder.SetInsertPoint(LbCond); 1737 Instruction *TcDec = cast<Instruction>( 1738 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 1739 "tcdec", false, true)); 1740 1741 TcPhi->addIncoming(Count, Preheader); 1742 TcPhi->addIncoming(TcDec, Body); 1743 1744 CmpInst::Predicate Pred = 1745 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; 1746 LbCond->setPredicate(Pred); 1747 LbCond->setOperand(0, TcDec); 1748 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 1749 1750 // Step 3: All the references to the original counter outside 1751 // the loop are replaced with the NewCount 1752 if (IsCntPhiUsedOutsideLoop) 1753 CntPhi->replaceUsesOutsideBlock(NewCount, Body); 1754 else 1755 CntInst->replaceUsesOutsideBlock(NewCount, Body); 1756 1757 // step 4: Forget the "non-computable" trip-count SCEV associated with the 1758 // loop. The loop would otherwise not be deleted even if it becomes empty. 1759 SE->forgetLoop(CurLoop); 1760 } 1761 1762 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, 1763 Instruction *CntInst, 1764 PHINode *CntPhi, Value *Var) { 1765 BasicBlock *PreHead = CurLoop->getLoopPreheader(); 1766 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator()); 1767 const DebugLoc &DL = CntInst->getDebugLoc(); 1768 1769 // Assuming before transformation, the loop is following: 1770 // if (x) // the precondition 1771 // do { cnt++; x &= x - 1; } while(x); 1772 1773 // Step 1: Insert the ctpop instruction at the end of the precondition block 1774 IRBuilder<> Builder(PreCondBr); 1775 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; 1776 { 1777 PopCnt = createPopcntIntrinsic(Builder, Var, DL); 1778 NewCount = PopCntZext = 1779 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); 1780 1781 if (NewCount != PopCnt) 1782 (cast<Instruction>(NewCount))->setDebugLoc(DL); 1783 1784 // TripCnt is exactly the number of iterations the loop has 1785 TripCnt = NewCount; 1786 1787 // If the population counter's initial value is not zero, insert Add Inst. 1788 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); 1789 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 1790 if (!InitConst || !InitConst->isZero()) { 1791 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 1792 (cast<Instruction>(NewCount))->setDebugLoc(DL); 1793 } 1794 } 1795 1796 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to 1797 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic 1798 // function would be partial dead code, and downstream passes will drag 1799 // it back from the precondition block to the preheader. 1800 { 1801 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); 1802 1803 Value *Opnd0 = PopCntZext; 1804 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); 1805 if (PreCond->getOperand(0) != Var) 1806 std::swap(Opnd0, Opnd1); 1807 1808 ICmpInst *NewPreCond = cast<ICmpInst>( 1809 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); 1810 PreCondBr->setCondition(NewPreCond); 1811 1812 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); 1813 } 1814 1815 // Step 3: Note that the population count is exactly the trip count of the 1816 // loop in question, which enable us to convert the loop from noncountable 1817 // loop into a countable one. The benefit is twofold: 1818 // 1819 // - If the loop only counts population, the entire loop becomes dead after 1820 // the transformation. It is a lot easier to prove a countable loop dead 1821 // than to prove a noncountable one. (In some C dialects, an infinite loop 1822 // isn't dead even if it computes nothing useful. In general, DCE needs 1823 // to prove a noncountable loop finite before safely delete it.) 1824 // 1825 // - If the loop also performs something else, it remains alive. 1826 // Since it is transformed to countable form, it can be aggressively 1827 // optimized by some optimizations which are in general not applicable 1828 // to a noncountable loop. 1829 // 1830 // After this step, this loop (conceptually) would look like following: 1831 // newcnt = __builtin_ctpop(x); 1832 // t = newcnt; 1833 // if (x) 1834 // do { cnt++; x &= x-1; t--) } while (t > 0); 1835 BasicBlock *Body = *(CurLoop->block_begin()); 1836 { 1837 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 1838 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 1839 Type *Ty = TripCnt->getType(); 1840 1841 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 1842 1843 Builder.SetInsertPoint(LbCond); 1844 Instruction *TcDec = cast<Instruction>( 1845 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 1846 "tcdec", false, true)); 1847 1848 TcPhi->addIncoming(TripCnt, PreHead); 1849 TcPhi->addIncoming(TcDec, Body); 1850 1851 CmpInst::Predicate Pred = 1852 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; 1853 LbCond->setPredicate(Pred); 1854 LbCond->setOperand(0, TcDec); 1855 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 1856 } 1857 1858 // Step 4: All the references to the original population counter outside 1859 // the loop are replaced with the NewCount -- the value returned from 1860 // __builtin_ctpop(). 1861 CntInst->replaceUsesOutsideBlock(NewCount, Body); 1862 1863 // step 5: Forget the "non-computable" trip-count SCEV associated with the 1864 // loop. The loop would otherwise not be deleted even if it becomes empty. 1865 SE->forgetLoop(CurLoop); 1866 } 1867