1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// 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 defines the LoopInfo class that is used to identify natural loops 10 // and determine the loop depth of various nodes of the CFG. Note that the 11 // loops identified may actually be several natural loops that share the same 12 // header node... not just a single natural loop. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Analysis/LoopInfo.h" 17 #include "llvm/ADT/DepthFirstIterator.h" 18 #include "llvm/ADT/ScopeExit.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/Analysis/LoopInfoImpl.h" 21 #include "llvm/Analysis/LoopIterator.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/Config/llvm-config.h" 24 #include "llvm/IR/CFG.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DebugLoc.h" 27 #include "llvm/IR/Dominators.h" 28 #include "llvm/IR/IRPrintingPasses.h" 29 #include "llvm/IR/Instructions.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/PassManager.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <algorithm> 37 using namespace llvm; 38 39 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops. 40 template class llvm::LoopBase<BasicBlock, Loop>; 41 template class llvm::LoopInfoBase<BasicBlock, Loop>; 42 43 // Always verify loopinfo if expensive checking is enabled. 44 #ifdef EXPENSIVE_CHECKS 45 bool llvm::VerifyLoopInfo = true; 46 #else 47 bool llvm::VerifyLoopInfo = false; 48 #endif 49 static cl::opt<bool, true> 50 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), 51 cl::Hidden, cl::desc("Verify loop info (time consuming)")); 52 53 //===----------------------------------------------------------------------===// 54 // Loop implementation 55 // 56 57 bool Loop::isLoopInvariant(const Value *V) const { 58 if (const Instruction *I = dyn_cast<Instruction>(V)) 59 return !contains(I); 60 return true; // All non-instructions are loop invariant 61 } 62 63 bool Loop::hasLoopInvariantOperands(const Instruction *I) const { 64 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); }); 65 } 66 67 bool Loop::makeLoopInvariant(Value *V, bool &Changed, 68 Instruction *InsertPt) const { 69 if (Instruction *I = dyn_cast<Instruction>(V)) 70 return makeLoopInvariant(I, Changed, InsertPt); 71 return true; // All non-instructions are loop-invariant. 72 } 73 74 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed, 75 Instruction *InsertPt) const { 76 // Test if the value is already loop-invariant. 77 if (isLoopInvariant(I)) 78 return true; 79 if (!isSafeToSpeculativelyExecute(I)) 80 return false; 81 if (I->mayReadFromMemory()) 82 return false; 83 // EH block instructions are immobile. 84 if (I->isEHPad()) 85 return false; 86 // Determine the insertion point, unless one was given. 87 if (!InsertPt) { 88 BasicBlock *Preheader = getLoopPreheader(); 89 // Without a preheader, hoisting is not feasible. 90 if (!Preheader) 91 return false; 92 InsertPt = Preheader->getTerminator(); 93 } 94 // Don't hoist instructions with loop-variant operands. 95 for (Value *Operand : I->operands()) 96 if (!makeLoopInvariant(Operand, Changed, InsertPt)) 97 return false; 98 99 // Hoist. 100 I->moveBefore(InsertPt); 101 102 // There is possibility of hoisting this instruction above some arbitrary 103 // condition. Any metadata defined on it can be control dependent on this 104 // condition. Conservatively strip it here so that we don't give any wrong 105 // information to the optimizer. 106 I->dropUnknownNonDebugMetadata(); 107 108 Changed = true; 109 return true; 110 } 111 112 bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming, 113 BasicBlock *&Backedge) const { 114 BasicBlock *H = getHeader(); 115 116 Incoming = nullptr; 117 Backedge = nullptr; 118 pred_iterator PI = pred_begin(H); 119 assert(PI != pred_end(H) && "Loop must have at least one backedge!"); 120 Backedge = *PI++; 121 if (PI == pred_end(H)) 122 return false; // dead loop 123 Incoming = *PI++; 124 if (PI != pred_end(H)) 125 return false; // multiple backedges? 126 127 if (contains(Incoming)) { 128 if (contains(Backedge)) 129 return false; 130 std::swap(Incoming, Backedge); 131 } else if (!contains(Backedge)) 132 return false; 133 134 assert(Incoming && Backedge && "expected non-null incoming and backedges"); 135 return true; 136 } 137 138 PHINode *Loop::getCanonicalInductionVariable() const { 139 BasicBlock *H = getHeader(); 140 141 BasicBlock *Incoming = nullptr, *Backedge = nullptr; 142 if (!getIncomingAndBackEdge(Incoming, Backedge)) 143 return nullptr; 144 145 // Loop over all of the PHI nodes, looking for a canonical indvar. 146 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) { 147 PHINode *PN = cast<PHINode>(I); 148 if (ConstantInt *CI = 149 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming))) 150 if (CI->isZero()) 151 if (Instruction *Inc = 152 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge))) 153 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN) 154 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1))) 155 if (CI->isOne()) 156 return PN; 157 } 158 return nullptr; 159 } 160 161 // Check that 'BB' doesn't have any uses outside of the 'L' 162 static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB, 163 DominatorTree &DT) { 164 for (const Instruction &I : BB) { 165 // Tokens can't be used in PHI nodes and live-out tokens prevent loop 166 // optimizations, so for the purposes of considered LCSSA form, we 167 // can ignore them. 168 if (I.getType()->isTokenTy()) 169 continue; 170 171 for (const Use &U : I.uses()) { 172 const Instruction *UI = cast<Instruction>(U.getUser()); 173 const BasicBlock *UserBB = UI->getParent(); 174 if (const PHINode *P = dyn_cast<PHINode>(UI)) 175 UserBB = P->getIncomingBlock(U); 176 177 // Check the current block, as a fast-path, before checking whether 178 // the use is anywhere in the loop. Most values are used in the same 179 // block they are defined in. Also, blocks not reachable from the 180 // entry are special; uses in them don't need to go through PHIs. 181 if (UserBB != &BB && !L.contains(UserBB) && 182 DT.isReachableFromEntry(UserBB)) 183 return false; 184 } 185 } 186 return true; 187 } 188 189 bool Loop::isLCSSAForm(DominatorTree &DT) const { 190 // For each block we check that it doesn't have any uses outside of this loop. 191 return all_of(this->blocks(), [&](const BasicBlock *BB) { 192 return isBlockInLCSSAForm(*this, *BB, DT); 193 }); 194 } 195 196 bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const { 197 // For each block we check that it doesn't have any uses outside of its 198 // innermost loop. This process will transitively guarantee that the current 199 // loop and all of the nested loops are in LCSSA form. 200 return all_of(this->blocks(), [&](const BasicBlock *BB) { 201 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT); 202 }); 203 } 204 205 bool Loop::isLoopSimplifyForm() const { 206 // Normal-form loops have a preheader, a single backedge, and all of their 207 // exits have all their predecessors inside the loop. 208 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits(); 209 } 210 211 // Routines that reform the loop CFG and split edges often fail on indirectbr. 212 bool Loop::isSafeToClone() const { 213 // Return false if any loop blocks contain indirectbrs, or there are any calls 214 // to noduplicate functions. 215 for (BasicBlock *BB : this->blocks()) { 216 if (isa<IndirectBrInst>(BB->getTerminator())) 217 return false; 218 219 for (Instruction &I : *BB) 220 if (auto CS = CallSite(&I)) 221 if (CS.cannotDuplicate()) 222 return false; 223 } 224 return true; 225 } 226 227 MDNode *Loop::getLoopID() const { 228 MDNode *LoopID = nullptr; 229 230 // Go through the latch blocks and check the terminator for the metadata. 231 SmallVector<BasicBlock *, 4> LatchesBlocks; 232 getLoopLatches(LatchesBlocks); 233 for (BasicBlock *BB : LatchesBlocks) { 234 Instruction *TI = BB->getTerminator(); 235 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop); 236 237 if (!MD) 238 return nullptr; 239 240 if (!LoopID) 241 LoopID = MD; 242 else if (MD != LoopID) 243 return nullptr; 244 } 245 if (!LoopID || LoopID->getNumOperands() == 0 || 246 LoopID->getOperand(0) != LoopID) 247 return nullptr; 248 return LoopID; 249 } 250 251 void Loop::setLoopID(MDNode *LoopID) const { 252 assert((!LoopID || LoopID->getNumOperands() > 0) && 253 "Loop ID needs at least one operand"); 254 assert((!LoopID || LoopID->getOperand(0) == LoopID) && 255 "Loop ID should refer to itself"); 256 257 BasicBlock *H = getHeader(); 258 for (BasicBlock *BB : this->blocks()) { 259 Instruction *TI = BB->getTerminator(); 260 for (BasicBlock *Successor : successors(TI)) { 261 if (Successor == H) { 262 TI->setMetadata(LLVMContext::MD_loop, LoopID); 263 break; 264 } 265 } 266 } 267 } 268 269 void Loop::setLoopAlreadyUnrolled() { 270 LLVMContext &Context = getHeader()->getContext(); 271 272 MDNode *DisableUnrollMD = 273 MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable")); 274 MDNode *LoopID = getLoopID(); 275 MDNode *NewLoopID = makePostTransformationMetadata( 276 Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD}); 277 setLoopID(NewLoopID); 278 } 279 280 bool Loop::isAnnotatedParallel() const { 281 MDNode *DesiredLoopIdMetadata = getLoopID(); 282 283 if (!DesiredLoopIdMetadata) 284 return false; 285 286 MDNode *ParallelAccesses = 287 findOptionMDForLoop(this, "llvm.loop.parallel_accesses"); 288 SmallPtrSet<MDNode *, 4> 289 ParallelAccessGroups; // For scalable 'contains' check. 290 if (ParallelAccesses) { 291 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands(), 1)) { 292 MDNode *AccGroup = cast<MDNode>(MD.get()); 293 assert(isValidAsAccessGroup(AccGroup) && 294 "List item must be an access group"); 295 ParallelAccessGroups.insert(AccGroup); 296 } 297 } 298 299 // The loop branch contains the parallel loop metadata. In order to ensure 300 // that any parallel-loop-unaware optimization pass hasn't added loop-carried 301 // dependencies (thus converted the loop back to a sequential loop), check 302 // that all the memory instructions in the loop belong to an access group that 303 // is parallel to this loop. 304 for (BasicBlock *BB : this->blocks()) { 305 for (Instruction &I : *BB) { 306 if (!I.mayReadOrWriteMemory()) 307 continue; 308 309 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) { 310 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool { 311 if (AG->getNumOperands() == 0) { 312 assert(isValidAsAccessGroup(AG) && "Item must be an access group"); 313 return ParallelAccessGroups.count(AG); 314 } 315 316 for (const MDOperand &AccessListItem : AG->operands()) { 317 MDNode *AccGroup = cast<MDNode>(AccessListItem.get()); 318 assert(isValidAsAccessGroup(AccGroup) && 319 "List item must be an access group"); 320 if (ParallelAccessGroups.count(AccGroup)) 321 return true; 322 } 323 return false; 324 }; 325 326 if (ContainsAccessGroup(AccessGroup)) 327 continue; 328 } 329 330 // The memory instruction can refer to the loop identifier metadata 331 // directly or indirectly through another list metadata (in case of 332 // nested parallel loops). The loop identifier metadata refers to 333 // itself so we can check both cases with the same routine. 334 MDNode *LoopIdMD = 335 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access); 336 337 if (!LoopIdMD) 338 return false; 339 340 bool LoopIdMDFound = false; 341 for (const MDOperand &MDOp : LoopIdMD->operands()) { 342 if (MDOp == DesiredLoopIdMetadata) { 343 LoopIdMDFound = true; 344 break; 345 } 346 } 347 348 if (!LoopIdMDFound) 349 return false; 350 } 351 } 352 return true; 353 } 354 355 DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); } 356 357 Loop::LocRange Loop::getLocRange() const { 358 // If we have a debug location in the loop ID, then use it. 359 if (MDNode *LoopID = getLoopID()) { 360 DebugLoc Start; 361 // We use the first DebugLoc in the header as the start location of the loop 362 // and if there is a second DebugLoc in the header we use it as end location 363 // of the loop. 364 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 365 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) { 366 if (!Start) 367 Start = DebugLoc(L); 368 else 369 return LocRange(Start, DebugLoc(L)); 370 } 371 } 372 373 if (Start) 374 return LocRange(Start); 375 } 376 377 // Try the pre-header first. 378 if (BasicBlock *PHeadBB = getLoopPreheader()) 379 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc()) 380 return LocRange(DL); 381 382 // If we have no pre-header or there are no instructions with debug 383 // info in it, try the header. 384 if (BasicBlock *HeadBB = getHeader()) 385 return LocRange(HeadBB->getTerminator()->getDebugLoc()); 386 387 return LocRange(); 388 } 389 390 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 391 LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); } 392 393 LLVM_DUMP_METHOD void Loop::dumpVerbose() const { 394 print(dbgs(), /*Depth=*/0, /*Verbose=*/true); 395 } 396 #endif 397 398 //===----------------------------------------------------------------------===// 399 // UnloopUpdater implementation 400 // 401 402 namespace { 403 /// Find the new parent loop for all blocks within the "unloop" whose last 404 /// backedges has just been removed. 405 class UnloopUpdater { 406 Loop &Unloop; 407 LoopInfo *LI; 408 409 LoopBlocksDFS DFS; 410 411 // Map unloop's immediate subloops to their nearest reachable parents. Nested 412 // loops within these subloops will not change parents. However, an immediate 413 // subloop's new parent will be the nearest loop reachable from either its own 414 // exits *or* any of its nested loop's exits. 415 DenseMap<Loop *, Loop *> SubloopParents; 416 417 // Flag the presence of an irreducible backedge whose destination is a block 418 // directly contained by the original unloop. 419 bool FoundIB; 420 421 public: 422 UnloopUpdater(Loop *UL, LoopInfo *LInfo) 423 : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {} 424 425 void updateBlockParents(); 426 427 void removeBlocksFromAncestors(); 428 429 void updateSubloopParents(); 430 431 protected: 432 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop); 433 }; 434 } // end anonymous namespace 435 436 /// Update the parent loop for all blocks that are directly contained within the 437 /// original "unloop". 438 void UnloopUpdater::updateBlockParents() { 439 if (Unloop.getNumBlocks()) { 440 // Perform a post order CFG traversal of all blocks within this loop, 441 // propagating the nearest loop from successors to predecessors. 442 LoopBlocksTraversal Traversal(DFS, LI); 443 for (BasicBlock *POI : Traversal) { 444 445 Loop *L = LI->getLoopFor(POI); 446 Loop *NL = getNearestLoop(POI, L); 447 448 if (NL != L) { 449 // For reducible loops, NL is now an ancestor of Unloop. 450 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) && 451 "uninitialized successor"); 452 LI->changeLoopFor(POI, NL); 453 } else { 454 // Or the current block is part of a subloop, in which case its parent 455 // is unchanged. 456 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor"); 457 } 458 } 459 } 460 // Each irreducible loop within the unloop induces a round of iteration using 461 // the DFS result cached by Traversal. 462 bool Changed = FoundIB; 463 for (unsigned NIters = 0; Changed; ++NIters) { 464 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm"); 465 466 // Iterate over the postorder list of blocks, propagating the nearest loop 467 // from successors to predecessors as before. 468 Changed = false; 469 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(), 470 POE = DFS.endPostorder(); 471 POI != POE; ++POI) { 472 473 Loop *L = LI->getLoopFor(*POI); 474 Loop *NL = getNearestLoop(*POI, L); 475 if (NL != L) { 476 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) && 477 "uninitialized successor"); 478 LI->changeLoopFor(*POI, NL); 479 Changed = true; 480 } 481 } 482 } 483 } 484 485 /// Remove unloop's blocks from all ancestors below their new parents. 486 void UnloopUpdater::removeBlocksFromAncestors() { 487 // Remove all unloop's blocks (including those in nested subloops) from 488 // ancestors below the new parent loop. 489 for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end(); 490 BI != BE; ++BI) { 491 Loop *OuterParent = LI->getLoopFor(*BI); 492 if (Unloop.contains(OuterParent)) { 493 while (OuterParent->getParentLoop() != &Unloop) 494 OuterParent = OuterParent->getParentLoop(); 495 OuterParent = SubloopParents[OuterParent]; 496 } 497 // Remove blocks from former Ancestors except Unloop itself which will be 498 // deleted. 499 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent; 500 OldParent = OldParent->getParentLoop()) { 501 assert(OldParent && "new loop is not an ancestor of the original"); 502 OldParent->removeBlockFromLoop(*BI); 503 } 504 } 505 } 506 507 /// Update the parent loop for all subloops directly nested within unloop. 508 void UnloopUpdater::updateSubloopParents() { 509 while (!Unloop.empty()) { 510 Loop *Subloop = *std::prev(Unloop.end()); 511 Unloop.removeChildLoop(std::prev(Unloop.end())); 512 513 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop"); 514 if (Loop *Parent = SubloopParents[Subloop]) 515 Parent->addChildLoop(Subloop); 516 else 517 LI->addTopLevelLoop(Subloop); 518 } 519 } 520 521 /// Return the nearest parent loop among this block's successors. If a successor 522 /// is a subloop header, consider its parent to be the nearest parent of the 523 /// subloop's exits. 524 /// 525 /// For subloop blocks, simply update SubloopParents and return NULL. 526 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) { 527 528 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and 529 // is considered uninitialized. 530 Loop *NearLoop = BBLoop; 531 532 Loop *Subloop = nullptr; 533 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) { 534 Subloop = NearLoop; 535 // Find the subloop ancestor that is directly contained within Unloop. 536 while (Subloop->getParentLoop() != &Unloop) { 537 Subloop = Subloop->getParentLoop(); 538 assert(Subloop && "subloop is not an ancestor of the original loop"); 539 } 540 // Get the current nearest parent of the Subloop exits, initially Unloop. 541 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second; 542 } 543 544 succ_iterator I = succ_begin(BB), E = succ_end(BB); 545 if (I == E) { 546 assert(!Subloop && "subloop blocks must have a successor"); 547 NearLoop = nullptr; // unloop blocks may now exit the function. 548 } 549 for (; I != E; ++I) { 550 if (*I == BB) 551 continue; // self loops are uninteresting 552 553 Loop *L = LI->getLoopFor(*I); 554 if (L == &Unloop) { 555 // This successor has not been processed. This path must lead to an 556 // irreducible backedge. 557 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB"); 558 FoundIB = true; 559 } 560 if (L != &Unloop && Unloop.contains(L)) { 561 // Successor is in a subloop. 562 if (Subloop) 563 continue; // Branching within subloops. Ignore it. 564 565 // BB branches from the original into a subloop header. 566 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops"); 567 568 // Get the current nearest parent of the Subloop's exits. 569 L = SubloopParents[L]; 570 // L could be Unloop if the only exit was an irreducible backedge. 571 } 572 if (L == &Unloop) { 573 continue; 574 } 575 // Handle critical edges from Unloop into a sibling loop. 576 if (L && !L->contains(&Unloop)) { 577 L = L->getParentLoop(); 578 } 579 // Remember the nearest parent loop among successors or subloop exits. 580 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L)) 581 NearLoop = L; 582 } 583 if (Subloop) { 584 SubloopParents[Subloop] = NearLoop; 585 return BBLoop; 586 } 587 return NearLoop; 588 } 589 590 LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); } 591 592 bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA, 593 FunctionAnalysisManager::Invalidator &) { 594 // Check whether the analysis, all analyses on functions, or the function's 595 // CFG have been preserved. 596 auto PAC = PA.getChecker<LoopAnalysis>(); 597 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() || 598 PAC.preservedSet<CFGAnalyses>()); 599 } 600 601 void LoopInfo::erase(Loop *Unloop) { 602 assert(!Unloop->isInvalid() && "Loop has already been erased!"); 603 604 auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); }); 605 606 // First handle the special case of no parent loop to simplify the algorithm. 607 if (!Unloop->getParentLoop()) { 608 // Since BBLoop had no parent, Unloop blocks are no longer in a loop. 609 for (Loop::block_iterator I = Unloop->block_begin(), 610 E = Unloop->block_end(); 611 I != E; ++I) { 612 613 // Don't reparent blocks in subloops. 614 if (getLoopFor(*I) != Unloop) 615 continue; 616 617 // Blocks no longer have a parent but are still referenced by Unloop until 618 // the Unloop object is deleted. 619 changeLoopFor(*I, nullptr); 620 } 621 622 // Remove the loop from the top-level LoopInfo object. 623 for (iterator I = begin();; ++I) { 624 assert(I != end() && "Couldn't find loop"); 625 if (*I == Unloop) { 626 removeLoop(I); 627 break; 628 } 629 } 630 631 // Move all of the subloops to the top-level. 632 while (!Unloop->empty()) 633 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end()))); 634 635 return; 636 } 637 638 // Update the parent loop for all blocks within the loop. Blocks within 639 // subloops will not change parents. 640 UnloopUpdater Updater(Unloop, this); 641 Updater.updateBlockParents(); 642 643 // Remove blocks from former ancestor loops. 644 Updater.removeBlocksFromAncestors(); 645 646 // Add direct subloops as children in their new parent loop. 647 Updater.updateSubloopParents(); 648 649 // Remove unloop from its parent loop. 650 Loop *ParentLoop = Unloop->getParentLoop(); 651 for (Loop::iterator I = ParentLoop->begin();; ++I) { 652 assert(I != ParentLoop->end() && "Couldn't find loop"); 653 if (*I == Unloop) { 654 ParentLoop->removeChildLoop(I); 655 break; 656 } 657 } 658 } 659 660 AnalysisKey LoopAnalysis::Key; 661 662 LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) { 663 // FIXME: Currently we create a LoopInfo from scratch for every function. 664 // This may prove to be too wasteful due to deallocating and re-allocating 665 // memory each time for the underlying map and vector datastructures. At some 666 // point it may prove worthwhile to use a freelist and recycle LoopInfo 667 // objects. I don't want to add that kind of complexity until the scope of 668 // the problem is better understood. 669 LoopInfo LI; 670 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F)); 671 return LI; 672 } 673 674 PreservedAnalyses LoopPrinterPass::run(Function &F, 675 FunctionAnalysisManager &AM) { 676 AM.getResult<LoopAnalysis>(F).print(OS); 677 return PreservedAnalyses::all(); 678 } 679 680 void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) { 681 682 if (forcePrintModuleIR()) { 683 // handling -print-module-scope 684 OS << Banner << " (loop: "; 685 L.getHeader()->printAsOperand(OS, false); 686 OS << ")\n"; 687 688 // printing whole module 689 OS << *L.getHeader()->getModule(); 690 return; 691 } 692 693 OS << Banner; 694 695 auto *PreHeader = L.getLoopPreheader(); 696 if (PreHeader) { 697 OS << "\n; Preheader:"; 698 PreHeader->print(OS); 699 OS << "\n; Loop:"; 700 } 701 702 for (auto *Block : L.blocks()) 703 if (Block) 704 Block->print(OS); 705 else 706 OS << "Printing <null> block"; 707 708 SmallVector<BasicBlock *, 8> ExitBlocks; 709 L.getExitBlocks(ExitBlocks); 710 if (!ExitBlocks.empty()) { 711 OS << "\n; Exit blocks"; 712 for (auto *Block : ExitBlocks) 713 if (Block) 714 Block->print(OS); 715 else 716 OS << "Printing <null> block"; 717 } 718 } 719 720 MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) { 721 // No loop metadata node, no loop properties. 722 if (!LoopID) 723 return nullptr; 724 725 // First operand should refer to the metadata node itself, for legacy reasons. 726 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 727 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 728 729 // Iterate over the metdata node operands and look for MDString metadata. 730 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 731 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 732 if (!MD || MD->getNumOperands() < 1) 733 continue; 734 MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 735 if (!S) 736 continue; 737 // Return the operand node if MDString holds expected metadata. 738 if (Name.equals(S->getString())) 739 return MD; 740 } 741 742 // Loop property not found. 743 return nullptr; 744 } 745 746 MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) { 747 return findOptionMDForLoopID(TheLoop->getLoopID(), Name); 748 } 749 750 bool llvm::isValidAsAccessGroup(MDNode *Node) { 751 return Node->getNumOperands() == 0 && Node->isDistinct(); 752 } 753 754 MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context, 755 MDNode *OrigLoopID, 756 ArrayRef<StringRef> RemovePrefixes, 757 ArrayRef<MDNode *> AddAttrs) { 758 // First remove any existing loop metadata related to this transformation. 759 SmallVector<Metadata *, 4> MDs; 760 761 // Reserve first location for self reference to the LoopID metadata node. 762 TempMDTuple TempNode = MDNode::getTemporary(Context, None); 763 MDs.push_back(TempNode.get()); 764 765 // Remove metadata for the transformation that has been applied or that became 766 // outdated. 767 if (OrigLoopID) { 768 for (unsigned i = 1, ie = OrigLoopID->getNumOperands(); i < ie; ++i) { 769 bool IsVectorMetadata = false; 770 Metadata *Op = OrigLoopID->getOperand(i); 771 if (MDNode *MD = dyn_cast<MDNode>(Op)) { 772 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 773 if (S) 774 IsVectorMetadata = 775 llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool { 776 return S->getString().startswith(Prefix); 777 }); 778 } 779 if (!IsVectorMetadata) 780 MDs.push_back(Op); 781 } 782 } 783 784 // Add metadata to avoid reapplying a transformation, such as 785 // llvm.loop.unroll.disable and llvm.loop.isvectorized. 786 MDs.append(AddAttrs.begin(), AddAttrs.end()); 787 788 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs); 789 // Replace the temporary node with a self-reference. 790 NewLoopID->replaceOperandWith(0, NewLoopID); 791 return NewLoopID; 792 } 793 794 //===----------------------------------------------------------------------===// 795 // LoopInfo implementation 796 // 797 798 char LoopInfoWrapperPass::ID = 0; 799 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information", 800 true, true) 801 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 802 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information", 803 true, true) 804 805 bool LoopInfoWrapperPass::runOnFunction(Function &) { 806 releaseMemory(); 807 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree()); 808 return false; 809 } 810 811 void LoopInfoWrapperPass::verifyAnalysis() const { 812 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the 813 // function each time verifyAnalysis is called is very expensive. The 814 // -verify-loop-info option can enable this. In order to perform some 815 // checking by default, LoopPass has been taught to call verifyLoop manually 816 // during loop pass sequences. 817 if (VerifyLoopInfo) { 818 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 819 LI.verify(DT); 820 } 821 } 822 823 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 824 AU.setPreservesAll(); 825 AU.addRequired<DominatorTreeWrapperPass>(); 826 } 827 828 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const { 829 LI.print(OS); 830 } 831 832 PreservedAnalyses LoopVerifierPass::run(Function &F, 833 FunctionAnalysisManager &AM) { 834 LoopInfo &LI = AM.getResult<LoopAnalysis>(F); 835 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 836 LI.verify(DT); 837 return PreservedAnalyses::all(); 838 } 839 840 //===----------------------------------------------------------------------===// 841 // LoopBlocksDFS implementation 842 // 843 844 /// Traverse the loop blocks and store the DFS result. 845 /// Useful for clients that just want the final DFS result and don't need to 846 /// visit blocks during the initial traversal. 847 void LoopBlocksDFS::perform(LoopInfo *LI) { 848 LoopBlocksTraversal Traversal(*this, LI); 849 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(), 850 POE = Traversal.end(); 851 POI != POE; ++POI) 852 ; 853 } 854