1 //===-- UnrollLoop.cpp - 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. It does not define any 10 // actual pass or policy, but provides a single function to perform loop 11 // unrolling. 12 // 13 // The process of unrolling can produce extraneous basic blocks linked with 14 // unconditional branches. This will be corrected in the future. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AssumptionCache.h" 21 #include "llvm/Analysis/InstructionSimplify.h" 22 #include "llvm/Analysis/LoopIterator.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/Analysis/ScalarEvolution.h" 25 #include "llvm/IR/BasicBlock.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/DebugInfoMetadata.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 35 #include "llvm/Transforms/Utils/Cloning.h" 36 #include "llvm/Transforms/Utils/Local.h" 37 #include "llvm/Transforms/Utils/LoopSimplify.h" 38 #include "llvm/Transforms/Utils/LoopUtils.h" 39 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 40 #include "llvm/Transforms/Utils/UnrollLoop.h" 41 using namespace llvm; 42 43 #define DEBUG_TYPE "loop-unroll" 44 45 // TODO: Should these be here or in LoopUnroll? 46 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled"); 47 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)"); 48 STATISTIC(NumUnrolledWithHeader, "Number of loops unrolled without a " 49 "conditional latch (completely or otherwise)"); 50 51 static cl::opt<bool> 52 UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, 53 cl::desc("Allow runtime unrolled loops to be unrolled " 54 "with epilog instead of prolog.")); 55 56 static cl::opt<bool> 57 UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, 58 cl::desc("Verify domtree after unrolling"), 59 #ifdef EXPENSIVE_CHECKS 60 cl::init(true) 61 #else 62 cl::init(false) 63 #endif 64 ); 65 66 /// Convert the instruction operands from referencing the current values into 67 /// those specified by VMap. 68 void llvm::remapInstruction(Instruction *I, ValueToValueMapTy &VMap) { 69 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 70 Value *Op = I->getOperand(op); 71 72 // Unwrap arguments of dbg.value intrinsics. 73 bool Wrapped = false; 74 if (auto *V = dyn_cast<MetadataAsValue>(Op)) 75 if (auto *Unwrapped = dyn_cast<ValueAsMetadata>(V->getMetadata())) { 76 Op = Unwrapped->getValue(); 77 Wrapped = true; 78 } 79 80 auto wrap = [&](Value *V) { 81 auto &C = I->getContext(); 82 return Wrapped ? MetadataAsValue::get(C, ValueAsMetadata::get(V)) : V; 83 }; 84 85 ValueToValueMapTy::iterator It = VMap.find(Op); 86 if (It != VMap.end()) 87 I->setOperand(op, wrap(It->second)); 88 } 89 90 if (PHINode *PN = dyn_cast<PHINode>(I)) { 91 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 92 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i)); 93 if (It != VMap.end()) 94 PN->setIncomingBlock(i, cast<BasicBlock>(It->second)); 95 } 96 } 97 } 98 99 /// Check if unrolling created a situation where we need to insert phi nodes to 100 /// preserve LCSSA form. 101 /// \param Blocks is a vector of basic blocks representing unrolled loop. 102 /// \param L is the outer loop. 103 /// It's possible that some of the blocks are in L, and some are not. In this 104 /// case, if there is a use is outside L, and definition is inside L, we need to 105 /// insert a phi-node, otherwise LCSSA will be broken. 106 /// The function is just a helper function for llvm::UnrollLoop that returns 107 /// true if this situation occurs, indicating that LCSSA needs to be fixed. 108 static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks, 109 LoopInfo *LI) { 110 for (BasicBlock *BB : Blocks) { 111 if (LI->getLoopFor(BB) == L) 112 continue; 113 for (Instruction &I : *BB) { 114 for (Use &U : I.operands()) { 115 if (auto Def = dyn_cast<Instruction>(U)) { 116 Loop *DefLoop = LI->getLoopFor(Def->getParent()); 117 if (!DefLoop) 118 continue; 119 if (DefLoop->contains(L)) 120 return true; 121 } 122 } 123 } 124 } 125 return false; 126 } 127 128 /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary 129 /// and adds a mapping from the original loop to the new loop to NewLoops. 130 /// Returns nullptr if no new loop was created and a pointer to the 131 /// original loop OriginalBB was part of otherwise. 132 const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB, 133 BasicBlock *ClonedBB, LoopInfo *LI, 134 NewLoopsMap &NewLoops) { 135 // Figure out which loop New is in. 136 const Loop *OldLoop = LI->getLoopFor(OriginalBB); 137 assert(OldLoop && "Should (at least) be in the loop being unrolled!"); 138 139 Loop *&NewLoop = NewLoops[OldLoop]; 140 if (!NewLoop) { 141 // Found a new sub-loop. 142 assert(OriginalBB == OldLoop->getHeader() && 143 "Header should be first in RPO"); 144 145 NewLoop = LI->AllocateLoop(); 146 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop()); 147 148 if (NewLoopParent) 149 NewLoopParent->addChildLoop(NewLoop); 150 else 151 LI->addTopLevelLoop(NewLoop); 152 153 NewLoop->addBasicBlockToLoop(ClonedBB, *LI); 154 return OldLoop; 155 } else { 156 NewLoop->addBasicBlockToLoop(ClonedBB, *LI); 157 return nullptr; 158 } 159 } 160 161 /// The function chooses which type of unroll (epilog or prolog) is more 162 /// profitabale. 163 /// Epilog unroll is more profitable when there is PHI that starts from 164 /// constant. In this case epilog will leave PHI start from constant, 165 /// but prolog will convert it to non-constant. 166 /// 167 /// loop: 168 /// PN = PHI [I, Latch], [CI, PreHeader] 169 /// I = foo(PN) 170 /// ... 171 /// 172 /// Epilog unroll case. 173 /// loop: 174 /// PN = PHI [I2, Latch], [CI, PreHeader] 175 /// I1 = foo(PN) 176 /// I2 = foo(I1) 177 /// ... 178 /// Prolog unroll case. 179 /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader] 180 /// loop: 181 /// PN = PHI [I2, Latch], [NewPN, PreHeader] 182 /// I1 = foo(PN) 183 /// I2 = foo(I1) 184 /// ... 185 /// 186 static bool isEpilogProfitable(Loop *L) { 187 BasicBlock *PreHeader = L->getLoopPreheader(); 188 BasicBlock *Header = L->getHeader(); 189 assert(PreHeader && Header); 190 for (const PHINode &PN : Header->phis()) { 191 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader))) 192 return true; 193 } 194 return false; 195 } 196 197 /// Perform some cleanup and simplifications on loops after unrolling. It is 198 /// useful to simplify the IV's in the new loop, as well as do a quick 199 /// simplify/dce pass of the instructions. 200 void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, 201 ScalarEvolution *SE, DominatorTree *DT, 202 AssumptionCache *AC) { 203 // Simplify any new induction variables in the partially unrolled loop. 204 if (SE && SimplifyIVs) { 205 SmallVector<WeakTrackingVH, 16> DeadInsts; 206 simplifyLoopIVs(L, SE, DT, LI, DeadInsts); 207 208 // Aggressively clean up dead instructions that simplifyLoopIVs already 209 // identified. Any remaining should be cleaned up below. 210 while (!DeadInsts.empty()) { 211 Value *V = DeadInsts.pop_back_val(); 212 if (Instruction *Inst = dyn_cast_or_null<Instruction>(V)) 213 RecursivelyDeleteTriviallyDeadInstructions(Inst); 214 } 215 } 216 217 // At this point, the code is well formed. We now do a quick sweep over the 218 // inserted code, doing constant propagation and dead code elimination as we 219 // go. 220 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 221 for (BasicBlock *BB : L->getBlocks()) { 222 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 223 Instruction *Inst = &*I++; 224 225 if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC})) 226 if (LI->replacementPreservesLCSSAForm(Inst, V)) 227 Inst->replaceAllUsesWith(V); 228 if (isInstructionTriviallyDead(Inst)) 229 BB->getInstList().erase(Inst); 230 } 231 } 232 233 // TODO: after peeling or unrolling, previously loop variant conditions are 234 // likely to fold to constants, eagerly propagating those here will require 235 // fewer cleanup passes to be run. Alternatively, a LoopEarlyCSE might be 236 // appropriate. 237 } 238 239 /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling 240 /// can only fail when the loop's latch block is not terminated by a conditional 241 /// branch instruction. However, if the trip count (and multiple) are not known, 242 /// loop unrolling will mostly produce more code that is no faster. 243 /// 244 /// TripCount is the upper bound of the iteration on which control exits 245 /// LatchBlock. Control may exit the loop prior to TripCount iterations either 246 /// via an early branch in other loop block or via LatchBlock terminator. This 247 /// is relaxed from the general definition of trip count which is the number of 248 /// times the loop header executes. Note that UnrollLoop assumes that the loop 249 /// counter test is in LatchBlock in order to remove unnecesssary instances of 250 /// the test. If control can exit the loop from the LatchBlock's terminator 251 /// prior to TripCount iterations, flag PreserveCondBr needs to be set. 252 /// 253 /// PreserveCondBr indicates whether the conditional branch of the LatchBlock 254 /// needs to be preserved. It is needed when we use trip count upper bound to 255 /// fully unroll the loop. If PreserveOnlyFirst is also set then only the first 256 /// conditional branch needs to be preserved. 257 /// 258 /// Similarly, TripMultiple divides the number of times that the LatchBlock may 259 /// execute without exiting the loop. 260 /// 261 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that 262 /// have a runtime (i.e. not compile time constant) trip count. Unrolling these 263 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count" 264 /// iterations before branching into the unrolled loop. UnrollLoop will not 265 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and 266 /// AllowExpensiveTripCount is false. 267 /// 268 /// If we want to perform PGO-based loop peeling, PeelCount is set to the 269 /// number of iterations we want to peel off. 270 /// 271 /// The LoopInfo Analysis that is passed will be kept consistent. 272 /// 273 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and 274 /// DominatorTree if they are non-null. 275 /// 276 /// If RemainderLoop is non-null, it will receive the remainder loop (if 277 /// required and not fully unrolled). 278 LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, 279 ScalarEvolution *SE, DominatorTree *DT, 280 AssumptionCache *AC, 281 OptimizationRemarkEmitter *ORE, 282 bool PreserveLCSSA, Loop **RemainderLoop) { 283 284 BasicBlock *Preheader = L->getLoopPreheader(); 285 if (!Preheader) { 286 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n"); 287 return LoopUnrollResult::Unmodified; 288 } 289 290 BasicBlock *LatchBlock = L->getLoopLatch(); 291 if (!LatchBlock) { 292 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n"); 293 return LoopUnrollResult::Unmodified; 294 } 295 296 // Loops with indirectbr cannot be cloned. 297 if (!L->isSafeToClone()) { 298 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n"); 299 return LoopUnrollResult::Unmodified; 300 } 301 302 // The current loop unroll pass can unroll loops with a single latch or header 303 // that's a conditional branch exiting the loop. 304 // FIXME: The implementation can be extended to work with more complicated 305 // cases, e.g. loops with multiple latches. 306 BasicBlock *Header = L->getHeader(); 307 BranchInst *HeaderBI = dyn_cast<BranchInst>(Header->getTerminator()); 308 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); 309 310 // FIXME: Support loops without conditional latch and multiple exiting blocks. 311 if (!BI || 312 (BI->isUnconditional() && (!HeaderBI || HeaderBI->isUnconditional() || 313 L->getExitingBlock() != Header))) { 314 LLVM_DEBUG(dbgs() << " Can't unroll; loop not terminated by a conditional " 315 "branch in the latch or header.\n"); 316 return LoopUnrollResult::Unmodified; 317 } 318 319 auto CheckLatchSuccessors = [&](unsigned S1, unsigned S2) { 320 return BI->isConditional() && BI->getSuccessor(S1) == Header && 321 !L->contains(BI->getSuccessor(S2)); 322 }; 323 324 // If we have a conditional latch, it must exit the loop. 325 if (BI && BI->isConditional() && !CheckLatchSuccessors(0, 1) && 326 !CheckLatchSuccessors(1, 0)) { 327 LLVM_DEBUG( 328 dbgs() << "Can't unroll; a conditional latch must exit the loop"); 329 return LoopUnrollResult::Unmodified; 330 } 331 332 auto CheckHeaderSuccessors = [&](unsigned S1, unsigned S2) { 333 return HeaderBI && HeaderBI->isConditional() && 334 L->contains(HeaderBI->getSuccessor(S1)) && 335 !L->contains(HeaderBI->getSuccessor(S2)); 336 }; 337 338 // If we do not have a conditional latch, the header must exit the loop. 339 if (BI && !BI->isConditional() && HeaderBI && HeaderBI->isConditional() && 340 !CheckHeaderSuccessors(0, 1) && !CheckHeaderSuccessors(1, 0)) { 341 LLVM_DEBUG(dbgs() << "Can't unroll; conditional header must exit the loop"); 342 return LoopUnrollResult::Unmodified; 343 } 344 345 if (Header->hasAddressTaken()) { 346 // The loop-rotate pass can be helpful to avoid this in many cases. 347 LLVM_DEBUG( 348 dbgs() << " Won't unroll loop: address of header block is taken.\n"); 349 return LoopUnrollResult::Unmodified; 350 } 351 352 if (ULO.TripCount != 0) 353 LLVM_DEBUG(dbgs() << " Trip Count = " << ULO.TripCount << "\n"); 354 if (ULO.TripMultiple != 1) 355 LLVM_DEBUG(dbgs() << " Trip Multiple = " << ULO.TripMultiple << "\n"); 356 357 // Effectively "DCE" unrolled iterations that are beyond the tripcount 358 // and will never be executed. 359 if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount) 360 ULO.Count = ULO.TripCount; 361 362 // Don't enter the unroll code if there is nothing to do. 363 if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) { 364 LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n"); 365 return LoopUnrollResult::Unmodified; 366 } 367 368 assert(ULO.Count > 0); 369 assert(ULO.TripMultiple > 0); 370 assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0); 371 372 // Are we eliminating the loop control altogether? 373 bool CompletelyUnroll = ULO.Count == ULO.TripCount; 374 SmallVector<BasicBlock *, 4> ExitBlocks; 375 L->getExitBlocks(ExitBlocks); 376 std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks(); 377 378 // Go through all exits of L and see if there are any phi-nodes there. We just 379 // conservatively assume that they're inserted to preserve LCSSA form, which 380 // means that complete unrolling might break this form. We need to either fix 381 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For 382 // now we just recompute LCSSA for the outer loop, but it should be possible 383 // to fix it in-place. 384 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll && 385 any_of(ExitBlocks, [](const BasicBlock *BB) { 386 return isa<PHINode>(BB->begin()); 387 }); 388 389 // We assume a run-time trip count if the compiler cannot 390 // figure out the loop trip count and the unroll-runtime 391 // flag is specified. 392 bool RuntimeTripCount = 393 (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime); 394 395 assert((!RuntimeTripCount || !ULO.PeelCount) && 396 "Did not expect runtime trip-count unrolling " 397 "and peeling for the same loop"); 398 399 bool Peeled = false; 400 if (ULO.PeelCount) { 401 Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA); 402 403 // Successful peeling may result in a change in the loop preheader/trip 404 // counts. If we later unroll the loop, we want these to be updated. 405 if (Peeled) { 406 // According to our guards and profitability checks the only 407 // meaningful exit should be latch block. Other exits go to deopt, 408 // so we do not worry about them. 409 BasicBlock *ExitingBlock = L->getLoopLatch(); 410 assert(ExitingBlock && "Loop without exiting block?"); 411 assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?"); 412 Preheader = L->getLoopPreheader(); 413 ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 414 ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 415 } 416 } 417 418 // Loops containing convergent instructions must have a count that divides 419 // their TripMultiple. 420 LLVM_DEBUG( 421 { 422 bool HasConvergent = false; 423 for (auto &BB : L->blocks()) 424 for (auto &I : *BB) 425 if (auto CS = CallSite(&I)) 426 HasConvergent |= CS.isConvergent(); 427 assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && 428 "Unroll count must divide trip multiple if loop contains a " 429 "convergent operation."); 430 }); 431 432 bool EpilogProfitability = 433 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog 434 : isEpilogProfitable(L); 435 436 if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 && 437 !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount, 438 EpilogProfitability, ULO.UnrollRemainder, 439 ULO.ForgetAllSCEV, LI, SE, DT, AC, 440 PreserveLCSSA, RemainderLoop)) { 441 if (ULO.Force) 442 RuntimeTripCount = false; 443 else { 444 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be " 445 "generated when assuming runtime trip count\n"); 446 return LoopUnrollResult::Unmodified; 447 } 448 } 449 450 // If we know the trip count, we know the multiple... 451 unsigned BreakoutTrip = 0; 452 if (ULO.TripCount != 0) { 453 BreakoutTrip = ULO.TripCount % ULO.Count; 454 ULO.TripMultiple = 0; 455 } else { 456 // Figure out what multiple to use. 457 BreakoutTrip = ULO.TripMultiple = 458 (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple); 459 } 460 461 using namespace ore; 462 // Report the unrolling decision. 463 if (CompletelyUnroll) { 464 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName() 465 << " with trip count " << ULO.TripCount << "!\n"); 466 if (ORE) 467 ORE->emit([&]() { 468 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(), 469 L->getHeader()) 470 << "completely unrolled loop with " 471 << NV("UnrollCount", ULO.TripCount) << " iterations"; 472 }); 473 } else if (ULO.PeelCount) { 474 LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName() 475 << " with iteration count " << ULO.PeelCount << "!\n"); 476 if (ORE) 477 ORE->emit([&]() { 478 return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(), 479 L->getHeader()) 480 << " peeled loop by " << NV("PeelCount", ULO.PeelCount) 481 << " iterations"; 482 }); 483 } else { 484 auto DiagBuilder = [&]() { 485 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(), 486 L->getHeader()); 487 return Diag << "unrolled loop by a factor of " 488 << NV("UnrollCount", ULO.Count); 489 }; 490 491 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by " 492 << ULO.Count); 493 if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) { 494 LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip); 495 if (ORE) 496 ORE->emit([&]() { 497 return DiagBuilder() << " with a breakout at trip " 498 << NV("BreakoutTrip", BreakoutTrip); 499 }); 500 } else if (ULO.TripMultiple != 1) { 501 LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch"); 502 if (ORE) 503 ORE->emit([&]() { 504 return DiagBuilder() 505 << " with " << NV("TripMultiple", ULO.TripMultiple) 506 << " trips per branch"; 507 }); 508 } else if (RuntimeTripCount) { 509 LLVM_DEBUG(dbgs() << " with run-time trip count"); 510 if (ORE) 511 ORE->emit( 512 [&]() { return DiagBuilder() << " with run-time trip count"; }); 513 } 514 LLVM_DEBUG(dbgs() << "!\n"); 515 } 516 517 // We are going to make changes to this loop. SCEV may be keeping cached info 518 // about it, in particular about backedge taken count. The changes we make 519 // are guaranteed to invalidate this information for our loop. It is tempting 520 // to only invalidate the loop being unrolled, but it is incorrect as long as 521 // all exiting branches from all inner loops have impact on the outer loops, 522 // and if something changes inside them then any of outer loops may also 523 // change. When we forget outermost loop, we also forget all contained loops 524 // and this is what we need here. 525 if (SE) { 526 if (ULO.ForgetAllSCEV) 527 SE->forgetAllLoops(); 528 else 529 SE->forgetTopmostLoop(L); 530 } 531 532 bool ContinueOnTrue; 533 bool LatchIsExiting = BI->isConditional(); 534 BasicBlock *LoopExit = nullptr; 535 if (LatchIsExiting) { 536 ContinueOnTrue = L->contains(BI->getSuccessor(0)); 537 LoopExit = BI->getSuccessor(ContinueOnTrue); 538 } else { 539 NumUnrolledWithHeader++; 540 ContinueOnTrue = L->contains(HeaderBI->getSuccessor(0)); 541 LoopExit = HeaderBI->getSuccessor(ContinueOnTrue); 542 } 543 544 // For the first iteration of the loop, we should use the precloned values for 545 // PHI nodes. Insert associations now. 546 ValueToValueMapTy LastValueMap; 547 std::vector<PHINode*> OrigPHINode; 548 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 549 OrigPHINode.push_back(cast<PHINode>(I)); 550 } 551 552 std::vector<BasicBlock *> Headers; 553 std::vector<BasicBlock *> HeaderSucc; 554 std::vector<BasicBlock *> Latches; 555 Headers.push_back(Header); 556 Latches.push_back(LatchBlock); 557 558 if (!LatchIsExiting) { 559 auto *Term = cast<BranchInst>(Header->getTerminator()); 560 if (Term->isUnconditional() || L->contains(Term->getSuccessor(0))) { 561 assert(L->contains(Term->getSuccessor(0))); 562 HeaderSucc.push_back(Term->getSuccessor(0)); 563 } else { 564 assert(L->contains(Term->getSuccessor(1))); 565 HeaderSucc.push_back(Term->getSuccessor(1)); 566 } 567 } 568 569 // The current on-the-fly SSA update requires blocks to be processed in 570 // reverse postorder so that LastValueMap contains the correct value at each 571 // exit. 572 LoopBlocksDFS DFS(L); 573 DFS.perform(LI); 574 575 // Stash the DFS iterators before adding blocks to the loop. 576 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO(); 577 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO(); 578 579 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks(); 580 581 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we 582 // might break loop-simplified form for these loops (as they, e.g., would 583 // share the same exit blocks). We'll keep track of loops for which we can 584 // break this so that later we can re-simplify them. 585 SmallSetVector<Loop *, 4> LoopsToSimplify; 586 for (Loop *SubLoop : *L) 587 LoopsToSimplify.insert(SubLoop); 588 589 if (Header->getParent()->isDebugInfoForProfiling()) 590 for (BasicBlock *BB : L->getBlocks()) 591 for (Instruction &I : *BB) 592 if (!isa<DbgInfoIntrinsic>(&I)) 593 if (const DILocation *DIL = I.getDebugLoc()) { 594 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count); 595 if (NewDIL) 596 I.setDebugLoc(NewDIL.getValue()); 597 else 598 LLVM_DEBUG(dbgs() 599 << "Failed to create new discriminator: " 600 << DIL->getFilename() << " Line: " << DIL->getLine()); 601 } 602 603 for (unsigned It = 1; It != ULO.Count; ++It) { 604 std::vector<BasicBlock*> NewBlocks; 605 SmallDenseMap<const Loop *, Loop *, 4> NewLoops; 606 NewLoops[L] = L; 607 608 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 609 ValueToValueMapTy VMap; 610 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It)); 611 Header->getParent()->getBasicBlockList().push_back(New); 612 613 assert((*BB != Header || LI->getLoopFor(*BB) == L) && 614 "Header should not be in a sub-loop"); 615 // Tell LI about New. 616 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops); 617 if (OldLoop) 618 LoopsToSimplify.insert(NewLoops[OldLoop]); 619 620 if (*BB == Header) 621 // Loop over all of the PHI nodes in the block, changing them to use 622 // the incoming values from the previous block. 623 for (PHINode *OrigPHI : OrigPHINode) { 624 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]); 625 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock); 626 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) 627 if (It > 1 && L->contains(InValI)) 628 InVal = LastValueMap[InValI]; 629 VMap[OrigPHI] = InVal; 630 New->getInstList().erase(NewPHI); 631 } 632 633 // Update our running map of newest clones 634 LastValueMap[*BB] = New; 635 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end(); 636 VI != VE; ++VI) 637 LastValueMap[VI->first] = VI->second; 638 639 // Add phi entries for newly created values to all exit blocks. 640 for (BasicBlock *Succ : successors(*BB)) { 641 if (L->contains(Succ)) 642 continue; 643 for (PHINode &PHI : Succ->phis()) { 644 Value *Incoming = PHI.getIncomingValueForBlock(*BB); 645 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming); 646 if (It != LastValueMap.end()) 647 Incoming = It->second; 648 PHI.addIncoming(Incoming, New); 649 } 650 } 651 // Keep track of new headers and latches as we create them, so that 652 // we can insert the proper branches later. 653 if (*BB == Header) 654 Headers.push_back(New); 655 if (*BB == LatchBlock) 656 Latches.push_back(New); 657 658 // Keep track of the successor of the new header in the current iteration. 659 for (auto *Pred : predecessors(*BB)) 660 if (Pred == Header) { 661 HeaderSucc.push_back(New); 662 break; 663 } 664 665 NewBlocks.push_back(New); 666 UnrolledLoopBlocks.push_back(New); 667 668 // Update DomTree: since we just copy the loop body, and each copy has a 669 // dedicated entry block (copy of the header block), this header's copy 670 // dominates all copied blocks. That means, dominance relations in the 671 // copied body are the same as in the original body. 672 if (DT) { 673 if (*BB == Header) 674 DT->addNewBlock(New, Latches[It - 1]); 675 else { 676 auto BBDomNode = DT->getNode(*BB); 677 auto BBIDom = BBDomNode->getIDom(); 678 BasicBlock *OriginalBBIDom = BBIDom->getBlock(); 679 DT->addNewBlock( 680 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)])); 681 } 682 } 683 } 684 685 // Remap all instructions in the most recent iteration 686 for (BasicBlock *NewBlock : NewBlocks) { 687 for (Instruction &I : *NewBlock) { 688 ::remapInstruction(&I, LastValueMap); 689 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 690 if (II->getIntrinsicID() == Intrinsic::assume) 691 AC->registerAssumption(II); 692 } 693 } 694 } 695 696 // Loop over the PHI nodes in the original block, setting incoming values. 697 for (PHINode *PN : OrigPHINode) { 698 if (CompletelyUnroll) { 699 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); 700 Header->getInstList().erase(PN); 701 } else if (ULO.Count > 1) { 702 Value *InVal = PN->removeIncomingValue(LatchBlock, false); 703 // If this value was defined in the loop, take the value defined by the 704 // last iteration of the loop. 705 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) { 706 if (L->contains(InValI)) 707 InVal = LastValueMap[InVal]; 708 } 709 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch"); 710 PN->addIncoming(InVal, Latches.back()); 711 } 712 } 713 714 auto setDest = [LoopExit, ContinueOnTrue](BasicBlock *Src, BasicBlock *Dest, 715 ArrayRef<BasicBlock *> NextBlocks, 716 BasicBlock *BlockInLoop, 717 bool NeedConditional) { 718 auto *Term = cast<BranchInst>(Src->getTerminator()); 719 if (NeedConditional) { 720 // Update the conditional branch's successor for the following 721 // iteration. 722 Term->setSuccessor(!ContinueOnTrue, Dest); 723 } else { 724 // Remove phi operands at this loop exit 725 if (Dest != LoopExit) { 726 BasicBlock *BB = Src; 727 for (BasicBlock *Succ : successors(BB)) { 728 // Preserve the incoming value from BB if we are jumping to the block 729 // in the current loop. 730 if (Succ == BlockInLoop) 731 continue; 732 for (PHINode &Phi : Succ->phis()) 733 Phi.removeIncomingValue(BB, false); 734 } 735 } 736 // Replace the conditional branch with an unconditional one. 737 BranchInst::Create(Dest, Term); 738 Term->eraseFromParent(); 739 } 740 }; 741 742 // Now that all the basic blocks for the unrolled iterations are in place, 743 // set up the branches to connect them. 744 if (LatchIsExiting) { 745 // Set up latches to branch to the new header in the unrolled iterations or 746 // the loop exit for the last latch in a fully unrolled loop. 747 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 748 // The branch destination. 749 unsigned j = (i + 1) % e; 750 BasicBlock *Dest = Headers[j]; 751 bool NeedConditional = true; 752 753 if (RuntimeTripCount && j != 0) { 754 NeedConditional = false; 755 } 756 757 // For a complete unroll, make the last iteration end with a branch 758 // to the exit block. 759 if (CompletelyUnroll) { 760 if (j == 0) 761 Dest = LoopExit; 762 // If using trip count upper bound to completely unroll, we need to keep 763 // the conditional branch except the last one because the loop may exit 764 // after any iteration. 765 assert(NeedConditional && 766 "NeedCondition cannot be modified by both complete " 767 "unrolling and runtime unrolling"); 768 NeedConditional = 769 (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0)); 770 } else if (j != BreakoutTrip && 771 (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) { 772 // If we know the trip count or a multiple of it, we can safely use an 773 // unconditional branch for some iterations. 774 NeedConditional = false; 775 } 776 777 setDest(Latches[i], Dest, Headers, Headers[i], NeedConditional); 778 } 779 } else { 780 // Setup headers to branch to their new successors in the unrolled 781 // iterations. 782 for (unsigned i = 0, e = Headers.size(); i != e; ++i) { 783 // The branch destination. 784 unsigned j = (i + 1) % e; 785 BasicBlock *Dest = HeaderSucc[i]; 786 bool NeedConditional = true; 787 788 if (RuntimeTripCount && j != 0) 789 NeedConditional = false; 790 791 if (CompletelyUnroll) 792 // We cannot drop the conditional branch for the last condition, as we 793 // may have to execute the loop body depending on the condition. 794 NeedConditional = j == 0 || ULO.PreserveCondBr; 795 else if (j != BreakoutTrip && 796 (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) 797 // If we know the trip count or a multiple of it, we can safely use an 798 // unconditional branch for some iterations. 799 NeedConditional = false; 800 801 setDest(Headers[i], Dest, Headers, HeaderSucc[i], NeedConditional); 802 } 803 804 // Set up latches to branch to the new header in the unrolled iterations or 805 // the loop exit for the last latch in a fully unrolled loop. 806 807 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 808 // The original branch was replicated in each unrolled iteration. 809 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 810 811 // The branch destination. 812 unsigned j = (i + 1) % e; 813 BasicBlock *Dest = Headers[j]; 814 815 // When completely unrolling, the last latch becomes unreachable. 816 if (CompletelyUnroll && j == 0) 817 new UnreachableInst(Term->getContext(), Term); 818 else 819 // Replace the conditional branch with an unconditional one. 820 BranchInst::Create(Dest, Term); 821 822 Term->eraseFromParent(); 823 } 824 } 825 826 // Update dominators of blocks we might reach through exits. 827 // Immediate dominator of such block might change, because we add more 828 // routes which can lead to the exit: we can now reach it from the copied 829 // iterations too. 830 if (DT && ULO.Count > 1) { 831 for (auto *BB : OriginalLoopBlocks) { 832 auto *BBDomNode = DT->getNode(BB); 833 SmallVector<BasicBlock *, 16> ChildrenToUpdate; 834 for (auto *ChildDomNode : BBDomNode->getChildren()) { 835 auto *ChildBB = ChildDomNode->getBlock(); 836 if (!L->contains(ChildBB)) 837 ChildrenToUpdate.push_back(ChildBB); 838 } 839 BasicBlock *NewIDom; 840 BasicBlock *&TermBlock = LatchIsExiting ? LatchBlock : Header; 841 auto &TermBlocks = LatchIsExiting ? Latches : Headers; 842 if (BB == TermBlock) { 843 // The latch is special because we emit unconditional branches in 844 // some cases where the original loop contained a conditional branch. 845 // Since the latch is always at the bottom of the loop, if the latch 846 // dominated an exit before unrolling, the new dominator of that exit 847 // must also be a latch. Specifically, the dominator is the first 848 // latch which ends in a conditional branch, or the last latch if 849 // there is no such latch. 850 // For loops exiting from the header, we limit the supported loops 851 // to have a single exiting block. 852 NewIDom = TermBlocks.back(); 853 for (BasicBlock *Iter : TermBlocks) { 854 Instruction *Term = Iter->getTerminator(); 855 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) { 856 NewIDom = Iter; 857 break; 858 } 859 } 860 } else { 861 // The new idom of the block will be the nearest common dominator 862 // of all copies of the previous idom. This is equivalent to the 863 // nearest common dominator of the previous idom and the first latch, 864 // which dominates all copies of the previous idom. 865 NewIDom = DT->findNearestCommonDominator(BB, LatchBlock); 866 } 867 for (auto *ChildBB : ChildrenToUpdate) 868 DT->changeImmediateDominator(ChildBB, NewIDom); 869 } 870 } 871 872 assert(!DT || !UnrollVerifyDomtree || 873 DT->verify(DominatorTree::VerificationLevel::Fast)); 874 875 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 876 // Merge adjacent basic blocks, if possible. 877 for (BasicBlock *Latch : Latches) { 878 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator()); 879 assert((Term || 880 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) && 881 "Need a branch as terminator, except when fully unrolling with " 882 "unconditional latch"); 883 if (Term && Term->isUnconditional()) { 884 BasicBlock *Dest = Term->getSuccessor(0); 885 BasicBlock *Fold = Dest->getUniquePredecessor(); 886 if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) { 887 // Dest has been folded into Fold. Update our worklists accordingly. 888 std::replace(Latches.begin(), Latches.end(), Dest, Fold); 889 UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(), 890 UnrolledLoopBlocks.end(), Dest), 891 UnrolledLoopBlocks.end()); 892 } 893 } 894 } 895 // Apply updates to the DomTree. 896 DT = &DTU.getDomTree(); 897 898 // At this point, the code is well formed. We now simplify the unrolled loop, 899 // doing constant propagation and dead code elimination as we go. 900 simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI, 901 SE, DT, AC); 902 903 NumCompletelyUnrolled += CompletelyUnroll; 904 ++NumUnrolled; 905 906 Loop *OuterL = L->getParentLoop(); 907 // Update LoopInfo if the loop is completely removed. 908 if (CompletelyUnroll) 909 LI->erase(L); 910 911 // After complete unrolling most of the blocks should be contained in OuterL. 912 // However, some of them might happen to be out of OuterL (e.g. if they 913 // precede a loop exit). In this case we might need to insert PHI nodes in 914 // order to preserve LCSSA form. 915 // We don't need to check this if we already know that we need to fix LCSSA 916 // form. 917 // TODO: For now we just recompute LCSSA for the outer loop in this case, but 918 // it should be possible to fix it in-place. 919 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA) 920 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI); 921 922 // If we have a pass and a DominatorTree we should re-simplify impacted loops 923 // to ensure subsequent analyses can rely on this form. We want to simplify 924 // at least one layer outside of the loop that was unrolled so that any 925 // changes to the parent loop exposed by the unrolling are considered. 926 if (DT) { 927 if (OuterL) { 928 // OuterL includes all loops for which we can break loop-simplify, so 929 // it's sufficient to simplify only it (it'll recursively simplify inner 930 // loops too). 931 if (NeedToFixLCSSA) { 932 // LCSSA must be performed on the outermost affected loop. The unrolled 933 // loop's last loop latch is guaranteed to be in the outermost loop 934 // after LoopInfo's been updated by LoopInfo::erase. 935 Loop *LatchLoop = LI->getLoopFor(Latches.back()); 936 Loop *FixLCSSALoop = OuterL; 937 if (!FixLCSSALoop->contains(LatchLoop)) 938 while (FixLCSSALoop->getParentLoop() != LatchLoop) 939 FixLCSSALoop = FixLCSSALoop->getParentLoop(); 940 941 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE); 942 } else if (PreserveLCSSA) { 943 assert(OuterL->isLCSSAForm(*DT) && 944 "Loops should be in LCSSA form after loop-unroll."); 945 } 946 947 // TODO: That potentially might be compile-time expensive. We should try 948 // to fix the loop-simplified form incrementally. 949 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA); 950 } else { 951 // Simplify loops for which we might've broken loop-simplify form. 952 for (Loop *SubLoop : LoopsToSimplify) 953 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA); 954 } 955 } 956 957 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled 958 : LoopUnrollResult::PartiallyUnrolled; 959 } 960 961 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata 962 /// node with the given name (for example, "llvm.loop.unroll.count"). If no 963 /// such metadata node exists, then nullptr is returned. 964 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) { 965 // First operand should refer to the loop id itself. 966 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 967 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 968 969 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 970 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 971 if (!MD) 972 continue; 973 974 MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 975 if (!S) 976 continue; 977 978 if (Name.equals(S->getString())) 979 return MD; 980 } 981 return nullptr; 982 } 983