LLVM API Documentation

RegionInfo.cpp
Go to the documentation of this file.
00001 //===- RegionInfo.cpp - SESE region detection analysis --------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 // Detects single entry single exit regions in the control flow graph.
00010 //===----------------------------------------------------------------------===//
00011 
00012 #include "llvm/Analysis/RegionInfo.h"
00013 #include "llvm/ADT/PostOrderIterator.h"
00014 #include "llvm/ADT/Statistic.h"
00015 #include "llvm/Analysis/LoopInfo.h"
00016 #include "llvm/Analysis/RegionIterator.h"
00017 #include "llvm/Assembly/Writer.h"
00018 #include "llvm/Support/CommandLine.h"
00019 #include "llvm/Support/ErrorHandling.h"
00020 
00021 #define DEBUG_TYPE "region"
00022 #include "llvm/Support/Debug.h"
00023 
00024 #include <set>
00025 #include <algorithm>
00026 
00027 using namespace llvm;
00028 
00029 // Always verify if expensive checking is enabled.
00030 #ifdef XDEBUG
00031 static bool VerifyRegionInfo = true;
00032 #else
00033 static bool VerifyRegionInfo = false;
00034 #endif
00035 
00036 static cl::opt<bool,true>
00037 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
00038                 cl::desc("Verify region info (time consuming)"));
00039 
00040 STATISTIC(numRegions,       "The # of regions");
00041 STATISTIC(numSimpleRegions, "The # of simple regions");
00042 
00043 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
00044   cl::Hidden,
00045   cl::desc("style of printing regions"),
00046   cl::values(
00047     clEnumValN(Region::PrintNone, "none",  "print no details"),
00048     clEnumValN(Region::PrintBB, "bb",
00049                "print regions in detail with block_iterator"),
00050     clEnumValN(Region::PrintRN, "rn",
00051                "print regions in detail with element_iterator"),
00052     clEnumValEnd));
00053 //===----------------------------------------------------------------------===//
00054 /// Region Implementation
00055 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
00056                DominatorTree *dt, Region *Parent)
00057                : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
00058 
00059 Region::~Region() {
00060   // Free the cached nodes.
00061   for (BBNodeMapT::iterator it = BBNodeMap.begin(),
00062          ie = BBNodeMap.end(); it != ie; ++it)
00063     delete it->second;
00064 
00065   // Only clean the cache for this Region. Caches of child Regions will be
00066   // cleaned when the child Regions are deleted.
00067   BBNodeMap.clear();
00068 
00069   for (iterator I = begin(), E = end(); I != E; ++I)
00070     delete *I;
00071 }
00072 
00073 void Region::replaceEntry(BasicBlock *BB) {
00074   entry.setPointer(BB);
00075 }
00076 
00077 void Region::replaceExit(BasicBlock *BB) {
00078   assert(exit && "No exit to replace!");
00079   exit = BB;
00080 }
00081 
00082 void Region::replaceEntryRecursive(BasicBlock *NewEntry) {
00083   std::vector<Region *> RegionQueue;
00084   BasicBlock *OldEntry = getEntry();
00085 
00086   RegionQueue.push_back(this);
00087   while (!RegionQueue.empty()) {
00088     Region *R = RegionQueue.back();
00089     RegionQueue.pop_back();
00090 
00091     R->replaceEntry(NewEntry);
00092     for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
00093       if ((*RI)->getEntry() == OldEntry)
00094         RegionQueue.push_back(*RI);
00095   }
00096 }
00097 
00098 void Region::replaceExitRecursive(BasicBlock *NewExit) {
00099   std::vector<Region *> RegionQueue;
00100   BasicBlock *OldExit = getExit();
00101 
00102   RegionQueue.push_back(this);
00103   while (!RegionQueue.empty()) {
00104     Region *R = RegionQueue.back();
00105     RegionQueue.pop_back();
00106 
00107     R->replaceExit(NewExit);
00108     for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
00109       if ((*RI)->getExit() == OldExit)
00110         RegionQueue.push_back(*RI);
00111   }
00112 }
00113 
00114 bool Region::contains(const BasicBlock *B) const {
00115   BasicBlock *BB = const_cast<BasicBlock*>(B);
00116 
00117   if (!DT->getNode(BB))
00118     return false;
00119 
00120   BasicBlock *entry = getEntry(), *exit = getExit();
00121 
00122   // Toplevel region.
00123   if (!exit)
00124     return true;
00125 
00126   return (DT->dominates(entry, BB)
00127     && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
00128 }
00129 
00130 bool Region::contains(const Loop *L) const {
00131   // BBs that are not part of any loop are element of the Loop
00132   // described by the NULL pointer. This loop is not part of any region,
00133   // except if the region describes the whole function.
00134   if (L == 0)
00135     return getExit() == 0;
00136 
00137   if (!contains(L->getHeader()))
00138     return false;
00139 
00140   SmallVector<BasicBlock *, 8> ExitingBlocks;
00141   L->getExitingBlocks(ExitingBlocks);
00142 
00143   for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
00144        BE = ExitingBlocks.end(); BI != BE; ++BI)
00145     if (!contains(*BI))
00146       return false;
00147 
00148   return true;
00149 }
00150 
00151 Loop *Region::outermostLoopInRegion(Loop *L) const {
00152   if (!contains(L))
00153     return 0;
00154 
00155   while (L && contains(L->getParentLoop())) {
00156     L = L->getParentLoop();
00157   }
00158 
00159   return L;
00160 }
00161 
00162 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
00163   assert(LI && BB && "LI and BB cannot be null!");
00164   Loop *L = LI->getLoopFor(BB);
00165   return outermostLoopInRegion(L);
00166 }
00167 
00168 BasicBlock *Region::getEnteringBlock() const {
00169   BasicBlock *entry = getEntry();
00170   BasicBlock *Pred;
00171   BasicBlock *enteringBlock = 0;
00172 
00173   for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
00174        ++PI) {
00175     Pred = *PI;
00176     if (DT->getNode(Pred) && !contains(Pred)) {
00177       if (enteringBlock)
00178         return 0;
00179 
00180       enteringBlock = Pred;
00181     }
00182   }
00183 
00184   return enteringBlock;
00185 }
00186 
00187 BasicBlock *Region::getExitingBlock() const {
00188   BasicBlock *exit = getExit();
00189   BasicBlock *Pred;
00190   BasicBlock *exitingBlock = 0;
00191 
00192   if (!exit)
00193     return 0;
00194 
00195   for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
00196        ++PI) {
00197     Pred = *PI;
00198     if (contains(Pred)) {
00199       if (exitingBlock)
00200         return 0;
00201 
00202       exitingBlock = Pred;
00203     }
00204   }
00205 
00206   return exitingBlock;
00207 }
00208 
00209 bool Region::isSimple() const {
00210   return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
00211 }
00212 
00213 std::string Region::getNameStr() const {
00214   std::string exitName;
00215   std::string entryName;
00216 
00217   if (getEntry()->getName().empty()) {
00218     raw_string_ostream OS(entryName);
00219 
00220     WriteAsOperand(OS, getEntry(), false);
00221   } else
00222     entryName = getEntry()->getName();
00223 
00224   if (getExit()) {
00225     if (getExit()->getName().empty()) {
00226       raw_string_ostream OS(exitName);
00227 
00228       WriteAsOperand(OS, getExit(), false);
00229     } else
00230       exitName = getExit()->getName();
00231   } else
00232     exitName = "<Function Return>";
00233 
00234   return entryName + " => " + exitName;
00235 }
00236 
00237 void Region::verifyBBInRegion(BasicBlock *BB) const {
00238   if (!contains(BB))
00239     llvm_unreachable("Broken region found!");
00240 
00241   BasicBlock *entry = getEntry(), *exit = getExit();
00242 
00243   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
00244     if (!contains(*SI) && exit != *SI)
00245       llvm_unreachable("Broken region found!");
00246 
00247   if (entry != BB)
00248     for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
00249       if (!contains(*SI))
00250         llvm_unreachable("Broken region found!");
00251 }
00252 
00253 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
00254   BasicBlock *exit = getExit();
00255 
00256   visited->insert(BB);
00257 
00258   verifyBBInRegion(BB);
00259 
00260   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
00261     if (*SI != exit && visited->find(*SI) == visited->end())
00262         verifyWalk(*SI, visited);
00263 }
00264 
00265 void Region::verifyRegion() const {
00266   // Only do verification when user wants to, otherwise this expensive
00267   // check will be invoked by PassManager.
00268   if (!VerifyRegionInfo) return;
00269 
00270   std::set<BasicBlock*> visited;
00271   verifyWalk(getEntry(), &visited);
00272 }
00273 
00274 void Region::verifyRegionNest() const {
00275   for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
00276     (*RI)->verifyRegionNest();
00277 
00278   verifyRegion();
00279 }
00280 
00281 Region::element_iterator Region::element_begin() {
00282   return GraphTraits<Region*>::nodes_begin(this);
00283 }
00284 
00285 Region::element_iterator Region::element_end() {
00286   return GraphTraits<Region*>::nodes_end(this);
00287 }
00288 
00289 Region::const_element_iterator Region::element_begin() const {
00290   return GraphTraits<const Region*>::nodes_begin(this);
00291 }
00292 
00293 Region::const_element_iterator Region::element_end() const {
00294   return GraphTraits<const Region*>::nodes_end(this);
00295 }
00296 
00297 Region* Region::getSubRegionNode(BasicBlock *BB) const {
00298   Region *R = RI->getRegionFor(BB);
00299 
00300   if (!R || R == this)
00301     return 0;
00302 
00303   // If we pass the BB out of this region, that means our code is broken.
00304   assert(contains(R) && "BB not in current region!");
00305 
00306   while (contains(R->getParent()) && R->getParent() != this)
00307     R = R->getParent();
00308 
00309   if (R->getEntry() != BB)
00310     return 0;
00311 
00312   return R;
00313 }
00314 
00315 RegionNode* Region::getBBNode(BasicBlock *BB) const {
00316   assert(contains(BB) && "Can get BB node out of this region!");
00317 
00318   BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
00319 
00320   if (at != BBNodeMap.end())
00321     return at->second;
00322 
00323   RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
00324   BBNodeMap.insert(std::make_pair(BB, NewNode));
00325   return NewNode;
00326 }
00327 
00328 RegionNode* Region::getNode(BasicBlock *BB) const {
00329   assert(contains(BB) && "Can get BB node out of this region!");
00330   if (Region* Child = getSubRegionNode(BB))
00331     return Child->getNode();
00332 
00333   return getBBNode(BB);
00334 }
00335 
00336 void Region::transferChildrenTo(Region *To) {
00337   for (iterator I = begin(), E = end(); I != E; ++I) {
00338     (*I)->parent = To;
00339     To->children.push_back(*I);
00340   }
00341   children.clear();
00342 }
00343 
00344 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
00345   assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
00346   assert(std::find(begin(), end(), SubRegion) == children.end()
00347          && "Subregion already exists!");
00348 
00349   SubRegion->parent = this;
00350   children.push_back(SubRegion);
00351 
00352   if (!moveChildren)
00353     return;
00354 
00355   assert(SubRegion->children.size() == 0
00356          && "SubRegions that contain children are not supported");
00357 
00358   for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
00359     if (!(*I)->isSubRegion()) {
00360       BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
00361 
00362       if (SubRegion->contains(BB))
00363         RI->setRegionFor(BB, SubRegion);
00364     }
00365 
00366   std::vector<Region*> Keep;
00367   for (iterator I = begin(), E = end(); I != E; ++I)
00368     if (SubRegion->contains(*I) && *I != SubRegion) {
00369       SubRegion->children.push_back(*I);
00370       (*I)->parent = SubRegion;
00371     } else
00372       Keep.push_back(*I);
00373 
00374   children.clear();
00375   children.insert(children.begin(), Keep.begin(), Keep.end());
00376 }
00377 
00378 
00379 Region *Region::removeSubRegion(Region *Child) {
00380   assert(Child->parent == this && "Child is not a child of this region!");
00381   Child->parent = 0;
00382   RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
00383   assert(I != children.end() && "Region does not exit. Unable to remove.");
00384   children.erase(children.begin()+(I-begin()));
00385   return Child;
00386 }
00387 
00388 unsigned Region::getDepth() const {
00389   unsigned Depth = 0;
00390 
00391   for (Region *R = parent; R != 0; R = R->parent)
00392     ++Depth;
00393 
00394   return Depth;
00395 }
00396 
00397 Region *Region::getExpandedRegion() const {
00398   unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
00399 
00400   if (NumSuccessors == 0)
00401     return NULL;
00402 
00403   for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
00404        PI != PE; ++PI)
00405     if (!DT->dominates(getEntry(), *PI))
00406       return NULL;
00407 
00408   Region *R = RI->getRegionFor(exit);
00409 
00410   if (R->getEntry() != exit) {
00411     if (exit->getTerminator()->getNumSuccessors() == 1)
00412       return new Region(getEntry(), *succ_begin(exit), RI, DT);
00413     else
00414       return NULL;
00415   }
00416 
00417   while (R->getParent() && R->getParent()->getEntry() == exit)
00418     R = R->getParent();
00419 
00420   if (!DT->dominates(getEntry(), R->getExit()))
00421     for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
00422          PI != PE; ++PI)
00423     if (!DT->dominates(R->getExit(), *PI))
00424       return NULL;
00425 
00426   return new Region(getEntry(), R->getExit(), RI, DT);
00427 }
00428 
00429 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
00430                    enum PrintStyle Style) const {
00431   if (print_tree)
00432     OS.indent(level*2) << "[" << level << "] " << getNameStr();
00433   else
00434     OS.indent(level*2) << getNameStr();
00435 
00436   OS << "\n";
00437 
00438 
00439   if (Style != PrintNone) {
00440     OS.indent(level*2) << "{\n";
00441     OS.indent(level*2 + 2);
00442 
00443     if (Style == PrintBB) {
00444       for (const_block_iterator I = block_begin(), E = block_end(); I != E; ++I)
00445         OS << (*I)->getName() << ", "; // TODO: remove the last ","
00446     } else if (Style == PrintRN) {
00447       for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
00448         OS << **I << ", "; // TODO: remove the last ",
00449     }
00450 
00451     OS << "\n";
00452   }
00453 
00454   if (print_tree)
00455     for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
00456       (*RI)->print(OS, print_tree, level+1, Style);
00457 
00458   if (Style != PrintNone)
00459     OS.indent(level*2) << "} \n";
00460 }
00461 
00462 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00463 void Region::dump() const {
00464   print(dbgs(), true, getDepth(), printStyle.getValue());
00465 }
00466 #endif
00467 
00468 void Region::clearNodeCache() {
00469   // Free the cached nodes.
00470   for (BBNodeMapT::iterator I = BBNodeMap.begin(),
00471        IE = BBNodeMap.end(); I != IE; ++I)
00472     delete I->second;
00473 
00474   BBNodeMap.clear();
00475   for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
00476     (*RI)->clearNodeCache();
00477 }
00478 
00479 //===----------------------------------------------------------------------===//
00480 // RegionInfo implementation
00481 //
00482 
00483 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
00484                                      BasicBlock *exit) const {
00485   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
00486     BasicBlock *P = *PI;
00487     if (DT->dominates(entry, P) && !DT->dominates(exit, P))
00488       return false;
00489   }
00490   return true;
00491 }
00492 
00493 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
00494   assert(entry && exit && "entry and exit must not be null!");
00495   typedef DominanceFrontier::DomSetType DST;
00496 
00497   DST *entrySuccs = &DF->find(entry)->second;
00498 
00499   // Exit is the header of a loop that contains the entry. In this case,
00500   // the dominance frontier must only contain the exit.
00501   if (!DT->dominates(entry, exit)) {
00502     for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
00503          SI != SE; ++SI)
00504       if (*SI != exit && *SI != entry)
00505         return false;
00506 
00507     return true;
00508   }
00509 
00510   DST *exitSuccs = &DF->find(exit)->second;
00511 
00512   // Do not allow edges leaving the region.
00513   for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
00514        SI != SE; ++SI) {
00515     if (*SI == exit || *SI == entry)
00516       continue;
00517     if (exitSuccs->find(*SI) == exitSuccs->end())
00518       return false;
00519     if (!isCommonDomFrontier(*SI, entry, exit))
00520       return false;
00521   }
00522 
00523   // Do not allow edges pointing into the region.
00524   for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
00525        SI != SE; ++SI)
00526     if (DT->properlyDominates(entry, *SI) && *SI != exit)
00527       return false;
00528 
00529 
00530   return true;
00531 }
00532 
00533 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
00534                              BBtoBBMap *ShortCut) const {
00535   assert(entry && exit && "entry and exit must not be null!");
00536 
00537   BBtoBBMap::iterator e = ShortCut->find(exit);
00538 
00539   if (e == ShortCut->end())
00540     // No further region at exit available.
00541     (*ShortCut)[entry] = exit;
00542   else {
00543     // We found a region e that starts at exit. Therefore (entry, e->second)
00544     // is also a region, that is larger than (entry, exit). Insert the
00545     // larger one.
00546     BasicBlock *BB = e->second;
00547     (*ShortCut)[entry] = BB;
00548   }
00549 }
00550 
00551 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
00552                                         BBtoBBMap *ShortCut) const {
00553   BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
00554 
00555   if (e == ShortCut->end())
00556     return N->getIDom();
00557 
00558   return PDT->getNode(e->second)->getIDom();
00559 }
00560 
00561 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
00562   assert(entry && exit && "entry and exit must not be null!");
00563 
00564   unsigned num_successors = succ_end(entry) - succ_begin(entry);
00565 
00566   if (num_successors <= 1 && exit == *(succ_begin(entry)))
00567     return true;
00568 
00569   return false;
00570 }
00571 
00572 void RegionInfo::updateStatistics(Region *R) {
00573   ++numRegions;
00574 
00575   // TODO: Slow. Should only be enabled if -stats is used.
00576   if (R->isSimple()) ++numSimpleRegions;
00577 }
00578 
00579 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
00580   assert(entry && exit && "entry and exit must not be null!");
00581 
00582   if (isTrivialRegion(entry, exit))
00583     return 0;
00584 
00585   Region *region = new Region(entry, exit, this, DT);
00586   BBtoRegion.insert(std::make_pair(entry, region));
00587 
00588  #ifdef XDEBUG
00589     region->verifyRegion();
00590  #else
00591     DEBUG(region->verifyRegion());
00592  #endif
00593 
00594   updateStatistics(region);
00595   return region;
00596 }
00597 
00598 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
00599   assert(entry);
00600 
00601   DomTreeNode *N = PDT->getNode(entry);
00602 
00603   if (!N)
00604     return;
00605 
00606   Region *lastRegion= 0;
00607   BasicBlock *lastExit = entry;
00608 
00609   // As only a BasicBlock that postdominates entry can finish a region, walk the
00610   // post dominance tree upwards.
00611   while ((N = getNextPostDom(N, ShortCut))) {
00612     BasicBlock *exit = N->getBlock();
00613 
00614     if (!exit)
00615       break;
00616 
00617     if (isRegion(entry, exit)) {
00618       Region *newRegion = createRegion(entry, exit);
00619 
00620       if (lastRegion)
00621         newRegion->addSubRegion(lastRegion);
00622 
00623       lastRegion = newRegion;
00624       lastExit = exit;
00625     }
00626 
00627     // This can never be a region, so stop the search.
00628     if (!DT->dominates(entry, exit))
00629       break;
00630   }
00631 
00632   // Tried to create regions from entry to lastExit.  Next time take a
00633   // shortcut from entry to lastExit.
00634   if (lastExit != entry)
00635     insertShortCut(entry, lastExit, ShortCut);
00636 }
00637 
00638 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
00639   BasicBlock *entry = &(F.getEntryBlock());
00640   DomTreeNode *N = DT->getNode(entry);
00641 
00642   // Iterate over the dominance tree in post order to start with the small
00643   // regions from the bottom of the dominance tree.  If the small regions are
00644   // detected first, detection of bigger regions is faster, as we can jump
00645   // over the small regions.
00646   for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
00647     ++FI) {
00648     findRegionsWithEntry(FI->getBlock(), ShortCut);
00649   }
00650 }
00651 
00652 Region *RegionInfo::getTopMostParent(Region *region) {
00653   while (region->parent)
00654     region = region->getParent();
00655 
00656   return region;
00657 }
00658 
00659 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
00660   BasicBlock *BB = N->getBlock();
00661 
00662   // Passed region exit
00663   while (BB == region->getExit())
00664     region = region->getParent();
00665 
00666   BBtoRegionMap::iterator it = BBtoRegion.find(BB);
00667 
00668   // This basic block is a start block of a region. It is already in the
00669   // BBtoRegion relation. Only the child basic blocks have to be updated.
00670   if (it != BBtoRegion.end()) {
00671     Region *newRegion = it->second;
00672     region->addSubRegion(getTopMostParent(newRegion));
00673     region = newRegion;
00674   } else {
00675     BBtoRegion[BB] = region;
00676   }
00677 
00678   for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
00679     buildRegionsTree(*CI, region);
00680 }
00681 
00682 void RegionInfo::releaseMemory() {
00683   BBtoRegion.clear();
00684   if (TopLevelRegion)
00685     delete TopLevelRegion;
00686   TopLevelRegion = 0;
00687 }
00688 
00689 RegionInfo::RegionInfo() : FunctionPass(ID) {
00690   initializeRegionInfoPass(*PassRegistry::getPassRegistry());
00691   TopLevelRegion = 0;
00692 }
00693 
00694 RegionInfo::~RegionInfo() {
00695   releaseMemory();
00696 }
00697 
00698 void RegionInfo::Calculate(Function &F) {
00699   // ShortCut a function where for every BB the exit of the largest region
00700   // starting with BB is stored. These regions can be threated as single BBS.
00701   // This improves performance on linear CFGs.
00702   BBtoBBMap ShortCut;
00703 
00704   scanForRegions(F, &ShortCut);
00705   BasicBlock *BB = &F.getEntryBlock();
00706   buildRegionsTree(DT->getNode(BB), TopLevelRegion);
00707 }
00708 
00709 bool RegionInfo::runOnFunction(Function &F) {
00710   releaseMemory();
00711 
00712   DT = &getAnalysis<DominatorTree>();
00713   PDT = &getAnalysis<PostDominatorTree>();
00714   DF = &getAnalysis<DominanceFrontier>();
00715 
00716   TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
00717   updateStatistics(TopLevelRegion);
00718 
00719   Calculate(F);
00720 
00721   return false;
00722 }
00723 
00724 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
00725   AU.setPreservesAll();
00726   AU.addRequiredTransitive<DominatorTree>();
00727   AU.addRequired<PostDominatorTree>();
00728   AU.addRequired<DominanceFrontier>();
00729 }
00730 
00731 void RegionInfo::print(raw_ostream &OS, const Module *) const {
00732   OS << "Region tree:\n";
00733   TopLevelRegion->print(OS, true, 0, printStyle.getValue());
00734   OS << "End region tree\n";
00735 }
00736 
00737 void RegionInfo::verifyAnalysis() const {
00738   // Only do verification when user wants to, otherwise this expensive check
00739   // will be invoked by PMDataManager::verifyPreservedAnalysis when
00740   // a regionpass (marked PreservedAll) finish.
00741   if (!VerifyRegionInfo) return;
00742 
00743   TopLevelRegion->verifyRegionNest();
00744 }
00745 
00746 // Region pass manager support.
00747 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
00748   BBtoRegionMap::const_iterator I=
00749     BBtoRegion.find(BB);
00750   return I != BBtoRegion.end() ? I->second : 0;
00751 }
00752 
00753 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
00754   BBtoRegion[BB] = R;
00755 }
00756 
00757 Region *RegionInfo::operator[](BasicBlock *BB) const {
00758   return getRegionFor(BB);
00759 }
00760 
00761 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
00762   BasicBlock *Exit = NULL;
00763 
00764   while (true) {
00765     // Get largest region that starts at BB.
00766     Region *R = getRegionFor(BB);
00767     while (R && R->getParent() && R->getParent()->getEntry() == BB)
00768       R = R->getParent();
00769 
00770     // Get the single exit of BB.
00771     if (R && R->getEntry() == BB)
00772       Exit = R->getExit();
00773     else if (++succ_begin(BB) == succ_end(BB))
00774       Exit = *succ_begin(BB);
00775     else // No single exit exists.
00776       return Exit;
00777 
00778     // Get largest region that starts at Exit.
00779     Region *ExitR = getRegionFor(Exit);
00780     while (ExitR && ExitR->getParent()
00781            && ExitR->getParent()->getEntry() == Exit)
00782       ExitR = ExitR->getParent();
00783 
00784     for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
00785          ++PI)
00786       if (!R->contains(*PI) && !ExitR->contains(*PI))
00787         break;
00788 
00789     // This stops infinite cycles.
00790     if (DT->dominates(Exit, BB))
00791       break;
00792 
00793     BB = Exit;
00794   }
00795 
00796   return Exit;
00797 }
00798 
00799 Region*
00800 RegionInfo::getCommonRegion(Region *A, Region *B) const {
00801   assert (A && B && "One of the Regions is NULL");
00802 
00803   if (A->contains(B)) return A;
00804 
00805   while (!B->contains(A))
00806     B = B->getParent();
00807 
00808   return B;
00809 }
00810 
00811 Region*
00812 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
00813   Region* ret = Regions.back();
00814   Regions.pop_back();
00815 
00816   for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
00817        E = Regions.end(); I != E; ++I)
00818       ret = getCommonRegion(ret, *I);
00819 
00820   return ret;
00821 }
00822 
00823 Region*
00824 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
00825   Region* ret = getRegionFor(BBs.back());
00826   BBs.pop_back();
00827 
00828   for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
00829        E = BBs.end(); I != E; ++I)
00830       ret = getCommonRegion(ret, getRegionFor(*I));
00831 
00832   return ret;
00833 }
00834 
00835 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
00836 {
00837   Region *R = getRegionFor(OldBB);
00838 
00839   setRegionFor(NewBB, R);
00840 
00841   while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
00842     R->replaceEntry(NewBB);
00843     R = R->getParent();
00844   }
00845 
00846   setRegionFor(OldBB, R);
00847 }
00848 
00849 char RegionInfo::ID = 0;
00850 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
00851                 "Detect single entry single exit regions", true, true)
00852 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
00853 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
00854 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
00855 INITIALIZE_PASS_END(RegionInfo, "regions",
00856                 "Detect single entry single exit regions", true, true)
00857 
00858 // Create methods available outside of this file, to use them
00859 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
00860 // the link time optimization.
00861 
00862 namespace llvm {
00863   FunctionPass *createRegionInfoPass() {
00864     return new RegionInfo();
00865   }
00866 }
00867