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