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(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(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 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(HardwareLoopInfo &HWLoopInfo) { 229 230 Loop *L = HWLoopInfo.L; 231 LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L); 232 233 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop, 234 ForceHardwareLoopPHI)) 235 return false; 236 237 assert( 238 (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) && 239 "Hardware Loop must have set exit info."); 240 241 BasicBlock *Preheader = L->getLoopPreheader(); 242 243 // If we don't have a preheader, then insert one. 244 if (!Preheader) 245 Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA); 246 if (!Preheader) 247 return false; 248 249 HardwareLoop HWLoop(HWLoopInfo, *SE, *DL); 250 HWLoop.Create(); 251 ++NumHWLoops; 252 return true; 253 } 254 255 void HardwareLoop::Create() { 256 LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n"); 257 BasicBlock *BeginBB = L->getLoopPreheader(); 258 Value *LoopCountInit = InitLoopCount(BeginBB); 259 if (!LoopCountInit) 260 return; 261 262 InsertIterationSetup(LoopCountInit, BeginBB); 263 264 if (UsePHICounter || ForceHardwareLoopPHI) { 265 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit); 266 Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec); 267 LoopDec->setOperand(0, EltsRem); 268 UpdateBranch(LoopDec); 269 } else 270 InsertLoopDec(); 271 272 // Run through the basic blocks of the loop and see if any of them have dead 273 // PHIs that can be removed. 274 for (auto I : L->blocks()) 275 DeleteDeadPHIs(I); 276 } 277 278 Value *HardwareLoop::InitLoopCount(BasicBlock *BB) { 279 SCEVExpander SCEVE(SE, DL, "loopcnt"); 280 if (!ExitCount->getType()->isPointerTy() && 281 ExitCount->getType() != CountType) 282 ExitCount = SE.getZeroExtendExpr(ExitCount, CountType); 283 284 ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType)); 285 286 if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) { 287 LLVM_DEBUG(dbgs() << "HWLoops: Bailing, unsafe to expand ExitCount " 288 << *ExitCount << "\n"); 289 return nullptr; 290 } 291 292 Value *Count = SCEVE.expandCodeFor(ExitCount, CountType, 293 BB->getTerminator()); 294 LLVM_DEBUG(dbgs() << "HWLoops: Loop Count: " << *Count << "\n"); 295 return Count; 296 } 297 298 void HardwareLoop::InsertIterationSetup(Value *LoopCountInit, 299 BasicBlock *BB) { 300 IRBuilder<> Builder(BB->getTerminator()); 301 Type *Ty = LoopCountInit->getType(); 302 Function *LoopIter = 303 Intrinsic::getDeclaration(M, Intrinsic::set_loop_iterations, Ty); 304 Builder.CreateCall(LoopIter, LoopCountInit); 305 } 306 307 void HardwareLoop::InsertLoopDec() { 308 IRBuilder<> CondBuilder(ExitBranch); 309 310 Function *DecFunc = 311 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement, 312 LoopDecrement->getType()); 313 Value *Ops[] = { LoopDecrement }; 314 Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops); 315 Value *OldCond = ExitBranch->getCondition(); 316 ExitBranch->setCondition(NewCond); 317 318 // The false branch must exit the loop. 319 if (!L->contains(ExitBranch->getSuccessor(0))) 320 ExitBranch->swapSuccessors(); 321 322 // The old condition may be dead now, and may have even created a dead PHI 323 // (the original induction variable). 324 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 325 326 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n"); 327 } 328 329 Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) { 330 IRBuilder<> CondBuilder(ExitBranch); 331 332 Function *DecFunc = 333 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg, 334 { EltsRem->getType(), EltsRem->getType(), 335 LoopDecrement->getType() 336 }); 337 Value *Ops[] = { EltsRem, LoopDecrement }; 338 Value *Call = CondBuilder.CreateCall(DecFunc, Ops); 339 340 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n"); 341 return cast<Instruction>(Call); 342 } 343 344 PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) { 345 BasicBlock *Preheader = L->getLoopPreheader(); 346 BasicBlock *Header = L->getHeader(); 347 BasicBlock *Latch = ExitBranch->getParent(); 348 IRBuilder<> Builder(Header->getFirstNonPHI()); 349 PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2); 350 Index->addIncoming(NumElts, Preheader); 351 Index->addIncoming(EltsRem, Latch); 352 LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n"); 353 return Index; 354 } 355 356 void HardwareLoop::UpdateBranch(Value *EltsRem) { 357 IRBuilder<> CondBuilder(ExitBranch); 358 Value *NewCond = 359 CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0)); 360 Value *OldCond = ExitBranch->getCondition(); 361 ExitBranch->setCondition(NewCond); 362 363 // The false branch must exit the loop. 364 if (!L->contains(ExitBranch->getSuccessor(0))) 365 ExitBranch->swapSuccessors(); 366 367 // The old condition may be dead now, and may have even created a dead PHI 368 // (the original induction variable). 369 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 370 } 371 372 INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 373 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 374 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 375 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 376 INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 377 378 FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); } 379