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