1 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===// 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 file implements some loop unrolling utilities for loops with run-time 10 // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time 11 // trip counts. 12 // 13 // The functions in this file are used to generate extra code when the 14 // run-time trip count modulo the unroll factor is not 0. When this is the 15 // case, we need to generate code to execute these 'left over' iterations. 16 // 17 // The current strategy generates an if-then-else sequence prior to the 18 // unrolled loop to execute the 'left over' iterations before or after the 19 // unrolled loop. 20 // 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/LoopIterator.h" 26 #include "llvm/Analysis/ScalarEvolution.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/MDBuilder.h" 30 #include "llvm/IR/Metadata.h" 31 #include "llvm/IR/Module.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Transforms/Utils.h" 36 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 37 #include "llvm/Transforms/Utils/Cloning.h" 38 #include "llvm/Transforms/Utils/LoopUtils.h" 39 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 40 #include "llvm/Transforms/Utils/UnrollLoop.h" 41 #include <algorithm> 42 43 using namespace llvm; 44 45 #define DEBUG_TYPE "loop-unroll" 46 47 STATISTIC(NumRuntimeUnrolled, 48 "Number of loops unrolled with run-time trip counts"); 49 static cl::opt<bool> UnrollRuntimeMultiExit( 50 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden, 51 cl::desc("Allow runtime unrolling for loops with multiple exits, when " 52 "epilog is generated")); 53 static cl::opt<bool> UnrollRuntimeOtherExitPredictable( 54 "unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden, 55 cl::desc("Assume the non latch exit block to be predictable")); 56 57 /// Connect the unrolling prolog code to the original loop. 58 /// The unrolling prolog code contains code to execute the 59 /// 'extra' iterations if the run-time trip count modulo the 60 /// unroll count is non-zero. 61 /// 62 /// This function performs the following: 63 /// - Create PHI nodes at prolog end block to combine values 64 /// that exit the prolog code and jump around the prolog. 65 /// - Add a PHI operand to a PHI node at the loop exit block 66 /// for values that exit the prolog and go around the loop. 67 /// - Branch around the original loop if the trip count is less 68 /// than the unroll factor. 69 /// 70 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, 71 BasicBlock *PrologExit, 72 BasicBlock *OriginalLoopLatchExit, 73 BasicBlock *PreHeader, BasicBlock *NewPreHeader, 74 ValueToValueMapTy &VMap, DominatorTree *DT, 75 LoopInfo *LI, bool PreserveLCSSA) { 76 // Loop structure should be the following: 77 // Preheader 78 // PrologHeader 79 // ... 80 // PrologLatch 81 // PrologExit 82 // NewPreheader 83 // Header 84 // ... 85 // Latch 86 // LatchExit 87 BasicBlock *Latch = L->getLoopLatch(); 88 assert(Latch && "Loop must have a latch"); 89 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]); 90 91 // Create a PHI node for each outgoing value from the original loop 92 // (which means it is an outgoing value from the prolog code too). 93 // The new PHI node is inserted in the prolog end basic block. 94 // The new PHI node value is added as an operand of a PHI node in either 95 // the loop header or the loop exit block. 96 for (BasicBlock *Succ : successors(Latch)) { 97 for (PHINode &PN : Succ->phis()) { 98 // Add a new PHI node to the prolog end block and add the 99 // appropriate incoming values. 100 // TODO: This code assumes that the PrologExit (or the LatchExit block for 101 // prolog loop) contains only one predecessor from the loop, i.e. the 102 // PrologLatch. When supporting multiple-exiting block loops, we can have 103 // two or more blocks that have the LatchExit as the target in the 104 // original loop. 105 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr", 106 PrologExit->getFirstNonPHI()); 107 // Adding a value to the new PHI node from the original loop preheader. 108 // This is the value that skips all the prolog code. 109 if (L->contains(&PN)) { 110 // Succ is loop header. 111 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), 112 PreHeader); 113 } else { 114 // Succ is LatchExit. 115 NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader); 116 } 117 118 Value *V = PN.getIncomingValueForBlock(Latch); 119 if (Instruction *I = dyn_cast<Instruction>(V)) { 120 if (L->contains(I)) { 121 V = VMap.lookup(I); 122 } 123 } 124 // Adding a value to the new PHI node from the last prolog block 125 // that was created. 126 NewPN->addIncoming(V, PrologLatch); 127 128 // Update the existing PHI node operand with the value from the 129 // new PHI node. How this is done depends on if the existing 130 // PHI node is in the original loop block, or the exit block. 131 if (L->contains(&PN)) 132 PN.setIncomingValueForBlock(NewPreHeader, NewPN); 133 else 134 PN.addIncoming(NewPN, PrologExit); 135 } 136 } 137 138 // Make sure that created prolog loop is in simplified form 139 SmallVector<BasicBlock *, 4> PrologExitPreds; 140 Loop *PrologLoop = LI->getLoopFor(PrologLatch); 141 if (PrologLoop) { 142 for (BasicBlock *PredBB : predecessors(PrologExit)) 143 if (PrologLoop->contains(PredBB)) 144 PrologExitPreds.push_back(PredBB); 145 146 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI, 147 nullptr, PreserveLCSSA); 148 } 149 150 // Create a branch around the original loop, which is taken if there are no 151 // iterations remaining to be executed after running the prologue. 152 Instruction *InsertPt = PrologExit->getTerminator(); 153 IRBuilder<> B(InsertPt); 154 155 assert(Count != 0 && "nonsensical Count!"); 156 157 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1) 158 // This means %xtraiter is (BECount + 1) and all of the iterations of this 159 // loop were executed by the prologue. Note that if BECount <u (Count - 1) 160 // then (BECount + 1) cannot unsigned-overflow. 161 Value *BrLoopExit = 162 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1)); 163 // Split the exit to maintain loop canonicalization guarantees 164 SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit)); 165 SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI, 166 nullptr, PreserveLCSSA); 167 // Add the branch to the exit block (around the unrolled loop) 168 B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader); 169 InsertPt->eraseFromParent(); 170 if (DT) 171 DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit); 172 } 173 174 /// Connect the unrolling epilog code to the original loop. 175 /// The unrolling epilog code contains code to execute the 176 /// 'extra' iterations if the run-time trip count modulo the 177 /// unroll count is non-zero. 178 /// 179 /// This function performs the following: 180 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit 181 /// - Create PHI nodes at the unrolling loop exit to combine 182 /// values that exit the unrolling loop code and jump around it. 183 /// - Update PHI operands in the epilog loop by the new PHI nodes 184 /// - Branch around the epilog loop if extra iters (ModVal) is zero. 185 /// 186 static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, 187 BasicBlock *Exit, BasicBlock *PreHeader, 188 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, 189 ValueToValueMapTy &VMap, DominatorTree *DT, 190 LoopInfo *LI, bool PreserveLCSSA) { 191 BasicBlock *Latch = L->getLoopLatch(); 192 assert(Latch && "Loop must have a latch"); 193 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]); 194 195 // Loop structure should be the following: 196 // 197 // PreHeader 198 // NewPreHeader 199 // Header 200 // ... 201 // Latch 202 // NewExit (PN) 203 // EpilogPreHeader 204 // EpilogHeader 205 // ... 206 // EpilogLatch 207 // Exit (EpilogPN) 208 209 // Update PHI nodes at NewExit and Exit. 210 for (PHINode &PN : NewExit->phis()) { 211 // PN should be used in another PHI located in Exit block as 212 // Exit was split by SplitBlockPredecessors into Exit and NewExit 213 // Basicaly it should look like: 214 // NewExit: 215 // PN = PHI [I, Latch] 216 // ... 217 // Exit: 218 // EpilogPN = PHI [PN, EpilogPreHeader] 219 // 220 // There is EpilogPreHeader incoming block instead of NewExit as 221 // NewExit was spilt 1 more time to get EpilogPreHeader. 222 assert(PN.hasOneUse() && "The phi should have 1 use"); 223 PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser()); 224 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block"); 225 226 // Add incoming PreHeader from branch around the Loop 227 PN.addIncoming(UndefValue::get(PN.getType()), PreHeader); 228 229 Value *V = PN.getIncomingValueForBlock(Latch); 230 Instruction *I = dyn_cast<Instruction>(V); 231 if (I && L->contains(I)) 232 // If value comes from an instruction in the loop add VMap value. 233 V = VMap.lookup(I); 234 // For the instruction out of the loop, constant or undefined value 235 // insert value itself. 236 EpilogPN->addIncoming(V, EpilogLatch); 237 238 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 && 239 "EpilogPN should have EpilogPreHeader incoming block"); 240 // Change EpilogPreHeader incoming block to NewExit. 241 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader), 242 NewExit); 243 // Now PHIs should look like: 244 // NewExit: 245 // PN = PHI [I, Latch], [undef, PreHeader] 246 // ... 247 // Exit: 248 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch] 249 } 250 251 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader). 252 // Update corresponding PHI nodes in epilog loop. 253 for (BasicBlock *Succ : successors(Latch)) { 254 // Skip this as we already updated phis in exit blocks. 255 if (!L->contains(Succ)) 256 continue; 257 for (PHINode &PN : Succ->phis()) { 258 // Add new PHI nodes to the loop exit block and update epilog 259 // PHIs with the new PHI values. 260 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr", 261 NewExit->getFirstNonPHI()); 262 // Adding a value to the new PHI node from the unrolling loop preheader. 263 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader); 264 // Adding a value to the new PHI node from the unrolling loop latch. 265 NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch); 266 267 // Update the existing PHI node operand with the value from the new PHI 268 // node. Corresponding instruction in epilog loop should be PHI. 269 PHINode *VPN = cast<PHINode>(VMap[&PN]); 270 VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN); 271 } 272 } 273 274 Instruction *InsertPt = NewExit->getTerminator(); 275 IRBuilder<> B(InsertPt); 276 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod"); 277 assert(Exit && "Loop must have a single exit block only"); 278 // Split the epilogue exit to maintain loop canonicalization guarantees 279 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); 280 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr, 281 PreserveLCSSA); 282 // Add the branch to the exit block (around the unrolling loop) 283 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit); 284 InsertPt->eraseFromParent(); 285 if (DT) 286 DT->changeImmediateDominator(Exit, NewExit); 287 288 // Split the main loop exit to maintain canonicalization guarantees. 289 SmallVector<BasicBlock*, 4> NewExitPreds{Latch}; 290 SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr, 291 PreserveLCSSA); 292 } 293 294 /// Create a clone of the blocks in a loop and connect them together. 295 /// If CreateRemainderLoop is false, loop structure will not be cloned, 296 /// otherwise a new loop will be created including all cloned blocks, and the 297 /// iterator of it switches to count NewIter down to 0. 298 /// The cloned blocks should be inserted between InsertTop and InsertBot. 299 /// If loop structure is cloned InsertTop should be new preheader, InsertBot 300 /// new loop exit. 301 /// Return the new cloned loop that is created when CreateRemainderLoop is true. 302 static Loop * 303 CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop, 304 const bool UseEpilogRemainder, const bool UnrollRemainder, 305 BasicBlock *InsertTop, 306 BasicBlock *InsertBot, BasicBlock *Preheader, 307 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 308 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) { 309 StringRef suffix = UseEpilogRemainder ? "epil" : "prol"; 310 BasicBlock *Header = L->getHeader(); 311 BasicBlock *Latch = L->getLoopLatch(); 312 Function *F = Header->getParent(); 313 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 314 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 315 Loop *ParentLoop = L->getParentLoop(); 316 NewLoopsMap NewLoops; 317 NewLoops[ParentLoop] = ParentLoop; 318 if (!CreateRemainderLoop) 319 NewLoops[L] = ParentLoop; 320 321 // For each block in the original loop, create a new copy, 322 // and update the value map with the newly created values. 323 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 324 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F); 325 NewBlocks.push_back(NewBB); 326 327 // If we're unrolling the outermost loop, there's no remainder loop, 328 // and this block isn't in a nested loop, then the new block is not 329 // in any loop. Otherwise, add it to loopinfo. 330 if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop) 331 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops); 332 333 VMap[*BB] = NewBB; 334 if (Header == *BB) { 335 // For the first block, add a CFG connection to this newly 336 // created block. 337 InsertTop->getTerminator()->setSuccessor(0, NewBB); 338 } 339 340 if (DT) { 341 if (Header == *BB) { 342 // The header is dominated by the preheader. 343 DT->addNewBlock(NewBB, InsertTop); 344 } else { 345 // Copy information from original loop to unrolled loop. 346 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock(); 347 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB])); 348 } 349 } 350 351 if (Latch == *BB) { 352 // For the last block, if CreateRemainderLoop is false, create a direct 353 // jump to InsertBot. If not, create a loop back to cloned head. 354 VMap.erase((*BB)->getTerminator()); 355 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); 356 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); 357 IRBuilder<> Builder(LatchBR); 358 if (!CreateRemainderLoop) { 359 Builder.CreateBr(InsertBot); 360 } else { 361 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, 362 suffix + ".iter", 363 FirstLoopBB->getFirstNonPHI()); 364 Value *IdxSub = 365 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), 366 NewIdx->getName() + ".sub"); 367 Value *IdxCmp = 368 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); 369 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot); 370 NewIdx->addIncoming(NewIter, InsertTop); 371 NewIdx->addIncoming(IdxSub, NewBB); 372 } 373 LatchBR->eraseFromParent(); 374 } 375 } 376 377 // Change the incoming values to the ones defined in the preheader or 378 // cloned loop. 379 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 380 PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 381 if (!CreateRemainderLoop) { 382 if (UseEpilogRemainder) { 383 unsigned idx = NewPHI->getBasicBlockIndex(Preheader); 384 NewPHI->setIncomingBlock(idx, InsertTop); 385 NewPHI->removeIncomingValue(Latch, false); 386 } else { 387 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader); 388 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 389 } 390 } else { 391 unsigned idx = NewPHI->getBasicBlockIndex(Preheader); 392 NewPHI->setIncomingBlock(idx, InsertTop); 393 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 394 idx = NewPHI->getBasicBlockIndex(Latch); 395 Value *InVal = NewPHI->getIncomingValue(idx); 396 NewPHI->setIncomingBlock(idx, NewLatch); 397 if (Value *V = VMap.lookup(InVal)) 398 NewPHI->setIncomingValue(idx, V); 399 } 400 } 401 if (CreateRemainderLoop) { 402 Loop *NewLoop = NewLoops[L]; 403 assert(NewLoop && "L should have been cloned"); 404 MDNode *LoopID = NewLoop->getLoopID(); 405 406 // Only add loop metadata if the loop is not going to be completely 407 // unrolled. 408 if (UnrollRemainder) 409 return NewLoop; 410 411 Optional<MDNode *> NewLoopID = makeFollowupLoopID( 412 LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder}); 413 if (NewLoopID.hasValue()) { 414 NewLoop->setLoopID(NewLoopID.getValue()); 415 416 // Do not setLoopAlreadyUnrolled if loop attributes have been defined 417 // explicitly. 418 return NewLoop; 419 } 420 421 // Add unroll disable metadata to disable future unrolling for this loop. 422 NewLoop->setLoopAlreadyUnrolled(); 423 return NewLoop; 424 } 425 else 426 return nullptr; 427 } 428 429 /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits 430 /// is populated with all the loop exit blocks other than the LatchExit block. 431 static bool canSafelyUnrollMultiExitLoop(Loop *L, BasicBlock *LatchExit, 432 bool PreserveLCSSA, 433 bool UseEpilogRemainder) { 434 435 // We currently have some correctness constrains in unrolling a multi-exit 436 // loop. Check for these below. 437 438 // We rely on LCSSA form being preserved when the exit blocks are transformed. 439 // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.) 440 if (!PreserveLCSSA) 441 return false; 442 443 // TODO: Support multiple exiting blocks jumping to the `LatchExit` when 444 // UnrollRuntimeMultiExit is true. This will need updating the logic in 445 // connectEpilog/connectProlog. 446 if (!LatchExit->getSinglePredecessor()) { 447 LLVM_DEBUG( 448 dbgs() << "Bailout for multi-exit handling when latch exit has >1 " 449 "predecessor.\n"); 450 return false; 451 } 452 // FIXME: We bail out of multi-exit unrolling when epilog loop is generated 453 // and L is an inner loop. This is because in presence of multiple exits, the 454 // outer loop is incorrect: we do not add the EpilogPreheader and exit to the 455 // outer loop. This is automatically handled in the prolog case, so we do not 456 // have that bug in prolog generation. 457 if (UseEpilogRemainder && L->getParentLoop()) 458 return false; 459 460 // All constraints have been satisfied. 461 return true; 462 } 463 464 /// Returns true if we can profitably unroll the multi-exit loop L. Currently, 465 /// we return true only if UnrollRuntimeMultiExit is set to true. 466 static bool canProfitablyUnrollMultiExitLoop( 467 Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit, 468 bool PreserveLCSSA, bool UseEpilogRemainder) { 469 470 #if !defined(NDEBUG) 471 assert(canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA, 472 UseEpilogRemainder) && 473 "Should be safe to unroll before checking profitability!"); 474 #endif 475 476 // Priority goes to UnrollRuntimeMultiExit if it's supplied. 477 if (UnrollRuntimeMultiExit.getNumOccurrences()) 478 return UnrollRuntimeMultiExit; 479 480 // The main pain point with multi-exit loop unrolling is that once unrolled, 481 // we will not be able to merge all blocks into a straight line code. 482 // There are branches within the unrolled loop that go to the OtherExits. 483 // The second point is the increase in code size, but this is true 484 // irrespective of multiple exits. 485 486 // Note: Both the heuristics below are coarse grained. We are essentially 487 // enabling unrolling of loops that have a single side exit other than the 488 // normal LatchExit (i.e. exiting into a deoptimize block). 489 // The heuristics considered are: 490 // 1. low number of branches in the unrolled version. 491 // 2. high predictability of these extra branches. 492 // We avoid unrolling loops that have more than two exiting blocks. This 493 // limits the total number of branches in the unrolled loop to be atmost 494 // the unroll factor (since one of the exiting blocks is the latch block). 495 SmallVector<BasicBlock*, 4> ExitingBlocks; 496 L->getExitingBlocks(ExitingBlocks); 497 if (ExitingBlocks.size() > 2) 498 return false; 499 500 // Allow unrolling of loops with no non latch exit blocks. 501 if (OtherExits.size() == 0) 502 return true; 503 504 // The second heuristic is that L has one exit other than the latchexit and 505 // that exit is a deoptimize block. We know that deoptimize blocks are rarely 506 // taken, which also implies the branch leading to the deoptimize block is 507 // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we 508 // assume the other exit branch is predictable even if it has no deoptimize 509 // call. 510 return (OtherExits.size() == 1 && 511 (UnrollRuntimeOtherExitPredictable || 512 OtherExits[0]->getTerminatingDeoptimizeCall())); 513 // TODO: These can be fine-tuned further to consider code size or deopt states 514 // that are captured by the deoptimize exit block. 515 // Also, we can extend this to support more cases, if we actually 516 // know of kinds of multiexit loops that would benefit from unrolling. 517 } 518 519 // Assign the maximum possible trip count as the back edge weight for the 520 // remainder loop if the original loop comes with a branch weight. 521 static void updateLatchBranchWeightsForRemainderLoop(Loop *OrigLoop, 522 Loop *RemainderLoop, 523 uint64_t UnrollFactor) { 524 uint64_t TrueWeight, FalseWeight; 525 BranchInst *LatchBR = 526 cast<BranchInst>(OrigLoop->getLoopLatch()->getTerminator()); 527 if (LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) { 528 uint64_t ExitWeight = LatchBR->getSuccessor(0) == OrigLoop->getHeader() 529 ? FalseWeight 530 : TrueWeight; 531 assert(UnrollFactor > 1); 532 uint64_t BackEdgeWeight = (UnrollFactor - 1) * ExitWeight; 533 BasicBlock *Header = RemainderLoop->getHeader(); 534 BasicBlock *Latch = RemainderLoop->getLoopLatch(); 535 auto *RemainderLatchBR = cast<BranchInst>(Latch->getTerminator()); 536 unsigned HeaderIdx = (RemainderLatchBR->getSuccessor(0) == Header ? 0 : 1); 537 MDBuilder MDB(RemainderLatchBR->getContext()); 538 MDNode *WeightNode = 539 HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight) 540 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight); 541 RemainderLatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 542 } 543 } 544 545 /// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain 546 /// accounting for the possibility of unsigned overflow in the 2s complement 547 /// domain. Preconditions: 548 /// 1) TripCount = BECount + 1 (allowing overflow) 549 /// 2) Log2(Count) <= BitWidth(BECount) 550 static Value *CreateTripRemainder(IRBuilder<> &B, Value *BECount, 551 Value *TripCount, unsigned Count) { 552 // Note that TripCount is BECount + 1. 553 if (isPowerOf2_32(Count)) 554 // If the expression is zero, then either: 555 // 1. There are no iterations to be run in the prolog/epilog loop. 556 // OR 557 // 2. The addition computing TripCount overflowed. 558 // 559 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so 560 // the number of iterations that remain to be run in the original loop is a 561 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a 562 // precondition of this method). 563 return B.CreateAnd(TripCount, Count - 1, "xtraiter"); 564 565 // As (BECount + 1) can potentially unsigned overflow we count 566 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count. 567 Constant *CountC = ConstantInt::get(BECount->getType(), Count); 568 Value *ModValTmp = B.CreateURem(BECount, CountC); 569 Value *ModValAdd = B.CreateAdd(ModValTmp, 570 ConstantInt::get(ModValTmp->getType(), 1)); 571 // At that point (BECount % Count) + 1 could be equal to Count. 572 // To handle this case we need to take mod by Count one more time. 573 return B.CreateURem(ModValAdd, CountC, "xtraiter"); 574 } 575 576 577 /// Insert code in the prolog/epilog code when unrolling a loop with a 578 /// run-time trip-count. 579 /// 580 /// This method assumes that the loop unroll factor is total number 581 /// of loop bodies in the loop after unrolling. (Some folks refer 582 /// to the unroll factor as the number of *extra* copies added). 583 /// We assume also that the loop unroll factor is a power-of-two. So, after 584 /// unrolling the loop, the number of loop bodies executed is 2, 585 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch 586 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for 587 /// the switch instruction is generated. 588 /// 589 /// ***Prolog case*** 590 /// extraiters = tripcount % loopfactor 591 /// if (extraiters == 0) jump Loop: 592 /// else jump Prol: 593 /// Prol: LoopBody; 594 /// extraiters -= 1 // Omitted if unroll factor is 2. 595 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. 596 /// if (tripcount < loopfactor) jump End: 597 /// Loop: 598 /// ... 599 /// End: 600 /// 601 /// ***Epilog case*** 602 /// extraiters = tripcount % loopfactor 603 /// if (tripcount < loopfactor) jump LoopExit: 604 /// unroll_iters = tripcount - extraiters 605 /// Loop: LoopBody; (executes unroll_iter times); 606 /// unroll_iter -= 1 607 /// if (unroll_iter != 0) jump Loop: 608 /// LoopExit: 609 /// if (extraiters == 0) jump EpilExit: 610 /// Epil: LoopBody; (executes extraiters times) 611 /// extraiters -= 1 // Omitted if unroll factor is 2. 612 /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2. 613 /// EpilExit: 614 615 bool llvm::UnrollRuntimeLoopRemainder( 616 Loop *L, unsigned Count, bool AllowExpensiveTripCount, 617 bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV, 618 LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, 619 const TargetTransformInfo *TTI, bool PreserveLCSSA, Loop **ResultLoop) { 620 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n"); 621 LLVM_DEBUG(L->dump()); 622 LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n" 623 : dbgs() << "Using prolog remainder.\n"); 624 625 // Make sure the loop is in canonical form. 626 if (!L->isLoopSimplifyForm()) { 627 LLVM_DEBUG(dbgs() << "Not in simplify form!\n"); 628 return false; 629 } 630 631 // Guaranteed by LoopSimplifyForm. 632 BasicBlock *Latch = L->getLoopLatch(); 633 BasicBlock *Header = L->getHeader(); 634 635 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); 636 637 if (!LatchBR || LatchBR->isUnconditional()) { 638 // The loop-rotate pass can be helpful to avoid this in many cases. 639 LLVM_DEBUG( 640 dbgs() 641 << "Loop latch not terminated by a conditional branch.\n"); 642 return false; 643 } 644 645 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0; 646 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex); 647 648 if (L->contains(LatchExit)) { 649 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the 650 // targets of the Latch be an exit block out of the loop. 651 LLVM_DEBUG( 652 dbgs() 653 << "One of the loop latch successors must be the exit block.\n"); 654 return false; 655 } 656 657 // These are exit blocks other than the target of the latch exiting block. 658 SmallVector<BasicBlock *, 4> OtherExits; 659 L->getUniqueNonLatchExitBlocks(OtherExits); 660 bool isMultiExitUnrollingEnabled = 661 canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA, 662 UseEpilogRemainder) && 663 canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA, 664 UseEpilogRemainder); 665 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled. 666 if (!isMultiExitUnrollingEnabled && 667 (!L->getExitingBlock() || OtherExits.size())) { 668 LLVM_DEBUG( 669 dbgs() 670 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not " 671 "enabled!\n"); 672 return false; 673 } 674 // Use Scalar Evolution to compute the trip count. This allows more loops to 675 // be unrolled than relying on induction var simplification. 676 if (!SE) 677 return false; 678 679 // Only unroll loops with a computable trip count, and the trip count needs 680 // to be an int value (allowing a pointer type is a TODO item). 681 // We calculate the backedge count by using getExitCount on the Latch block, 682 // which is proven to be the only exiting block in this loop. This is same as 683 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all 684 // exiting blocks). 685 const SCEV *BECountSC = SE->getExitCount(L, Latch); 686 if (isa<SCEVCouldNotCompute>(BECountSC) || 687 !BECountSC->getType()->isIntegerTy()) { 688 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n"); 689 return false; 690 } 691 692 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth(); 693 694 // Add 1 since the backedge count doesn't include the first loop iteration. 695 // (Note that overflow can occur, this is handled explicitly below) 696 const SCEV *TripCountSC = 697 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1)); 698 if (isa<SCEVCouldNotCompute>(TripCountSC)) { 699 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n"); 700 return false; 701 } 702 703 BasicBlock *PreHeader = L->getLoopPreheader(); 704 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); 705 const DataLayout &DL = Header->getModule()->getDataLayout(); 706 SCEVExpander Expander(*SE, DL, "loop-unroll"); 707 if (!AllowExpensiveTripCount && 708 Expander.isHighCostExpansion(TripCountSC, L, SCEVCheapExpansionBudget, 709 TTI, PreHeaderBR)) { 710 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n"); 711 return false; 712 } 713 714 // This constraint lets us deal with an overflowing trip count easily; see the 715 // comment on ModVal below. 716 if (Log2_32(Count) > BEWidth) { 717 LLVM_DEBUG( 718 dbgs() 719 << "Count failed constraint on overflow trip count calculation.\n"); 720 return false; 721 } 722 723 // Loop structure is the following: 724 // 725 // PreHeader 726 // Header 727 // ... 728 // Latch 729 // LatchExit 730 731 BasicBlock *NewPreHeader; 732 BasicBlock *NewExit = nullptr; 733 BasicBlock *PrologExit = nullptr; 734 BasicBlock *EpilogPreHeader = nullptr; 735 BasicBlock *PrologPreHeader = nullptr; 736 737 if (UseEpilogRemainder) { 738 // If epilog remainder 739 // Split PreHeader to insert a branch around loop for unrolling. 740 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI); 741 NewPreHeader->setName(PreHeader->getName() + ".new"); 742 // Split LatchExit to create phi nodes from branch above. 743 SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit)); 744 NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI, 745 nullptr, PreserveLCSSA); 746 // NewExit gets its DebugLoc from LatchExit, which is not part of the 747 // original Loop. 748 // Fix this by setting Loop's DebugLoc to NewExit. 749 auto *NewExitTerminator = NewExit->getTerminator(); 750 NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc()); 751 // Split NewExit to insert epilog remainder loop. 752 EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI); 753 EpilogPreHeader->setName(Header->getName() + ".epil.preheader"); 754 } else { 755 // If prolog remainder 756 // Split the original preheader twice to insert prolog remainder loop 757 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI); 758 PrologPreHeader->setName(Header->getName() + ".prol.preheader"); 759 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(), 760 DT, LI); 761 PrologExit->setName(Header->getName() + ".prol.loopexit"); 762 // Split PrologExit to get NewPreHeader. 763 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI); 764 NewPreHeader->setName(PreHeader->getName() + ".new"); 765 } 766 // Loop structure should be the following: 767 // Epilog Prolog 768 // 769 // PreHeader PreHeader 770 // *NewPreHeader *PrologPreHeader 771 // Header *PrologExit 772 // ... *NewPreHeader 773 // Latch Header 774 // *NewExit ... 775 // *EpilogPreHeader Latch 776 // LatchExit LatchExit 777 778 // Calculate conditions for branch around loop for unrolling 779 // in epilog case and around prolog remainder loop in prolog case. 780 // Compute the number of extra iterations required, which is: 781 // extra iterations = run-time trip count % loop unroll factor 782 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); 783 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), 784 PreHeaderBR); 785 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(), 786 PreHeaderBR); 787 IRBuilder<> B(PreHeaderBR); 788 Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count); 789 790 Value *BranchVal = 791 UseEpilogRemainder ? B.CreateICmpULT(BECount, 792 ConstantInt::get(BECount->getType(), 793 Count - 1)) : 794 B.CreateIsNotNull(ModVal, "lcmp.mod"); 795 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader; 796 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit; 797 // Branch to either remainder (extra iterations) loop or unrolling loop. 798 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop); 799 PreHeaderBR->eraseFromParent(); 800 if (DT) { 801 if (UseEpilogRemainder) 802 DT->changeImmediateDominator(NewExit, PreHeader); 803 else 804 DT->changeImmediateDominator(PrologExit, PreHeader); 805 } 806 Function *F = Header->getParent(); 807 // Get an ordered list of blocks in the loop to help with the ordering of the 808 // cloned blocks in the prolog/epilog code 809 LoopBlocksDFS LoopBlocks(L); 810 LoopBlocks.perform(LI); 811 812 // 813 // For each extra loop iteration, create a copy of the loop's basic blocks 814 // and generate a condition that branches to the copy depending on the 815 // number of 'left over' iterations. 816 // 817 std::vector<BasicBlock *> NewBlocks; 818 ValueToValueMapTy VMap; 819 820 // For unroll factor 2 remainder loop will have 1 iterations. 821 // Do not create 1 iteration loop. 822 bool CreateRemainderLoop = (Count != 2); 823 824 // Clone all the basic blocks in the loop. If Count is 2, we don't clone 825 // the loop, otherwise we create a cloned loop to execute the extra 826 // iterations. This function adds the appropriate CFG connections. 827 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit; 828 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader; 829 Loop *remainderLoop = CloneLoopBlocks( 830 L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder, 831 InsertTop, InsertBot, 832 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI); 833 834 // Assign the maximum possible trip count as the back edge weight for the 835 // remainder loop if the original loop comes with a branch weight. 836 if (remainderLoop && !UnrollRemainder) 837 updateLatchBranchWeightsForRemainderLoop(L, remainderLoop, Count); 838 839 // Insert the cloned blocks into the function. 840 F->getBasicBlockList().splice(InsertBot->getIterator(), 841 F->getBasicBlockList(), 842 NewBlocks[0]->getIterator(), 843 F->end()); 844 845 // Now the loop blocks are cloned and the other exiting blocks from the 846 // remainder are connected to the original Loop's exit blocks. The remaining 847 // work is to update the phi nodes in the original loop, and take in the 848 // values from the cloned region. 849 for (auto *BB : OtherExits) { 850 // Given we preserve LCSSA form, we know that the values used outside the 851 // loop will be used through these phi nodes at the exit blocks that are 852 // transformed below. 853 for (PHINode &PN : BB->phis()) { 854 unsigned oldNumOperands = PN.getNumIncomingValues(); 855 // Add the incoming values from the remainder code to the end of the phi 856 // node. 857 for (unsigned i = 0; i < oldNumOperands; i++){ 858 auto *PredBB =PN.getIncomingBlock(i); 859 auto *V = PN.getIncomingValue(i); 860 if (Instruction *I = dyn_cast<Instruction>(V)) 861 if (L->contains(I)) 862 V = VMap.lookup(I); 863 PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB])); 864 } 865 } 866 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG) 867 for (BasicBlock *SuccBB : successors(BB)) { 868 assert(!(any_of(OtherExits, 869 [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) || 870 SuccBB == LatchExit) && 871 "Breaks the definition of dedicated exits!"); 872 } 873 #endif 874 } 875 876 // Update the immediate dominator of the exit blocks and blocks that are 877 // reachable from the exit blocks. This is needed because we now have paths 878 // from both the original loop and the remainder code reaching the exit 879 // blocks. While the IDom of these exit blocks were from the original loop, 880 // now the IDom is the preheader (which decides whether the original loop or 881 // remainder code should run). 882 if (DT && !L->getExitingBlock()) { 883 SmallVector<BasicBlock *, 16> ChildrenToUpdate; 884 // NB! We have to examine the dom children of all loop blocks, not just 885 // those which are the IDom of the exit blocks. This is because blocks 886 // reachable from the exit blocks can have their IDom as the nearest common 887 // dominator of the exit blocks. 888 for (auto *BB : L->blocks()) { 889 auto *DomNodeBB = DT->getNode(BB); 890 for (auto *DomChild : DomNodeBB->children()) { 891 auto *DomChildBB = DomChild->getBlock(); 892 if (!L->contains(LI->getLoopFor(DomChildBB))) 893 ChildrenToUpdate.push_back(DomChildBB); 894 } 895 } 896 for (auto *BB : ChildrenToUpdate) 897 DT->changeImmediateDominator(BB, PreHeader); 898 } 899 900 // Loop structure should be the following: 901 // Epilog Prolog 902 // 903 // PreHeader PreHeader 904 // NewPreHeader PrologPreHeader 905 // Header PrologHeader 906 // ... ... 907 // Latch PrologLatch 908 // NewExit PrologExit 909 // EpilogPreHeader NewPreHeader 910 // EpilogHeader Header 911 // ... ... 912 // EpilogLatch Latch 913 // LatchExit LatchExit 914 915 // Rewrite the cloned instruction operands to use the values created when the 916 // clone is created. 917 for (BasicBlock *BB : NewBlocks) { 918 for (Instruction &I : *BB) { 919 RemapInstruction(&I, VMap, 920 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 921 } 922 } 923 924 if (UseEpilogRemainder) { 925 // Connect the epilog code to the original loop and update the 926 // PHI functions. 927 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, 928 EpilogPreHeader, NewPreHeader, VMap, DT, LI, 929 PreserveLCSSA); 930 931 // Update counter in loop for unrolling. 932 // I should be multiply of Count. 933 IRBuilder<> B2(NewPreHeader->getTerminator()); 934 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter"); 935 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); 936 B2.SetInsertPoint(LatchBR); 937 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter", 938 Header->getFirstNonPHI()); 939 Value *IdxSub = 940 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), 941 NewIdx->getName() + ".nsub"); 942 Value *IdxCmp; 943 if (LatchBR->getSuccessor(0) == Header) 944 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp"); 945 else 946 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp"); 947 NewIdx->addIncoming(TestVal, NewPreHeader); 948 NewIdx->addIncoming(IdxSub, Latch); 949 LatchBR->setCondition(IdxCmp); 950 } else { 951 // Connect the prolog code to the original loop and update the 952 // PHI functions. 953 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader, 954 NewPreHeader, VMap, DT, LI, PreserveLCSSA); 955 } 956 957 // If this loop is nested, then the loop unroller changes the code in the any 958 // of its parent loops, so the Scalar Evolution pass needs to be run again. 959 SE->forgetTopmostLoop(L); 960 961 // Verify that the Dom Tree is correct. 962 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG) 963 if (DT) 964 assert(DT->verify(DominatorTree::VerificationLevel::Full)); 965 #endif 966 967 // Canonicalize to LoopSimplifyForm both original and remainder loops. We 968 // cannot rely on the LoopUnrollPass to do this because it only does 969 // canonicalization for parent/subloops and not the sibling loops. 970 if (OtherExits.size() > 0) { 971 // Generate dedicated exit blocks for the original loop, to preserve 972 // LoopSimplifyForm. 973 formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA); 974 // Generate dedicated exit blocks for the remainder loop if one exists, to 975 // preserve LoopSimplifyForm. 976 if (remainderLoop) 977 formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA); 978 } 979 980 auto UnrollResult = LoopUnrollResult::Unmodified; 981 if (remainderLoop && UnrollRemainder) { 982 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n"); 983 UnrollResult = 984 UnrollLoop(remainderLoop, 985 {/*Count*/ Count - 1, /*Force*/ false, /*Runtime*/ false, 986 /*AllowExpensiveTripCount*/ false, 987 /*UnrollRemainder*/ false, ForgetAllSCEV}, 988 LI, SE, DT, AC, TTI, /*ORE*/ nullptr, PreserveLCSSA); 989 } 990 991 if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled) 992 *ResultLoop = remainderLoop; 993 NumRuntimeUnrolled++; 994 return true; 995 } 996