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/CFG.h" 24 #include "llvm/Analysis/LoopInfo.h" 25 #include "llvm/Analysis/LoopIterator.h" 26 #include "llvm/Analysis/ScalarEvolution.h" 27 #include "llvm/Analysis/ScalarEvolutionExpander.h" 28 #include "llvm/Analysis/TargetTransformInfo.h" 29 #include "llvm/CodeGen/Passes.h" 30 #include "llvm/CodeGen/TargetPassConfig.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/Dominators.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/IRBuilder.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Transforms/Scalar.h" 41 #include "llvm/Transforms/Utils.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 #include "llvm/Transforms/Utils/Local.h" 44 #include "llvm/Transforms/Utils/LoopUtils.h" 45 46 #define DEBUG_TYPE "hardware-loops" 47 48 #define HW_LOOPS_NAME "Hardware Loop Insertion" 49 50 using namespace llvm; 51 52 static cl::opt<bool> 53 ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false), 54 cl::desc("Force hardware loops intrinsics to be inserted")); 55 56 static cl::opt<bool> 57 ForceHardwareLoopPHI( 58 "force-hardware-loop-phi", cl::Hidden, cl::init(false), 59 cl::desc("Force hardware loop counter to be updated through a phi")); 60 61 static cl::opt<bool> 62 ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false), 63 cl::desc("Force allowance of nested hardware loops")); 64 65 static cl::opt<unsigned> 66 LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1), 67 cl::desc("Set the loop decrement value")); 68 69 static cl::opt<unsigned> 70 CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32), 71 cl::desc("Set the loop counter bitwidth")); 72 73 STATISTIC(NumHWLoops, "Number of loops converted to hardware loops"); 74 75 namespace { 76 77 using TTI = TargetTransformInfo; 78 79 class HardwareLoops : public FunctionPass { 80 public: 81 static char ID; 82 83 HardwareLoops() : FunctionPass(ID) { 84 initializeHardwareLoopsPass(*PassRegistry::getPassRegistry()); 85 } 86 87 bool runOnFunction(Function &F) override; 88 89 void getAnalysisUsage(AnalysisUsage &AU) const override { 90 AU.addRequired<LoopInfoWrapperPass>(); 91 AU.addPreserved<LoopInfoWrapperPass>(); 92 AU.addRequired<DominatorTreeWrapperPass>(); 93 AU.addPreserved<DominatorTreeWrapperPass>(); 94 AU.addRequired<ScalarEvolutionWrapperPass>(); 95 AU.addRequired<AssumptionCacheTracker>(); 96 AU.addRequired<TargetTransformInfoWrapperPass>(); 97 } 98 99 // Try to convert the given Loop into a hardware loop. 100 bool TryConvertLoop(Loop *L); 101 102 // Given that the target believes the loop to be profitable, try to 103 // convert it. 104 bool TryConvertLoop(TTI::HardwareLoopInfo &HWLoopInfo); 105 106 private: 107 ScalarEvolution *SE = nullptr; 108 LoopInfo *LI = nullptr; 109 const DataLayout *DL = nullptr; 110 const TargetTransformInfo *TTI = nullptr; 111 DominatorTree *DT = nullptr; 112 bool PreserveLCSSA = false; 113 AssumptionCache *AC = nullptr; 114 TargetLibraryInfo *LibInfo = nullptr; 115 Module *M = nullptr; 116 bool MadeChange = false; 117 }; 118 119 class HardwareLoop { 120 // Expand the trip count scev into a value that we can use. 121 Value *InitLoopCount(BasicBlock *BB); 122 123 // Insert the set_loop_iteration intrinsic. 124 void InsertIterationSetup(Value *LoopCountInit, BasicBlock *BB); 125 126 // Insert the loop_decrement intrinsic. 127 void InsertLoopDec(); 128 129 // Insert the loop_decrement_reg intrinsic. 130 Instruction *InsertLoopRegDec(Value *EltsRem); 131 132 // If the target requires the counter value to be updated in the loop, 133 // insert a phi to hold the value. The intended purpose is for use by 134 // loop_decrement_reg. 135 PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem); 136 137 // Create a new cmp, that checks the returned value of loop_decrement*, 138 // and update the exit branch to use it. 139 void UpdateBranch(Value *EltsRem); 140 141 public: 142 HardwareLoop(TTI::HardwareLoopInfo &Info, ScalarEvolution &SE, 143 const DataLayout &DL) : 144 SE(SE), DL(DL), L(Info.L), M(L->getHeader()->getModule()), 145 ExitCount(Info.ExitCount), 146 CountType(Info.CountType), 147 ExitBranch(Info.ExitBranch), 148 LoopDecrement(Info.LoopDecrement), 149 UsePHICounter(Info.CounterInReg) { } 150 151 void Create(); 152 153 private: 154 ScalarEvolution &SE; 155 const DataLayout &DL; 156 Loop *L = nullptr; 157 Module *M = nullptr; 158 const SCEV *ExitCount = nullptr; 159 Type *CountType = nullptr; 160 BranchInst *ExitBranch = nullptr; 161 Value *LoopDecrement = nullptr; 162 bool UsePHICounter = false; 163 }; 164 } 165 166 char HardwareLoops::ID = 0; 167 168 bool HardwareLoops::runOnFunction(Function &F) { 169 if (skipFunction(F)) 170 return false; 171 172 LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n"); 173 174 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 175 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 176 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 177 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 178 DL = &F.getParent()->getDataLayout(); 179 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 180 LibInfo = TLIP ? &TLIP->getTLI() : nullptr; 181 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 182 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 183 M = F.getParent(); 184 185 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) { 186 Loop *L = *I; 187 if (!L->getParentLoop()) 188 TryConvertLoop(L); 189 } 190 191 return MadeChange; 192 } 193 194 // Return true if the search should stop, which will be when an inner loop is 195 // converted and the parent loop doesn't support containing a hardware loop. 196 bool HardwareLoops::TryConvertLoop(Loop *L) { 197 // Process nested loops first. 198 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 199 if (TryConvertLoop(*I)) 200 return true; // Stop search. 201 202 // Bail out if the loop has irreducible control flow. 203 LoopBlocksRPO RPOT(L); 204 RPOT.perform(LI); 205 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) 206 return false; 207 208 TTI::HardwareLoopInfo HWLoopInfo(L); 209 if (TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo) || 210 ForceHardwareLoops) { 211 212 // Allow overriding of the counter width and loop decrement value. 213 if (CounterBitWidth.getNumOccurrences()) 214 HWLoopInfo.CountType = 215 IntegerType::get(M->getContext(), CounterBitWidth); 216 217 if (LoopDecrement.getNumOccurrences()) 218 HWLoopInfo.LoopDecrement = 219 ConstantInt::get(HWLoopInfo.CountType, LoopDecrement); 220 221 MadeChange |= TryConvertLoop(HWLoopInfo); 222 return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop); 223 } 224 225 return false; 226 } 227 228 bool HardwareLoops::TryConvertLoop(TTI::HardwareLoopInfo &HWLoopInfo) { 229 230 Loop *L = HWLoopInfo.L; 231 LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L); 232 233 SmallVector<BasicBlock*, 4> ExitingBlocks; 234 L->getExitingBlocks(ExitingBlocks); 235 236 for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(), 237 IE = ExitingBlocks.end(); I != IE; ++I) { 238 BasicBlock *BB = *I; 239 240 // If we pass the updated counter back through a phi, we need to know 241 // which latch the updated value will be coming from. 242 if (!L->isLoopLatch(BB)) { 243 if ((ForceHardwareLoopPHI.getNumOccurrences() && ForceHardwareLoopPHI) || 244 HWLoopInfo.CounterInReg) 245 continue; 246 } 247 248 const SCEV *EC = SE->getExitCount(L, BB); 249 if (isa<SCEVCouldNotCompute>(EC)) 250 continue; 251 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) { 252 if (ConstEC->getValue()->isZero()) 253 continue; 254 } else if (!SE->isLoopInvariant(EC, L)) 255 continue; 256 257 if (SE->getTypeSizeInBits(EC->getType()) > 258 HWLoopInfo.CountType->getBitWidth()) 259 continue; 260 261 // If this exiting block is contained in a nested loop, it is not eligible 262 // for insertion of the branch-and-decrement since the inner loop would 263 // end up messing up the value in the CTR. 264 if (!HWLoopInfo.IsNestingLegal && LI->getLoopFor(BB) != L && 265 !ForceNestedLoop) 266 continue; 267 268 // We now have a loop-invariant count of loop iterations (which is not the 269 // constant zero) for which we know that this loop will not exit via this 270 // existing block. 271 272 // We need to make sure that this block will run on every loop iteration. 273 // For this to be true, we must dominate all blocks with backedges. Such 274 // blocks are in-loop predecessors to the header block. 275 bool NotAlways = false; 276 for (pred_iterator PI = pred_begin(L->getHeader()), 277 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) { 278 if (!L->contains(*PI)) 279 continue; 280 281 if (!DT->dominates(*I, *PI)) { 282 NotAlways = true; 283 break; 284 } 285 } 286 287 if (NotAlways) 288 continue; 289 290 // Make sure this blocks ends with a conditional branch. 291 Instruction *TI = BB->getTerminator(); 292 if (!TI) 293 continue; 294 295 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 296 if (!BI->isConditional()) 297 continue; 298 299 HWLoopInfo.ExitBranch = BI; 300 } else 301 continue; 302 303 // Note that this block may not be the loop latch block, even if the loop 304 // has a latch block. 305 HWLoopInfo.ExitBlock = *I; 306 HWLoopInfo.ExitCount = EC; 307 break; 308 } 309 310 if (!HWLoopInfo.ExitBlock) 311 return false; 312 313 BasicBlock *Preheader = L->getLoopPreheader(); 314 315 // If we don't have a preheader, then insert one. 316 if (!Preheader) 317 Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA); 318 if (!Preheader) 319 return false; 320 321 HardwareLoop HWLoop(HWLoopInfo, *SE, *DL); 322 HWLoop.Create(); 323 ++NumHWLoops; 324 return true; 325 } 326 327 void HardwareLoop::Create() { 328 LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n"); 329 BasicBlock *BeginBB = L->getLoopPreheader(); 330 Value *LoopCountInit = InitLoopCount(BeginBB); 331 if (!LoopCountInit) 332 return; 333 334 InsertIterationSetup(LoopCountInit, BeginBB); 335 336 if (UsePHICounter || ForceHardwareLoopPHI) { 337 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit); 338 Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec); 339 LoopDec->setOperand(0, EltsRem); 340 UpdateBranch(LoopDec); 341 } else 342 InsertLoopDec(); 343 344 // Run through the basic blocks of the loop and see if any of them have dead 345 // PHIs that can be removed. 346 for (auto I : L->blocks()) 347 DeleteDeadPHIs(I); 348 } 349 350 Value *HardwareLoop::InitLoopCount(BasicBlock *BB) { 351 SCEVExpander SCEVE(SE, DL, "loopcnt"); 352 if (!ExitCount->getType()->isPointerTy() && 353 ExitCount->getType() != CountType) 354 ExitCount = SE.getZeroExtendExpr(ExitCount, CountType); 355 356 ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType)); 357 358 if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) { 359 LLVM_DEBUG(dbgs() << "HWLoops: Bailing, unsafe to expand ExitCount " 360 << *ExitCount << "\n"); 361 return nullptr; 362 } 363 364 Value *Count = SCEVE.expandCodeFor(ExitCount, CountType, 365 BB->getTerminator()); 366 LLVM_DEBUG(dbgs() << "HWLoops: Loop Count: " << *Count << "\n"); 367 return Count; 368 } 369 370 void HardwareLoop::InsertIterationSetup(Value *LoopCountInit, 371 BasicBlock *BB) { 372 IRBuilder<> Builder(BB->getTerminator()); 373 Type *Ty = LoopCountInit->getType(); 374 Function *LoopIter = 375 Intrinsic::getDeclaration(M, Intrinsic::set_loop_iterations, Ty); 376 Builder.CreateCall(LoopIter, LoopCountInit); 377 } 378 379 void HardwareLoop::InsertLoopDec() { 380 IRBuilder<> CondBuilder(ExitBranch); 381 382 Function *DecFunc = 383 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement, 384 LoopDecrement->getType()); 385 Value *Ops[] = { LoopDecrement }; 386 Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops); 387 Value *OldCond = ExitBranch->getCondition(); 388 ExitBranch->setCondition(NewCond); 389 390 // The false branch must exit the loop. 391 if (!L->contains(ExitBranch->getSuccessor(0))) 392 ExitBranch->swapSuccessors(); 393 394 // The old condition may be dead now, and may have even created a dead PHI 395 // (the original induction variable). 396 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 397 398 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n"); 399 } 400 401 Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) { 402 IRBuilder<> CondBuilder(ExitBranch); 403 404 Function *DecFunc = 405 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg, 406 { EltsRem->getType(), EltsRem->getType(), 407 LoopDecrement->getType() 408 }); 409 Value *Ops[] = { EltsRem, LoopDecrement }; 410 Value *Call = CondBuilder.CreateCall(DecFunc, Ops); 411 412 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n"); 413 return cast<Instruction>(Call); 414 } 415 416 PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) { 417 BasicBlock *Preheader = L->getLoopPreheader(); 418 BasicBlock *Header = L->getHeader(); 419 BasicBlock *Latch = ExitBranch->getParent(); 420 IRBuilder<> Builder(Header->getFirstNonPHI()); 421 PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2); 422 Index->addIncoming(NumElts, Preheader); 423 Index->addIncoming(EltsRem, Latch); 424 LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n"); 425 return Index; 426 } 427 428 void HardwareLoop::UpdateBranch(Value *EltsRem) { 429 IRBuilder<> CondBuilder(ExitBranch); 430 Value *NewCond = 431 CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0)); 432 Value *OldCond = ExitBranch->getCondition(); 433 ExitBranch->setCondition(NewCond); 434 435 // The false branch must exit the loop. 436 if (!L->contains(ExitBranch->getSuccessor(0))) 437 ExitBranch->swapSuccessors(); 438 439 // The old condition may be dead now, and may have even created a dead PHI 440 // (the original induction variable). 441 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 442 } 443 444 INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 445 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 446 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 447 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 448 INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 449 450 FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); } 451