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