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