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