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