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"
27 // Always verify if expensive checking is enabled.
29 static bool VerifyRegionInfo = true;
31 static bool VerifyRegionInfo = false;
34 static cl::opt<bool,true>
35 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
36 cl::desc("Verify region info (time consuming)"));
38 STATISTIC(numRegions, "The # of regions");
39 STATISTIC(numSimpleRegions, "The # of simple regions");
41 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
43 cl::desc("style of printing regions"),
45 clEnumValN(Region::PrintNone, "none", "print no details"),
46 clEnumValN(Region::PrintBB, "bb",
47 "print regions in detail with block_iterator"),
48 clEnumValN(Region::PrintRN, "rn",
49 "print regions in detail with element_iterator"),
51 //===----------------------------------------------------------------------===//
52 /// Region Implementation
53 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
54 DominatorTree *dt, Region *Parent)
55 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
58 // Free the cached nodes.
59 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
60 ie = BBNodeMap.end(); it != ie; ++it)
63 // Only clean the cache for this Region. Caches of child Regions will be
64 // cleaned when the child Regions are deleted.
68 void Region::replaceEntry(BasicBlock *BB) {
72 void Region::replaceExit(BasicBlock *BB) {
73 assert(exit && "No exit to replace!");
77 void Region::replaceEntryRecursive(BasicBlock *NewEntry) {
78 std::vector<Region *> RegionQueue;
79 BasicBlock *OldEntry = getEntry();
81 RegionQueue.push_back(this);
82 while (!RegionQueue.empty()) {
83 Region *R = RegionQueue.back();
84 RegionQueue.pop_back();
86 R->replaceEntry(NewEntry);
87 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
88 if ((*RI)->getEntry() == OldEntry)
89 RegionQueue.push_back(RI->get());
93 void Region::replaceExitRecursive(BasicBlock *NewExit) {
94 std::vector<Region *> RegionQueue;
95 BasicBlock *OldExit = getExit();
97 RegionQueue.push_back(this);
98 while (!RegionQueue.empty()) {
99 Region *R = RegionQueue.back();
100 RegionQueue.pop_back();
102 R->replaceExit(NewExit);
103 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
104 if ((*RI)->getExit() == OldExit)
105 RegionQueue.push_back(RI->get());
109 bool Region::contains(const BasicBlock *B) const {
110 BasicBlock *BB = const_cast<BasicBlock*>(B);
112 if (!DT->getNode(BB))
115 BasicBlock *entry = getEntry(), *exit = getExit();
121 return (DT->dominates(entry, BB)
122 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
125 bool Region::contains(const Loop *L) const {
126 // BBs that are not part of any loop are element of the Loop
127 // described by the NULL pointer. This loop is not part of any region,
128 // except if the region describes the whole function.
130 return getExit() == nullptr;
132 if (!contains(L->getHeader()))
135 SmallVector<BasicBlock *, 8> ExitingBlocks;
136 L->getExitingBlocks(ExitingBlocks);
138 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
139 BE = ExitingBlocks.end(); BI != BE; ++BI)
146 Loop *Region::outermostLoopInRegion(Loop *L) const {
150 while (L && contains(L->getParentLoop())) {
151 L = L->getParentLoop();
157 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
158 assert(LI && BB && "LI and BB cannot be null!");
159 Loop *L = LI->getLoopFor(BB);
160 return outermostLoopInRegion(L);
163 BasicBlock *Region::getEnteringBlock() const {
164 BasicBlock *entry = getEntry();
166 BasicBlock *enteringBlock = nullptr;
168 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
171 if (DT->getNode(Pred) && !contains(Pred)) {
175 enteringBlock = Pred;
179 return enteringBlock;
182 BasicBlock *Region::getExitingBlock() const {
183 BasicBlock *exit = getExit();
185 BasicBlock *exitingBlock = nullptr;
190 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
193 if (contains(Pred)) {
204 bool Region::isSimple() const {
205 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
208 std::string Region::getNameStr() const {
209 std::string exitName;
210 std::string entryName;
212 if (getEntry()->getName().empty()) {
213 raw_string_ostream OS(entryName);
215 getEntry()->printAsOperand(OS, false);
217 entryName = getEntry()->getName();
220 if (getExit()->getName().empty()) {
221 raw_string_ostream OS(exitName);
223 getExit()->printAsOperand(OS, false);
225 exitName = getExit()->getName();
227 exitName = "<Function Return>";
229 return entryName + " => " + exitName;
232 void Region::verifyBBInRegion(BasicBlock *BB) const {
234 llvm_unreachable("Broken region found!");
236 BasicBlock *entry = getEntry(), *exit = getExit();
238 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
239 if (!contains(*SI) && exit != *SI)
240 llvm_unreachable("Broken region found!");
243 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
245 llvm_unreachable("Broken region found!");
248 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
249 BasicBlock *exit = getExit();
253 verifyBBInRegion(BB);
255 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
256 if (*SI != exit && visited->find(*SI) == visited->end())
257 verifyWalk(*SI, visited);
260 void Region::verifyRegion() const {
261 // Only do verification when user wants to, otherwise this expensive
262 // check will be invoked by PassManager.
263 if (!VerifyRegionInfo) return;
265 std::set<BasicBlock*> visited;
266 verifyWalk(getEntry(), &visited);
269 void Region::verifyRegionNest() const {
270 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
271 (*RI)->verifyRegionNest();
276 Region::element_iterator Region::element_begin() {
277 return GraphTraits<Region*>::nodes_begin(this);
280 Region::element_iterator Region::element_end() {
281 return GraphTraits<Region*>::nodes_end(this);
284 Region::const_element_iterator Region::element_begin() const {
285 return GraphTraits<const Region*>::nodes_begin(this);
288 Region::const_element_iterator Region::element_end() const {
289 return GraphTraits<const Region*>::nodes_end(this);
292 Region* Region::getSubRegionNode(BasicBlock *BB) const {
293 Region *R = RI->getRegionFor(BB);
298 // If we pass the BB out of this region, that means our code is broken.
299 assert(contains(R) && "BB not in current region!");
301 while (contains(R->getParent()) && R->getParent() != this)
304 if (R->getEntry() != BB)
310 RegionNode* Region::getBBNode(BasicBlock *BB) const {
311 assert(contains(BB) && "Can get BB node out of this region!");
313 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
315 if (at != BBNodeMap.end())
318 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
319 BBNodeMap.insert(std::make_pair(BB, NewNode));
323 RegionNode* Region::getNode(BasicBlock *BB) const {
324 assert(contains(BB) && "Can get BB node out of this region!");
325 if (Region* Child = getSubRegionNode(BB))
326 return Child->getNode();
328 return getBBNode(BB);
331 void Region::transferChildrenTo(Region *To) {
332 for (iterator I = begin(), E = end(); I != E; ++I) {
334 To->children.push_back(std::move(*I));
339 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
340 assert(!SubRegion->parent && "SubRegion already has a parent!");
341 assert(std::find_if(begin(), end(), [&](const std::unique_ptr<Region> &R) {
342 return R.get() == SubRegion;
343 }) == children.end() &&
344 "Subregion already exists!");
346 SubRegion->parent = this;
347 children.push_back(std::unique_ptr<Region>(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<std::unique_ptr<Region>> Keep;
364 for (iterator I = begin(), E = end(); I != E; ++I)
365 if (SubRegion->contains(I->get()) && I->get() != SubRegion) {
366 (*I)->parent = SubRegion;
367 SubRegion->children.push_back(std::move(*I));
369 Keep.push_back(std::move(*I));
372 children.insert(children.begin(),
373 std::move_iterator<RegionSet::iterator>(Keep.begin()),
374 std::move_iterator<RegionSet::iterator>(Keep.end()));
378 Region *Region::removeSubRegion(Region *Child) {
379 assert(Child->parent == this && "Child is not a child of this region!");
380 Child->parent = nullptr;
381 RegionSet::iterator I = std::find_if(
382 children.begin(), children.end(),
383 [&](const std::unique_ptr<Region> &R) { return R.get() == Child; });
384 assert(I != children.end() && "Region does not exit. Unable to remove.");
385 children.erase(children.begin()+(I-begin()));
389 unsigned Region::getDepth() const {
392 for (Region *R = parent; R != nullptr; R = R->parent)
398 Region *Region::getExpandedRegion() const {
399 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
401 if (NumSuccessors == 0)
404 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
406 if (!DT->dominates(getEntry(), *PI))
409 Region *R = RI->getRegionFor(exit);
411 if (R->getEntry() != exit) {
412 if (exit->getTerminator()->getNumSuccessors() == 1)
413 return new Region(getEntry(), *succ_begin(exit), RI, DT);
418 while (R->getParent() && R->getParent()->getEntry() == exit)
421 if (!DT->dominates(getEntry(), R->getExit()))
422 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
424 if (!DT->dominates(R->getExit(), *PI))
427 return new Region(getEntry(), R->getExit(), RI, DT);
430 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
431 enum PrintStyle Style) const {
433 OS.indent(level*2) << "[" << level << "] " << getNameStr();
435 OS.indent(level*2) << getNameStr();
440 if (Style != PrintNone) {
441 OS.indent(level*2) << "{\n";
442 OS.indent(level*2 + 2);
444 if (Style == PrintBB) {
445 for (const auto &BB : blocks())
446 OS << BB->getName() << ", "; // TODO: remove the last ","
447 } else if (Style == PrintRN) {
448 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
449 OS << **I << ", "; // TODO: remove the last ",
456 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
457 (*RI)->print(OS, print_tree, level+1, Style);
459 if (Style != PrintNone)
460 OS.indent(level*2) << "} \n";
463 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
464 void Region::dump() const {
465 print(dbgs(), true, getDepth(), printStyle.getValue());
469 void Region::clearNodeCache() {
470 // Free the cached nodes.
471 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
472 IE = BBNodeMap.end(); I != IE; ++I)
476 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
477 (*RI)->clearNodeCache();
480 //===----------------------------------------------------------------------===//
481 // RegionInfo implementation
484 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
485 BasicBlock *exit) const {
486 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
488 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
494 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
495 assert(entry && exit && "entry and exit must not be null!");
496 typedef DominanceFrontier::DomSetType DST;
498 DST *entrySuccs = &DF->find(entry)->second;
500 // Exit is the header of a loop that contains the entry. In this case,
501 // the dominance frontier must only contain the exit.
502 if (!DT->dominates(entry, exit)) {
503 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
505 if (*SI != exit && *SI != entry)
511 DST *exitSuccs = &DF->find(exit)->second;
513 // Do not allow edges leaving the region.
514 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
516 if (*SI == exit || *SI == entry)
518 if (exitSuccs->find(*SI) == exitSuccs->end())
520 if (!isCommonDomFrontier(*SI, entry, exit))
524 // Do not allow edges pointing into the region.
525 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
527 if (DT->properlyDominates(entry, *SI) && *SI != exit)
534 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
535 BBtoBBMap *ShortCut) const {
536 assert(entry && exit && "entry and exit must not be null!");
538 BBtoBBMap::iterator e = ShortCut->find(exit);
540 if (e == ShortCut->end())
541 // No further region at exit available.
542 (*ShortCut)[entry] = exit;
544 // We found a region e that starts at exit. Therefore (entry, e->second)
545 // is also a region, that is larger than (entry, exit). Insert the
547 BasicBlock *BB = e->second;
548 (*ShortCut)[entry] = BB;
552 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
553 BBtoBBMap *ShortCut) const {
554 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
556 if (e == ShortCut->end())
559 return PDT->getNode(e->second)->getIDom();
562 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
563 assert(entry && exit && "entry and exit must not be null!");
565 unsigned num_successors = succ_end(entry) - succ_begin(entry);
567 if (num_successors <= 1 && exit == *(succ_begin(entry)))
573 void RegionInfo::updateStatistics(Region *R) {
576 // TODO: Slow. Should only be enabled if -stats is used.
577 if (R->isSimple()) ++numSimpleRegions;
580 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
581 assert(entry && exit && "entry and exit must not be null!");
583 if (isTrivialRegion(entry, exit))
586 Region *region = new Region(entry, exit, this, DT);
587 BBtoRegion.insert(std::make_pair(entry, region));
590 region->verifyRegion();
592 DEBUG(region->verifyRegion());
595 updateStatistics(region);
599 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
602 DomTreeNode *N = PDT->getNode(entry);
607 Region *lastRegion= nullptr;
608 BasicBlock *lastExit = entry;
610 // As only a BasicBlock that postdominates entry can finish a region, walk the
611 // post dominance tree upwards.
612 while ((N = getNextPostDom(N, ShortCut))) {
613 BasicBlock *exit = N->getBlock();
618 if (isRegion(entry, exit)) {
619 Region *newRegion = createRegion(entry, exit);
622 newRegion->addSubRegion(lastRegion);
624 lastRegion = newRegion;
628 // This can never be a region, so stop the search.
629 if (!DT->dominates(entry, exit))
633 // Tried to create regions from entry to lastExit. Next time take a
634 // shortcut from entry to lastExit.
635 if (lastExit != entry)
636 insertShortCut(entry, lastExit, ShortCut);
639 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
640 BasicBlock *entry = &(F.getEntryBlock());
641 DomTreeNode *N = DT->getNode(entry);
643 // Iterate over the dominance tree in post order to start with the small
644 // regions from the bottom of the dominance tree. If the small regions are
645 // detected first, detection of bigger regions is faster, as we can jump
646 // over the small regions.
647 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
649 findRegionsWithEntry(FI->getBlock(), ShortCut);
653 Region *RegionInfo::getTopMostParent(Region *region) {
654 while (region->parent)
655 region = region->getParent();
660 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
661 BasicBlock *BB = N->getBlock();
663 // Passed region exit
664 while (BB == region->getExit())
665 region = region->getParent();
667 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
669 // This basic block is a start block of a region. It is already in the
670 // BBtoRegion relation. Only the child basic blocks have to be updated.
671 if (it != BBtoRegion.end()) {
672 Region *newRegion = it->second;
673 region->addSubRegion(getTopMostParent(newRegion));
676 BBtoRegion[BB] = region;
679 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
680 buildRegionsTree(*CI, region);
683 void RegionInfo::releaseMemory() {
686 delete TopLevelRegion;
687 TopLevelRegion = nullptr;
690 RegionInfo::RegionInfo() : FunctionPass(ID) {
691 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
692 TopLevelRegion = nullptr;
695 RegionInfo::~RegionInfo() {
699 void RegionInfo::Calculate(Function &F) {
700 // ShortCut a function where for every BB the exit of the largest region
701 // starting with BB is stored. These regions can be threated as single BBS.
702 // This improves performance on linear CFGs.
705 scanForRegions(F, &ShortCut);
706 BasicBlock *BB = &F.getEntryBlock();
707 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
710 bool RegionInfo::runOnFunction(Function &F) {
713 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
714 PDT = &getAnalysis<PostDominatorTree>();
715 DF = &getAnalysis<DominanceFrontier>();
717 TopLevelRegion = new Region(&F.getEntryBlock(), nullptr, this, DT, nullptr);
718 updateStatistics(TopLevelRegion);
725 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
726 AU.setPreservesAll();
727 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
728 AU.addRequired<PostDominatorTree>();
729 AU.addRequired<DominanceFrontier>();
732 void RegionInfo::print(raw_ostream &OS, const Module *) const {
733 OS << "Region tree:\n";
734 TopLevelRegion->print(OS, true, 0, printStyle.getValue());
735 OS << "End region tree\n";
738 void RegionInfo::verifyAnalysis() const {
739 // Only do verification when user wants to, otherwise this expensive check
740 // will be invoked by PMDataManager::verifyPreservedAnalysis when
741 // a regionpass (marked PreservedAll) finish.
742 if (!VerifyRegionInfo) return;
744 TopLevelRegion->verifyRegionNest();
747 // Region pass manager support.
748 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
749 BBtoRegionMap::const_iterator I=
751 return I != BBtoRegion.end() ? I->second : nullptr;
754 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
758 Region *RegionInfo::operator[](BasicBlock *BB) const {
759 return getRegionFor(BB);
762 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
763 BasicBlock *Exit = nullptr;
766 // Get largest region that starts at BB.
767 Region *R = getRegionFor(BB);
768 while (R && R->getParent() && R->getParent()->getEntry() == BB)
771 // Get the single exit of BB.
772 if (R && R->getEntry() == BB)
774 else if (++succ_begin(BB) == succ_end(BB))
775 Exit = *succ_begin(BB);
776 else // No single exit exists.
779 // Get largest region that starts at Exit.
780 Region *ExitR = getRegionFor(Exit);
781 while (ExitR && ExitR->getParent()
782 && ExitR->getParent()->getEntry() == Exit)
783 ExitR = ExitR->getParent();
785 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
787 if (!R->contains(*PI) && !ExitR->contains(*PI))
790 // This stops infinite cycles.
791 if (DT->dominates(Exit, BB))
801 RegionInfo::getCommonRegion(Region *A, Region *B) const {
802 assert (A && B && "One of the Regions is NULL");
804 if (A->contains(B)) return A;
806 while (!B->contains(A))
813 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
814 Region* ret = Regions.back();
817 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
818 E = Regions.end(); I != E; ++I)
819 ret = getCommonRegion(ret, *I);
825 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
826 Region* ret = getRegionFor(BBs.back());
829 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
830 E = BBs.end(); I != E; ++I)
831 ret = getCommonRegion(ret, getRegionFor(*I));
836 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
838 Region *R = getRegionFor(OldBB);
840 setRegionFor(NewBB, R);
842 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
843 R->replaceEntry(NewBB);
847 setRegionFor(OldBB, R);
850 char RegionInfo::ID = 0;
851 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
852 "Detect single entry single exit regions", true, true)
853 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
854 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
855 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
856 INITIALIZE_PASS_END(RegionInfo, "regions",
857 "Detect single entry single exit regions", true, true)
859 // Create methods available outside of this file, to use them
860 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
861 // the link time optimization.
864 FunctionPass *createRegionInfoPass() {
865 return new RegionInfo();