LoopInfo.h revision 5786b4cdc118a7fbcdae238e264a884691ab43b7
1//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the LoopInfo class that is used to identify natural loops 11// and determine the loop depth of various nodes of the CFG. A natural loop 12// has exactly one entry-point, which is called the header. Note that natural 13// loops may actually be several loops that share the same header node. 14// 15// This analysis calculates the nesting structure of loops in a function. For 16// each natural loop identified, this analysis identifies natural loops 17// contained entirely within the loop and the basic blocks the make up the loop. 18// 19// It can calculate on the fly various bits of information, for example: 20// 21// * whether there is a preheader for the loop 22// * the number of back edges to the header 23// * whether or not a particular block branches out of the loop 24// * the successor blocks of the loop 25// * the loop depth 26// * the trip count 27// * etc... 28// 29//===----------------------------------------------------------------------===// 30 31#ifndef LLVM_ANALYSIS_LOOP_INFO_H 32#define LLVM_ANALYSIS_LOOP_INFO_H 33 34#include "llvm/Pass.h" 35#include "llvm/ADT/DenseMap.h" 36#include "llvm/ADT/DenseSet.h" 37#include "llvm/ADT/DepthFirstIterator.h" 38#include "llvm/ADT/GraphTraits.h" 39#include "llvm/ADT/SmallVector.h" 40#include "llvm/ADT/STLExtras.h" 41#include "llvm/Analysis/Dominators.h" 42#include "llvm/Support/CFG.h" 43#include "llvm/Support/raw_ostream.h" 44#include <algorithm> 45#include <map> 46 47namespace llvm { 48 49template<typename T> 50static void RemoveFromVector(std::vector<T*> &V, T *N) { 51 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N); 52 assert(I != V.end() && "N is not in this list!"); 53 V.erase(I); 54} 55 56class DominatorTree; 57class LoopInfo; 58class Loop; 59class PHINode; 60template<class N, class M> class LoopInfoBase; 61template<class N, class M> class LoopBase; 62 63//===----------------------------------------------------------------------===// 64/// LoopBase class - Instances of this class are used to represent loops that 65/// are detected in the flow graph 66/// 67template<class BlockT, class LoopT> 68class LoopBase { 69 LoopT *ParentLoop; 70 // SubLoops - Loops contained entirely within this one. 71 std::vector<LoopT *> SubLoops; 72 73 // Blocks - The list of blocks in this loop. First entry is the header node. 74 std::vector<BlockT*> Blocks; 75 76 // DO NOT IMPLEMENT 77 LoopBase(const LoopBase<BlockT, LoopT> &); 78 // DO NOT IMPLEMENT 79 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &); 80public: 81 /// Loop ctor - This creates an empty loop. 82 LoopBase() : ParentLoop(0) {} 83 ~LoopBase() { 84 for (size_t i = 0, e = SubLoops.size(); i != e; ++i) 85 delete SubLoops[i]; 86 } 87 88 /// getLoopDepth - Return the nesting level of this loop. An outer-most 89 /// loop has depth 1, for consistency with loop depth values used for basic 90 /// blocks, where depth 0 is used for blocks not inside any loops. 91 unsigned getLoopDepth() const { 92 unsigned D = 1; 93 for (const LoopT *CurLoop = ParentLoop; CurLoop; 94 CurLoop = CurLoop->ParentLoop) 95 ++D; 96 return D; 97 } 98 BlockT *getHeader() const { return Blocks.front(); } 99 LoopT *getParentLoop() const { return ParentLoop; } 100 101 /// contains - Return true if the specified loop is contained within in 102 /// this loop. 103 /// 104 bool contains(const LoopT *L) const { 105 if (L == this) return true; 106 if (L == 0) return false; 107 return contains(L->getParentLoop()); 108 } 109 110 /// contains - Return true if the specified basic block is in this loop. 111 /// 112 bool contains(const BlockT *BB) const { 113 return std::find(block_begin(), block_end(), BB) != block_end(); 114 } 115 116 /// contains - Return true if the specified instruction is in this loop. 117 /// 118 template<class InstT> 119 bool contains(const InstT *Inst) const { 120 return contains(Inst->getParent()); 121 } 122 123 /// iterator/begin/end - Return the loops contained entirely within this loop. 124 /// 125 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; } 126 typedef typename std::vector<LoopT *>::const_iterator iterator; 127 iterator begin() const { return SubLoops.begin(); } 128 iterator end() const { return SubLoops.end(); } 129 bool empty() const { return SubLoops.empty(); } 130 131 /// getBlocks - Get a list of the basic blocks which make up this loop. 132 /// 133 const std::vector<BlockT*> &getBlocks() const { return Blocks; } 134 typedef typename std::vector<BlockT*>::const_iterator block_iterator; 135 block_iterator block_begin() const { return Blocks.begin(); } 136 block_iterator block_end() const { return Blocks.end(); } 137 138 /// getNumBlocks - Get the number of blocks in this loop in constant time. 139 unsigned getNumBlocks() const { 140 return Blocks.size(); 141 } 142 143 /// isLoopExiting - True if terminator in the block can branch to another 144 /// block that is outside of the current loop. 145 /// 146 bool isLoopExiting(const BlockT *BB) const { 147 typedef GraphTraits<BlockT*> BlockTraits; 148 for (typename BlockTraits::ChildIteratorType SI = 149 BlockTraits::child_begin(const_cast<BlockT*>(BB)), 150 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) { 151 if (!contains(*SI)) 152 return true; 153 } 154 return false; 155 } 156 157 /// getNumBackEdges - Calculate the number of back edges to the loop header 158 /// 159 unsigned getNumBackEdges() const { 160 unsigned NumBackEdges = 0; 161 BlockT *H = getHeader(); 162 163 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits; 164 for (typename InvBlockTraits::ChildIteratorType I = 165 InvBlockTraits::child_begin(const_cast<BlockT*>(H)), 166 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I) 167 if (contains(*I)) 168 ++NumBackEdges; 169 170 return NumBackEdges; 171 } 172 173 //===--------------------------------------------------------------------===// 174 // APIs for simple analysis of the loop. 175 // 176 // Note that all of these methods can fail on general loops (ie, there may not 177 // be a preheader, etc). For best success, the loop simplification and 178 // induction variable canonicalization pass should be used to normalize loops 179 // for easy analysis. These methods assume canonical loops. 180 181 /// getExitingBlocks - Return all blocks inside the loop that have successors 182 /// outside of the loop. These are the blocks _inside of the current loop_ 183 /// which branch out. The returned list is always unique. 184 /// 185 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const { 186 // Sort the blocks vector so that we can use binary search to do quick 187 // lookups. 188 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end()); 189 std::sort(LoopBBs.begin(), LoopBBs.end()); 190 191 typedef GraphTraits<BlockT*> BlockTraits; 192 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) 193 for (typename BlockTraits::ChildIteratorType I = 194 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI); 195 I != E; ++I) 196 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) { 197 // Not in current loop? It must be an exit block. 198 ExitingBlocks.push_back(*BI); 199 break; 200 } 201 } 202 203 /// getExitingBlock - If getExitingBlocks would return exactly one block, 204 /// return that block. Otherwise return null. 205 BlockT *getExitingBlock() const { 206 SmallVector<BlockT*, 8> ExitingBlocks; 207 getExitingBlocks(ExitingBlocks); 208 if (ExitingBlocks.size() == 1) 209 return ExitingBlocks[0]; 210 return 0; 211 } 212 213 /// getExitBlocks - Return all of the successor blocks of this loop. These 214 /// are the blocks _outside of the current loop_ which are branched to. 215 /// 216 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const { 217 // Sort the blocks vector so that we can use binary search to do quick 218 // lookups. 219 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end()); 220 std::sort(LoopBBs.begin(), LoopBBs.end()); 221 222 typedef GraphTraits<BlockT*> BlockTraits; 223 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) 224 for (typename BlockTraits::ChildIteratorType I = 225 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI); 226 I != E; ++I) 227 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) 228 // Not in current loop? It must be an exit block. 229 ExitBlocks.push_back(*I); 230 } 231 232 /// getExitBlock - If getExitBlocks would return exactly one block, 233 /// return that block. Otherwise return null. 234 BlockT *getExitBlock() const { 235 SmallVector<BlockT*, 8> ExitBlocks; 236 getExitBlocks(ExitBlocks); 237 if (ExitBlocks.size() == 1) 238 return ExitBlocks[0]; 239 return 0; 240 } 241 242 /// Edge type. 243 typedef std::pair<BlockT*, BlockT*> Edge; 244 245 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_). 246 template <typename EdgeT> 247 void getExitEdges(SmallVectorImpl<EdgeT> &ExitEdges) const { 248 // Sort the blocks vector so that we can use binary search to do quick 249 // lookups. 250 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end()); 251 array_pod_sort(LoopBBs.begin(), LoopBBs.end()); 252 253 typedef GraphTraits<BlockT*> BlockTraits; 254 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) 255 for (typename BlockTraits::ChildIteratorType I = 256 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI); 257 I != E; ++I) 258 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) 259 // Not in current loop? It must be an exit block. 260 ExitEdges.push_back(EdgeT(*BI, *I)); 261 } 262 263 /// getLoopPreheader - If there is a preheader for this loop, return it. A 264 /// loop has a preheader if there is only one edge to the header of the loop 265 /// from outside of the loop. If this is the case, the block branching to the 266 /// header of the loop is the preheader node. 267 /// 268 /// This method returns null if there is no preheader for the loop. 269 /// 270 BlockT *getLoopPreheader() const { 271 // Keep track of nodes outside the loop branching to the header... 272 BlockT *Out = getLoopPredecessor(); 273 if (!Out) return 0; 274 275 // Make sure there is only one exit out of the preheader. 276 typedef GraphTraits<BlockT*> BlockTraits; 277 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out); 278 ++SI; 279 if (SI != BlockTraits::child_end(Out)) 280 return 0; // Multiple exits from the block, must not be a preheader. 281 282 // The predecessor has exactly one successor, so it is a preheader. 283 return Out; 284 } 285 286 /// getLoopPredecessor - If the given loop's header has exactly one unique 287 /// predecessor outside the loop, return it. Otherwise return null. 288 /// This is less strict that the loop "preheader" concept, which requires 289 /// the predecessor to have exactly one successor. 290 /// 291 BlockT *getLoopPredecessor() const { 292 // Keep track of nodes outside the loop branching to the header... 293 BlockT *Out = 0; 294 295 // Loop over the predecessors of the header node... 296 BlockT *Header = getHeader(); 297 typedef GraphTraits<BlockT*> BlockTraits; 298 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits; 299 for (typename InvBlockTraits::ChildIteratorType PI = 300 InvBlockTraits::child_begin(Header), 301 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) { 302 typename InvBlockTraits::NodeType *N = *PI; 303 if (!contains(N)) { // If the block is not in the loop... 304 if (Out && Out != N) 305 return 0; // Multiple predecessors outside the loop 306 Out = N; 307 } 308 } 309 310 // Make sure there is only one exit out of the preheader. 311 assert(Out && "Header of loop has no predecessors from outside loop?"); 312 return Out; 313 } 314 315 /// getLoopLatch - If there is a single latch block for this loop, return it. 316 /// A latch block is a block that contains a branch back to the header. 317 BlockT *getLoopLatch() const { 318 BlockT *Header = getHeader(); 319 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits; 320 typename InvBlockTraits::ChildIteratorType PI = 321 InvBlockTraits::child_begin(Header); 322 typename InvBlockTraits::ChildIteratorType PE = 323 InvBlockTraits::child_end(Header); 324 BlockT *Latch = 0; 325 for (; PI != PE; ++PI) { 326 typename InvBlockTraits::NodeType *N = *PI; 327 if (contains(N)) { 328 if (Latch) return 0; 329 Latch = N; 330 } 331 } 332 333 return Latch; 334 } 335 336 //===--------------------------------------------------------------------===// 337 // APIs for updating loop information after changing the CFG 338 // 339 340 /// addBasicBlockToLoop - This method is used by other analyses to update loop 341 /// information. NewBB is set to be a new member of the current loop. 342 /// Because of this, it is added as a member of all parent loops, and is added 343 /// to the specified LoopInfo object as being in the current basic block. It 344 /// is not valid to replace the loop header with this method. 345 /// 346 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI); 347 348 /// replaceChildLoopWith - This is used when splitting loops up. It replaces 349 /// the OldChild entry in our children list with NewChild, and updates the 350 /// parent pointer of OldChild to be null and the NewChild to be this loop. 351 /// This updates the loop depth of the new child. 352 void replaceChildLoopWith(LoopT *OldChild, 353 LoopT *NewChild) { 354 assert(OldChild->ParentLoop == this && "This loop is already broken!"); 355 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!"); 356 typename std::vector<LoopT *>::iterator I = 357 std::find(SubLoops.begin(), SubLoops.end(), OldChild); 358 assert(I != SubLoops.end() && "OldChild not in loop!"); 359 *I = NewChild; 360 OldChild->ParentLoop = 0; 361 NewChild->ParentLoop = static_cast<LoopT *>(this); 362 } 363 364 /// addChildLoop - Add the specified loop to be a child of this loop. This 365 /// updates the loop depth of the new child. 366 /// 367 void addChildLoop(LoopT *NewChild) { 368 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!"); 369 NewChild->ParentLoop = static_cast<LoopT *>(this); 370 SubLoops.push_back(NewChild); 371 } 372 373 /// removeChildLoop - This removes the specified child from being a subloop of 374 /// this loop. The loop is not deleted, as it will presumably be inserted 375 /// into another loop. 376 LoopT *removeChildLoop(iterator I) { 377 assert(I != SubLoops.end() && "Cannot remove end iterator!"); 378 LoopT *Child = *I; 379 assert(Child->ParentLoop == this && "Child is not a child of this loop!"); 380 SubLoops.erase(SubLoops.begin()+(I-begin())); 381 Child->ParentLoop = 0; 382 return Child; 383 } 384 385 /// addBlockEntry - This adds a basic block directly to the basic block list. 386 /// This should only be used by transformations that create new loops. Other 387 /// transformations should use addBasicBlockToLoop. 388 void addBlockEntry(BlockT *BB) { 389 Blocks.push_back(BB); 390 } 391 392 /// moveToHeader - This method is used to move BB (which must be part of this 393 /// loop) to be the loop header of the loop (the block that dominates all 394 /// others). 395 void moveToHeader(BlockT *BB) { 396 if (Blocks[0] == BB) return; 397 for (unsigned i = 0; ; ++i) { 398 assert(i != Blocks.size() && "Loop does not contain BB!"); 399 if (Blocks[i] == BB) { 400 Blocks[i] = Blocks[0]; 401 Blocks[0] = BB; 402 return; 403 } 404 } 405 } 406 407 /// removeBlockFromLoop - This removes the specified basic block from the 408 /// current loop, updating the Blocks as appropriate. This does not update 409 /// the mapping in the LoopInfo class. 410 void removeBlockFromLoop(BlockT *BB) { 411 RemoveFromVector(Blocks, BB); 412 } 413 414 /// verifyLoop - Verify loop structure 415 void verifyLoop() const { 416#ifndef NDEBUG 417 assert(!Blocks.empty() && "Loop header is missing"); 418 419 // Setup for using a depth-first iterator to visit every block in the loop. 420 SmallVector<BlockT*, 8> ExitBBs; 421 getExitBlocks(ExitBBs); 422 llvm::SmallPtrSet<BlockT*, 8> VisitSet; 423 VisitSet.insert(ExitBBs.begin(), ExitBBs.end()); 424 df_ext_iterator<BlockT*, llvm::SmallPtrSet<BlockT*, 8> > 425 BI = df_ext_begin(getHeader(), VisitSet), 426 BE = df_ext_end(getHeader(), VisitSet); 427 428 // Keep track of the number of BBs visited. 429 unsigned NumVisited = 0; 430 431 // Sort the blocks vector so that we can use binary search to do quick 432 // lookups. 433 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end()); 434 std::sort(LoopBBs.begin(), LoopBBs.end()); 435 436 // Check the individual blocks. 437 for ( ; BI != BE; ++BI) { 438 BlockT *BB = *BI; 439 bool HasInsideLoopSuccs = false; 440 bool HasInsideLoopPreds = false; 441 SmallVector<BlockT *, 2> OutsideLoopPreds; 442 443 typedef GraphTraits<BlockT*> BlockTraits; 444 for (typename BlockTraits::ChildIteratorType SI = 445 BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB); 446 SI != SE; ++SI) 447 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) { 448 HasInsideLoopSuccs = true; 449 break; 450 } 451 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits; 452 for (typename InvBlockTraits::ChildIteratorType PI = 453 InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB); 454 PI != PE; ++PI) { 455 BlockT *N = *PI; 456 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N)) 457 HasInsideLoopPreds = true; 458 else 459 OutsideLoopPreds.push_back(N); 460 } 461 462 if (BB == getHeader()) { 463 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!"); 464 } else if (!OutsideLoopPreds.empty()) { 465 // A non-header loop shouldn't be reachable from outside the loop, 466 // though it is permitted if the predecessor is not itself actually 467 // reachable. 468 BlockT *EntryBB = BB->getParent()->begin(); 469 for (df_iterator<BlockT *> NI = df_begin(EntryBB), 470 NE = df_end(EntryBB); NI != NE; ++NI) 471 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i) 472 assert(*NI != OutsideLoopPreds[i] && 473 "Loop has multiple entry points!"); 474 } 475 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!"); 476 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!"); 477 assert(BB != getHeader()->getParent()->begin() && 478 "Loop contains function entry block!"); 479 480 NumVisited++; 481 } 482 483 assert(NumVisited == getNumBlocks() && "Unreachable block in loop"); 484 485 // Check the subloops. 486 for (iterator I = begin(), E = end(); I != E; ++I) 487 // Each block in each subloop should be contained within this loop. 488 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end(); 489 BI != BE; ++BI) { 490 assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) && 491 "Loop does not contain all the blocks of a subloop!"); 492 } 493 494 // Check the parent loop pointer. 495 if (ParentLoop) { 496 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) != 497 ParentLoop->end() && 498 "Loop is not a subloop of its parent!"); 499 } 500#endif 501 } 502 503 /// verifyLoop - Verify loop structure of this loop and all nested loops. 504 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const { 505 Loops->insert(static_cast<const LoopT *>(this)); 506 // Verify this loop. 507 verifyLoop(); 508 // Verify the subloops. 509 for (iterator I = begin(), E = end(); I != E; ++I) 510 (*I)->verifyLoopNest(Loops); 511 } 512 513 void print(raw_ostream &OS, unsigned Depth = 0) const { 514 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth() 515 << " containing: "; 516 517 for (unsigned i = 0; i < getBlocks().size(); ++i) { 518 if (i) OS << ","; 519 BlockT *BB = getBlocks()[i]; 520 WriteAsOperand(OS, BB, false); 521 if (BB == getHeader()) OS << "<header>"; 522 if (BB == getLoopLatch()) OS << "<latch>"; 523 if (isLoopExiting(BB)) OS << "<exiting>"; 524 } 525 OS << "\n"; 526 527 for (iterator I = begin(), E = end(); I != E; ++I) 528 (*I)->print(OS, Depth+2); 529 } 530 531protected: 532 friend class LoopInfoBase<BlockT, LoopT>; 533 explicit LoopBase(BlockT *BB) : ParentLoop(0) { 534 Blocks.push_back(BB); 535 } 536}; 537 538template<class BlockT, class LoopT> 539raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) { 540 Loop.print(OS); 541 return OS; 542} 543 544class Loop : public LoopBase<BasicBlock, Loop> { 545public: 546 Loop() {} 547 548 /// isLoopInvariant - Return true if the specified value is loop invariant 549 /// 550 bool isLoopInvariant(Value *V) const; 551 552 /// hasLoopInvariantOperands - Return true if all the operands of the 553 /// specified instruction are loop invariant. 554 bool hasLoopInvariantOperands(Instruction *I) const; 555 556 /// makeLoopInvariant - If the given value is an instruction inside of the 557 /// loop and it can be hoisted, do so to make it trivially loop-invariant. 558 /// Return true if the value after any hoisting is loop invariant. This 559 /// function can be used as a slightly more aggressive replacement for 560 /// isLoopInvariant. 561 /// 562 /// If InsertPt is specified, it is the point to hoist instructions to. 563 /// If null, the terminator of the loop preheader is used. 564 /// 565 bool makeLoopInvariant(Value *V, bool &Changed, 566 Instruction *InsertPt = 0) const; 567 568 /// makeLoopInvariant - If the given instruction is inside of the 569 /// loop and it can be hoisted, do so to make it trivially loop-invariant. 570 /// Return true if the instruction after any hoisting is loop invariant. This 571 /// function can be used as a slightly more aggressive replacement for 572 /// isLoopInvariant. 573 /// 574 /// If InsertPt is specified, it is the point to hoist instructions to. 575 /// If null, the terminator of the loop preheader is used. 576 /// 577 bool makeLoopInvariant(Instruction *I, bool &Changed, 578 Instruction *InsertPt = 0) const; 579 580 /// getCanonicalInductionVariable - Check to see if the loop has a canonical 581 /// induction variable: an integer recurrence that starts at 0 and increments 582 /// by one each time through the loop. If so, return the phi node that 583 /// corresponds to it. 584 /// 585 /// The IndVarSimplify pass transforms loops to have a canonical induction 586 /// variable. 587 /// 588 PHINode *getCanonicalInductionVariable() const; 589 590 /// getTripCount - Return a loop-invariant LLVM value indicating the number of 591 /// times the loop will be executed. Note that this means that the backedge 592 /// of the loop executes N-1 times. If the trip-count cannot be determined, 593 /// this returns null. 594 /// 595 /// The IndVarSimplify pass transforms loops to have a form that this 596 /// function easily understands. 597 /// 598 Value *getTripCount() const; 599 600 /// getSmallConstantTripCount - Returns the trip count of this loop as a 601 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown 602 /// of not constant. Will also return 0 if the trip count is very large 603 /// (>= 2^32) 604 /// 605 /// The IndVarSimplify pass transforms loops to have a form that this 606 /// function easily understands. 607 /// 608 unsigned getSmallConstantTripCount() const; 609 610 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the 611 /// trip count of this loop as a normal unsigned value, if possible. This 612 /// means that the actual trip count is always a multiple of the returned 613 /// value (don't forget the trip count could very well be zero as well!). 614 /// 615 /// Returns 1 if the trip count is unknown or not guaranteed to be the 616 /// multiple of a constant (which is also the case if the trip count is simply 617 /// constant, use getSmallConstantTripCount for that case), Will also return 1 618 /// if the trip count is very large (>= 2^32). 619 unsigned getSmallConstantTripMultiple() const; 620 621 /// isLCSSAForm - Return true if the Loop is in LCSSA form 622 bool isLCSSAForm(DominatorTree &DT) const; 623 624 /// isLoopSimplifyForm - Return true if the Loop is in the form that 625 /// the LoopSimplify form transforms loops to, which is sometimes called 626 /// normal form. 627 bool isLoopSimplifyForm() const; 628 629 /// hasDedicatedExits - Return true if no exit block for the loop 630 /// has a predecessor that is outside the loop. 631 bool hasDedicatedExits() const; 632 633 /// getUniqueExitBlocks - Return all unique successor blocks of this loop. 634 /// These are the blocks _outside of the current loop_ which are branched to. 635 /// This assumes that loop exits are in canonical form. 636 /// 637 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const; 638 639 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one 640 /// block, return that block. Otherwise return null. 641 BasicBlock *getUniqueExitBlock() const; 642 643 void dump() const; 644 645private: 646 friend class LoopInfoBase<BasicBlock, Loop>; 647 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {} 648}; 649 650//===----------------------------------------------------------------------===// 651/// LoopInfo - This class builds and contains all of the top level loop 652/// structures in the specified function. 653/// 654 655template<class BlockT, class LoopT> 656class LoopInfoBase { 657 // BBMap - Mapping of basic blocks to the inner most loop they occur in 658 DenseMap<BlockT *, LoopT *> BBMap; 659 std::vector<LoopT *> TopLevelLoops; 660 friend class LoopBase<BlockT, LoopT>; 661 friend class LoopInfo; 662 663 void operator=(const LoopInfoBase &); // do not implement 664 LoopInfoBase(const LoopInfo &); // do not implement 665public: 666 LoopInfoBase() { } 667 ~LoopInfoBase() { releaseMemory(); } 668 669 void releaseMemory() { 670 for (typename std::vector<LoopT *>::iterator I = 671 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I) 672 delete *I; // Delete all of the loops... 673 674 BBMap.clear(); // Reset internal state of analysis 675 TopLevelLoops.clear(); 676 } 677 678 /// iterator/begin/end - The interface to the top-level loops in the current 679 /// function. 680 /// 681 typedef typename std::vector<LoopT *>::const_iterator iterator; 682 iterator begin() const { return TopLevelLoops.begin(); } 683 iterator end() const { return TopLevelLoops.end(); } 684 bool empty() const { return TopLevelLoops.empty(); } 685 686 /// getLoopFor - Return the inner most loop that BB lives in. If a basic 687 /// block is in no loop (for example the entry node), null is returned. 688 /// 689 LoopT *getLoopFor(const BlockT *BB) const { 690 typename DenseMap<BlockT *, LoopT *>::const_iterator I= 691 BBMap.find(const_cast<BlockT*>(BB)); 692 return I != BBMap.end() ? I->second : 0; 693 } 694 695 /// operator[] - same as getLoopFor... 696 /// 697 const LoopT *operator[](const BlockT *BB) const { 698 return getLoopFor(BB); 699 } 700 701 /// getLoopDepth - Return the loop nesting level of the specified block. A 702 /// depth of 0 means the block is not inside any loop. 703 /// 704 unsigned getLoopDepth(const BlockT *BB) const { 705 const LoopT *L = getLoopFor(BB); 706 return L ? L->getLoopDepth() : 0; 707 } 708 709 // isLoopHeader - True if the block is a loop header node 710 bool isLoopHeader(BlockT *BB) const { 711 const LoopT *L = getLoopFor(BB); 712 return L && L->getHeader() == BB; 713 } 714 715 /// removeLoop - This removes the specified top-level loop from this loop info 716 /// object. The loop is not deleted, as it will presumably be inserted into 717 /// another loop. 718 LoopT *removeLoop(iterator I) { 719 assert(I != end() && "Cannot remove end iterator!"); 720 LoopT *L = *I; 721 assert(L->getParentLoop() == 0 && "Not a top-level loop!"); 722 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin())); 723 return L; 724 } 725 726 /// changeLoopFor - Change the top-level loop that contains BB to the 727 /// specified loop. This should be used by transformations that restructure 728 /// the loop hierarchy tree. 729 void changeLoopFor(BlockT *BB, LoopT *L) { 730 if (!L) { 731 typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB); 732 if (I != BBMap.end()) 733 BBMap.erase(I); 734 return; 735 } 736 BBMap[BB] = L; 737 } 738 739 /// changeTopLevelLoop - Replace the specified loop in the top-level loops 740 /// list with the indicated loop. 741 void changeTopLevelLoop(LoopT *OldLoop, 742 LoopT *NewLoop) { 743 typename std::vector<LoopT *>::iterator I = 744 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop); 745 assert(I != TopLevelLoops.end() && "Old loop not at top level!"); 746 *I = NewLoop; 747 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 && 748 "Loops already embedded into a subloop!"); 749 } 750 751 /// addTopLevelLoop - This adds the specified loop to the collection of 752 /// top-level loops. 753 void addTopLevelLoop(LoopT *New) { 754 assert(New->getParentLoop() == 0 && "Loop already in subloop!"); 755 TopLevelLoops.push_back(New); 756 } 757 758 /// removeBlock - This method completely removes BB from all data structures, 759 /// including all of the Loop objects it is nested in and our mapping from 760 /// BasicBlocks to loops. 761 void removeBlock(BlockT *BB) { 762 typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB); 763 if (I != BBMap.end()) { 764 for (LoopT *L = I->second; L; L = L->getParentLoop()) 765 L->removeBlockFromLoop(BB); 766 767 BBMap.erase(I); 768 } 769 } 770 771 // Internals 772 773 static bool isNotAlreadyContainedIn(const LoopT *SubLoop, 774 const LoopT *ParentLoop) { 775 if (SubLoop == 0) return true; 776 if (SubLoop == ParentLoop) return false; 777 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop); 778 } 779 780 void Calculate(DominatorTreeBase<BlockT> &DT) { 781 BlockT *RootNode = DT.getRootNode()->getBlock(); 782 783 for (df_iterator<BlockT*> NI = df_begin(RootNode), 784 NE = df_end(RootNode); NI != NE; ++NI) 785 if (LoopT *L = ConsiderForLoop(*NI, DT)) 786 TopLevelLoops.push_back(L); 787 } 788 789 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) { 790 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node? 791 792 std::vector<BlockT *> TodoStack; 793 794 // Scan the predecessors of BB, checking to see if BB dominates any of 795 // them. This identifies backedges which target this node... 796 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits; 797 for (typename InvBlockTraits::ChildIteratorType I = 798 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB); 799 I != E; ++I) { 800 typename InvBlockTraits::NodeType *N = *I; 801 if (DT.dominates(BB, N)) // If BB dominates its predecessor... 802 TodoStack.push_back(N); 803 } 804 805 if (TodoStack.empty()) return 0; // No backedges to this block... 806 807 // Create a new loop to represent this basic block... 808 LoopT *L = new LoopT(BB); 809 BBMap[BB] = L; 810 811 BlockT *EntryBlock = BB->getParent()->begin(); 812 813 while (!TodoStack.empty()) { // Process all the nodes in the loop 814 BlockT *X = TodoStack.back(); 815 TodoStack.pop_back(); 816 817 if (!L->contains(X) && // As of yet unprocessed?? 818 DT.dominates(EntryBlock, X)) { // X is reachable from entry block? 819 // Check to see if this block already belongs to a loop. If this occurs 820 // then we have a case where a loop that is supposed to be a child of 821 // the current loop was processed before the current loop. When this 822 // occurs, this child loop gets added to a part of the current loop, 823 // making it a sibling to the current loop. We have to reparent this 824 // loop. 825 if (LoopT *SubLoop = 826 const_cast<LoopT *>(getLoopFor(X))) 827 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){ 828 // Remove the subloop from its current parent... 829 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L); 830 LoopT *SLP = SubLoop->ParentLoop; // SubLoopParent 831 typename std::vector<LoopT *>::iterator I = 832 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop); 833 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?"); 834 SLP->SubLoops.erase(I); // Remove from parent... 835 836 // Add the subloop to THIS loop... 837 SubLoop->ParentLoop = L; 838 L->SubLoops.push_back(SubLoop); 839 } 840 841 // Normal case, add the block to our loop... 842 L->Blocks.push_back(X); 843 844 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits; 845 846 // Add all of the predecessors of X to the end of the work stack... 847 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X), 848 InvBlockTraits::child_end(X)); 849 } 850 } 851 852 // If there are any loops nested within this loop, create them now! 853 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(), 854 E = L->Blocks.end(); I != E; ++I) 855 if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) { 856 L->SubLoops.push_back(NewLoop); 857 NewLoop->ParentLoop = L; 858 } 859 860 // Add the basic blocks that comprise this loop to the BBMap so that this 861 // loop can be found for them. 862 // 863 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(), 864 E = L->Blocks.end(); I != E; ++I) 865 BBMap.insert(std::make_pair(*I, L)); 866 867 // Now that we have a list of all of the child loops of this loop, check to 868 // see if any of them should actually be nested inside of each other. We 869 // can accidentally pull loops our of their parents, so we must make sure to 870 // organize the loop nests correctly now. 871 { 872 std::map<BlockT *, LoopT *> ContainingLoops; 873 for (unsigned i = 0; i != L->SubLoops.size(); ++i) { 874 LoopT *Child = L->SubLoops[i]; 875 assert(Child->getParentLoop() == L && "Not proper child loop?"); 876 877 if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) { 878 // If there is already a loop which contains this loop, move this loop 879 // into the containing loop. 880 MoveSiblingLoopInto(Child, ContainingLoop); 881 --i; // The loop got removed from the SubLoops list. 882 } else { 883 // This is currently considered to be a top-level loop. Check to see 884 // if any of the contained blocks are loop headers for subloops we 885 // have already processed. 886 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) { 887 LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]]; 888 if (BlockLoop == 0) { // Child block not processed yet... 889 BlockLoop = Child; 890 } else if (BlockLoop != Child) { 891 LoopT *SubLoop = BlockLoop; 892 // Reparent all of the blocks which used to belong to BlockLoops 893 for (unsigned j = 0, f = SubLoop->Blocks.size(); j != f; ++j) 894 ContainingLoops[SubLoop->Blocks[j]] = Child; 895 896 // There is already a loop which contains this block, that means 897 // that we should reparent the loop which the block is currently 898 // considered to belong to to be a child of this loop. 899 MoveSiblingLoopInto(SubLoop, Child); 900 --i; // We just shrunk the SubLoops list. 901 } 902 } 903 } 904 } 905 } 906 907 return L; 908 } 909 910 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside 911 /// of the NewParent Loop, instead of being a sibling of it. 912 void MoveSiblingLoopInto(LoopT *NewChild, 913 LoopT *NewParent) { 914 LoopT *OldParent = NewChild->getParentLoop(); 915 assert(OldParent && OldParent == NewParent->getParentLoop() && 916 NewChild != NewParent && "Not sibling loops!"); 917 918 // Remove NewChild from being a child of OldParent 919 typename std::vector<LoopT *>::iterator I = 920 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), 921 NewChild); 922 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??"); 923 OldParent->SubLoops.erase(I); // Remove from parent's subloops list 924 NewChild->ParentLoop = 0; 925 926 InsertLoopInto(NewChild, NewParent); 927 } 928 929 /// InsertLoopInto - This inserts loop L into the specified parent loop. If 930 /// the parent loop contains a loop which should contain L, the loop gets 931 /// inserted into L instead. 932 void InsertLoopInto(LoopT *L, LoopT *Parent) { 933 BlockT *LHeader = L->getHeader(); 934 assert(Parent->contains(LHeader) && 935 "This loop should not be inserted here!"); 936 937 // Check to see if it belongs in a child loop... 938 for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size()); 939 i != e; ++i) 940 if (Parent->SubLoops[i]->contains(LHeader)) { 941 InsertLoopInto(L, Parent->SubLoops[i]); 942 return; 943 } 944 945 // If not, insert it here! 946 Parent->SubLoops.push_back(L); 947 L->ParentLoop = Parent; 948 } 949 950 // Debugging 951 952 void print(raw_ostream &OS) const { 953 for (unsigned i = 0; i < TopLevelLoops.size(); ++i) 954 TopLevelLoops[i]->print(OS); 955 #if 0 956 for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(), 957 E = BBMap.end(); I != E; ++I) 958 OS << "BB '" << I->first->getName() << "' level = " 959 << I->second->getLoopDepth() << "\n"; 960 #endif 961 } 962}; 963 964class LoopInfo : public FunctionPass { 965 LoopInfoBase<BasicBlock, Loop> LI; 966 friend class LoopBase<BasicBlock, Loop>; 967 968 void operator=(const LoopInfo &); // do not implement 969 LoopInfo(const LoopInfo &); // do not implement 970public: 971 static char ID; // Pass identification, replacement for typeid 972 973 LoopInfo() : FunctionPass(ID) { 974 initializeLoopInfoPass(*PassRegistry::getPassRegistry()); 975 } 976 977 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; } 978 979 /// iterator/begin/end - The interface to the top-level loops in the current 980 /// function. 981 /// 982 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator; 983 inline iterator begin() const { return LI.begin(); } 984 inline iterator end() const { return LI.end(); } 985 bool empty() const { return LI.empty(); } 986 987 /// getLoopFor - Return the inner most loop that BB lives in. If a basic 988 /// block is in no loop (for example the entry node), null is returned. 989 /// 990 inline Loop *getLoopFor(const BasicBlock *BB) const { 991 return LI.getLoopFor(BB); 992 } 993 994 /// operator[] - same as getLoopFor... 995 /// 996 inline const Loop *operator[](const BasicBlock *BB) const { 997 return LI.getLoopFor(BB); 998 } 999 1000 /// getLoopDepth - Return the loop nesting level of the specified block. A 1001 /// depth of 0 means the block is not inside any loop. 1002 /// 1003 inline unsigned getLoopDepth(const BasicBlock *BB) const { 1004 return LI.getLoopDepth(BB); 1005 } 1006 1007 // isLoopHeader - True if the block is a loop header node 1008 inline bool isLoopHeader(BasicBlock *BB) const { 1009 return LI.isLoopHeader(BB); 1010 } 1011 1012 /// runOnFunction - Calculate the natural loop information. 1013 /// 1014 virtual bool runOnFunction(Function &F); 1015 1016 virtual void verifyAnalysis() const; 1017 1018 virtual void releaseMemory() { LI.releaseMemory(); } 1019 1020 virtual void print(raw_ostream &O, const Module* M = 0) const; 1021 1022 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 1023 1024 /// removeLoop - This removes the specified top-level loop from this loop info 1025 /// object. The loop is not deleted, as it will presumably be inserted into 1026 /// another loop. 1027 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); } 1028 1029 /// changeLoopFor - Change the top-level loop that contains BB to the 1030 /// specified loop. This should be used by transformations that restructure 1031 /// the loop hierarchy tree. 1032 inline void changeLoopFor(BasicBlock *BB, Loop *L) { 1033 LI.changeLoopFor(BB, L); 1034 } 1035 1036 /// changeTopLevelLoop - Replace the specified loop in the top-level loops 1037 /// list with the indicated loop. 1038 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) { 1039 LI.changeTopLevelLoop(OldLoop, NewLoop); 1040 } 1041 1042 /// addTopLevelLoop - This adds the specified loop to the collection of 1043 /// top-level loops. 1044 inline void addTopLevelLoop(Loop *New) { 1045 LI.addTopLevelLoop(New); 1046 } 1047 1048 /// removeBlock - This method completely removes BB from all data structures, 1049 /// including all of the Loop objects it is nested in and our mapping from 1050 /// BasicBlocks to loops. 1051 void removeBlock(BasicBlock *BB) { 1052 LI.removeBlock(BB); 1053 } 1054 1055 /// updateUnloop - Update LoopInfo after removing the last backedge from a 1056 /// loop--now the "unloop". This updates the loop forest and parent loops for 1057 /// each block so that Unloop is no longer referenced, but the caller must 1058 /// actually delete the Unloop object. 1059 void updateUnloop(Loop *Unloop); 1060 1061 /// replacementPreservesLCSSAForm - Returns true if replacing From with To 1062 /// everywhere is guaranteed to preserve LCSSA form. 1063 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) { 1064 // Preserving LCSSA form is only problematic if the replacing value is an 1065 // instruction. 1066 Instruction *I = dyn_cast<Instruction>(To); 1067 if (!I) return true; 1068 // If both instructions are defined in the same basic block then replacement 1069 // cannot break LCSSA form. 1070 if (I->getParent() == From->getParent()) 1071 return true; 1072 // If the instruction is not defined in a loop then it can safely replace 1073 // anything. 1074 Loop *ToLoop = getLoopFor(I->getParent()); 1075 if (!ToLoop) return true; 1076 // If the replacing instruction is defined in the same loop as the original 1077 // instruction, or in a loop that contains it as an inner loop, then using 1078 // it as a replacement will not break LCSSA form. 1079 return ToLoop->contains(getLoopFor(From->getParent())); 1080 } 1081}; 1082 1083 1084// Allow clients to walk the list of nested loops... 1085template <> struct GraphTraits<const Loop*> { 1086 typedef const Loop NodeType; 1087 typedef LoopInfo::iterator ChildIteratorType; 1088 1089 static NodeType *getEntryNode(const Loop *L) { return L; } 1090 static inline ChildIteratorType child_begin(NodeType *N) { 1091 return N->begin(); 1092 } 1093 static inline ChildIteratorType child_end(NodeType *N) { 1094 return N->end(); 1095 } 1096}; 1097 1098template <> struct GraphTraits<Loop*> { 1099 typedef Loop NodeType; 1100 typedef LoopInfo::iterator ChildIteratorType; 1101 1102 static NodeType *getEntryNode(Loop *L) { return L; } 1103 static inline ChildIteratorType child_begin(NodeType *N) { 1104 return N->begin(); 1105 } 1106 static inline ChildIteratorType child_end(NodeType *N) { 1107 return N->end(); 1108 } 1109}; 1110 1111template<class BlockT, class LoopT> 1112void 1113LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB, 1114 LoopInfoBase<BlockT, LoopT> &LIB) { 1115 assert((Blocks.empty() || LIB[getHeader()] == this) && 1116 "Incorrect LI specified for this loop!"); 1117 assert(NewBB && "Cannot add a null basic block to the loop!"); 1118 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!"); 1119 1120 LoopT *L = static_cast<LoopT *>(this); 1121 1122 // Add the loop mapping to the LoopInfo object... 1123 LIB.BBMap[NewBB] = L; 1124 1125 // Add the basic block to this loop and all parent loops... 1126 while (L) { 1127 L->Blocks.push_back(NewBB); 1128 L = L->getParentLoop(); 1129 } 1130} 1131 1132} // End llvm namespace 1133 1134#endif 1135