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, 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/CmpInstAnalysis.h" 51 #include "llvm/Analysis/LoopAccessAnalysis.h" 52 #include "llvm/Analysis/LoopInfo.h" 53 #include "llvm/Analysis/LoopPass.h" 54 #include "llvm/Analysis/MemoryLocation.h" 55 #include "llvm/Analysis/MemorySSA.h" 56 #include "llvm/Analysis/MemorySSAUpdater.h" 57 #include "llvm/Analysis/MustExecute.h" 58 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 59 #include "llvm/Analysis/ScalarEvolution.h" 60 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 61 #include "llvm/Analysis/TargetLibraryInfo.h" 62 #include "llvm/Analysis/TargetTransformInfo.h" 63 #include "llvm/Analysis/ValueTracking.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/BasicBlock.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Dominators.h" 72 #include "llvm/IR/GlobalValue.h" 73 #include "llvm/IR/GlobalVariable.h" 74 #include "llvm/IR/IRBuilder.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instruction.h" 77 #include "llvm/IR/Instructions.h" 78 #include "llvm/IR/IntrinsicInst.h" 79 #include "llvm/IR/Intrinsics.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/PassManager.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Type.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/IR/ValueHandle.h" 88 #include "llvm/InitializePasses.h" 89 #include "llvm/Pass.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Debug.h" 93 #include "llvm/Support/InstructionCost.h" 94 #include "llvm/Support/raw_ostream.h" 95 #include "llvm/Transforms/Scalar.h" 96 #include "llvm/Transforms/Utils/BuildLibCalls.h" 97 #include "llvm/Transforms/Utils/Local.h" 98 #include "llvm/Transforms/Utils/LoopUtils.h" 99 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 100 #include <algorithm> 101 #include <cassert> 102 #include <cstdint> 103 #include <utility> 104 #include <vector> 105 106 using namespace llvm; 107 108 #define DEBUG_TYPE "loop-idiom" 109 110 STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); 111 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); 112 STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores"); 113 STATISTIC( 114 NumShiftUntilBitTest, 115 "Number of uncountable loops recognized as 'shift until bitttest' idiom"); 116 STATISTIC(NumShiftUntilZero, 117 "Number of uncountable loops recognized as 'shift until zero' idiom"); 118 119 bool DisableLIRP::All; 120 static cl::opt<bool, true> 121 DisableLIRPAll("disable-" DEBUG_TYPE "-all", 122 cl::desc("Options to disable Loop Idiom Recognize Pass."), 123 cl::location(DisableLIRP::All), cl::init(false), 124 cl::ReallyHidden); 125 126 bool DisableLIRP::Memset; 127 static cl::opt<bool, true> 128 DisableLIRPMemset("disable-" DEBUG_TYPE "-memset", 129 cl::desc("Proceed with loop idiom recognize pass, but do " 130 "not convert loop(s) to memset."), 131 cl::location(DisableLIRP::Memset), cl::init(false), 132 cl::ReallyHidden); 133 134 bool DisableLIRP::Memcpy; 135 static cl::opt<bool, true> 136 DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy", 137 cl::desc("Proceed with loop idiom recognize pass, but do " 138 "not convert loop(s) to memcpy."), 139 cl::location(DisableLIRP::Memcpy), cl::init(false), 140 cl::ReallyHidden); 141 142 static cl::opt<bool> UseLIRCodeSizeHeurs( 143 "use-lir-code-size-heurs", 144 cl::desc("Use loop idiom recognition code size heuristics when compiling" 145 "with -Os/-Oz"), 146 cl::init(true), cl::Hidden); 147 148 namespace { 149 150 class LoopIdiomRecognize { 151 Loop *CurLoop = nullptr; 152 AliasAnalysis *AA; 153 DominatorTree *DT; 154 LoopInfo *LI; 155 ScalarEvolution *SE; 156 TargetLibraryInfo *TLI; 157 const TargetTransformInfo *TTI; 158 const DataLayout *DL; 159 OptimizationRemarkEmitter &ORE; 160 bool ApplyCodeSizeHeuristics; 161 std::unique_ptr<MemorySSAUpdater> MSSAU; 162 163 public: 164 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, 165 LoopInfo *LI, ScalarEvolution *SE, 166 TargetLibraryInfo *TLI, 167 const TargetTransformInfo *TTI, MemorySSA *MSSA, 168 const DataLayout *DL, 169 OptimizationRemarkEmitter &ORE) 170 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) { 171 if (MSSA) 172 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 173 } 174 175 bool runOnLoop(Loop *L); 176 177 private: 178 using StoreList = SmallVector<StoreInst *, 8>; 179 using StoreListMap = MapVector<Value *, StoreList>; 180 181 StoreListMap StoreRefsForMemset; 182 StoreListMap StoreRefsForMemsetPattern; 183 StoreList StoreRefsForMemcpy; 184 bool HasMemset; 185 bool HasMemsetPattern; 186 bool HasMemcpy; 187 188 /// Return code for isLegalStore() 189 enum LegalStoreKind { 190 None = 0, 191 Memset, 192 MemsetPattern, 193 Memcpy, 194 UnorderedAtomicMemcpy, 195 DontUse // Dummy retval never to be used. Allows catching errors in retval 196 // handling. 197 }; 198 199 /// \name Countable Loop Idiom Handling 200 /// @{ 201 202 bool runOnCountableLoop(); 203 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, 204 SmallVectorImpl<BasicBlock *> &ExitBlocks); 205 206 void collectStores(BasicBlock *BB); 207 LegalStoreKind isLegalStore(StoreInst *SI); 208 enum class ForMemset { No, Yes }; 209 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, 210 ForMemset For); 211 212 template <typename MemInst> 213 bool processLoopMemIntrinsic( 214 BasicBlock *BB, 215 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *), 216 const SCEV *BECount); 217 bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount); 218 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); 219 220 bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV, 221 MaybeAlign StoreAlignment, Value *StoredVal, 222 Instruction *TheStore, 223 SmallPtrSetImpl<Instruction *> &Stores, 224 const SCEVAddRecExpr *Ev, const SCEV *BECount, 225 bool IsNegStride, bool IsLoopMemset = false); 226 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); 227 bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr, 228 unsigned StoreSize, MaybeAlign StoreAlign, 229 MaybeAlign LoadAlign, Instruction *TheStore, 230 Instruction *TheLoad, 231 const SCEVAddRecExpr *StoreEv, 232 const SCEVAddRecExpr *LoadEv, 233 const SCEV *BECount); 234 bool avoidLIRForMultiBlockLoop(bool IsMemset = false, 235 bool IsLoopMemset = false); 236 237 /// @} 238 /// \name Noncountable Loop Idiom Handling 239 /// @{ 240 241 bool runOnNoncountableLoop(); 242 243 bool recognizePopcount(); 244 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, 245 PHINode *CntPhi, Value *Var); 246 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz 247 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB, 248 Instruction *CntInst, PHINode *CntPhi, 249 Value *Var, Instruction *DefX, 250 const DebugLoc &DL, bool ZeroCheck, 251 bool IsCntPhiUsedOutsideLoop); 252 253 bool recognizeShiftUntilBitTest(); 254 bool recognizeShiftUntilZero(); 255 256 /// @} 257 }; 258 259 class LoopIdiomRecognizeLegacyPass : public LoopPass { 260 public: 261 static char ID; 262 263 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) { 264 initializeLoopIdiomRecognizeLegacyPassPass( 265 *PassRegistry::getPassRegistry()); 266 } 267 268 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 269 if (DisableLIRP::All) 270 return false; 271 272 if (skipLoop(L)) 273 return false; 274 275 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 276 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 277 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 278 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 279 TargetLibraryInfo *TLI = 280 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 281 *L->getHeader()->getParent()); 282 const TargetTransformInfo *TTI = 283 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 284 *L->getHeader()->getParent()); 285 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout(); 286 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 287 MemorySSA *MSSA = nullptr; 288 if (MSSAAnalysis) 289 MSSA = &MSSAAnalysis->getMSSA(); 290 291 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 292 // pass. Function analyses need to be preserved across loop transformations 293 // but ORE cannot be preserved (see comment before the pass definition). 294 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 295 296 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, MSSA, DL, ORE); 297 return LIR.runOnLoop(L); 298 } 299 300 /// This transformation requires natural loop information & requires that 301 /// loop preheaders be inserted into the CFG. 302 void getAnalysisUsage(AnalysisUsage &AU) const override { 303 AU.addRequired<TargetLibraryInfoWrapperPass>(); 304 AU.addRequired<TargetTransformInfoWrapperPass>(); 305 AU.addPreserved<MemorySSAWrapperPass>(); 306 getLoopAnalysisUsage(AU); 307 } 308 }; 309 310 } // end anonymous namespace 311 312 char LoopIdiomRecognizeLegacyPass::ID = 0; 313 314 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM, 315 LoopStandardAnalysisResults &AR, 316 LPMUpdater &) { 317 if (DisableLIRP::All) 318 return PreservedAnalyses::all(); 319 320 const auto *DL = &L.getHeader()->getModule()->getDataLayout(); 321 322 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis 323 // pass. Function analyses need to be preserved across loop transformations 324 // but ORE cannot be preserved (see comment before the pass definition). 325 OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 326 327 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, 328 AR.MSSA, DL, ORE); 329 if (!LIR.runOnLoop(&L)) 330 return PreservedAnalyses::all(); 331 332 auto PA = getLoopPassPreservedAnalyses(); 333 if (AR.MSSA) 334 PA.preserve<MemorySSAAnalysis>(); 335 return PA; 336 } 337 338 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", 339 "Recognize loop idioms", false, false) 340 INITIALIZE_PASS_DEPENDENCY(LoopPass) 341 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 342 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 343 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom", 344 "Recognize loop idioms", false, false) 345 346 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); } 347 348 static void deleteDeadInstruction(Instruction *I) { 349 I->replaceAllUsesWith(UndefValue::get(I->getType())); 350 I->eraseFromParent(); 351 } 352 353 //===----------------------------------------------------------------------===// 354 // 355 // Implementation of LoopIdiomRecognize 356 // 357 //===----------------------------------------------------------------------===// 358 359 bool LoopIdiomRecognize::runOnLoop(Loop *L) { 360 CurLoop = L; 361 // If the loop could not be converted to canonical form, it must have an 362 // indirectbr in it, just give up. 363 if (!L->getLoopPreheader()) 364 return false; 365 366 // Disable loop idiom recognition if the function's name is a common idiom. 367 StringRef Name = L->getHeader()->getParent()->getName(); 368 if (Name == "memset" || Name == "memcpy") 369 return false; 370 371 // Determine if code size heuristics need to be applied. 372 ApplyCodeSizeHeuristics = 373 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs; 374 375 HasMemset = TLI->has(LibFunc_memset); 376 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16); 377 HasMemcpy = TLI->has(LibFunc_memcpy); 378 379 if (HasMemset || HasMemsetPattern || HasMemcpy) 380 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 381 return runOnCountableLoop(); 382 383 return runOnNoncountableLoop(); 384 } 385 386 bool LoopIdiomRecognize::runOnCountableLoop() { 387 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); 388 assert(!isa<SCEVCouldNotCompute>(BECount) && 389 "runOnCountableLoop() called on a loop without a predictable" 390 "backedge-taken count"); 391 392 // If this loop executes exactly one time, then it should be peeled, not 393 // optimized by this pass. 394 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 395 if (BECst->getAPInt() == 0) 396 return false; 397 398 SmallVector<BasicBlock *, 8> ExitBlocks; 399 CurLoop->getUniqueExitBlocks(ExitBlocks); 400 401 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 402 << CurLoop->getHeader()->getParent()->getName() 403 << "] Countable Loop %" << CurLoop->getHeader()->getName() 404 << "\n"); 405 406 // The following transforms hoist stores/memsets into the loop pre-header. 407 // Give up if the loop has instructions that may throw. 408 SimpleLoopSafetyInfo SafetyInfo; 409 SafetyInfo.computeLoopSafetyInfo(CurLoop); 410 if (SafetyInfo.anyBlockMayThrow()) 411 return false; 412 413 bool MadeChange = false; 414 415 // Scan all the blocks in the loop that are not in subloops. 416 for (auto *BB : CurLoop->getBlocks()) { 417 // Ignore blocks in subloops. 418 if (LI->getLoopFor(BB) != CurLoop) 419 continue; 420 421 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); 422 } 423 return MadeChange; 424 } 425 426 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { 427 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); 428 return ConstStride->getAPInt(); 429 } 430 431 /// getMemSetPatternValue - If a strided store of the specified value is safe to 432 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should 433 /// be passed in. Otherwise, return null. 434 /// 435 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these 436 /// just replicate their input array and then pass on to memset_pattern16. 437 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { 438 // FIXME: This could check for UndefValue because it can be merged into any 439 // other valid pattern. 440 441 // If the value isn't a constant, we can't promote it to being in a constant 442 // array. We could theoretically do a store to an alloca or something, but 443 // that doesn't seem worthwhile. 444 Constant *C = dyn_cast<Constant>(V); 445 if (!C) 446 return nullptr; 447 448 // Only handle simple values that are a power of two bytes in size. 449 uint64_t Size = DL->getTypeSizeInBits(V->getType()); 450 if (Size == 0 || (Size & 7) || (Size & (Size - 1))) 451 return nullptr; 452 453 // Don't care enough about darwin/ppc to implement this. 454 if (DL->isBigEndian()) 455 return nullptr; 456 457 // Convert to size in bytes. 458 Size /= 8; 459 460 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see 461 // if the top and bottom are the same (e.g. for vectors and large integers). 462 if (Size > 16) 463 return nullptr; 464 465 // If the constant is exactly 16 bytes, just use it. 466 if (Size == 16) 467 return C; 468 469 // Otherwise, we'll use an array of the constants. 470 unsigned ArraySize = 16 / Size; 471 ArrayType *AT = ArrayType::get(V->getType(), ArraySize); 472 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); 473 } 474 475 LoopIdiomRecognize::LegalStoreKind 476 LoopIdiomRecognize::isLegalStore(StoreInst *SI) { 477 // Don't touch volatile stores. 478 if (SI->isVolatile()) 479 return LegalStoreKind::None; 480 // We only want simple or unordered-atomic stores. 481 if (!SI->isUnordered()) 482 return LegalStoreKind::None; 483 484 // Avoid merging nontemporal stores. 485 if (SI->getMetadata(LLVMContext::MD_nontemporal)) 486 return LegalStoreKind::None; 487 488 Value *StoredVal = SI->getValueOperand(); 489 Value *StorePtr = SI->getPointerOperand(); 490 491 // Don't convert stores of non-integral pointer types to memsets (which stores 492 // integers). 493 if (DL->isNonIntegralPointerType(StoredVal->getType()->getScalarType())) 494 return LegalStoreKind::None; 495 496 // Reject stores that are so large that they overflow an unsigned. 497 // When storing out scalable vectors we bail out for now, since the code 498 // below currently only works for constant strides. 499 TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); 500 if (SizeInBits.isScalable() || (SizeInBits.getFixedSize() & 7) || 501 (SizeInBits.getFixedSize() >> 32) != 0) 502 return LegalStoreKind::None; 503 504 // See if the pointer expression is an AddRec like {base,+,1} on the current 505 // loop, which indicates a strided store. If we have something else, it's a 506 // random store we can't handle. 507 const SCEVAddRecExpr *StoreEv = 508 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 509 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 510 return LegalStoreKind::None; 511 512 // Check to see if we have a constant stride. 513 if (!isa<SCEVConstant>(StoreEv->getOperand(1))) 514 return LegalStoreKind::None; 515 516 // See if the store can be turned into a memset. 517 518 // If the stored value is a byte-wise value (like i32 -1), then it may be 519 // turned into a memset of i8 -1, assuming that all the consecutive bytes 520 // are stored. A store of i32 0x01020304 can never be turned into a memset, 521 // but it can be turned into memset_pattern if the target supports it. 522 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 523 524 // Note: memset and memset_pattern on unordered-atomic is yet not supported 525 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple(); 526 527 // If we're allowed to form a memset, and the stored value would be 528 // acceptable for memset, use it. 529 if (!UnorderedAtomic && HasMemset && SplatValue && !DisableLIRP::Memset && 530 // Verify that the stored value is loop invariant. If not, we can't 531 // promote the memset. 532 CurLoop->isLoopInvariant(SplatValue)) { 533 // It looks like we can use SplatValue. 534 return LegalStoreKind::Memset; 535 } 536 if (!UnorderedAtomic && HasMemsetPattern && !DisableLIRP::Memset && 537 // Don't create memset_pattern16s with address spaces. 538 StorePtr->getType()->getPointerAddressSpace() == 0 && 539 getMemSetPatternValue(StoredVal, DL)) { 540 // It looks like we can use PatternValue! 541 return LegalStoreKind::MemsetPattern; 542 } 543 544 // Otherwise, see if the store can be turned into a memcpy. 545 if (HasMemcpy && !DisableLIRP::Memcpy) { 546 // Check to see if the stride matches the size of the store. If so, then we 547 // know that every byte is touched in the loop. 548 APInt Stride = getStoreStride(StoreEv); 549 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 550 if (StoreSize != Stride && StoreSize != -Stride) 551 return LegalStoreKind::None; 552 553 // The store must be feeding a non-volatile load. 554 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); 555 556 // Only allow non-volatile loads 557 if (!LI || LI->isVolatile()) 558 return LegalStoreKind::None; 559 // Only allow simple or unordered-atomic loads 560 if (!LI->isUnordered()) 561 return LegalStoreKind::None; 562 563 // See if the pointer expression is an AddRec like {base,+,1} on the current 564 // loop, which indicates a strided load. If we have something else, it's a 565 // random load we can't handle. 566 const SCEVAddRecExpr *LoadEv = 567 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 568 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 569 return LegalStoreKind::None; 570 571 // The store and load must share the same stride. 572 if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) 573 return LegalStoreKind::None; 574 575 // Success. This store can be converted into a memcpy. 576 UnorderedAtomic = UnorderedAtomic || LI->isAtomic(); 577 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy 578 : LegalStoreKind::Memcpy; 579 } 580 // This store can't be transformed into a memset/memcpy. 581 return LegalStoreKind::None; 582 } 583 584 void LoopIdiomRecognize::collectStores(BasicBlock *BB) { 585 StoreRefsForMemset.clear(); 586 StoreRefsForMemsetPattern.clear(); 587 StoreRefsForMemcpy.clear(); 588 for (Instruction &I : *BB) { 589 StoreInst *SI = dyn_cast<StoreInst>(&I); 590 if (!SI) 591 continue; 592 593 // Make sure this is a strided store with a constant stride. 594 switch (isLegalStore(SI)) { 595 case LegalStoreKind::None: 596 // Nothing to do 597 break; 598 case LegalStoreKind::Memset: { 599 // Find the base pointer. 600 Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); 601 StoreRefsForMemset[Ptr].push_back(SI); 602 } break; 603 case LegalStoreKind::MemsetPattern: { 604 // Find the base pointer. 605 Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); 606 StoreRefsForMemsetPattern[Ptr].push_back(SI); 607 } break; 608 case LegalStoreKind::Memcpy: 609 case LegalStoreKind::UnorderedAtomicMemcpy: 610 StoreRefsForMemcpy.push_back(SI); 611 break; 612 default: 613 assert(false && "unhandled return value"); 614 break; 615 } 616 } 617 } 618 619 /// runOnLoopBlock - Process the specified block, which lives in a counted loop 620 /// with the specified backedge count. This block is known to be in the current 621 /// loop and not in any subloops. 622 bool LoopIdiomRecognize::runOnLoopBlock( 623 BasicBlock *BB, const SCEV *BECount, 624 SmallVectorImpl<BasicBlock *> &ExitBlocks) { 625 // We can only promote stores in this block if they are unconditionally 626 // executed in the loop. For a block to be unconditionally executed, it has 627 // to dominate all the exit blocks of the loop. Verify this now. 628 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 629 if (!DT->dominates(BB, ExitBlocks[i])) 630 return false; 631 632 bool MadeChange = false; 633 // Look for store instructions, which may be optimized to memset/memcpy. 634 collectStores(BB); 635 636 // Look for a single store or sets of stores with a common base, which can be 637 // optimized into a memset (memset_pattern). The latter most commonly happens 638 // with structs and handunrolled loops. 639 for (auto &SL : StoreRefsForMemset) 640 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes); 641 642 for (auto &SL : StoreRefsForMemsetPattern) 643 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No); 644 645 // Optimize the store into a memcpy, if it feeds an similarly strided load. 646 for (auto &SI : StoreRefsForMemcpy) 647 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); 648 649 MadeChange |= processLoopMemIntrinsic<MemCpyInst>( 650 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount); 651 MadeChange |= processLoopMemIntrinsic<MemSetInst>( 652 BB, &LoopIdiomRecognize::processLoopMemSet, BECount); 653 654 return MadeChange; 655 } 656 657 /// See if this store(s) can be promoted to a memset. 658 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, 659 const SCEV *BECount, ForMemset For) { 660 // Try to find consecutive stores that can be transformed into memsets. 661 SetVector<StoreInst *> Heads, Tails; 662 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; 663 664 // Do a quadratic search on all of the given stores and find 665 // all of the pairs of stores that follow each other. 666 SmallVector<unsigned, 16> IndexQueue; 667 for (unsigned i = 0, e = SL.size(); i < e; ++i) { 668 assert(SL[i]->isSimple() && "Expected only non-volatile stores."); 669 670 Value *FirstStoredVal = SL[i]->getValueOperand(); 671 Value *FirstStorePtr = SL[i]->getPointerOperand(); 672 const SCEVAddRecExpr *FirstStoreEv = 673 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); 674 APInt FirstStride = getStoreStride(FirstStoreEv); 675 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType()); 676 677 // See if we can optimize just this store in isolation. 678 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { 679 Heads.insert(SL[i]); 680 continue; 681 } 682 683 Value *FirstSplatValue = nullptr; 684 Constant *FirstPatternValue = nullptr; 685 686 if (For == ForMemset::Yes) 687 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL); 688 else 689 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); 690 691 assert((FirstSplatValue || FirstPatternValue) && 692 "Expected either splat value or pattern value."); 693 694 IndexQueue.clear(); 695 // If a store has multiple consecutive store candidates, search Stores 696 // array according to the sequence: from i+1 to e, then from i-1 to 0. 697 // This is because usually pairing with immediate succeeding or preceding 698 // candidate create the best chance to find memset opportunity. 699 unsigned j = 0; 700 for (j = i + 1; j < e; ++j) 701 IndexQueue.push_back(j); 702 for (j = i; j > 0; --j) 703 IndexQueue.push_back(j - 1); 704 705 for (auto &k : IndexQueue) { 706 assert(SL[k]->isSimple() && "Expected only non-volatile stores."); 707 Value *SecondStorePtr = SL[k]->getPointerOperand(); 708 const SCEVAddRecExpr *SecondStoreEv = 709 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); 710 APInt SecondStride = getStoreStride(SecondStoreEv); 711 712 if (FirstStride != SecondStride) 713 continue; 714 715 Value *SecondStoredVal = SL[k]->getValueOperand(); 716 Value *SecondSplatValue = nullptr; 717 Constant *SecondPatternValue = nullptr; 718 719 if (For == ForMemset::Yes) 720 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL); 721 else 722 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); 723 724 assert((SecondSplatValue || SecondPatternValue) && 725 "Expected either splat value or pattern value."); 726 727 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { 728 if (For == ForMemset::Yes) { 729 if (isa<UndefValue>(FirstSplatValue)) 730 FirstSplatValue = SecondSplatValue; 731 if (FirstSplatValue != SecondSplatValue) 732 continue; 733 } else { 734 if (isa<UndefValue>(FirstPatternValue)) 735 FirstPatternValue = SecondPatternValue; 736 if (FirstPatternValue != SecondPatternValue) 737 continue; 738 } 739 Tails.insert(SL[k]); 740 Heads.insert(SL[i]); 741 ConsecutiveChain[SL[i]] = SL[k]; 742 break; 743 } 744 } 745 } 746 747 // We may run into multiple chains that merge into a single chain. We mark the 748 // stores that we transformed so that we don't visit the same store twice. 749 SmallPtrSet<Value *, 16> TransformedStores; 750 bool Changed = false; 751 752 // For stores that start but don't end a link in the chain: 753 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); 754 it != e; ++it) { 755 if (Tails.count(*it)) 756 continue; 757 758 // We found a store instr that starts a chain. Now follow the chain and try 759 // to transform it. 760 SmallPtrSet<Instruction *, 8> AdjacentStores; 761 StoreInst *I = *it; 762 763 StoreInst *HeadStore = I; 764 unsigned StoreSize = 0; 765 766 // Collect the chain into a list. 767 while (Tails.count(I) || Heads.count(I)) { 768 if (TransformedStores.count(I)) 769 break; 770 AdjacentStores.insert(I); 771 772 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType()); 773 // Move to the next value in the chain. 774 I = ConsecutiveChain[I]; 775 } 776 777 Value *StoredVal = HeadStore->getValueOperand(); 778 Value *StorePtr = HeadStore->getPointerOperand(); 779 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 780 APInt Stride = getStoreStride(StoreEv); 781 782 // Check to see if the stride matches the size of the stores. If so, then 783 // we know that every byte is touched in the loop. 784 if (StoreSize != Stride && StoreSize != -Stride) 785 continue; 786 787 bool IsNegStride = StoreSize == -Stride; 788 789 const SCEV *StoreSizeSCEV = SE->getConstant(BECount->getType(), StoreSize); 790 if (processLoopStridedStore(StorePtr, StoreSizeSCEV, 791 MaybeAlign(HeadStore->getAlignment()), 792 StoredVal, HeadStore, AdjacentStores, StoreEv, 793 BECount, IsNegStride)) { 794 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); 795 Changed = true; 796 } 797 } 798 799 return Changed; 800 } 801 802 /// processLoopMemIntrinsic - Template function for calling different processor 803 /// functions based on mem instrinsic type. 804 template <typename MemInst> 805 bool LoopIdiomRecognize::processLoopMemIntrinsic( 806 BasicBlock *BB, 807 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *), 808 const SCEV *BECount) { 809 bool MadeChange = false; 810 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 811 Instruction *Inst = &*I++; 812 // Look for memory instructions, which may be optimized to a larger one. 813 if (MemInst *MI = dyn_cast<MemInst>(Inst)) { 814 WeakTrackingVH InstPtr(&*I); 815 if (!(this->*Processor)(MI, BECount)) 816 continue; 817 MadeChange = true; 818 819 // If processing the instruction invalidated our iterator, start over from 820 // the top of the block. 821 if (!InstPtr) 822 I = BB->begin(); 823 } 824 } 825 return MadeChange; 826 } 827 828 /// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy 829 bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI, 830 const SCEV *BECount) { 831 // We can only handle non-volatile memcpys with a constant size. 832 if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength())) 833 return false; 834 835 // If we're not allowed to hack on memcpy, we fail. 836 if ((!HasMemcpy && !isa<MemCpyInlineInst>(MCI)) || DisableLIRP::Memcpy) 837 return false; 838 839 Value *Dest = MCI->getDest(); 840 Value *Source = MCI->getSource(); 841 if (!Dest || !Source) 842 return false; 843 844 // See if the load and store pointer expressions are AddRec like {base,+,1} on 845 // the current loop, which indicates a strided load and store. If we have 846 // something else, it's a random load or store we can't handle. 847 const SCEVAddRecExpr *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Dest)); 848 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 849 return false; 850 const SCEVAddRecExpr *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Source)); 851 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 852 return false; 853 854 // Reject memcpys that are so large that they overflow an unsigned. 855 uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue(); 856 if ((SizeInBytes >> 32) != 0) 857 return false; 858 859 // Check if the stride matches the size of the memcpy. If so, then we know 860 // that every byte is touched in the loop. 861 const SCEVConstant *StoreStride = 862 dyn_cast<SCEVConstant>(StoreEv->getOperand(1)); 863 const SCEVConstant *LoadStride = 864 dyn_cast<SCEVConstant>(LoadEv->getOperand(1)); 865 if (!StoreStride || !LoadStride) 866 return false; 867 868 APInt StoreStrideValue = StoreStride->getAPInt(); 869 APInt LoadStrideValue = LoadStride->getAPInt(); 870 // Huge stride value - give up 871 if (StoreStrideValue.getBitWidth() > 64 || LoadStrideValue.getBitWidth() > 64) 872 return false; 873 874 if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) { 875 ORE.emit([&]() { 876 return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI) 877 << ore::NV("Inst", "memcpy") << " in " 878 << ore::NV("Function", MCI->getFunction()) 879 << " function will not be hoised: " 880 << ore::NV("Reason", "memcpy size is not equal to stride"); 881 }); 882 return false; 883 } 884 885 int64_t StoreStrideInt = StoreStrideValue.getSExtValue(); 886 int64_t LoadStrideInt = LoadStrideValue.getSExtValue(); 887 // Check if the load stride matches the store stride. 888 if (StoreStrideInt != LoadStrideInt) 889 return false; 890 891 return processLoopStoreOfLoopLoad(Dest, Source, (unsigned)SizeInBytes, 892 MCI->getDestAlign(), MCI->getSourceAlign(), 893 MCI, MCI, StoreEv, LoadEv, BECount); 894 } 895 896 /// processLoopMemSet - See if this memset can be promoted to a large memset. 897 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, 898 const SCEV *BECount) { 899 // We can only handle non-volatile memsets. 900 if (MSI->isVolatile()) 901 return false; 902 903 // If we're not allowed to hack on memset, we fail. 904 if (!HasMemset || DisableLIRP::Memset) 905 return false; 906 907 Value *Pointer = MSI->getDest(); 908 909 // See if the pointer expression is an AddRec like {base,+,1} on the current 910 // loop, which indicates a strided store. If we have something else, it's a 911 // random store we can't handle. 912 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); 913 if (!Ev || Ev->getLoop() != CurLoop) 914 return false; 915 if (!Ev->isAffine()) { 916 LLVM_DEBUG(dbgs() << " Pointer is not affine, abort\n"); 917 return false; 918 } 919 920 const SCEV *PointerStrideSCEV = Ev->getOperand(1); 921 const SCEV *MemsetSizeSCEV = SE->getSCEV(MSI->getLength()); 922 if (!PointerStrideSCEV || !MemsetSizeSCEV) 923 return false; 924 925 bool IsNegStride = false; 926 const bool IsConstantSize = isa<ConstantInt>(MSI->getLength()); 927 928 if (IsConstantSize) { 929 // Memset size is constant. 930 // Check if the pointer stride matches the memset size. If so, then 931 // we know that every byte is touched in the loop. 932 LLVM_DEBUG(dbgs() << " memset size is constant\n"); 933 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 934 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); 935 if (!ConstStride) 936 return false; 937 938 APInt Stride = ConstStride->getAPInt(); 939 if (SizeInBytes != Stride && SizeInBytes != -Stride) 940 return false; 941 942 IsNegStride = SizeInBytes == -Stride; 943 } else { 944 // Memset size is non-constant. 945 // Check if the pointer stride matches the memset size. 946 // To be conservative, the pass would not promote pointers that aren't in 947 // address space zero. Also, the pass only handles memset length and stride 948 // that are invariant for the top level loop. 949 LLVM_DEBUG(dbgs() << " memset size is non-constant\n"); 950 if (Pointer->getType()->getPointerAddressSpace() != 0) { 951 LLVM_DEBUG(dbgs() << " pointer is not in address space zero, " 952 << "abort\n"); 953 return false; 954 } 955 if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) { 956 LLVM_DEBUG(dbgs() << " memset size is not a loop-invariant, " 957 << "abort\n"); 958 return false; 959 } 960 961 // Compare positive direction PointerStrideSCEV with MemsetSizeSCEV 962 IsNegStride = PointerStrideSCEV->isNonConstantNegative(); 963 const SCEV *PositiveStrideSCEV = 964 IsNegStride ? SE->getNegativeSCEV(PointerStrideSCEV) 965 : PointerStrideSCEV; 966 LLVM_DEBUG(dbgs() << " MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n" 967 << " PositiveStrideSCEV: " << *PositiveStrideSCEV 968 << "\n"); 969 970 if (PositiveStrideSCEV != MemsetSizeSCEV) { 971 // TODO: folding can be done to the SCEVs 972 // The folding is to fold expressions that is covered by the loop guard 973 // at loop entry. After the folding, compare again and proceed 974 // optimization if equal. 975 LLVM_DEBUG(dbgs() << " SCEV don't match, abort\n"); 976 return false; 977 } 978 } 979 980 // Verify that the memset value is loop invariant. If not, we can't promote 981 // the memset. 982 Value *SplatValue = MSI->getValue(); 983 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) 984 return false; 985 986 SmallPtrSet<Instruction *, 1> MSIs; 987 MSIs.insert(MSI); 988 return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()), 989 MaybeAlign(MSI->getDestAlignment()), 990 SplatValue, MSI, MSIs, Ev, BECount, 991 IsNegStride, /*IsLoopMemset=*/true); 992 } 993 994 /// mayLoopAccessLocation - Return true if the specified loop might access the 995 /// specified pointer location, which is a loop-strided access. The 'Access' 996 /// argument specifies what the verboten forms of access are (read or write). 997 static bool 998 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, 999 const SCEV *BECount, const SCEV *StoreSizeSCEV, 1000 AliasAnalysis &AA, 1001 SmallPtrSetImpl<Instruction *> &IgnoredStores) { 1002 // Get the location that may be stored across the loop. Since the access is 1003 // strided positively through memory, we say that the modified location starts 1004 // at the pointer and has infinite size. 1005 LocationSize AccessSize = LocationSize::afterPointer(); 1006 1007 // If the loop iterates a fixed number of times, we can refine the access size 1008 // to be exactly the size of the memset, which is (BECount+1)*StoreSize 1009 const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount); 1010 const SCEVConstant *ConstSize = dyn_cast<SCEVConstant>(StoreSizeSCEV); 1011 if (BECst && ConstSize) 1012 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) * 1013 ConstSize->getValue()->getZExtValue()); 1014 1015 // TODO: For this to be really effective, we have to dive into the pointer 1016 // operand in the store. Store to &A[i] of 100 will always return may alias 1017 // with store of &A[100], we need to StoreLoc to be "A" with size of 100, 1018 // which will then no-alias a store to &A[100]. 1019 MemoryLocation StoreLoc(Ptr, AccessSize); 1020 1021 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; 1022 ++BI) 1023 for (Instruction &I : **BI) 1024 if (IgnoredStores.count(&I) == 0 && 1025 isModOrRefSet( 1026 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access))) 1027 return true; 1028 return false; 1029 } 1030 1031 // If we have a negative stride, Start refers to the end of the memory location 1032 // we're trying to memset. Therefore, we need to recompute the base pointer, 1033 // which is just Start - BECount*Size. 1034 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, 1035 Type *IntPtr, const SCEV *StoreSizeSCEV, 1036 ScalarEvolution *SE) { 1037 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); 1038 if (!StoreSizeSCEV->isOne()) { 1039 // index = back edge count * store size 1040 Index = SE->getMulExpr(Index, 1041 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr), 1042 SCEV::FlagNUW); 1043 } 1044 // base pointer = start - index * store size 1045 return SE->getMinusSCEV(Start, Index); 1046 } 1047 1048 /// Compute trip count from the backedge taken count. 1049 static const SCEV *getTripCount(const SCEV *BECount, Type *IntPtr, 1050 Loop *CurLoop, const DataLayout *DL, 1051 ScalarEvolution *SE) { 1052 const SCEV *TripCountS = nullptr; 1053 // The # stored bytes is (BECount+1). Expand the trip count out to 1054 // pointer size if it isn't already. 1055 // 1056 // If we're going to need to zero extend the BE count, check if we can add 1057 // one to it prior to zero extending without overflow. Provided this is safe, 1058 // it allows better simplification of the +1. 1059 if (DL->getTypeSizeInBits(BECount->getType()) < 1060 DL->getTypeSizeInBits(IntPtr) && 1061 SE->isLoopEntryGuardedByCond( 1062 CurLoop, ICmpInst::ICMP_NE, BECount, 1063 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) { 1064 TripCountS = SE->getZeroExtendExpr( 1065 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW), 1066 IntPtr); 1067 } else { 1068 TripCountS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr), 1069 SE->getOne(IntPtr), SCEV::FlagNUW); 1070 } 1071 1072 return TripCountS; 1073 } 1074 1075 /// Compute the number of bytes as a SCEV from the backedge taken count. 1076 /// 1077 /// This also maps the SCEV into the provided type and tries to handle the 1078 /// computation in a way that will fold cleanly. 1079 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr, 1080 const SCEV *StoreSizeSCEV, Loop *CurLoop, 1081 const DataLayout *DL, ScalarEvolution *SE) { 1082 const SCEV *TripCountSCEV = getTripCount(BECount, IntPtr, CurLoop, DL, SE); 1083 1084 return SE->getMulExpr(TripCountSCEV, 1085 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr), 1086 SCEV::FlagNUW); 1087 } 1088 1089 /// processLoopStridedStore - We see a strided store of some value. If we can 1090 /// transform this into a memset or memset_pattern in the loop preheader, do so. 1091 bool LoopIdiomRecognize::processLoopStridedStore( 1092 Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment, 1093 Value *StoredVal, Instruction *TheStore, 1094 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, 1095 const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) { 1096 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 1097 Constant *PatternValue = nullptr; 1098 1099 if (!SplatValue) 1100 PatternValue = getMemSetPatternValue(StoredVal, DL); 1101 1102 assert((SplatValue || PatternValue) && 1103 "Expected either splat value or pattern value."); 1104 1105 // The trip count of the loop and the base pointer of the addrec SCEV is 1106 // guaranteed to be loop invariant, which means that it should dominate the 1107 // header. This allows us to insert code for it in the preheader. 1108 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); 1109 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1110 IRBuilder<> Builder(Preheader->getTerminator()); 1111 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 1112 SCEVExpanderCleaner ExpCleaner(Expander, *DT); 1113 1114 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); 1115 Type *IntIdxTy = DL->getIndexType(DestPtr->getType()); 1116 1117 bool Changed = false; 1118 const SCEV *Start = Ev->getStart(); 1119 // Handle negative strided loops. 1120 if (IsNegStride) 1121 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE); 1122 1123 // TODO: ideally we should still be able to generate memset if SCEV expander 1124 // is taught to generate the dependencies at the latest point. 1125 if (!isSafeToExpand(Start, *SE)) 1126 return Changed; 1127 1128 // Okay, we have a strided store "p[i]" of a splattable value. We can turn 1129 // this into a memset in the loop preheader now if we want. However, this 1130 // would be unsafe to do if there is anything else in the loop that may read 1131 // or write to the aliased location. Check for any overlap by generating the 1132 // base pointer and checking the region. 1133 Value *BasePtr = 1134 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); 1135 1136 // From here on out, conservatively report to the pass manager that we've 1137 // changed the IR, even if we later clean up these added instructions. There 1138 // may be structural differences e.g. in the order of use lists not accounted 1139 // for in just a textual dump of the IR. This is written as a variable, even 1140 // though statically all the places this dominates could be replaced with 1141 // 'true', with the hope that anyone trying to be clever / "more precise" with 1142 // the return value will read this comment, and leave them alone. 1143 Changed = true; 1144 1145 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount, 1146 StoreSizeSCEV, *AA, Stores)) 1147 return Changed; 1148 1149 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset)) 1150 return Changed; 1151 1152 // Okay, everything looks good, insert the memset. 1153 1154 const SCEV *NumBytesS = 1155 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE); 1156 1157 // TODO: ideally we should still be able to generate memset if SCEV expander 1158 // is taught to generate the dependencies at the latest point. 1159 if (!isSafeToExpand(NumBytesS, *SE)) 1160 return Changed; 1161 1162 Value *NumBytes = 1163 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 1164 1165 CallInst *NewCall; 1166 if (SplatValue) { 1167 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, 1168 MaybeAlign(StoreAlignment)); 1169 } else { 1170 // Everything is emitted in default address space 1171 Type *Int8PtrTy = DestInt8PtrTy; 1172 1173 Module *M = TheStore->getModule(); 1174 StringRef FuncName = "memset_pattern16"; 1175 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(), 1176 Int8PtrTy, Int8PtrTy, IntIdxTy); 1177 inferLibFuncAttributes(M, FuncName, *TLI); 1178 1179 // Otherwise we should form a memset_pattern16. PatternValue is known to be 1180 // an constant array of 16-bytes. Plop the value into a mergable global. 1181 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, 1182 GlobalValue::PrivateLinkage, 1183 PatternValue, ".memset_pattern"); 1184 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. 1185 GV->setAlignment(Align(16)); 1186 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); 1187 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); 1188 } 1189 NewCall->setDebugLoc(TheStore->getDebugLoc()); 1190 1191 if (MSSAU) { 1192 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1193 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 1194 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1195 } 1196 1197 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" 1198 << " from store to: " << *Ev << " at: " << *TheStore 1199 << "\n"); 1200 1201 ORE.emit([&]() { 1202 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStridedStore", 1203 NewCall->getDebugLoc(), Preheader) 1204 << "Transformed loop-strided store in " 1205 << ore::NV("Function", TheStore->getFunction()) 1206 << " function into a call to " 1207 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1208 << "() intrinsic"; 1209 }); 1210 1211 // Okay, the memset has been formed. Zap the original store and anything that 1212 // feeds into it. 1213 for (auto *I : Stores) { 1214 if (MSSAU) 1215 MSSAU->removeMemoryAccess(I, true); 1216 deleteDeadInstruction(I); 1217 } 1218 if (MSSAU && VerifyMemorySSA) 1219 MSSAU->getMemorySSA()->verifyMemorySSA(); 1220 ++NumMemSet; 1221 ExpCleaner.markResultUsed(); 1222 return true; 1223 } 1224 1225 /// If the stored value is a strided load in the same loop with the same stride 1226 /// this may be transformable into a memcpy. This kicks in for stuff like 1227 /// for (i) A[i] = B[i]; 1228 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, 1229 const SCEV *BECount) { 1230 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores."); 1231 1232 Value *StorePtr = SI->getPointerOperand(); 1233 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 1234 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 1235 1236 // The store must be feeding a non-volatile load. 1237 LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); 1238 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads."); 1239 1240 // See if the pointer expression is an AddRec like {base,+,1} on the current 1241 // loop, which indicates a strided load. If we have something else, it's a 1242 // random load we can't handle. 1243 Value *LoadPtr = LI->getPointerOperand(); 1244 const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr)); 1245 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSize, 1246 SI->getAlign(), LI->getAlign(), SI, LI, 1247 StoreEv, LoadEv, BECount); 1248 } 1249 1250 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad( 1251 Value *DestPtr, Value *SourcePtr, unsigned StoreSize, MaybeAlign StoreAlign, 1252 MaybeAlign LoadAlign, Instruction *TheStore, Instruction *TheLoad, 1253 const SCEVAddRecExpr *StoreEv, const SCEVAddRecExpr *LoadEv, 1254 const SCEV *BECount) { 1255 1256 // FIXME: until llvm.memcpy.inline supports dynamic sizes, we need to 1257 // conservatively bail here, since otherwise we may have to transform 1258 // llvm.memcpy.inline into llvm.memcpy which is illegal. 1259 if (isa<MemCpyInlineInst>(TheStore)) 1260 return false; 1261 1262 // The trip count of the loop and the base pointer of the addrec SCEV is 1263 // guaranteed to be loop invariant, which means that it should dominate the 1264 // header. This allows us to insert code for it in the preheader. 1265 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1266 IRBuilder<> Builder(Preheader->getTerminator()); 1267 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 1268 1269 SCEVExpanderCleaner ExpCleaner(Expander, *DT); 1270 1271 bool Changed = false; 1272 const SCEV *StrStart = StoreEv->getStart(); 1273 unsigned StrAS = DestPtr->getType()->getPointerAddressSpace(); 1274 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS)); 1275 1276 APInt Stride = getStoreStride(StoreEv); 1277 bool IsNegStride = StoreSize == -Stride; 1278 1279 const SCEV *StoreSizeSCEV = SE->getConstant(BECount->getType(), StoreSize); 1280 // Handle negative strided loops. 1281 if (IsNegStride) 1282 StrStart = 1283 getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE); 1284 1285 // Okay, we have a strided store "p[i]" of a loaded value. We can turn 1286 // this into a memcpy in the loop preheader now if we want. However, this 1287 // would be unsafe to do if there is anything else in the loop that may read 1288 // or write the memory region we're storing to. This includes the load that 1289 // feeds the stores. Check for an alias by generating the base address and 1290 // checking everything. 1291 Value *StoreBasePtr = Expander.expandCodeFor( 1292 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); 1293 1294 // From here on out, conservatively report to the pass manager that we've 1295 // changed the IR, even if we later clean up these added instructions. There 1296 // may be structural differences e.g. in the order of use lists not accounted 1297 // for in just a textual dump of the IR. This is written as a variable, even 1298 // though statically all the places this dominates could be replaced with 1299 // 'true', with the hope that anyone trying to be clever / "more precise" with 1300 // the return value will read this comment, and leave them alone. 1301 Changed = true; 1302 1303 SmallPtrSet<Instruction *, 2> Stores; 1304 Stores.insert(TheStore); 1305 1306 bool IsMemCpy = isa<MemCpyInst>(TheStore); 1307 const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store"; 1308 1309 bool UseMemMove = 1310 mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount, 1311 StoreSizeSCEV, *AA, Stores); 1312 if (UseMemMove) { 1313 Stores.insert(TheLoad); 1314 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, 1315 BECount, StoreSizeSCEV, *AA, Stores)) { 1316 ORE.emit([&]() { 1317 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore", 1318 TheStore) 1319 << ore::NV("Inst", InstRemark) << " in " 1320 << ore::NV("Function", TheStore->getFunction()) 1321 << " function will not be hoisted: " 1322 << ore::NV("Reason", "The loop may access store location"); 1323 }); 1324 return Changed; 1325 } 1326 Stores.erase(TheLoad); 1327 } 1328 1329 const SCEV *LdStart = LoadEv->getStart(); 1330 unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace(); 1331 1332 // Handle negative strided loops. 1333 if (IsNegStride) 1334 LdStart = 1335 getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE); 1336 1337 // For a memcpy, we have to make sure that the input array is not being 1338 // mutated by the loop. 1339 Value *LoadBasePtr = Expander.expandCodeFor( 1340 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); 1341 1342 // If the store is a memcpy instruction, we must check if it will write to 1343 // the load memory locations. So remove it from the ignored stores. 1344 if (IsMemCpy) 1345 Stores.erase(TheStore); 1346 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount, 1347 StoreSizeSCEV, *AA, Stores)) { 1348 ORE.emit([&]() { 1349 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad) 1350 << ore::NV("Inst", InstRemark) << " in " 1351 << ore::NV("Function", TheStore->getFunction()) 1352 << " function will not be hoisted: " 1353 << ore::NV("Reason", "The loop may access load location"); 1354 }); 1355 return Changed; 1356 } 1357 if (UseMemMove) { 1358 // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr for 1359 // negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr. 1360 int64_t LoadOff = 0, StoreOff = 0; 1361 const Value *BP1 = llvm::GetPointerBaseWithConstantOffset( 1362 LoadBasePtr->stripPointerCasts(), LoadOff, *DL); 1363 const Value *BP2 = llvm::GetPointerBaseWithConstantOffset( 1364 StoreBasePtr->stripPointerCasts(), StoreOff, *DL); 1365 int64_t LoadSize = 1366 DL->getTypeSizeInBits(TheLoad->getType()).getFixedSize() / 8; 1367 if (BP1 != BP2 || LoadSize != int64_t(StoreSize)) 1368 return Changed; 1369 if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) || 1370 (IsNegStride && LoadOff + LoadSize > StoreOff)) 1371 return Changed; 1372 } 1373 1374 if (avoidLIRForMultiBlockLoop()) 1375 return Changed; 1376 1377 // Okay, everything is safe, we can transform this! 1378 1379 const SCEV *NumBytesS = getNumBytes( 1380 BECount, IntIdxTy, SE->getConstant(IntIdxTy, StoreSize), CurLoop, DL, SE); 1381 1382 Value *NumBytes = 1383 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 1384 1385 CallInst *NewCall = nullptr; 1386 // Check whether to generate an unordered atomic memcpy: 1387 // If the load or store are atomic, then they must necessarily be unordered 1388 // by previous checks. 1389 if (!TheStore->isAtomic() && !TheLoad->isAtomic()) { 1390 if (UseMemMove) 1391 NewCall = Builder.CreateMemMove(StoreBasePtr, StoreAlign, LoadBasePtr, 1392 LoadAlign, NumBytes); 1393 else 1394 NewCall = Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, 1395 LoadAlign, NumBytes); 1396 } else { 1397 // For now don't support unordered atomic memmove. 1398 if (UseMemMove) 1399 return Changed; 1400 // We cannot allow unaligned ops for unordered load/store, so reject 1401 // anything where the alignment isn't at least the element size. 1402 assert((StoreAlign.hasValue() && LoadAlign.hasValue()) && 1403 "Expect unordered load/store to have align."); 1404 if (StoreAlign.getValue() < StoreSize || LoadAlign.getValue() < StoreSize) 1405 return Changed; 1406 1407 // If the element.atomic memcpy is not lowered into explicit 1408 // loads/stores later, then it will be lowered into an element-size 1409 // specific lib call. If the lib call doesn't exist for our store size, then 1410 // we shouldn't generate the memcpy. 1411 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize()) 1412 return Changed; 1413 1414 // Create the call. 1415 // Note that unordered atomic loads/stores are *required* by the spec to 1416 // have an alignment but non-atomic loads/stores may not. 1417 NewCall = Builder.CreateElementUnorderedAtomicMemCpy( 1418 StoreBasePtr, StoreAlign.getValue(), LoadBasePtr, LoadAlign.getValue(), 1419 NumBytes, StoreSize); 1420 } 1421 NewCall->setDebugLoc(TheStore->getDebugLoc()); 1422 1423 if (MSSAU) { 1424 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1425 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 1426 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1427 } 1428 1429 LLVM_DEBUG(dbgs() << " Formed new call: " << *NewCall << "\n" 1430 << " from load ptr=" << *LoadEv << " at: " << *TheLoad 1431 << "\n" 1432 << " from store ptr=" << *StoreEv << " at: " << *TheStore 1433 << "\n"); 1434 1435 ORE.emit([&]() { 1436 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad", 1437 NewCall->getDebugLoc(), Preheader) 1438 << "Formed a call to " 1439 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1440 << "() intrinsic from " << ore::NV("Inst", InstRemark) 1441 << " instruction in " << ore::NV("Function", TheStore->getFunction()) 1442 << " function"; 1443 }); 1444 1445 // Okay, the memcpy has been formed. Zap the original store and anything that 1446 // feeds into it. 1447 if (MSSAU) 1448 MSSAU->removeMemoryAccess(TheStore, true); 1449 deleteDeadInstruction(TheStore); 1450 if (MSSAU && VerifyMemorySSA) 1451 MSSAU->getMemorySSA()->verifyMemorySSA(); 1452 if (UseMemMove) 1453 ++NumMemMove; 1454 else 1455 ++NumMemCpy; 1456 ExpCleaner.markResultUsed(); 1457 return true; 1458 } 1459 1460 // When compiling for codesize we avoid idiom recognition for a multi-block loop 1461 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop. 1462 // 1463 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, 1464 bool IsLoopMemset) { 1465 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) { 1466 if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) { 1467 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName() 1468 << " : LIR " << (IsMemset ? "Memset" : "Memcpy") 1469 << " avoided: multi-block top-level loop\n"); 1470 return true; 1471 } 1472 } 1473 1474 return false; 1475 } 1476 1477 bool LoopIdiomRecognize::runOnNoncountableLoop() { 1478 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 1479 << CurLoop->getHeader()->getParent()->getName() 1480 << "] Noncountable Loop %" 1481 << CurLoop->getHeader()->getName() << "\n"); 1482 1483 return recognizePopcount() || recognizeAndInsertFFS() || 1484 recognizeShiftUntilBitTest() || recognizeShiftUntilZero(); 1485 } 1486 1487 /// Check if the given conditional branch is based on the comparison between 1488 /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is 1489 /// true), the control yields to the loop entry. If the branch matches the 1490 /// behavior, the variable involved in the comparison is returned. This function 1491 /// will be called to see if the precondition and postcondition of the loop are 1492 /// in desirable form. 1493 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry, 1494 bool JmpOnZero = false) { 1495 if (!BI || !BI->isConditional()) 1496 return nullptr; 1497 1498 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 1499 if (!Cond) 1500 return nullptr; 1501 1502 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); 1503 if (!CmpZero || !CmpZero->isZero()) 1504 return nullptr; 1505 1506 BasicBlock *TrueSucc = BI->getSuccessor(0); 1507 BasicBlock *FalseSucc = BI->getSuccessor(1); 1508 if (JmpOnZero) 1509 std::swap(TrueSucc, FalseSucc); 1510 1511 ICmpInst::Predicate Pred = Cond->getPredicate(); 1512 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) || 1513 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry)) 1514 return Cond->getOperand(0); 1515 1516 return nullptr; 1517 } 1518 1519 // Check if the recurrence variable `VarX` is in the right form to create 1520 // the idiom. Returns the value coerced to a PHINode if so. 1521 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX, 1522 BasicBlock *LoopEntry) { 1523 auto *PhiX = dyn_cast<PHINode>(VarX); 1524 if (PhiX && PhiX->getParent() == LoopEntry && 1525 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX)) 1526 return PhiX; 1527 return nullptr; 1528 } 1529 1530 /// Return true iff the idiom is detected in the loop. 1531 /// 1532 /// Additionally: 1533 /// 1) \p CntInst is set to the instruction counting the population bit. 1534 /// 2) \p CntPhi is set to the corresponding phi node. 1535 /// 3) \p Var is set to the value whose population bits are being counted. 1536 /// 1537 /// The core idiom we are trying to detect is: 1538 /// \code 1539 /// if (x0 != 0) 1540 /// goto loop-exit // the precondition of the loop 1541 /// cnt0 = init-val; 1542 /// do { 1543 /// x1 = phi (x0, x2); 1544 /// cnt1 = phi(cnt0, cnt2); 1545 /// 1546 /// cnt2 = cnt1 + 1; 1547 /// ... 1548 /// x2 = x1 & (x1 - 1); 1549 /// ... 1550 /// } while(x != 0); 1551 /// 1552 /// loop-exit: 1553 /// \endcode 1554 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, 1555 Instruction *&CntInst, PHINode *&CntPhi, 1556 Value *&Var) { 1557 // step 1: Check to see if the look-back branch match this pattern: 1558 // "if (a!=0) goto loop-entry". 1559 BasicBlock *LoopEntry; 1560 Instruction *DefX2, *CountInst; 1561 Value *VarX1, *VarX0; 1562 PHINode *PhiX, *CountPhi; 1563 1564 DefX2 = CountInst = nullptr; 1565 VarX1 = VarX0 = nullptr; 1566 PhiX = CountPhi = nullptr; 1567 LoopEntry = *(CurLoop->block_begin()); 1568 1569 // step 1: Check if the loop-back branch is in desirable form. 1570 { 1571 if (Value *T = matchCondition( 1572 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1573 DefX2 = dyn_cast<Instruction>(T); 1574 else 1575 return false; 1576 } 1577 1578 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" 1579 { 1580 if (!DefX2 || DefX2->getOpcode() != Instruction::And) 1581 return false; 1582 1583 BinaryOperator *SubOneOp; 1584 1585 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) 1586 VarX1 = DefX2->getOperand(1); 1587 else { 1588 VarX1 = DefX2->getOperand(0); 1589 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); 1590 } 1591 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1) 1592 return false; 1593 1594 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1)); 1595 if (!Dec || 1596 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) || 1597 (SubOneOp->getOpcode() == Instruction::Add && 1598 Dec->isMinusOne()))) { 1599 return false; 1600 } 1601 } 1602 1603 // step 3: Check the recurrence of variable X 1604 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry); 1605 if (!PhiX) 1606 return false; 1607 1608 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 1609 { 1610 CountInst = nullptr; 1611 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1612 IterE = LoopEntry->end(); 1613 Iter != IterE; Iter++) { 1614 Instruction *Inst = &*Iter; 1615 if (Inst->getOpcode() != Instruction::Add) 1616 continue; 1617 1618 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1619 if (!Inc || !Inc->isOne()) 1620 continue; 1621 1622 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1623 if (!Phi) 1624 continue; 1625 1626 // Check if the result of the instruction is live of the loop. 1627 bool LiveOutLoop = false; 1628 for (User *U : Inst->users()) { 1629 if ((cast<Instruction>(U))->getParent() != LoopEntry) { 1630 LiveOutLoop = true; 1631 break; 1632 } 1633 } 1634 1635 if (LiveOutLoop) { 1636 CountInst = Inst; 1637 CountPhi = Phi; 1638 break; 1639 } 1640 } 1641 1642 if (!CountInst) 1643 return false; 1644 } 1645 1646 // step 5: check if the precondition is in this form: 1647 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" 1648 { 1649 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1650 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); 1651 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) 1652 return false; 1653 1654 CntInst = CountInst; 1655 CntPhi = CountPhi; 1656 Var = T; 1657 } 1658 1659 return true; 1660 } 1661 1662 /// Return true if the idiom is detected in the loop. 1663 /// 1664 /// Additionally: 1665 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ) 1666 /// or nullptr if there is no such. 1667 /// 2) \p CntPhi is set to the corresponding phi node 1668 /// or nullptr if there is no such. 1669 /// 3) \p Var is set to the value whose CTLZ could be used. 1670 /// 4) \p DefX is set to the instruction calculating Loop exit condition. 1671 /// 1672 /// The core idiom we are trying to detect is: 1673 /// \code 1674 /// if (x0 == 0) 1675 /// goto loop-exit // the precondition of the loop 1676 /// cnt0 = init-val; 1677 /// do { 1678 /// x = phi (x0, x.next); //PhiX 1679 /// cnt = phi(cnt0, cnt.next); 1680 /// 1681 /// cnt.next = cnt + 1; 1682 /// ... 1683 /// x.next = x >> 1; // DefX 1684 /// ... 1685 /// } while(x.next != 0); 1686 /// 1687 /// loop-exit: 1688 /// \endcode 1689 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, 1690 Intrinsic::ID &IntrinID, Value *&InitX, 1691 Instruction *&CntInst, PHINode *&CntPhi, 1692 Instruction *&DefX) { 1693 BasicBlock *LoopEntry; 1694 Value *VarX = nullptr; 1695 1696 DefX = nullptr; 1697 CntInst = nullptr; 1698 CntPhi = nullptr; 1699 LoopEntry = *(CurLoop->block_begin()); 1700 1701 // step 1: Check if the loop-back branch is in desirable form. 1702 if (Value *T = matchCondition( 1703 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1704 DefX = dyn_cast<Instruction>(T); 1705 else 1706 return false; 1707 1708 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1" 1709 if (!DefX || !DefX->isShift()) 1710 return false; 1711 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz : 1712 Intrinsic::ctlz; 1713 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)); 1714 if (!Shft || !Shft->isOne()) 1715 return false; 1716 VarX = DefX->getOperand(0); 1717 1718 // step 3: Check the recurrence of variable X 1719 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry); 1720 if (!PhiX) 1721 return false; 1722 1723 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader()); 1724 1725 // Make sure the initial value can't be negative otherwise the ashr in the 1726 // loop might never reach zero which would make the loop infinite. 1727 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL)) 1728 return false; 1729 1730 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1 1731 // or cnt.next = cnt + -1. 1732 // TODO: We can skip the step. If loop trip count is known (CTLZ), 1733 // then all uses of "cnt.next" could be optimized to the trip count 1734 // plus "cnt0". Currently it is not optimized. 1735 // This step could be used to detect POPCNT instruction: 1736 // cnt.next = cnt + (x.next & 1) 1737 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1738 IterE = LoopEntry->end(); 1739 Iter != IterE; Iter++) { 1740 Instruction *Inst = &*Iter; 1741 if (Inst->getOpcode() != Instruction::Add) 1742 continue; 1743 1744 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1745 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne())) 1746 continue; 1747 1748 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1749 if (!Phi) 1750 continue; 1751 1752 CntInst = Inst; 1753 CntPhi = Phi; 1754 break; 1755 } 1756 if (!CntInst) 1757 return false; 1758 1759 return true; 1760 } 1761 1762 /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop 1763 /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new 1764 /// trip count returns true; otherwise, returns false. 1765 bool LoopIdiomRecognize::recognizeAndInsertFFS() { 1766 // Give up if the loop has multiple blocks or multiple backedges. 1767 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1768 return false; 1769 1770 Intrinsic::ID IntrinID; 1771 Value *InitX; 1772 Instruction *DefX = nullptr; 1773 PHINode *CntPhi = nullptr; 1774 Instruction *CntInst = nullptr; 1775 // Help decide if transformation is profitable. For ShiftUntilZero idiom, 1776 // this is always 6. 1777 size_t IdiomCanonicalSize = 6; 1778 1779 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, 1780 CntInst, CntPhi, DefX)) 1781 return false; 1782 1783 bool IsCntPhiUsedOutsideLoop = false; 1784 for (User *U : CntPhi->users()) 1785 if (!CurLoop->contains(cast<Instruction>(U))) { 1786 IsCntPhiUsedOutsideLoop = true; 1787 break; 1788 } 1789 bool IsCntInstUsedOutsideLoop = false; 1790 for (User *U : CntInst->users()) 1791 if (!CurLoop->contains(cast<Instruction>(U))) { 1792 IsCntInstUsedOutsideLoop = true; 1793 break; 1794 } 1795 // If both CntInst and CntPhi are used outside the loop the profitability 1796 // is questionable. 1797 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop) 1798 return false; 1799 1800 // For some CPUs result of CTLZ(X) intrinsic is undefined 1801 // when X is 0. If we can not guarantee X != 0, we need to check this 1802 // when expand. 1803 bool ZeroCheck = false; 1804 // It is safe to assume Preheader exist as it was checked in 1805 // parent function RunOnLoop. 1806 BasicBlock *PH = CurLoop->getLoopPreheader(); 1807 1808 // If we are using the count instruction outside the loop, make sure we 1809 // have a zero check as a precondition. Without the check the loop would run 1810 // one iteration for before any check of the input value. This means 0 and 1 1811 // would have identical behavior in the original loop and thus 1812 if (!IsCntPhiUsedOutsideLoop) { 1813 auto *PreCondBB = PH->getSinglePredecessor(); 1814 if (!PreCondBB) 1815 return false; 1816 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1817 if (!PreCondBI) 1818 return false; 1819 if (matchCondition(PreCondBI, PH) != InitX) 1820 return false; 1821 ZeroCheck = true; 1822 } 1823 1824 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always 1825 // profitable if we delete the loop. 1826 1827 // the loop has only 6 instructions: 1828 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ] 1829 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ] 1830 // %shr = ashr %n.addr.0, 1 1831 // %tobool = icmp eq %shr, 0 1832 // %inc = add nsw %i.0, 1 1833 // br i1 %tobool 1834 1835 const Value *Args[] = {InitX, 1836 ConstantInt::getBool(InitX->getContext(), ZeroCheck)}; 1837 1838 // @llvm.dbg doesn't count as they have no semantic effect. 1839 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug(); 1840 uint32_t HeaderSize = 1841 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end()); 1842 1843 IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args); 1844 InstructionCost Cost = 1845 TTI->getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency); 1846 if (HeaderSize != IdiomCanonicalSize && 1847 Cost > TargetTransformInfo::TCC_Basic) 1848 return false; 1849 1850 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX, 1851 DefX->getDebugLoc(), ZeroCheck, 1852 IsCntPhiUsedOutsideLoop); 1853 return true; 1854 } 1855 1856 /// Recognizes a population count idiom in a non-countable loop. 1857 /// 1858 /// If detected, transforms the relevant code to issue the popcount intrinsic 1859 /// function call, and returns true; otherwise, returns false. 1860 bool LoopIdiomRecognize::recognizePopcount() { 1861 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) 1862 return false; 1863 1864 // Counting population are usually conducted by few arithmetic instructions. 1865 // Such instructions can be easily "absorbed" by vacant slots in a 1866 // non-compact loop. Therefore, recognizing popcount idiom only makes sense 1867 // in a compact loop. 1868 1869 // Give up if the loop has multiple blocks or multiple backedges. 1870 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1871 return false; 1872 1873 BasicBlock *LoopBody = *(CurLoop->block_begin()); 1874 if (LoopBody->size() >= 20) { 1875 // The loop is too big, bail out. 1876 return false; 1877 } 1878 1879 // It should have a preheader containing nothing but an unconditional branch. 1880 BasicBlock *PH = CurLoop->getLoopPreheader(); 1881 if (!PH || &PH->front() != PH->getTerminator()) 1882 return false; 1883 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); 1884 if (!EntryBI || EntryBI->isConditional()) 1885 return false; 1886 1887 // It should have a precondition block where the generated popcount intrinsic 1888 // function can be inserted. 1889 auto *PreCondBB = PH->getSinglePredecessor(); 1890 if (!PreCondBB) 1891 return false; 1892 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1893 if (!PreCondBI || PreCondBI->isUnconditional()) 1894 return false; 1895 1896 Instruction *CntInst; 1897 PHINode *CntPhi; 1898 Value *Val; 1899 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) 1900 return false; 1901 1902 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); 1903 return true; 1904 } 1905 1906 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1907 const DebugLoc &DL) { 1908 Value *Ops[] = {Val}; 1909 Type *Tys[] = {Val->getType()}; 1910 1911 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1912 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); 1913 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1914 CI->setDebugLoc(DL); 1915 1916 return CI; 1917 } 1918 1919 static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1920 const DebugLoc &DL, bool ZeroCheck, 1921 Intrinsic::ID IID) { 1922 Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)}; 1923 Type *Tys[] = {Val->getType()}; 1924 1925 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1926 Function *Func = Intrinsic::getDeclaration(M, IID, Tys); 1927 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1928 CI->setDebugLoc(DL); 1929 1930 return CI; 1931 } 1932 1933 /// Transform the following loop (Using CTLZ, CTTZ is similar): 1934 /// loop: 1935 /// CntPhi = PHI [Cnt0, CntInst] 1936 /// PhiX = PHI [InitX, DefX] 1937 /// CntInst = CntPhi + 1 1938 /// DefX = PhiX >> 1 1939 /// LOOP_BODY 1940 /// Br: loop if (DefX != 0) 1941 /// Use(CntPhi) or Use(CntInst) 1942 /// 1943 /// Into: 1944 /// If CntPhi used outside the loop: 1945 /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1) 1946 /// Count = CountPrev + 1 1947 /// else 1948 /// Count = BitWidth(InitX) - CTLZ(InitX) 1949 /// loop: 1950 /// CntPhi = PHI [Cnt0, CntInst] 1951 /// PhiX = PHI [InitX, DefX] 1952 /// PhiCount = PHI [Count, Dec] 1953 /// CntInst = CntPhi + 1 1954 /// DefX = PhiX >> 1 1955 /// Dec = PhiCount - 1 1956 /// LOOP_BODY 1957 /// Br: loop if (Dec != 0) 1958 /// Use(CountPrev + Cnt0) // Use(CntPhi) 1959 /// or 1960 /// Use(Count + Cnt0) // Use(CntInst) 1961 /// 1962 /// If LOOP_BODY is empty the loop will be deleted. 1963 /// If CntInst and DefX are not used in LOOP_BODY they will be removed. 1964 void LoopIdiomRecognize::transformLoopToCountable( 1965 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst, 1966 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL, 1967 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) { 1968 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator()); 1969 1970 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block 1971 IRBuilder<> Builder(PreheaderBr); 1972 Builder.SetCurrentDebugLocation(DL); 1973 1974 // If there are no uses of CntPhi crate: 1975 // Count = BitWidth - CTLZ(InitX); 1976 // NewCount = Count; 1977 // If there are uses of CntPhi create: 1978 // NewCount = BitWidth - CTLZ(InitX >> 1); 1979 // Count = NewCount + 1; 1980 Value *InitXNext; 1981 if (IsCntPhiUsedOutsideLoop) { 1982 if (DefX->getOpcode() == Instruction::AShr) 1983 InitXNext = Builder.CreateAShr(InitX, 1); 1984 else if (DefX->getOpcode() == Instruction::LShr) 1985 InitXNext = Builder.CreateLShr(InitX, 1); 1986 else if (DefX->getOpcode() == Instruction::Shl) // cttz 1987 InitXNext = Builder.CreateShl(InitX, 1); 1988 else 1989 llvm_unreachable("Unexpected opcode!"); 1990 } else 1991 InitXNext = InitX; 1992 Value *Count = 1993 createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID); 1994 Type *CountTy = Count->getType(); 1995 Count = Builder.CreateSub( 1996 ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count); 1997 Value *NewCount = Count; 1998 if (IsCntPhiUsedOutsideLoop) 1999 Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1)); 2000 2001 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType()); 2002 2003 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader); 2004 if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) { 2005 // If the counter was being incremented in the loop, add NewCount to the 2006 // counter's initial value, but only if the initial value is not zero. 2007 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 2008 if (!InitConst || !InitConst->isZero()) 2009 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 2010 } else { 2011 // If the count was being decremented in the loop, subtract NewCount from 2012 // the counter's initial value. 2013 NewCount = Builder.CreateSub(CntInitVal, NewCount); 2014 } 2015 2016 // Step 2: Insert new IV and loop condition: 2017 // loop: 2018 // ... 2019 // PhiCount = PHI [Count, Dec] 2020 // ... 2021 // Dec = PhiCount - 1 2022 // ... 2023 // Br: loop if (Dec != 0) 2024 BasicBlock *Body = *(CurLoop->block_begin()); 2025 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 2026 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 2027 2028 PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi", &Body->front()); 2029 2030 Builder.SetInsertPoint(LbCond); 2031 Instruction *TcDec = cast<Instruction>(Builder.CreateSub( 2032 TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true)); 2033 2034 TcPhi->addIncoming(Count, Preheader); 2035 TcPhi->addIncoming(TcDec, Body); 2036 2037 CmpInst::Predicate Pred = 2038 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; 2039 LbCond->setPredicate(Pred); 2040 LbCond->setOperand(0, TcDec); 2041 LbCond->setOperand(1, ConstantInt::get(CountTy, 0)); 2042 2043 // Step 3: All the references to the original counter outside 2044 // the loop are replaced with the NewCount 2045 if (IsCntPhiUsedOutsideLoop) 2046 CntPhi->replaceUsesOutsideBlock(NewCount, Body); 2047 else 2048 CntInst->replaceUsesOutsideBlock(NewCount, Body); 2049 2050 // step 4: Forget the "non-computable" trip-count SCEV associated with the 2051 // loop. The loop would otherwise not be deleted even if it becomes empty. 2052 SE->forgetLoop(CurLoop); 2053 } 2054 2055 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, 2056 Instruction *CntInst, 2057 PHINode *CntPhi, Value *Var) { 2058 BasicBlock *PreHead = CurLoop->getLoopPreheader(); 2059 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator()); 2060 const DebugLoc &DL = CntInst->getDebugLoc(); 2061 2062 // Assuming before transformation, the loop is following: 2063 // if (x) // the precondition 2064 // do { cnt++; x &= x - 1; } while(x); 2065 2066 // Step 1: Insert the ctpop instruction at the end of the precondition block 2067 IRBuilder<> Builder(PreCondBr); 2068 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; 2069 { 2070 PopCnt = createPopcntIntrinsic(Builder, Var, DL); 2071 NewCount = PopCntZext = 2072 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); 2073 2074 if (NewCount != PopCnt) 2075 (cast<Instruction>(NewCount))->setDebugLoc(DL); 2076 2077 // TripCnt is exactly the number of iterations the loop has 2078 TripCnt = NewCount; 2079 2080 // If the population counter's initial value is not zero, insert Add Inst. 2081 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); 2082 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 2083 if (!InitConst || !InitConst->isZero()) { 2084 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 2085 (cast<Instruction>(NewCount))->setDebugLoc(DL); 2086 } 2087 } 2088 2089 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to 2090 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic 2091 // function would be partial dead code, and downstream passes will drag 2092 // it back from the precondition block to the preheader. 2093 { 2094 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); 2095 2096 Value *Opnd0 = PopCntZext; 2097 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); 2098 if (PreCond->getOperand(0) != Var) 2099 std::swap(Opnd0, Opnd1); 2100 2101 ICmpInst *NewPreCond = cast<ICmpInst>( 2102 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); 2103 PreCondBr->setCondition(NewPreCond); 2104 2105 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); 2106 } 2107 2108 // Step 3: Note that the population count is exactly the trip count of the 2109 // loop in question, which enable us to convert the loop from noncountable 2110 // loop into a countable one. The benefit is twofold: 2111 // 2112 // - If the loop only counts population, the entire loop becomes dead after 2113 // the transformation. It is a lot easier to prove a countable loop dead 2114 // than to prove a noncountable one. (In some C dialects, an infinite loop 2115 // isn't dead even if it computes nothing useful. In general, DCE needs 2116 // to prove a noncountable loop finite before safely delete it.) 2117 // 2118 // - If the loop also performs something else, it remains alive. 2119 // Since it is transformed to countable form, it can be aggressively 2120 // optimized by some optimizations which are in general not applicable 2121 // to a noncountable loop. 2122 // 2123 // After this step, this loop (conceptually) would look like following: 2124 // newcnt = __builtin_ctpop(x); 2125 // t = newcnt; 2126 // if (x) 2127 // do { cnt++; x &= x-1; t--) } while (t > 0); 2128 BasicBlock *Body = *(CurLoop->block_begin()); 2129 { 2130 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 2131 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 2132 Type *Ty = TripCnt->getType(); 2133 2134 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 2135 2136 Builder.SetInsertPoint(LbCond); 2137 Instruction *TcDec = cast<Instruction>( 2138 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 2139 "tcdec", false, true)); 2140 2141 TcPhi->addIncoming(TripCnt, PreHead); 2142 TcPhi->addIncoming(TcDec, Body); 2143 2144 CmpInst::Predicate Pred = 2145 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; 2146 LbCond->setPredicate(Pred); 2147 LbCond->setOperand(0, TcDec); 2148 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 2149 } 2150 2151 // Step 4: All the references to the original population counter outside 2152 // the loop are replaced with the NewCount -- the value returned from 2153 // __builtin_ctpop(). 2154 CntInst->replaceUsesOutsideBlock(NewCount, Body); 2155 2156 // step 5: Forget the "non-computable" trip-count SCEV associated with the 2157 // loop. The loop would otherwise not be deleted even if it becomes empty. 2158 SE->forgetLoop(CurLoop); 2159 } 2160 2161 /// Match loop-invariant value. 2162 template <typename SubPattern_t> struct match_LoopInvariant { 2163 SubPattern_t SubPattern; 2164 const Loop *L; 2165 2166 match_LoopInvariant(const SubPattern_t &SP, const Loop *L) 2167 : SubPattern(SP), L(L) {} 2168 2169 template <typename ITy> bool match(ITy *V) { 2170 return L->isLoopInvariant(V) && SubPattern.match(V); 2171 } 2172 }; 2173 2174 /// Matches if the value is loop-invariant. 2175 template <typename Ty> 2176 inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) { 2177 return match_LoopInvariant<Ty>(M, L); 2178 } 2179 2180 /// Return true if the idiom is detected in the loop. 2181 /// 2182 /// The core idiom we are trying to detect is: 2183 /// \code 2184 /// entry: 2185 /// <...> 2186 /// %bitmask = shl i32 1, %bitpos 2187 /// br label %loop 2188 /// 2189 /// loop: 2190 /// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ] 2191 /// %x.curr.bitmasked = and i32 %x.curr, %bitmask 2192 /// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0 2193 /// %x.next = shl i32 %x.curr, 1 2194 /// <...> 2195 /// br i1 %x.curr.isbitunset, label %loop, label %end 2196 /// 2197 /// end: 2198 /// %x.curr.res = phi i32 [ %x.curr, %loop ] <...> 2199 /// %x.next.res = phi i32 [ %x.next, %loop ] <...> 2200 /// <...> 2201 /// \endcode 2202 static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX, 2203 Value *&BitMask, Value *&BitPos, 2204 Value *&CurrX, Instruction *&NextX) { 2205 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2206 " Performing shift-until-bittest idiom detection.\n"); 2207 2208 // Give up if the loop has multiple blocks or multiple backedges. 2209 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) { 2210 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n"); 2211 return false; 2212 } 2213 2214 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2215 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2216 assert(LoopPreheaderBB && "There is always a loop preheader."); 2217 2218 using namespace PatternMatch; 2219 2220 // Step 1: Check if the loop backedge is in desirable form. 2221 2222 ICmpInst::Predicate Pred; 2223 Value *CmpLHS, *CmpRHS; 2224 BasicBlock *TrueBB, *FalseBB; 2225 if (!match(LoopHeaderBB->getTerminator(), 2226 m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)), 2227 m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) { 2228 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n"); 2229 return false; 2230 } 2231 2232 // Step 2: Check if the backedge's condition is in desirable form. 2233 2234 auto MatchVariableBitMask = [&]() { 2235 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) && 2236 match(CmpLHS, 2237 m_c_And(m_Value(CurrX), 2238 m_CombineAnd( 2239 m_Value(BitMask), 2240 m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)), 2241 CurLoop)))); 2242 }; 2243 auto MatchConstantBitMask = [&]() { 2244 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) && 2245 match(CmpLHS, m_And(m_Value(CurrX), 2246 m_CombineAnd(m_Value(BitMask), m_Power2()))) && 2247 (BitPos = ConstantExpr::getExactLogBase2(cast<Constant>(BitMask))); 2248 }; 2249 auto MatchDecomposableConstantBitMask = [&]() { 2250 APInt Mask; 2251 return llvm::decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, CurrX, Mask) && 2252 ICmpInst::isEquality(Pred) && Mask.isPowerOf2() && 2253 (BitMask = ConstantInt::get(CurrX->getType(), Mask)) && 2254 (BitPos = ConstantInt::get(CurrX->getType(), Mask.logBase2())); 2255 }; 2256 2257 if (!MatchVariableBitMask() && !MatchConstantBitMask() && 2258 !MatchDecomposableConstantBitMask()) { 2259 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n"); 2260 return false; 2261 } 2262 2263 // Step 3: Check if the recurrence is in desirable form. 2264 auto *CurrXPN = dyn_cast<PHINode>(CurrX); 2265 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) { 2266 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n"); 2267 return false; 2268 } 2269 2270 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB); 2271 NextX = 2272 dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB)); 2273 2274 assert(CurLoop->isLoopInvariant(BaseX) && 2275 "Expected BaseX to be avaliable in the preheader!"); 2276 2277 if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) { 2278 // FIXME: support right-shift? 2279 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n"); 2280 return false; 2281 } 2282 2283 // Step 4: Check if the backedge's destinations are in desirable form. 2284 2285 assert(ICmpInst::isEquality(Pred) && 2286 "Should only get equality predicates here."); 2287 2288 // cmp-br is commutative, so canonicalize to a single variant. 2289 if (Pred != ICmpInst::Predicate::ICMP_EQ) { 2290 Pred = ICmpInst::getInversePredicate(Pred); 2291 std::swap(TrueBB, FalseBB); 2292 } 2293 2294 // We expect to exit loop when comparison yields false, 2295 // so when it yields true we should branch back to loop header. 2296 if (TrueBB != LoopHeaderBB) { 2297 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n"); 2298 return false; 2299 } 2300 2301 // Okay, idiom checks out. 2302 return true; 2303 } 2304 2305 /// Look for the following loop: 2306 /// \code 2307 /// entry: 2308 /// <...> 2309 /// %bitmask = shl i32 1, %bitpos 2310 /// br label %loop 2311 /// 2312 /// loop: 2313 /// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ] 2314 /// %x.curr.bitmasked = and i32 %x.curr, %bitmask 2315 /// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0 2316 /// %x.next = shl i32 %x.curr, 1 2317 /// <...> 2318 /// br i1 %x.curr.isbitunset, label %loop, label %end 2319 /// 2320 /// end: 2321 /// %x.curr.res = phi i32 [ %x.curr, %loop ] <...> 2322 /// %x.next.res = phi i32 [ %x.next, %loop ] <...> 2323 /// <...> 2324 /// \endcode 2325 /// 2326 /// And transform it into: 2327 /// \code 2328 /// entry: 2329 /// %bitmask = shl i32 1, %bitpos 2330 /// %lowbitmask = add i32 %bitmask, -1 2331 /// %mask = or i32 %lowbitmask, %bitmask 2332 /// %x.masked = and i32 %x, %mask 2333 /// %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked, 2334 /// i1 true) 2335 /// %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros 2336 /// %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1 2337 /// %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos 2338 /// %tripcount = add i32 %backedgetakencount, 1 2339 /// %x.curr = shl i32 %x, %backedgetakencount 2340 /// %x.next = shl i32 %x, %tripcount 2341 /// br label %loop 2342 /// 2343 /// loop: 2344 /// %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ] 2345 /// %loop.iv.next = add nuw i32 %loop.iv, 1 2346 /// %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount 2347 /// <...> 2348 /// br i1 %loop.ivcheck, label %end, label %loop 2349 /// 2350 /// end: 2351 /// %x.curr.res = phi i32 [ %x.curr, %loop ] <...> 2352 /// %x.next.res = phi i32 [ %x.next, %loop ] <...> 2353 /// <...> 2354 /// \endcode 2355 bool LoopIdiomRecognize::recognizeShiftUntilBitTest() { 2356 bool MadeChange = false; 2357 2358 Value *X, *BitMask, *BitPos, *XCurr; 2359 Instruction *XNext; 2360 if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr, 2361 XNext)) { 2362 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2363 " shift-until-bittest idiom detection failed.\n"); 2364 return MadeChange; 2365 } 2366 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n"); 2367 2368 // Ok, it is the idiom we were looking for, we *could* transform this loop, 2369 // but is it profitable to transform? 2370 2371 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2372 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2373 assert(LoopPreheaderBB && "There is always a loop preheader."); 2374 2375 BasicBlock *SuccessorBB = CurLoop->getExitBlock(); 2376 assert(SuccessorBB && "There is only a single successor."); 2377 2378 IRBuilder<> Builder(LoopPreheaderBB->getTerminator()); 2379 Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc()); 2380 2381 Intrinsic::ID IntrID = Intrinsic::ctlz; 2382 Type *Ty = X->getType(); 2383 unsigned Bitwidth = Ty->getScalarSizeInBits(); 2384 2385 TargetTransformInfo::TargetCostKind CostKind = 2386 TargetTransformInfo::TCK_SizeAndLatency; 2387 2388 // The rewrite is considered to be unprofitable iff and only iff the 2389 // intrinsic/shift we'll use are not cheap. Note that we are okay with *just* 2390 // making the loop countable, even if nothing else changes. 2391 IntrinsicCostAttributes Attrs( 2392 IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getTrue()}); 2393 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind); 2394 if (Cost > TargetTransformInfo::TCC_Basic) { 2395 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2396 " Intrinsic is too costly, not beneficial\n"); 2397 return MadeChange; 2398 } 2399 if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) > 2400 TargetTransformInfo::TCC_Basic) { 2401 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n"); 2402 return MadeChange; 2403 } 2404 2405 // Ok, transform appears worthwhile. 2406 MadeChange = true; 2407 2408 // Step 1: Compute the loop trip count. 2409 2410 Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty), 2411 BitPos->getName() + ".lowbitmask"); 2412 Value *Mask = 2413 Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask"); 2414 Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked"); 2415 CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic( 2416 IntrID, Ty, {XMasked, /*is_zero_undef=*/Builder.getTrue()}, 2417 /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros"); 2418 Value *XMaskedNumActiveBits = Builder.CreateSub( 2419 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros, 2420 XMasked->getName() + ".numactivebits", /*HasNUW=*/true, 2421 /*HasNSW=*/Bitwidth != 2); 2422 Value *XMaskedLeadingOnePos = 2423 Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty), 2424 XMasked->getName() + ".leadingonepos", /*HasNUW=*/false, 2425 /*HasNSW=*/Bitwidth > 2); 2426 2427 Value *LoopBackedgeTakenCount = Builder.CreateSub( 2428 BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount", 2429 /*HasNUW=*/true, /*HasNSW=*/true); 2430 // We know loop's backedge-taken count, but what's loop's trip count? 2431 // Note that while NUW is always safe, while NSW is only for bitwidths != 2. 2432 Value *LoopTripCount = 2433 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1), 2434 CurLoop->getName() + ".tripcount", /*HasNUW=*/true, 2435 /*HasNSW=*/Bitwidth != 2); 2436 2437 // Step 2: Compute the recurrence's final value without a loop. 2438 2439 // NewX is always safe to compute, because `LoopBackedgeTakenCount` 2440 // will always be smaller than `bitwidth(X)`, i.e. we never get poison. 2441 Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount); 2442 NewX->takeName(XCurr); 2443 if (auto *I = dyn_cast<Instruction>(NewX)) 2444 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true); 2445 2446 Value *NewXNext; 2447 // Rewriting XNext is more complicated, however, because `X << LoopTripCount` 2448 // will be poison iff `LoopTripCount == bitwidth(X)` (which will happen 2449 // iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know 2450 // that isn't the case, we'll need to emit an alternative, safe IR. 2451 if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() || 2452 PatternMatch::match( 2453 BitPos, PatternMatch::m_SpecificInt_ICMP( 2454 ICmpInst::ICMP_NE, APInt(Ty->getScalarSizeInBits(), 2455 Ty->getScalarSizeInBits() - 1)))) 2456 NewXNext = Builder.CreateShl(X, LoopTripCount); 2457 else { 2458 // Otherwise, just additionally shift by one. It's the smallest solution, 2459 // alternatively, we could check that NewX is INT_MIN (or BitPos is ) 2460 // and select 0 instead. 2461 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1)); 2462 } 2463 2464 NewXNext->takeName(XNext); 2465 if (auto *I = dyn_cast<Instruction>(NewXNext)) 2466 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true); 2467 2468 // Step 3: Adjust the successor basic block to recieve the computed 2469 // recurrence's final value instead of the recurrence itself. 2470 2471 XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB); 2472 XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB); 2473 2474 // Step 4: Rewrite the loop into a countable form, with canonical IV. 2475 2476 // The new canonical induction variable. 2477 Builder.SetInsertPoint(&LoopHeaderBB->front()); 2478 auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv"); 2479 2480 // The induction itself. 2481 // Note that while NUW is always safe, while NSW is only for bitwidths != 2. 2482 Builder.SetInsertPoint(LoopHeaderBB->getTerminator()); 2483 auto *IVNext = 2484 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next", 2485 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2); 2486 2487 // The loop trip count check. 2488 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount, 2489 CurLoop->getName() + ".ivcheck"); 2490 Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB); 2491 LoopHeaderBB->getTerminator()->eraseFromParent(); 2492 2493 // Populate the IV PHI. 2494 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB); 2495 IV->addIncoming(IVNext, LoopHeaderBB); 2496 2497 // Step 5: Forget the "non-computable" trip-count SCEV associated with the 2498 // loop. The loop would otherwise not be deleted even if it becomes empty. 2499 2500 SE->forgetLoop(CurLoop); 2501 2502 // Other passes will take care of actually deleting the loop if possible. 2503 2504 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n"); 2505 2506 ++NumShiftUntilBitTest; 2507 return MadeChange; 2508 } 2509 2510 /// Return true if the idiom is detected in the loop. 2511 /// 2512 /// The core idiom we are trying to detect is: 2513 /// \code 2514 /// entry: 2515 /// <...> 2516 /// %start = <...> 2517 /// %extraoffset = <...> 2518 /// <...> 2519 /// br label %for.cond 2520 /// 2521 /// loop: 2522 /// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ] 2523 /// %nbits = add nsw i8 %iv, %extraoffset 2524 /// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits 2525 /// %val.shifted.iszero = icmp eq i8 %val.shifted, 0 2526 /// %iv.next = add i8 %iv, 1 2527 /// <...> 2528 /// br i1 %val.shifted.iszero, label %end, label %loop 2529 /// 2530 /// end: 2531 /// %iv.res = phi i8 [ %iv, %loop ] <...> 2532 /// %nbits.res = phi i8 [ %nbits, %loop ] <...> 2533 /// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...> 2534 /// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...> 2535 /// %iv.next.res = phi i8 [ %iv.next, %loop ] <...> 2536 /// <...> 2537 /// \endcode 2538 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, ScalarEvolution *SE, 2539 Instruction *&ValShiftedIsZero, 2540 Intrinsic::ID &IntrinID, Instruction *&IV, 2541 Value *&Start, Value *&Val, 2542 const SCEV *&ExtraOffsetExpr, 2543 bool &InvertedCond) { 2544 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2545 " Performing shift-until-zero idiom detection.\n"); 2546 2547 // Give up if the loop has multiple blocks or multiple backedges. 2548 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) { 2549 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n"); 2550 return false; 2551 } 2552 2553 Instruction *ValShifted, *NBits, *IVNext; 2554 Value *ExtraOffset; 2555 2556 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2557 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2558 assert(LoopPreheaderBB && "There is always a loop preheader."); 2559 2560 using namespace PatternMatch; 2561 2562 // Step 1: Check if the loop backedge, condition is in desirable form. 2563 2564 ICmpInst::Predicate Pred; 2565 BasicBlock *TrueBB, *FalseBB; 2566 if (!match(LoopHeaderBB->getTerminator(), 2567 m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB), 2568 m_BasicBlock(FalseBB))) || 2569 !match(ValShiftedIsZero, 2570 m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) || 2571 !ICmpInst::isEquality(Pred)) { 2572 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n"); 2573 return false; 2574 } 2575 2576 // Step 2: Check if the comparison's operand is in desirable form. 2577 // FIXME: Val could be a one-input PHI node, which we should look past. 2578 if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop), 2579 m_Instruction(NBits)))) { 2580 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n"); 2581 return false; 2582 } 2583 IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz 2584 : Intrinsic::ctlz; 2585 2586 // Step 3: Check if the shift amount is in desirable form. 2587 2588 if (match(NBits, m_c_Add(m_Instruction(IV), 2589 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) && 2590 (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap())) 2591 ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset)); 2592 else if (match(NBits, 2593 m_Sub(m_Instruction(IV), 2594 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) && 2595 NBits->hasNoSignedWrap()) 2596 ExtraOffsetExpr = SE->getSCEV(ExtraOffset); 2597 else { 2598 IV = NBits; 2599 ExtraOffsetExpr = SE->getZero(NBits->getType()); 2600 } 2601 2602 // Step 4: Check if the recurrence is in desirable form. 2603 auto *IVPN = dyn_cast<PHINode>(IV); 2604 if (!IVPN || IVPN->getParent() != LoopHeaderBB) { 2605 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n"); 2606 return false; 2607 } 2608 2609 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB); 2610 IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB)); 2611 2612 if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) { 2613 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n"); 2614 return false; 2615 } 2616 2617 // Step 4: Check if the backedge's destinations are in desirable form. 2618 2619 assert(ICmpInst::isEquality(Pred) && 2620 "Should only get equality predicates here."); 2621 2622 // cmp-br is commutative, so canonicalize to a single variant. 2623 InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ; 2624 if (InvertedCond) { 2625 Pred = ICmpInst::getInversePredicate(Pred); 2626 std::swap(TrueBB, FalseBB); 2627 } 2628 2629 // We expect to exit loop when comparison yields true, 2630 // so when it yields false we should branch back to loop header. 2631 if (FalseBB != LoopHeaderBB) { 2632 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n"); 2633 return false; 2634 } 2635 2636 // The new, countable, loop will certainly only run a known number of 2637 // iterations, It won't be infinite. But the old loop might be infinite 2638 // under certain conditions. For logical shifts, the value will become zero 2639 // after at most bitwidth(%Val) loop iterations. However, for arithmetic 2640 // right-shift, iff the sign bit was set, the value will never become zero, 2641 // and the loop may never finish. 2642 if (ValShifted->getOpcode() == Instruction::AShr && 2643 !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) { 2644 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n"); 2645 return false; 2646 } 2647 2648 // Okay, idiom checks out. 2649 return true; 2650 } 2651 2652 /// Look for the following loop: 2653 /// \code 2654 /// entry: 2655 /// <...> 2656 /// %start = <...> 2657 /// %extraoffset = <...> 2658 /// <...> 2659 /// br label %for.cond 2660 /// 2661 /// loop: 2662 /// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ] 2663 /// %nbits = add nsw i8 %iv, %extraoffset 2664 /// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits 2665 /// %val.shifted.iszero = icmp eq i8 %val.shifted, 0 2666 /// %iv.next = add i8 %iv, 1 2667 /// <...> 2668 /// br i1 %val.shifted.iszero, label %end, label %loop 2669 /// 2670 /// end: 2671 /// %iv.res = phi i8 [ %iv, %loop ] <...> 2672 /// %nbits.res = phi i8 [ %nbits, %loop ] <...> 2673 /// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...> 2674 /// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...> 2675 /// %iv.next.res = phi i8 [ %iv.next, %loop ] <...> 2676 /// <...> 2677 /// \endcode 2678 /// 2679 /// And transform it into: 2680 /// \code 2681 /// entry: 2682 /// <...> 2683 /// %start = <...> 2684 /// %extraoffset = <...> 2685 /// <...> 2686 /// %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0) 2687 /// %val.numactivebits = sub i8 8, %val.numleadingzeros 2688 /// %extraoffset.neg = sub i8 0, %extraoffset 2689 /// %tmp = add i8 %val.numactivebits, %extraoffset.neg 2690 /// %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start) 2691 /// %loop.tripcount = sub i8 %iv.final, %start 2692 /// br label %loop 2693 /// 2694 /// loop: 2695 /// %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ] 2696 /// %loop.iv.next = add i8 %loop.iv, 1 2697 /// %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount 2698 /// %iv = add i8 %loop.iv, %start 2699 /// <...> 2700 /// br i1 %loop.ivcheck, label %end, label %loop 2701 /// 2702 /// end: 2703 /// %iv.res = phi i8 [ %iv.final, %loop ] <...> 2704 /// <...> 2705 /// \endcode 2706 bool LoopIdiomRecognize::recognizeShiftUntilZero() { 2707 bool MadeChange = false; 2708 2709 Instruction *ValShiftedIsZero; 2710 Intrinsic::ID IntrID; 2711 Instruction *IV; 2712 Value *Start, *Val; 2713 const SCEV *ExtraOffsetExpr; 2714 bool InvertedCond; 2715 if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV, 2716 Start, Val, ExtraOffsetExpr, InvertedCond)) { 2717 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2718 " shift-until-zero idiom detection failed.\n"); 2719 return MadeChange; 2720 } 2721 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n"); 2722 2723 // Ok, it is the idiom we were looking for, we *could* transform this loop, 2724 // but is it profitable to transform? 2725 2726 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2727 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2728 assert(LoopPreheaderBB && "There is always a loop preheader."); 2729 2730 BasicBlock *SuccessorBB = CurLoop->getExitBlock(); 2731 assert(SuccessorBB && "There is only a single successor."); 2732 2733 IRBuilder<> Builder(LoopPreheaderBB->getTerminator()); 2734 Builder.SetCurrentDebugLocation(IV->getDebugLoc()); 2735 2736 Type *Ty = Val->getType(); 2737 unsigned Bitwidth = Ty->getScalarSizeInBits(); 2738 2739 TargetTransformInfo::TargetCostKind CostKind = 2740 TargetTransformInfo::TCK_SizeAndLatency; 2741 2742 // The rewrite is considered to be unprofitable iff and only iff the 2743 // intrinsic we'll use are not cheap. Note that we are okay with *just* 2744 // making the loop countable, even if nothing else changes. 2745 IntrinsicCostAttributes Attrs( 2746 IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getFalse()}); 2747 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind); 2748 if (Cost > TargetTransformInfo::TCC_Basic) { 2749 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2750 " Intrinsic is too costly, not beneficial\n"); 2751 return MadeChange; 2752 } 2753 2754 // Ok, transform appears worthwhile. 2755 MadeChange = true; 2756 2757 bool OffsetIsZero = false; 2758 if (auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr)) 2759 OffsetIsZero = ExtraOffsetExprC->isZero(); 2760 2761 // Step 1: Compute the loop's final IV value / trip count. 2762 2763 CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic( 2764 IntrID, Ty, {Val, /*is_zero_undef=*/Builder.getFalse()}, 2765 /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros"); 2766 Value *ValNumActiveBits = Builder.CreateSub( 2767 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros, 2768 Val->getName() + ".numactivebits", /*HasNUW=*/true, 2769 /*HasNSW=*/Bitwidth != 2); 2770 2771 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 2772 Expander.setInsertPoint(&*Builder.GetInsertPoint()); 2773 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr); 2774 2775 Value *ValNumActiveBitsOffset = Builder.CreateAdd( 2776 ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset", 2777 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true); 2778 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty}, 2779 {ValNumActiveBitsOffset, Start}, 2780 /*FMFSource=*/nullptr, "iv.final"); 2781 2782 auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub( 2783 IVFinal, Start, CurLoop->getName() + ".backedgetakencount", 2784 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true)); 2785 // FIXME: or when the offset was `add nuw` 2786 2787 // We know loop's backedge-taken count, but what's loop's trip count? 2788 Value *LoopTripCount = 2789 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1), 2790 CurLoop->getName() + ".tripcount", /*HasNUW=*/true, 2791 /*HasNSW=*/Bitwidth != 2); 2792 2793 // Step 2: Adjust the successor basic block to recieve the original 2794 // induction variable's final value instead of the orig. IV itself. 2795 2796 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB); 2797 2798 // Step 3: Rewrite the loop into a countable form, with canonical IV. 2799 2800 // The new canonical induction variable. 2801 Builder.SetInsertPoint(&LoopHeaderBB->front()); 2802 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv"); 2803 2804 // The induction itself. 2805 Builder.SetInsertPoint(LoopHeaderBB->getFirstNonPHI()); 2806 auto *CIVNext = 2807 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next", 2808 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2); 2809 2810 // The loop trip count check. 2811 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount, 2812 CurLoop->getName() + ".ivcheck"); 2813 auto *NewIVCheck = CIVCheck; 2814 if (InvertedCond) { 2815 NewIVCheck = Builder.CreateNot(CIVCheck); 2816 NewIVCheck->takeName(ValShiftedIsZero); 2817 } 2818 2819 // The original IV, but rebased to be an offset to the CIV. 2820 auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false, 2821 /*HasNSW=*/true); // FIXME: what about NUW? 2822 IVDePHId->takeName(IV); 2823 2824 // The loop terminator. 2825 Builder.SetInsertPoint(LoopHeaderBB->getTerminator()); 2826 Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB); 2827 LoopHeaderBB->getTerminator()->eraseFromParent(); 2828 2829 // Populate the IV PHI. 2830 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB); 2831 CIV->addIncoming(CIVNext, LoopHeaderBB); 2832 2833 // Step 4: Forget the "non-computable" trip-count SCEV associated with the 2834 // loop. The loop would otherwise not be deleted even if it becomes empty. 2835 2836 SE->forgetLoop(CurLoop); 2837 2838 // Step 5: Try to cleanup the loop's body somewhat. 2839 IV->replaceAllUsesWith(IVDePHId); 2840 IV->eraseFromParent(); 2841 2842 ValShiftedIsZero->replaceAllUsesWith(NewIVCheck); 2843 ValShiftedIsZero->eraseFromParent(); 2844 2845 // Other passes will take care of actually deleting the loop if possible. 2846 2847 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n"); 2848 2849 ++NumShiftUntilZero; 2850 return MadeChange; 2851 } 2852