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