1 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements some loop unrolling utilities for loops with run-time 11 // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time 12 // trip counts. 13 // 14 // The functions in this file are used to generate extra code when the 15 // run-time trip count modulo the unroll factor is not 0. When this is the 16 // case, we need to generate code to execute these 'left over' iterations. 17 // 18 // The current strategy generates an if-then-else sequence prior to the 19 // unrolled loop to execute the 'left over' iterations before or after the 20 // unrolled loop. 21 // 22 //===----------------------------------------------------------------------===// 23 24 #include "llvm/Transforms/Utils/UnrollLoop.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/LoopIterator.h" 28 #include "llvm/Analysis/LoopPass.h" 29 #include "llvm/Analysis/ScalarEvolution.h" 30 #include "llvm/Analysis/ScalarEvolutionExpander.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/Metadata.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Transforms/Scalar.h" 38 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 39 #include "llvm/Transforms/Utils/Cloning.h" 40 #include <algorithm> 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "loop-unroll" 45 46 STATISTIC(NumRuntimeUnrolled, 47 "Number of loops unrolled with run-time trip counts"); 48 49 /// Connect the unrolling prolog code to the original loop. 50 /// The unrolling prolog code contains code to execute the 51 /// 'extra' iterations if the run-time trip count modulo the 52 /// unroll count is non-zero. 53 /// 54 /// This function performs the following: 55 /// - Create PHI nodes at prolog end block to combine values 56 /// that exit the prolog code and jump around the prolog. 57 /// - Add a PHI operand to a PHI node at the loop exit block 58 /// for values that exit the prolog and go around the loop. 59 /// - Branch around the original loop if the trip count is less 60 /// than the unroll factor. 61 /// 62 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, 63 BasicBlock *PrologExit, BasicBlock *PreHeader, 64 BasicBlock *NewPreHeader, ValueToValueMapTy &VMap, 65 DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA) { 66 BasicBlock *Latch = L->getLoopLatch(); 67 assert(Latch && "Loop must have a latch"); 68 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]); 69 70 // Create a PHI node for each outgoing value from the original loop 71 // (which means it is an outgoing value from the prolog code too). 72 // The new PHI node is inserted in the prolog end basic block. 73 // The new PHI node value is added as an operand of a PHI node in either 74 // the loop header or the loop exit block. 75 for (BasicBlock *Succ : successors(Latch)) { 76 for (Instruction &BBI : *Succ) { 77 PHINode *PN = dyn_cast<PHINode>(&BBI); 78 // Exit when we passed all PHI nodes. 79 if (!PN) 80 break; 81 // Add a new PHI node to the prolog end block and add the 82 // appropriate incoming values. 83 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr", 84 PrologExit->getFirstNonPHI()); 85 // Adding a value to the new PHI node from the original loop preheader. 86 // This is the value that skips all the prolog code. 87 if (L->contains(PN)) { 88 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), 89 PreHeader); 90 } else { 91 NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader); 92 } 93 94 Value *V = PN->getIncomingValueForBlock(Latch); 95 if (Instruction *I = dyn_cast<Instruction>(V)) { 96 if (L->contains(I)) { 97 V = VMap.lookup(I); 98 } 99 } 100 // Adding a value to the new PHI node from the last prolog block 101 // that was created. 102 NewPN->addIncoming(V, PrologLatch); 103 104 // Update the existing PHI node operand with the value from the 105 // new PHI node. How this is done depends on if the existing 106 // PHI node is in the original loop block, or the exit block. 107 if (L->contains(PN)) { 108 PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN); 109 } else { 110 PN->addIncoming(NewPN, PrologExit); 111 } 112 } 113 } 114 115 // Make sure that created prolog loop is in simplified form 116 SmallVector<BasicBlock *, 4> PrologExitPreds; 117 Loop *PrologLoop = LI->getLoopFor(PrologLatch); 118 if (PrologLoop) { 119 for (BasicBlock *PredBB : predecessors(PrologExit)) 120 if (PrologLoop->contains(PredBB)) 121 PrologExitPreds.push_back(PredBB); 122 123 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI, 124 PreserveLCSSA); 125 } 126 127 // Create a branch around the original loop, which is taken if there are no 128 // iterations remaining to be executed after running the prologue. 129 Instruction *InsertPt = PrologExit->getTerminator(); 130 IRBuilder<> B(InsertPt); 131 132 assert(Count != 0 && "nonsensical Count!"); 133 134 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1) 135 // This means %xtraiter is (BECount + 1) and all of the iterations of this 136 // loop were executed by the prologue. Note that if BECount <u (Count - 1) 137 // then (BECount + 1) cannot unsigned-overflow. 138 Value *BrLoopExit = 139 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1)); 140 BasicBlock *Exit = L->getUniqueExitBlock(); 141 assert(Exit && "Loop must have a single exit block only"); 142 // Split the exit to maintain loop canonicalization guarantees 143 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); 144 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", DT, LI, 145 PreserveLCSSA); 146 // Add the branch to the exit block (around the unrolled loop) 147 B.CreateCondBr(BrLoopExit, Exit, NewPreHeader); 148 InsertPt->eraseFromParent(); 149 } 150 151 /// Connect the unrolling epilog code to the original loop. 152 /// The unrolling epilog code contains code to execute the 153 /// 'extra' iterations if the run-time trip count modulo the 154 /// unroll count is non-zero. 155 /// 156 /// This function performs the following: 157 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit 158 /// - Create PHI nodes at the unrolling loop exit to combine 159 /// values that exit the unrolling loop code and jump around it. 160 /// - Update PHI operands in the epilog loop by the new PHI nodes 161 /// - Branch around the epilog loop if extra iters (ModVal) is zero. 162 /// 163 static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, 164 BasicBlock *Exit, BasicBlock *PreHeader, 165 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, 166 ValueToValueMapTy &VMap, DominatorTree *DT, 167 LoopInfo *LI, bool PreserveLCSSA) { 168 BasicBlock *Latch = L->getLoopLatch(); 169 assert(Latch && "Loop must have a latch"); 170 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]); 171 172 // Loop structure should be the following: 173 // 174 // PreHeader 175 // NewPreHeader 176 // Header 177 // ... 178 // Latch 179 // NewExit (PN) 180 // EpilogPreHeader 181 // EpilogHeader 182 // ... 183 // EpilogLatch 184 // Exit (EpilogPN) 185 186 // Update PHI nodes at NewExit and Exit. 187 for (Instruction &BBI : *NewExit) { 188 PHINode *PN = dyn_cast<PHINode>(&BBI); 189 // Exit when we passed all PHI nodes. 190 if (!PN) 191 break; 192 // PN should be used in another PHI located in Exit block as 193 // Exit was split by SplitBlockPredecessors into Exit and NewExit 194 // Basicaly it should look like: 195 // NewExit: 196 // PN = PHI [I, Latch] 197 // ... 198 // Exit: 199 // EpilogPN = PHI [PN, EpilogPreHeader] 200 // 201 // There is EpilogPreHeader incoming block instead of NewExit as 202 // NewExit was spilt 1 more time to get EpilogPreHeader. 203 assert(PN->hasOneUse() && "The phi should have 1 use"); 204 PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser()); 205 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block"); 206 207 // Add incoming PreHeader from branch around the Loop 208 PN->addIncoming(UndefValue::get(PN->getType()), PreHeader); 209 210 Value *V = PN->getIncomingValueForBlock(Latch); 211 Instruction *I = dyn_cast<Instruction>(V); 212 if (I && L->contains(I)) 213 // If value comes from an instruction in the loop add VMap value. 214 V = VMap.lookup(I); 215 // For the instruction out of the loop, constant or undefined value 216 // insert value itself. 217 EpilogPN->addIncoming(V, EpilogLatch); 218 219 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 && 220 "EpilogPN should have EpilogPreHeader incoming block"); 221 // Change EpilogPreHeader incoming block to NewExit. 222 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader), 223 NewExit); 224 // Now PHIs should look like: 225 // NewExit: 226 // PN = PHI [I, Latch], [undef, PreHeader] 227 // ... 228 // Exit: 229 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch] 230 } 231 232 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader). 233 // Update corresponding PHI nodes in epilog loop. 234 for (BasicBlock *Succ : successors(Latch)) { 235 // Skip this as we already updated phis in exit blocks. 236 if (!L->contains(Succ)) 237 continue; 238 for (Instruction &BBI : *Succ) { 239 PHINode *PN = dyn_cast<PHINode>(&BBI); 240 // Exit when we passed all PHI nodes. 241 if (!PN) 242 break; 243 // Add new PHI nodes to the loop exit block and update epilog 244 // PHIs with the new PHI values. 245 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr", 246 NewExit->getFirstNonPHI()); 247 // Adding a value to the new PHI node from the unrolling loop preheader. 248 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader); 249 // Adding a value to the new PHI node from the unrolling loop latch. 250 NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch); 251 252 // Update the existing PHI node operand with the value from the new PHI 253 // node. Corresponding instruction in epilog loop should be PHI. 254 PHINode *VPN = cast<PHINode>(VMap[&BBI]); 255 VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN); 256 } 257 } 258 259 Instruction *InsertPt = NewExit->getTerminator(); 260 IRBuilder<> B(InsertPt); 261 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod"); 262 assert(Exit && "Loop must have a single exit block only"); 263 // Split the exit to maintain loop canonicalization guarantees 264 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); 265 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, 266 PreserveLCSSA); 267 // Add the branch to the exit block (around the unrolling loop) 268 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit); 269 InsertPt->eraseFromParent(); 270 } 271 272 /// Create a clone of the blocks in a loop and connect them together. 273 /// If CreateRemainderLoop is false, loop structure will not be cloned, 274 /// otherwise a new loop will be created including all cloned blocks, and the 275 /// iterator of it switches to count NewIter down to 0. 276 /// The cloned blocks should be inserted between InsertTop and InsertBot. 277 /// If loop structure is cloned InsertTop should be new preheader, InsertBot 278 /// new loop exit. 279 /// 280 static void CloneLoopBlocks(Loop *L, Value *NewIter, 281 const bool CreateRemainderLoop, 282 const bool UseEpilogRemainder, 283 BasicBlock *InsertTop, BasicBlock *InsertBot, 284 BasicBlock *Preheader, 285 std::vector<BasicBlock *> &NewBlocks, 286 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, 287 LoopInfo *LI) { 288 StringRef suffix = UseEpilogRemainder ? "epil" : "prol"; 289 BasicBlock *Header = L->getHeader(); 290 BasicBlock *Latch = L->getLoopLatch(); 291 Function *F = Header->getParent(); 292 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 293 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 294 Loop *ParentLoop = L->getParentLoop(); 295 296 // The map from original loops to their cloned copies. 297 SmallDenseMap<const Loop *, Loop *, 4> NewLoops; 298 299 // For each block in the original loop, create a new copy, 300 // and update the value map with the newly created values. 301 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 302 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F); 303 NewBlocks.push_back(NewBB); 304 305 // Figure out which loop NewBB is in. 306 auto findClonedLoop = [&](const Loop *OldLoop) { 307 Loop *&NewLoop = NewLoops[OldLoop]; 308 // If we've encountered this loop before, return it right away. 309 if (NewLoop) 310 return NewLoop; 311 312 // If BB is from L, and we're not creating a remainder, the loop for 313 // NewBB will be ParentLoop, which might be null. Update NewLoops map and 314 // return ParentLoop. 315 if (OldLoop == L && !CreateRemainderLoop) 316 return (NewLoop = ParentLoop); 317 318 // Now we know that there should be a cloned counterpart for OldLoop, but 319 // we haven't seen it yet. Note that OldLoop might be L if we're 320 // generating a remainder loop, or it can be an inner loop of L - in this 321 // case we'll recreate the loop structure of L in its clone. 322 323 // This is a first block belonging to OldLoop encountered in our RPO 324 // traversal. 325 assert(*BB == OldLoop->getHeader() && "Header should be first in RPO"); 326 327 NewLoop = new Loop; 328 Loop *OldLoopParent = OldLoop->getParentLoop(); 329 // If OldLoop has a parent loop, we have two options: 330 // 1. ParentLoop is the parent of L. It won't be cloned, and it will 331 // be a parent for NewLoop too. 332 // 2. ParentLoop is not a parent of L. In this case, it should be one 333 // of the cloned loops and we should be able to find it in our map. 334 // 335 // If OldLoop doesn't have a parent, then NewLoop should be yet another 336 // top-level loop. 337 if (OldLoopParent) { 338 Loop *NewLoopParent = ParentLoop == OldLoopParent 339 ? ParentLoop 340 : NewLoops.lookup(OldLoopParent); 341 assert(NewLoopParent && "Expected parent loop before sub-loop in RPO"); 342 NewLoopParent->addChildLoop(NewLoop); 343 } else 344 LI->addTopLevelLoop(NewLoop); 345 return NewLoop; 346 }; 347 348 Loop *NewLoop = findClonedLoop(LI->getLoopFor(*BB)); 349 350 assert(NewLoop || 351 (!CreateRemainderLoop && !ParentLoop) && 352 "NewLoop can only be null if we are cloning top-level loop " 353 "without creating a remainder loop."); 354 if (NewLoop) 355 NewLoop->addBasicBlockToLoop(NewBB, *LI); 356 357 VMap[*BB] = NewBB; 358 if (Header == *BB) { 359 // For the first block, add a CFG connection to this newly 360 // created block. 361 InsertTop->getTerminator()->setSuccessor(0, NewBB); 362 } 363 364 if (Latch == *BB) { 365 // For the last block, if CreateRemainderLoop is false, create a direct 366 // jump to InsertBot. If not, create a loop back to cloned head. 367 VMap.erase((*BB)->getTerminator()); 368 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); 369 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); 370 IRBuilder<> Builder(LatchBR); 371 if (!CreateRemainderLoop) { 372 Builder.CreateBr(InsertBot); 373 } else { 374 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, 375 suffix + ".iter", 376 FirstLoopBB->getFirstNonPHI()); 377 Value *IdxSub = 378 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), 379 NewIdx->getName() + ".sub"); 380 Value *IdxCmp = 381 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); 382 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot); 383 NewIdx->addIncoming(NewIter, InsertTop); 384 NewIdx->addIncoming(IdxSub, NewBB); 385 } 386 LatchBR->eraseFromParent(); 387 } 388 } 389 390 // Change the incoming values to the ones defined in the preheader or 391 // cloned loop. 392 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 393 PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 394 if (!CreateRemainderLoop) { 395 if (UseEpilogRemainder) { 396 unsigned idx = NewPHI->getBasicBlockIndex(Preheader); 397 NewPHI->setIncomingBlock(idx, InsertTop); 398 NewPHI->removeIncomingValue(Latch, false); 399 } else { 400 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader); 401 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 402 } 403 } else { 404 unsigned idx = NewPHI->getBasicBlockIndex(Preheader); 405 NewPHI->setIncomingBlock(idx, InsertTop); 406 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 407 idx = NewPHI->getBasicBlockIndex(Latch); 408 Value *InVal = NewPHI->getIncomingValue(idx); 409 NewPHI->setIncomingBlock(idx, NewLatch); 410 if (Value *V = VMap.lookup(InVal)) 411 NewPHI->setIncomingValue(idx, V); 412 } 413 } 414 if (CreateRemainderLoop) { 415 Loop *NewLoop = NewLoops[L]; 416 // Add unroll disable metadata to disable future unrolling for this loop. 417 SmallVector<Metadata *, 4> MDs; 418 // Reserve first location for self reference to the LoopID metadata node. 419 MDs.push_back(nullptr); 420 MDNode *LoopID = NewLoop->getLoopID(); 421 if (LoopID) { 422 // First remove any existing loop unrolling metadata. 423 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 424 bool IsUnrollMetadata = false; 425 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 426 if (MD) { 427 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 428 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 429 } 430 if (!IsUnrollMetadata) 431 MDs.push_back(LoopID->getOperand(i)); 432 } 433 } 434 435 LLVMContext &Context = NewLoop->getHeader()->getContext(); 436 SmallVector<Metadata *, 1> DisableOperands; 437 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 438 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 439 MDs.push_back(DisableNode); 440 441 MDNode *NewLoopID = MDNode::get(Context, MDs); 442 // Set operand 0 to refer to the loop id itself. 443 NewLoopID->replaceOperandWith(0, NewLoopID); 444 NewLoop->setLoopID(NewLoopID); 445 } 446 } 447 448 /// Insert code in the prolog/epilog code when unrolling a loop with a 449 /// run-time trip-count. 450 /// 451 /// This method assumes that the loop unroll factor is total number 452 /// of loop bodies in the loop after unrolling. (Some folks refer 453 /// to the unroll factor as the number of *extra* copies added). 454 /// We assume also that the loop unroll factor is a power-of-two. So, after 455 /// unrolling the loop, the number of loop bodies executed is 2, 456 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch 457 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for 458 /// the switch instruction is generated. 459 /// 460 /// ***Prolog case*** 461 /// extraiters = tripcount % loopfactor 462 /// if (extraiters == 0) jump Loop: 463 /// else jump Prol: 464 /// Prol: LoopBody; 465 /// extraiters -= 1 // Omitted if unroll factor is 2. 466 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. 467 /// if (tripcount < loopfactor) jump End: 468 /// Loop: 469 /// ... 470 /// End: 471 /// 472 /// ***Epilog case*** 473 /// extraiters = tripcount % loopfactor 474 /// if (tripcount < loopfactor) jump LoopExit: 475 /// unroll_iters = tripcount - extraiters 476 /// Loop: LoopBody; (executes unroll_iter times); 477 /// unroll_iter -= 1 478 /// if (unroll_iter != 0) jump Loop: 479 /// LoopExit: 480 /// if (extraiters == 0) jump EpilExit: 481 /// Epil: LoopBody; (executes extraiters times) 482 /// extraiters -= 1 // Omitted if unroll factor is 2. 483 /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2. 484 /// EpilExit: 485 486 bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, 487 bool AllowExpensiveTripCount, 488 bool UseEpilogRemainder, 489 LoopInfo *LI, ScalarEvolution *SE, 490 DominatorTree *DT, bool PreserveLCSSA) { 491 // for now, only unroll loops that contain a single exit 492 if (!L->getExitingBlock()) 493 return false; 494 495 // Make sure the loop is in canonical form, and there is a single 496 // exit block only. 497 if (!L->isLoopSimplifyForm()) 498 return false; 499 BasicBlock *Exit = L->getUniqueExitBlock(); // successor out of loop 500 if (!Exit) 501 return false; 502 503 // Use Scalar Evolution to compute the trip count. This allows more loops to 504 // be unrolled than relying on induction var simplification. 505 if (!SE) 506 return false; 507 508 // Only unroll loops with a computable trip count, and the trip count needs 509 // to be an int value (allowing a pointer type is a TODO item). 510 const SCEV *BECountSC = SE->getBackedgeTakenCount(L); 511 if (isa<SCEVCouldNotCompute>(BECountSC) || 512 !BECountSC->getType()->isIntegerTy()) 513 return false; 514 515 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth(); 516 517 // Add 1 since the backedge count doesn't include the first loop iteration. 518 const SCEV *TripCountSC = 519 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1)); 520 if (isa<SCEVCouldNotCompute>(TripCountSC)) 521 return false; 522 523 BasicBlock *Header = L->getHeader(); 524 BasicBlock *PreHeader = L->getLoopPreheader(); 525 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); 526 const DataLayout &DL = Header->getModule()->getDataLayout(); 527 SCEVExpander Expander(*SE, DL, "loop-unroll"); 528 if (!AllowExpensiveTripCount && 529 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) 530 return false; 531 532 // This constraint lets us deal with an overflowing trip count easily; see the 533 // comment on ModVal below. 534 if (Log2_32(Count) > BEWidth) 535 return false; 536 537 BasicBlock *Latch = L->getLoopLatch(); 538 539 // Loop structure is the following: 540 // 541 // PreHeader 542 // Header 543 // ... 544 // Latch 545 // Exit 546 547 BasicBlock *NewPreHeader; 548 BasicBlock *NewExit = nullptr; 549 BasicBlock *PrologExit = nullptr; 550 BasicBlock *EpilogPreHeader = nullptr; 551 BasicBlock *PrologPreHeader = nullptr; 552 553 if (UseEpilogRemainder) { 554 // If epilog remainder 555 // Split PreHeader to insert a branch around loop for unrolling. 556 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI); 557 NewPreHeader->setName(PreHeader->getName() + ".new"); 558 // Split Exit to create phi nodes from branch above. 559 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); 560 NewExit = SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", 561 DT, LI, PreserveLCSSA); 562 // Split NewExit to insert epilog remainder loop. 563 EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI); 564 EpilogPreHeader->setName(Header->getName() + ".epil.preheader"); 565 } else { 566 // If prolog remainder 567 // Split the original preheader twice to insert prolog remainder loop 568 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI); 569 PrologPreHeader->setName(Header->getName() + ".prol.preheader"); 570 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(), 571 DT, LI); 572 PrologExit->setName(Header->getName() + ".prol.loopexit"); 573 // Split PrologExit to get NewPreHeader. 574 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI); 575 NewPreHeader->setName(PreHeader->getName() + ".new"); 576 } 577 // Loop structure should be the following: 578 // Epilog Prolog 579 // 580 // PreHeader PreHeader 581 // *NewPreHeader *PrologPreHeader 582 // Header *PrologExit 583 // ... *NewPreHeader 584 // Latch Header 585 // *NewExit ... 586 // *EpilogPreHeader Latch 587 // Exit Exit 588 589 // Calculate conditions for branch around loop for unrolling 590 // in epilog case and around prolog remainder loop in prolog case. 591 // Compute the number of extra iterations required, which is: 592 // extra iterations = run-time trip count % loop unroll factor 593 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); 594 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), 595 PreHeaderBR); 596 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(), 597 PreHeaderBR); 598 IRBuilder<> B(PreHeaderBR); 599 Value *ModVal; 600 // Calculate ModVal = (BECount + 1) % Count. 601 // Note that TripCount is BECount + 1. 602 if (isPowerOf2_32(Count)) { 603 // When Count is power of 2 we don't BECount for epilog case, however we'll 604 // need it for a branch around unrolling loop for prolog case. 605 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter"); 606 // 1. There are no iterations to be run in the prolog/epilog loop. 607 // OR 608 // 2. The addition computing TripCount overflowed. 609 // 610 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so 611 // the number of iterations that remain to be run in the original loop is a 612 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we 613 // explicitly check this above). 614 } else { 615 // As (BECount + 1) can potentially unsigned overflow we count 616 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count. 617 Value *ModValTmp = B.CreateURem(BECount, 618 ConstantInt::get(BECount->getType(), 619 Count)); 620 Value *ModValAdd = B.CreateAdd(ModValTmp, 621 ConstantInt::get(ModValTmp->getType(), 1)); 622 // At that point (BECount % Count) + 1 could be equal to Count. 623 // To handle this case we need to take mod by Count one more time. 624 ModVal = B.CreateURem(ModValAdd, 625 ConstantInt::get(BECount->getType(), Count), 626 "xtraiter"); 627 } 628 Value *BranchVal = 629 UseEpilogRemainder ? B.CreateICmpULT(BECount, 630 ConstantInt::get(BECount->getType(), 631 Count - 1)) : 632 B.CreateIsNotNull(ModVal, "lcmp.mod"); 633 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader; 634 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit; 635 // Branch to either remainder (extra iterations) loop or unrolling loop. 636 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop); 637 PreHeaderBR->eraseFromParent(); 638 Function *F = Header->getParent(); 639 // Get an ordered list of blocks in the loop to help with the ordering of the 640 // cloned blocks in the prolog/epilog code 641 LoopBlocksDFS LoopBlocks(L); 642 LoopBlocks.perform(LI); 643 644 // 645 // For each extra loop iteration, create a copy of the loop's basic blocks 646 // and generate a condition that branches to the copy depending on the 647 // number of 'left over' iterations. 648 // 649 std::vector<BasicBlock *> NewBlocks; 650 ValueToValueMapTy VMap; 651 652 // For unroll factor 2 remainder loop will have 1 iterations. 653 // Do not create 1 iteration loop. 654 bool CreateRemainderLoop = (Count != 2); 655 656 // Clone all the basic blocks in the loop. If Count is 2, we don't clone 657 // the loop, otherwise we create a cloned loop to execute the extra 658 // iterations. This function adds the appropriate CFG connections. 659 BasicBlock *InsertBot = UseEpilogRemainder ? Exit : PrologExit; 660 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader; 661 CloneLoopBlocks(L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop, 662 InsertBot, NewPreHeader, NewBlocks, LoopBlocks, VMap, LI); 663 664 // Insert the cloned blocks into the function. 665 F->getBasicBlockList().splice(InsertBot->getIterator(), 666 F->getBasicBlockList(), 667 NewBlocks[0]->getIterator(), 668 F->end()); 669 670 // Loop structure should be the following: 671 // Epilog Prolog 672 // 673 // PreHeader PreHeader 674 // NewPreHeader PrologPreHeader 675 // Header PrologHeader 676 // ... ... 677 // Latch PrologLatch 678 // NewExit PrologExit 679 // EpilogPreHeader NewPreHeader 680 // EpilogHeader Header 681 // ... ... 682 // EpilogLatch Latch 683 // Exit Exit 684 685 // Rewrite the cloned instruction operands to use the values created when the 686 // clone is created. 687 for (BasicBlock *BB : NewBlocks) { 688 for (Instruction &I : *BB) { 689 RemapInstruction(&I, VMap, 690 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 691 } 692 } 693 694 if (UseEpilogRemainder) { 695 // Connect the epilog code to the original loop and update the 696 // PHI functions. 697 ConnectEpilog(L, ModVal, NewExit, Exit, PreHeader, 698 EpilogPreHeader, NewPreHeader, VMap, DT, LI, 699 PreserveLCSSA); 700 701 // Update counter in loop for unrolling. 702 // I should be multiply of Count. 703 IRBuilder<> B2(NewPreHeader->getTerminator()); 704 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter"); 705 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); 706 B2.SetInsertPoint(LatchBR); 707 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter", 708 Header->getFirstNonPHI()); 709 Value *IdxSub = 710 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), 711 NewIdx->getName() + ".nsub"); 712 Value *IdxCmp; 713 if (LatchBR->getSuccessor(0) == Header) 714 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp"); 715 else 716 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp"); 717 NewIdx->addIncoming(TestVal, NewPreHeader); 718 NewIdx->addIncoming(IdxSub, Latch); 719 LatchBR->setCondition(IdxCmp); 720 } else { 721 // Connect the prolog code to the original loop and update the 722 // PHI functions. 723 ConnectProlog(L, BECount, Count, PrologExit, PreHeader, NewPreHeader, 724 VMap, DT, LI, PreserveLCSSA); 725 } 726 727 // If this loop is nested, then the loop unroller changes the code in the 728 // parent loop, so the Scalar Evolution pass needs to be run again. 729 if (Loop *ParentLoop = L->getParentLoop()) 730 SE->forgetLoop(ParentLoop); 731 732 NumRuntimeUnrolled++; 733 return true; 734 } 735