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