1 //===-- HardwareLoops.cpp - Target Independent Hardware Loops --*- C++ -*-===// 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 /// \file 9 /// Insert hardware loop intrinsics into loops which are deemed profitable by 10 /// the target, by querying TargetTransformInfo. A hardware loop comprises of 11 /// two intrinsics: one, outside the loop, to set the loop iteration count and 12 /// another, in the exit block, to decrement the counter. The decremented value 13 /// can either be carried through the loop via a phi or handled in some opaque 14 /// way by the target. 15 /// 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Pass.h" 19 #include "llvm/PassRegistry.h" 20 #include "llvm/PassSupport.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AssumptionCache.h" 23 #include "llvm/Analysis/LoopInfo.h" 24 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Analysis/ScalarEvolutionExpander.h" 27 #include "llvm/Analysis/TargetTransformInfo.h" 28 #include "llvm/CodeGen/Passes.h" 29 #include "llvm/CodeGen/TargetPassConfig.h" 30 #include "llvm/IR/BasicBlock.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/IRBuilder.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/Value.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Transforms/Scalar.h" 40 #include "llvm/Transforms/Utils.h" 41 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 42 #include "llvm/Transforms/Utils/Local.h" 43 #include "llvm/Transforms/Utils/LoopUtils.h" 44 45 #define DEBUG_TYPE "hardware-loops" 46 47 #define HW_LOOPS_NAME "Hardware Loop Insertion" 48 49 using namespace llvm; 50 51 static cl::opt<bool> 52 ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false), 53 cl::desc("Force hardware loops intrinsics to be inserted")); 54 55 static cl::opt<bool> 56 ForceHardwareLoopPHI( 57 "force-hardware-loop-phi", cl::Hidden, cl::init(false), 58 cl::desc("Force hardware loop counter to be updated through a phi")); 59 60 static cl::opt<bool> 61 ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false), 62 cl::desc("Force allowance of nested hardware loops")); 63 64 static cl::opt<unsigned> 65 LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1), 66 cl::desc("Set the loop decrement value")); 67 68 static cl::opt<unsigned> 69 CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32), 70 cl::desc("Set the loop counter bitwidth")); 71 72 static cl::opt<bool> 73 ForceGuardLoopEntry( 74 "force-hardware-loop-guard", cl::Hidden, cl::init(false), 75 cl::desc("Force generation of loop guard intrinsic")); 76 77 STATISTIC(NumHWLoops, "Number of loops converted to hardware loops"); 78 79 #ifndef NDEBUG 80 static void debugHWLoopFailure(const StringRef DebugMsg, 81 Instruction *I) { 82 dbgs() << "HWLoops: " << DebugMsg; 83 if (I) 84 dbgs() << ' ' << *I; 85 else 86 dbgs() << '.'; 87 dbgs() << '\n'; 88 } 89 #endif 90 91 static OptimizationRemarkAnalysis 92 createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I) { 93 Value *CodeRegion = L->getHeader(); 94 DebugLoc DL = L->getStartLoc(); 95 96 if (I) { 97 CodeRegion = I->getParent(); 98 // If there is no debug location attached to the instruction, revert back to 99 // using the loop's. 100 if (I->getDebugLoc()) 101 DL = I->getDebugLoc(); 102 } 103 104 OptimizationRemarkAnalysis R(DEBUG_TYPE, RemarkName, DL, CodeRegion); 105 R << "hardware-loop not created: "; 106 return R; 107 } 108 109 namespace { 110 111 void reportHWLoopFailure(const StringRef Msg, const StringRef ORETag, 112 OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I = nullptr) { 113 LLVM_DEBUG(debugHWLoopFailure(Msg, I)); 114 ORE->emit(createHWLoopAnalysis(ORETag, TheLoop, I) << Msg); 115 } 116 117 using TTI = TargetTransformInfo; 118 119 class HardwareLoops : public FunctionPass { 120 public: 121 static char ID; 122 123 HardwareLoops() : FunctionPass(ID) { 124 initializeHardwareLoopsPass(*PassRegistry::getPassRegistry()); 125 } 126 127 bool runOnFunction(Function &F) override; 128 129 void getAnalysisUsage(AnalysisUsage &AU) const override { 130 AU.addRequired<LoopInfoWrapperPass>(); 131 AU.addPreserved<LoopInfoWrapperPass>(); 132 AU.addRequired<DominatorTreeWrapperPass>(); 133 AU.addPreserved<DominatorTreeWrapperPass>(); 134 AU.addRequired<ScalarEvolutionWrapperPass>(); 135 AU.addRequired<AssumptionCacheTracker>(); 136 AU.addRequired<TargetTransformInfoWrapperPass>(); 137 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 138 } 139 140 // Try to convert the given Loop into a hardware loop. 141 bool TryConvertLoop(Loop *L); 142 143 // Given that the target believes the loop to be profitable, try to 144 // convert it. 145 bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo); 146 147 private: 148 ScalarEvolution *SE = nullptr; 149 LoopInfo *LI = nullptr; 150 const DataLayout *DL = nullptr; 151 OptimizationRemarkEmitter *ORE = nullptr; 152 const TargetTransformInfo *TTI = nullptr; 153 DominatorTree *DT = nullptr; 154 bool PreserveLCSSA = false; 155 AssumptionCache *AC = nullptr; 156 TargetLibraryInfo *LibInfo = nullptr; 157 Module *M = nullptr; 158 bool MadeChange = false; 159 }; 160 161 class HardwareLoop { 162 // Expand the trip count scev into a value that we can use. 163 Value *InitLoopCount(); 164 165 // Insert the set_loop_iteration intrinsic. 166 void InsertIterationSetup(Value *LoopCountInit); 167 168 // Insert the loop_decrement intrinsic. 169 void InsertLoopDec(); 170 171 // Insert the loop_decrement_reg intrinsic. 172 Instruction *InsertLoopRegDec(Value *EltsRem); 173 174 // If the target requires the counter value to be updated in the loop, 175 // insert a phi to hold the value. The intended purpose is for use by 176 // loop_decrement_reg. 177 PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem); 178 179 // Create a new cmp, that checks the returned value of loop_decrement*, 180 // and update the exit branch to use it. 181 void UpdateBranch(Value *EltsRem); 182 183 public: 184 HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE, 185 const DataLayout &DL, 186 OptimizationRemarkEmitter *ORE) : 187 SE(SE), DL(DL), ORE(ORE), L(Info.L), M(L->getHeader()->getModule()), 188 ExitCount(Info.ExitCount), 189 CountType(Info.CountType), 190 ExitBranch(Info.ExitBranch), 191 LoopDecrement(Info.LoopDecrement), 192 UsePHICounter(Info.CounterInReg), 193 UseLoopGuard(Info.PerformEntryTest) { } 194 195 void Create(); 196 197 private: 198 ScalarEvolution &SE; 199 const DataLayout &DL; 200 OptimizationRemarkEmitter *ORE = nullptr; 201 Loop *L = nullptr; 202 Module *M = nullptr; 203 const SCEV *ExitCount = nullptr; 204 Type *CountType = nullptr; 205 BranchInst *ExitBranch = nullptr; 206 Value *LoopDecrement = nullptr; 207 bool UsePHICounter = false; 208 bool UseLoopGuard = false; 209 BasicBlock *BeginBB = nullptr; 210 }; 211 } 212 213 char HardwareLoops::ID = 0; 214 215 bool HardwareLoops::runOnFunction(Function &F) { 216 if (skipFunction(F)) 217 return false; 218 219 LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n"); 220 221 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 222 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 223 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 224 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 225 DL = &F.getParent()->getDataLayout(); 226 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 227 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 228 LibInfo = TLIP ? &TLIP->getTLI(F) : nullptr; 229 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 230 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 231 M = F.getParent(); 232 233 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) { 234 Loop *L = *I; 235 if (!L->getParentLoop()) 236 TryConvertLoop(L); 237 } 238 239 return MadeChange; 240 } 241 242 // Return true if the search should stop, which will be when an inner loop is 243 // converted and the parent loop doesn't support containing a hardware loop. 244 bool HardwareLoops::TryConvertLoop(Loop *L) { 245 // Process nested loops first. 246 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) { 247 if (TryConvertLoop(*I)) { 248 reportHWLoopFailure("nested hardware-loops not supported", "HWLoopNested", 249 ORE, L); 250 return true; // Stop search. 251 } 252 } 253 254 HardwareLoopInfo HWLoopInfo(L); 255 if (!HWLoopInfo.canAnalyze(*LI)) { 256 reportHWLoopFailure("cannot analyze loop, irreducible control flow", 257 "HWLoopCannotAnalyze", ORE, L); 258 return false; 259 } 260 261 if (!ForceHardwareLoops && 262 !TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) { 263 reportHWLoopFailure("it's not profitable to create a hardware-loop", 264 "HWLoopNotProfitable", ORE, L); 265 return false; 266 } 267 268 // Allow overriding of the counter width and loop decrement value. 269 if (CounterBitWidth.getNumOccurrences()) 270 HWLoopInfo.CountType = 271 IntegerType::get(M->getContext(), CounterBitWidth); 272 273 if (LoopDecrement.getNumOccurrences()) 274 HWLoopInfo.LoopDecrement = 275 ConstantInt::get(HWLoopInfo.CountType, LoopDecrement); 276 277 MadeChange |= TryConvertLoop(HWLoopInfo); 278 return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop); 279 } 280 281 bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) { 282 283 Loop *L = HWLoopInfo.L; 284 LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L); 285 286 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop, 287 ForceHardwareLoopPHI)) { 288 // TODO: there can be many reasons a loop is not considered a 289 // candidate, so we should let isHardwareLoopCandidate fill in the 290 // reason and then report a better message here. 291 reportHWLoopFailure("loop is not a candidate", "HWLoopNoCandidate", ORE, L); 292 return false; 293 } 294 295 assert( 296 (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) && 297 "Hardware Loop must have set exit info."); 298 299 BasicBlock *Preheader = L->getLoopPreheader(); 300 301 // If we don't have a preheader, then insert one. 302 if (!Preheader) 303 Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA); 304 if (!Preheader) 305 return false; 306 307 HardwareLoop HWLoop(HWLoopInfo, *SE, *DL, ORE); 308 HWLoop.Create(); 309 ++NumHWLoops; 310 return true; 311 } 312 313 void HardwareLoop::Create() { 314 LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n"); 315 316 Value *LoopCountInit = InitLoopCount(); 317 if (!LoopCountInit) { 318 reportHWLoopFailure("could not safely create a loop count expression", 319 "HWLoopNotSafe", ORE, L); 320 return; 321 } 322 323 InsertIterationSetup(LoopCountInit); 324 325 if (UsePHICounter || ForceHardwareLoopPHI) { 326 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit); 327 Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec); 328 LoopDec->setOperand(0, EltsRem); 329 UpdateBranch(LoopDec); 330 } else 331 InsertLoopDec(); 332 333 // Run through the basic blocks of the loop and see if any of them have dead 334 // PHIs that can be removed. 335 for (auto I : L->blocks()) 336 DeleteDeadPHIs(I); 337 } 338 339 static bool CanGenerateTest(Loop *L, Value *Count) { 340 BasicBlock *Preheader = L->getLoopPreheader(); 341 if (!Preheader->getSinglePredecessor()) 342 return false; 343 344 BasicBlock *Pred = Preheader->getSinglePredecessor(); 345 if (!isa<BranchInst>(Pred->getTerminator())) 346 return false; 347 348 auto *BI = cast<BranchInst>(Pred->getTerminator()); 349 if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition())) 350 return false; 351 352 // Check that the icmp is checking for equality of Count and zero and that 353 // a non-zero value results in entering the loop. 354 auto ICmp = cast<ICmpInst>(BI->getCondition()); 355 LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n"); 356 if (!ICmp->isEquality()) 357 return false; 358 359 auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) { 360 if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx))) 361 return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count; 362 return false; 363 }; 364 365 if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1)) 366 return false; 367 368 unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1; 369 if (BI->getSuccessor(SuccIdx) != Preheader) 370 return false; 371 372 return true; 373 } 374 375 Value *HardwareLoop::InitLoopCount() { 376 LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n"); 377 // Can we replace a conditional branch with an intrinsic that sets the 378 // loop counter and tests that is not zero? 379 380 SCEVExpander SCEVE(SE, DL, "loopcnt"); 381 if (!ExitCount->getType()->isPointerTy() && 382 ExitCount->getType() != CountType) 383 ExitCount = SE.getZeroExtendExpr(ExitCount, CountType); 384 385 ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType)); 386 387 // If we're trying to use the 'test and set' form of the intrinsic, we need 388 // to replace a conditional branch that is controlling entry to the loop. It 389 // is likely (guaranteed?) that the preheader has an unconditional branch to 390 // the loop header, so also check if it has a single predecessor. 391 if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount, 392 SE.getZero(ExitCount->getType()))) { 393 LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n"); 394 UseLoopGuard |= ForceGuardLoopEntry; 395 } else 396 UseLoopGuard = false; 397 398 BasicBlock *BB = L->getLoopPreheader(); 399 if (UseLoopGuard && BB->getSinglePredecessor() && 400 cast<BranchInst>(BB->getTerminator())->isUnconditional()) 401 BB = BB->getSinglePredecessor(); 402 403 if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) { 404 LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand ExitCount " 405 << *ExitCount << "\n"); 406 return nullptr; 407 } 408 409 Value *Count = SCEVE.expandCodeFor(ExitCount, CountType, 410 BB->getTerminator()); 411 412 // FIXME: We've expanded Count where we hope to insert the counter setting 413 // intrinsic. But, in the case of the 'test and set' form, we may fallback to 414 // the just 'set' form and in which case the insertion block is most likely 415 // different. It means there will be instruction(s) in a block that possibly 416 // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue, 417 // but it's doesn't appear to work in all cases. 418 419 UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count); 420 BeginBB = UseLoopGuard ? BB : L->getLoopPreheader(); 421 LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n" 422 << " - Expanded Count in " << BB->getName() << "\n" 423 << " - Will insert set counter intrinsic into: " 424 << BeginBB->getName() << "\n"); 425 return Count; 426 } 427 428 void HardwareLoop::InsertIterationSetup(Value *LoopCountInit) { 429 IRBuilder<> Builder(BeginBB->getTerminator()); 430 Type *Ty = LoopCountInit->getType(); 431 Intrinsic::ID ID = UseLoopGuard ? 432 Intrinsic::test_set_loop_iterations : Intrinsic::set_loop_iterations; 433 Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty); 434 Value *SetCount = Builder.CreateCall(LoopIter, LoopCountInit); 435 436 // Use the return value of the intrinsic to control the entry of the loop. 437 if (UseLoopGuard) { 438 assert((isa<BranchInst>(BeginBB->getTerminator()) && 439 cast<BranchInst>(BeginBB->getTerminator())->isConditional()) && 440 "Expected conditional branch"); 441 auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator()); 442 LoopGuard->setCondition(SetCount); 443 if (LoopGuard->getSuccessor(0) != L->getLoopPreheader()) 444 LoopGuard->swapSuccessors(); 445 } 446 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: " 447 << *SetCount << "\n"); 448 } 449 450 void HardwareLoop::InsertLoopDec() { 451 IRBuilder<> CondBuilder(ExitBranch); 452 453 Function *DecFunc = 454 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement, 455 LoopDecrement->getType()); 456 Value *Ops[] = { LoopDecrement }; 457 Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops); 458 Value *OldCond = ExitBranch->getCondition(); 459 ExitBranch->setCondition(NewCond); 460 461 // The false branch must exit the loop. 462 if (!L->contains(ExitBranch->getSuccessor(0))) 463 ExitBranch->swapSuccessors(); 464 465 // The old condition may be dead now, and may have even created a dead PHI 466 // (the original induction variable). 467 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 468 469 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n"); 470 } 471 472 Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) { 473 IRBuilder<> CondBuilder(ExitBranch); 474 475 Function *DecFunc = 476 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg, 477 { EltsRem->getType(), EltsRem->getType(), 478 LoopDecrement->getType() 479 }); 480 Value *Ops[] = { EltsRem, LoopDecrement }; 481 Value *Call = CondBuilder.CreateCall(DecFunc, Ops); 482 483 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n"); 484 return cast<Instruction>(Call); 485 } 486 487 PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) { 488 BasicBlock *Preheader = L->getLoopPreheader(); 489 BasicBlock *Header = L->getHeader(); 490 BasicBlock *Latch = ExitBranch->getParent(); 491 IRBuilder<> Builder(Header->getFirstNonPHI()); 492 PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2); 493 Index->addIncoming(NumElts, Preheader); 494 Index->addIncoming(EltsRem, Latch); 495 LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n"); 496 return Index; 497 } 498 499 void HardwareLoop::UpdateBranch(Value *EltsRem) { 500 IRBuilder<> CondBuilder(ExitBranch); 501 Value *NewCond = 502 CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0)); 503 Value *OldCond = ExitBranch->getCondition(); 504 ExitBranch->setCondition(NewCond); 505 506 // The false branch must exit the loop. 507 if (!L->contains(ExitBranch->getSuccessor(0))) 508 ExitBranch->swapSuccessors(); 509 510 // The old condition may be dead now, and may have even created a dead PHI 511 // (the original induction variable). 512 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 513 } 514 515 INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 516 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 517 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 518 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 519 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 520 INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 521 522 FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); } 523