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