1 //===- RegionInfo.cpp - SESE region detection analysis --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // Detects single entry single exit regions in the control flow graph.
10 //===----------------------------------------------------------------------===//
12 #define DEBUG_TYPE "region"
13 #include "llvm/Analysis/RegionInfo.h"
14 #include "llvm/ADT/PostOrderIterator.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/RegionIterator.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
26 // Always verify if expensive checking is enabled.
28 static bool VerifyRegionInfo = true;
30 static bool VerifyRegionInfo = false;
33 static cl::opt<bool,true>
34 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
35 cl::desc("Verify region info (time consuming)"));
37 STATISTIC(numRegions, "The # of regions");
38 STATISTIC(numSimpleRegions, "The # of simple regions");
40 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
42 cl::desc("style of printing regions"),
44 clEnumValN(Region::PrintNone, "none", "print no details"),
45 clEnumValN(Region::PrintBB, "bb",
46 "print regions in detail with block_iterator"),
47 clEnumValN(Region::PrintRN, "rn",
48 "print regions in detail with element_iterator"),
50 //===----------------------------------------------------------------------===//
51 /// Region Implementation
52 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
53 DominatorTree *dt, Region *Parent)
54 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
57 // Free the cached nodes.
58 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
59 ie = BBNodeMap.end(); it != ie; ++it)
62 // Only clean the cache for this Region. Caches of child Regions will be
63 // cleaned when the child Regions are deleted.
66 for (iterator I = begin(), E = end(); I != E; ++I)
70 void Region::replaceEntry(BasicBlock *BB) {
74 void Region::replaceExit(BasicBlock *BB) {
75 assert(exit && "No exit to replace!");
79 void Region::replaceEntryRecursive(BasicBlock *NewEntry) {
80 std::vector<Region *> RegionQueue;
81 BasicBlock *OldEntry = getEntry();
83 RegionQueue.push_back(this);
84 while (!RegionQueue.empty()) {
85 Region *R = RegionQueue.back();
86 RegionQueue.pop_back();
88 R->replaceEntry(NewEntry);
89 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
90 if ((*RI)->getEntry() == OldEntry)
91 RegionQueue.push_back(*RI);
95 void Region::replaceExitRecursive(BasicBlock *NewExit) {
96 std::vector<Region *> RegionQueue;
97 BasicBlock *OldExit = getExit();
99 RegionQueue.push_back(this);
100 while (!RegionQueue.empty()) {
101 Region *R = RegionQueue.back();
102 RegionQueue.pop_back();
104 R->replaceExit(NewExit);
105 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
106 if ((*RI)->getExit() == OldExit)
107 RegionQueue.push_back(*RI);
111 bool Region::contains(const BasicBlock *B) const {
112 BasicBlock *BB = const_cast<BasicBlock*>(B);
114 if (!DT->getNode(BB))
117 BasicBlock *entry = getEntry(), *exit = getExit();
123 return (DT->dominates(entry, BB)
124 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
127 bool Region::contains(const Loop *L) const {
128 // BBs that are not part of any loop are element of the Loop
129 // described by the NULL pointer. This loop is not part of any region,
130 // except if the region describes the whole function.
132 return getExit() == 0;
134 if (!contains(L->getHeader()))
137 SmallVector<BasicBlock *, 8> ExitingBlocks;
138 L->getExitingBlocks(ExitingBlocks);
140 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
141 BE = ExitingBlocks.end(); BI != BE; ++BI)
148 Loop *Region::outermostLoopInRegion(Loop *L) const {
152 while (L && contains(L->getParentLoop())) {
153 L = L->getParentLoop();
159 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
160 assert(LI && BB && "LI and BB cannot be null!");
161 Loop *L = LI->getLoopFor(BB);
162 return outermostLoopInRegion(L);
165 BasicBlock *Region::getEnteringBlock() const {
166 BasicBlock *entry = getEntry();
168 BasicBlock *enteringBlock = 0;
170 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
173 if (DT->getNode(Pred) && !contains(Pred)) {
177 enteringBlock = Pred;
181 return enteringBlock;
184 BasicBlock *Region::getExitingBlock() const {
185 BasicBlock *exit = getExit();
187 BasicBlock *exitingBlock = 0;
192 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
195 if (contains(Pred)) {
206 bool Region::isSimple() const {
207 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
210 std::string Region::getNameStr() const {
211 std::string exitName;
212 std::string entryName;
214 if (getEntry()->getName().empty()) {
215 raw_string_ostream OS(entryName);
217 getEntry()->printAsOperand(OS, false);
219 entryName = getEntry()->getName();
222 if (getExit()->getName().empty()) {
223 raw_string_ostream OS(exitName);
225 getExit()->printAsOperand(OS, false);
227 exitName = getExit()->getName();
229 exitName = "<Function Return>";
231 return entryName + " => " + exitName;
234 void Region::verifyBBInRegion(BasicBlock *BB) const {
236 llvm_unreachable("Broken region found!");
238 BasicBlock *entry = getEntry(), *exit = getExit();
240 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
241 if (!contains(*SI) && exit != *SI)
242 llvm_unreachable("Broken region found!");
245 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
247 llvm_unreachable("Broken region found!");
250 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
251 BasicBlock *exit = getExit();
255 verifyBBInRegion(BB);
257 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
258 if (*SI != exit && visited->find(*SI) == visited->end())
259 verifyWalk(*SI, visited);
262 void Region::verifyRegion() const {
263 // Only do verification when user wants to, otherwise this expensive
264 // check will be invoked by PassManager.
265 if (!VerifyRegionInfo) return;
267 std::set<BasicBlock*> visited;
268 verifyWalk(getEntry(), &visited);
271 void Region::verifyRegionNest() const {
272 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
273 (*RI)->verifyRegionNest();
278 Region::element_iterator Region::element_begin() {
279 return GraphTraits<Region*>::nodes_begin(this);
282 Region::element_iterator Region::element_end() {
283 return GraphTraits<Region*>::nodes_end(this);
286 Region::const_element_iterator Region::element_begin() const {
287 return GraphTraits<const Region*>::nodes_begin(this);
290 Region::const_element_iterator Region::element_end() const {
291 return GraphTraits<const Region*>::nodes_end(this);
294 Region* Region::getSubRegionNode(BasicBlock *BB) const {
295 Region *R = RI->getRegionFor(BB);
300 // If we pass the BB out of this region, that means our code is broken.
301 assert(contains(R) && "BB not in current region!");
303 while (contains(R->getParent()) && R->getParent() != this)
306 if (R->getEntry() != BB)
312 RegionNode* Region::getBBNode(BasicBlock *BB) const {
313 assert(contains(BB) && "Can get BB node out of this region!");
315 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
317 if (at != BBNodeMap.end())
320 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
321 BBNodeMap.insert(std::make_pair(BB, NewNode));
325 RegionNode* Region::getNode(BasicBlock *BB) const {
326 assert(contains(BB) && "Can get BB node out of this region!");
327 if (Region* Child = getSubRegionNode(BB))
328 return Child->getNode();
330 return getBBNode(BB);
333 void Region::transferChildrenTo(Region *To) {
334 for (iterator I = begin(), E = end(); I != E; ++I) {
336 To->children.push_back(*I);
341 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
342 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
343 assert(std::find(begin(), end(), SubRegion) == children.end()
344 && "Subregion already exists!");
346 SubRegion->parent = this;
347 children.push_back(SubRegion);
352 assert(SubRegion->children.size() == 0
353 && "SubRegions that contain children are not supported");
355 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
356 if (!(*I)->isSubRegion()) {
357 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
359 if (SubRegion->contains(BB))
360 RI->setRegionFor(BB, SubRegion);
363 std::vector<Region*> Keep;
364 for (iterator I = begin(), E = end(); I != E; ++I)
365 if (SubRegion->contains(*I) && *I != SubRegion) {
366 SubRegion->children.push_back(*I);
367 (*I)->parent = SubRegion;
372 children.insert(children.begin(), Keep.begin(), Keep.end());
376 Region *Region::removeSubRegion(Region *Child) {
377 assert(Child->parent == this && "Child is not a child of this region!");
379 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
380 assert(I != children.end() && "Region does not exit. Unable to remove.");
381 children.erase(children.begin()+(I-begin()));
385 unsigned Region::getDepth() const {
388 for (Region *R = parent; R != 0; R = R->parent)
394 Region *Region::getExpandedRegion() const {
395 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
397 if (NumSuccessors == 0)
400 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
402 if (!DT->dominates(getEntry(), *PI))
405 Region *R = RI->getRegionFor(exit);
407 if (R->getEntry() != exit) {
408 if (exit->getTerminator()->getNumSuccessors() == 1)
409 return new Region(getEntry(), *succ_begin(exit), RI, DT);
414 while (R->getParent() && R->getParent()->getEntry() == exit)
417 if (!DT->dominates(getEntry(), R->getExit()))
418 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
420 if (!DT->dominates(R->getExit(), *PI))
423 return new Region(getEntry(), R->getExit(), RI, DT);
426 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
427 enum PrintStyle Style) const {
429 OS.indent(level*2) << "[" << level << "] " << getNameStr();
431 OS.indent(level*2) << getNameStr();
436 if (Style != PrintNone) {
437 OS.indent(level*2) << "{\n";
438 OS.indent(level*2 + 2);
440 if (Style == PrintBB) {
441 for (const auto &BB : blocks())
442 OS << BB->getName() << ", "; // TODO: remove the last ","
443 } else if (Style == PrintRN) {
444 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
445 OS << **I << ", "; // TODO: remove the last ",
452 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
453 (*RI)->print(OS, print_tree, level+1, Style);
455 if (Style != PrintNone)
456 OS.indent(level*2) << "} \n";
459 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
460 void Region::dump() const {
461 print(dbgs(), true, getDepth(), printStyle.getValue());
465 void Region::clearNodeCache() {
466 // Free the cached nodes.
467 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
468 IE = BBNodeMap.end(); I != IE; ++I)
472 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
473 (*RI)->clearNodeCache();
476 //===----------------------------------------------------------------------===//
477 // RegionInfo implementation
480 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
481 BasicBlock *exit) const {
482 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
484 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
490 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
491 assert(entry && exit && "entry and exit must not be null!");
492 typedef DominanceFrontier::DomSetType DST;
494 DST *entrySuccs = &DF->find(entry)->second;
496 // Exit is the header of a loop that contains the entry. In this case,
497 // the dominance frontier must only contain the exit.
498 if (!DT->dominates(entry, exit)) {
499 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
501 if (*SI != exit && *SI != entry)
507 DST *exitSuccs = &DF->find(exit)->second;
509 // Do not allow edges leaving the region.
510 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
512 if (*SI == exit || *SI == entry)
514 if (exitSuccs->find(*SI) == exitSuccs->end())
516 if (!isCommonDomFrontier(*SI, entry, exit))
520 // Do not allow edges pointing into the region.
521 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
523 if (DT->properlyDominates(entry, *SI) && *SI != exit)
530 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
531 BBtoBBMap *ShortCut) const {
532 assert(entry && exit && "entry and exit must not be null!");
534 BBtoBBMap::iterator e = ShortCut->find(exit);
536 if (e == ShortCut->end())
537 // No further region at exit available.
538 (*ShortCut)[entry] = exit;
540 // We found a region e that starts at exit. Therefore (entry, e->second)
541 // is also a region, that is larger than (entry, exit). Insert the
543 BasicBlock *BB = e->second;
544 (*ShortCut)[entry] = BB;
548 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
549 BBtoBBMap *ShortCut) const {
550 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
552 if (e == ShortCut->end())
555 return PDT->getNode(e->second)->getIDom();
558 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
559 assert(entry && exit && "entry and exit must not be null!");
561 unsigned num_successors = succ_end(entry) - succ_begin(entry);
563 if (num_successors <= 1 && exit == *(succ_begin(entry)))
569 void RegionInfo::updateStatistics(Region *R) {
572 // TODO: Slow. Should only be enabled if -stats is used.
573 if (R->isSimple()) ++numSimpleRegions;
576 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
577 assert(entry && exit && "entry and exit must not be null!");
579 if (isTrivialRegion(entry, exit))
582 Region *region = new Region(entry, exit, this, DT);
583 BBtoRegion.insert(std::make_pair(entry, region));
586 region->verifyRegion();
588 DEBUG(region->verifyRegion());
591 updateStatistics(region);
595 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
598 DomTreeNode *N = PDT->getNode(entry);
603 Region *lastRegion= 0;
604 BasicBlock *lastExit = entry;
606 // As only a BasicBlock that postdominates entry can finish a region, walk the
607 // post dominance tree upwards.
608 while ((N = getNextPostDom(N, ShortCut))) {
609 BasicBlock *exit = N->getBlock();
614 if (isRegion(entry, exit)) {
615 Region *newRegion = createRegion(entry, exit);
618 newRegion->addSubRegion(lastRegion);
620 lastRegion = newRegion;
624 // This can never be a region, so stop the search.
625 if (!DT->dominates(entry, exit))
629 // Tried to create regions from entry to lastExit. Next time take a
630 // shortcut from entry to lastExit.
631 if (lastExit != entry)
632 insertShortCut(entry, lastExit, ShortCut);
635 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
636 BasicBlock *entry = &(F.getEntryBlock());
637 DomTreeNode *N = DT->getNode(entry);
639 // Iterate over the dominance tree in post order to start with the small
640 // regions from the bottom of the dominance tree. If the small regions are
641 // detected first, detection of bigger regions is faster, as we can jump
642 // over the small regions.
643 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
645 findRegionsWithEntry(FI->getBlock(), ShortCut);
649 Region *RegionInfo::getTopMostParent(Region *region) {
650 while (region->parent)
651 region = region->getParent();
656 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
657 BasicBlock *BB = N->getBlock();
659 // Passed region exit
660 while (BB == region->getExit())
661 region = region->getParent();
663 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
665 // This basic block is a start block of a region. It is already in the
666 // BBtoRegion relation. Only the child basic blocks have to be updated.
667 if (it != BBtoRegion.end()) {
668 Region *newRegion = it->second;
669 region->addSubRegion(getTopMostParent(newRegion));
672 BBtoRegion[BB] = region;
675 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
676 buildRegionsTree(*CI, region);
679 void RegionInfo::releaseMemory() {
682 delete TopLevelRegion;
686 RegionInfo::RegionInfo() : FunctionPass(ID) {
687 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
691 RegionInfo::~RegionInfo() {
695 void RegionInfo::Calculate(Function &F) {
696 // ShortCut a function where for every BB the exit of the largest region
697 // starting with BB is stored. These regions can be threated as single BBS.
698 // This improves performance on linear CFGs.
701 scanForRegions(F, &ShortCut);
702 BasicBlock *BB = &F.getEntryBlock();
703 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
706 bool RegionInfo::runOnFunction(Function &F) {
709 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
710 PDT = &getAnalysis<PostDominatorTree>();
711 DF = &getAnalysis<DominanceFrontier>();
713 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
714 updateStatistics(TopLevelRegion);
721 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
722 AU.setPreservesAll();
723 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
724 AU.addRequired<PostDominatorTree>();
725 AU.addRequired<DominanceFrontier>();
728 void RegionInfo::print(raw_ostream &OS, const Module *) const {
729 OS << "Region tree:\n";
730 TopLevelRegion->print(OS, true, 0, printStyle.getValue());
731 OS << "End region tree\n";
734 void RegionInfo::verifyAnalysis() const {
735 // Only do verification when user wants to, otherwise this expensive check
736 // will be invoked by PMDataManager::verifyPreservedAnalysis when
737 // a regionpass (marked PreservedAll) finish.
738 if (!VerifyRegionInfo) return;
740 TopLevelRegion->verifyRegionNest();
743 // Region pass manager support.
744 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
745 BBtoRegionMap::const_iterator I=
747 return I != BBtoRegion.end() ? I->second : 0;
750 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
754 Region *RegionInfo::operator[](BasicBlock *BB) const {
755 return getRegionFor(BB);
758 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
759 BasicBlock *Exit = NULL;
762 // Get largest region that starts at BB.
763 Region *R = getRegionFor(BB);
764 while (R && R->getParent() && R->getParent()->getEntry() == BB)
767 // Get the single exit of BB.
768 if (R && R->getEntry() == BB)
770 else if (++succ_begin(BB) == succ_end(BB))
771 Exit = *succ_begin(BB);
772 else // No single exit exists.
775 // Get largest region that starts at Exit.
776 Region *ExitR = getRegionFor(Exit);
777 while (ExitR && ExitR->getParent()
778 && ExitR->getParent()->getEntry() == Exit)
779 ExitR = ExitR->getParent();
781 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
783 if (!R->contains(*PI) && !ExitR->contains(*PI))
786 // This stops infinite cycles.
787 if (DT->dominates(Exit, BB))
797 RegionInfo::getCommonRegion(Region *A, Region *B) const {
798 assert (A && B && "One of the Regions is NULL");
800 if (A->contains(B)) return A;
802 while (!B->contains(A))
809 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
810 Region* ret = Regions.back();
813 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
814 E = Regions.end(); I != E; ++I)
815 ret = getCommonRegion(ret, *I);
821 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
822 Region* ret = getRegionFor(BBs.back());
825 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
826 E = BBs.end(); I != E; ++I)
827 ret = getCommonRegion(ret, getRegionFor(*I));
832 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
834 Region *R = getRegionFor(OldBB);
836 setRegionFor(NewBB, R);
838 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
839 R->replaceEntry(NewBB);
843 setRegionFor(OldBB, R);
846 char RegionInfo::ID = 0;
847 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
848 "Detect single entry single exit regions", true, true)
849 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
850 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
851 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
852 INITIALIZE_PASS_END(RegionInfo, "regions",
853 "Detect single entry single exit regions", true, true)
855 // Create methods available outside of this file, to use them
856 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
857 // the link time optimization.
860 FunctionPass *createRegionInfoPass() {
861 return new RegionInfo();