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 #include "llvm/Analysis/RegionInfo.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/RegionIterator.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/ErrorHandling.h"
26 #define DEBUG_TYPE "region"
28 // Always verify if expensive checking is enabled.
30 static bool VerifyRegionInfo = true;
32 static bool VerifyRegionInfo = false;
35 static cl::opt<bool,true>
36 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
37 cl::desc("Verify region info (time consuming)"));
39 STATISTIC(numRegions, "The # of regions");
40 STATISTIC(numSimpleRegions, "The # of simple regions");
42 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
44 cl::desc("style of printing regions"),
46 clEnumValN(Region::PrintNone, "none", "print no details"),
47 clEnumValN(Region::PrintBB, "bb",
48 "print regions in detail with block_iterator"),
49 clEnumValN(Region::PrintRN, "rn",
50 "print regions in detail with element_iterator"),
52 //===----------------------------------------------------------------------===//
53 /// Region Implementation
54 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
55 DominatorTree *dt, Region *Parent)
56 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
59 // Free the cached nodes.
60 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
61 ie = BBNodeMap.end(); it != ie; ++it)
64 // Only clean the cache for this Region. Caches of child Regions will be
65 // cleaned when the child Regions are deleted.
69 void Region::replaceEntry(BasicBlock *BB) {
73 void Region::replaceExit(BasicBlock *BB) {
74 assert(exit && "No exit to replace!");
78 void Region::replaceEntryRecursive(BasicBlock *NewEntry) {
79 std::vector<Region *> RegionQueue;
80 BasicBlock *OldEntry = getEntry();
82 RegionQueue.push_back(this);
83 while (!RegionQueue.empty()) {
84 Region *R = RegionQueue.back();
85 RegionQueue.pop_back();
87 R->replaceEntry(NewEntry);
88 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
89 if ((*RI)->getEntry() == OldEntry)
90 RegionQueue.push_back(RI->get());
94 void Region::replaceExitRecursive(BasicBlock *NewExit) {
95 std::vector<Region *> RegionQueue;
96 BasicBlock *OldExit = getExit();
98 RegionQueue.push_back(this);
99 while (!RegionQueue.empty()) {
100 Region *R = RegionQueue.back();
101 RegionQueue.pop_back();
103 R->replaceExit(NewExit);
104 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
105 if ((*RI)->getExit() == OldExit)
106 RegionQueue.push_back(RI->get());
110 bool Region::contains(const BasicBlock *B) const {
111 BasicBlock *BB = const_cast<BasicBlock*>(B);
113 if (!DT->getNode(BB))
116 BasicBlock *entry = getEntry(), *exit = getExit();
122 return (DT->dominates(entry, BB)
123 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
126 bool Region::contains(const Loop *L) const {
127 // BBs that are not part of any loop are element of the Loop
128 // described by the NULL pointer. This loop is not part of any region,
129 // except if the region describes the whole function.
131 return getExit() == nullptr;
133 if (!contains(L->getHeader()))
136 SmallVector<BasicBlock *, 8> ExitingBlocks;
137 L->getExitingBlocks(ExitingBlocks);
139 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
140 BE = ExitingBlocks.end(); BI != BE; ++BI)
147 Loop *Region::outermostLoopInRegion(Loop *L) const {
151 while (L && contains(L->getParentLoop())) {
152 L = L->getParentLoop();
158 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
159 assert(LI && BB && "LI and BB cannot be null!");
160 Loop *L = LI->getLoopFor(BB);
161 return outermostLoopInRegion(L);
164 BasicBlock *Region::getEnteringBlock() const {
165 BasicBlock *entry = getEntry();
167 BasicBlock *enteringBlock = nullptr;
169 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
172 if (DT->getNode(Pred) && !contains(Pred)) {
176 enteringBlock = Pred;
180 return enteringBlock;
183 BasicBlock *Region::getExitingBlock() const {
184 BasicBlock *exit = getExit();
186 BasicBlock *exitingBlock = nullptr;
191 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
194 if (contains(Pred)) {
205 bool Region::isSimple() const {
206 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
209 std::string Region::getNameStr() const {
210 std::string exitName;
211 std::string entryName;
213 if (getEntry()->getName().empty()) {
214 raw_string_ostream OS(entryName);
216 getEntry()->printAsOperand(OS, false);
218 entryName = getEntry()->getName();
221 if (getExit()->getName().empty()) {
222 raw_string_ostream OS(exitName);
224 getExit()->printAsOperand(OS, false);
226 exitName = getExit()->getName();
228 exitName = "<Function Return>";
230 return entryName + " => " + exitName;
233 void Region::verifyBBInRegion(BasicBlock *BB) const {
235 llvm_unreachable("Broken region found!");
237 BasicBlock *entry = getEntry(), *exit = getExit();
239 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
240 if (!contains(*SI) && exit != *SI)
241 llvm_unreachable("Broken region found!");
244 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
246 llvm_unreachable("Broken region found!");
249 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
250 BasicBlock *exit = getExit();
254 verifyBBInRegion(BB);
256 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
257 if (*SI != exit && visited->find(*SI) == visited->end())
258 verifyWalk(*SI, visited);
261 void Region::verifyRegion() const {
262 // Only do verification when user wants to, otherwise this expensive
263 // check will be invoked by PassManager.
264 if (!VerifyRegionInfo) return;
266 std::set<BasicBlock*> visited;
267 verifyWalk(getEntry(), &visited);
270 void Region::verifyRegionNest() const {
271 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
272 (*RI)->verifyRegionNest();
277 Region::element_iterator Region::element_begin() {
278 return GraphTraits<Region*>::nodes_begin(this);
281 Region::element_iterator Region::element_end() {
282 return GraphTraits<Region*>::nodes_end(this);
285 Region::const_element_iterator Region::element_begin() const {
286 return GraphTraits<const Region*>::nodes_begin(this);
289 Region::const_element_iterator Region::element_end() const {
290 return GraphTraits<const Region*>::nodes_end(this);
293 Region* Region::getSubRegionNode(BasicBlock *BB) const {
294 Region *R = RI->getRegionFor(BB);
299 // If we pass the BB out of this region, that means our code is broken.
300 assert(contains(R) && "BB not in current region!");
302 while (contains(R->getParent()) && R->getParent() != this)
305 if (R->getEntry() != BB)
311 RegionNode* Region::getBBNode(BasicBlock *BB) const {
312 assert(contains(BB) && "Can get BB node out of this region!");
314 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
316 if (at != BBNodeMap.end())
319 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
320 BBNodeMap.insert(std::make_pair(BB, NewNode));
324 RegionNode* Region::getNode(BasicBlock *BB) const {
325 assert(contains(BB) && "Can get BB node out of this region!");
326 if (Region* Child = getSubRegionNode(BB))
327 return Child->getNode();
329 return getBBNode(BB);
332 void Region::transferChildrenTo(Region *To) {
333 for (iterator I = begin(), E = end(); I != E; ++I) {
335 To->children.push_back(std::move(*I));
340 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
341 assert(!SubRegion->parent && "SubRegion already has a parent!");
342 assert(std::find_if(begin(), end(), [&](const std::unique_ptr<Region> &R) {
343 return R.get() == SubRegion;
344 }) == children.end() &&
345 "Subregion already exists!");
347 SubRegion->parent = this;
348 children.push_back(std::unique_ptr<Region>(SubRegion));
353 assert(SubRegion->children.size() == 0
354 && "SubRegions that contain children are not supported");
356 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
357 if (!(*I)->isSubRegion()) {
358 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
360 if (SubRegion->contains(BB))
361 RI->setRegionFor(BB, SubRegion);
364 std::vector<std::unique_ptr<Region>> Keep;
365 for (iterator I = begin(), E = end(); I != E; ++I)
366 if (SubRegion->contains(I->get()) && I->get() != SubRegion) {
367 (*I)->parent = SubRegion;
368 SubRegion->children.push_back(std::move(*I));
370 Keep.push_back(std::move(*I));
373 children.insert(children.begin(),
374 std::move_iterator<RegionSet::iterator>(Keep.begin()),
375 std::move_iterator<RegionSet::iterator>(Keep.end()));
379 Region *Region::removeSubRegion(Region *Child) {
380 assert(Child->parent == this && "Child is not a child of this region!");
381 Child->parent = nullptr;
382 RegionSet::iterator I = std::find_if(
383 children.begin(), children.end(),
384 [&](const std::unique_ptr<Region> &R) { return R.get() == Child; });
385 assert(I != children.end() && "Region does not exit. Unable to remove.");
386 children.erase(children.begin()+(I-begin()));
390 unsigned Region::getDepth() const {
393 for (Region *R = parent; R != nullptr; R = R->parent)
399 Region *Region::getExpandedRegion() const {
400 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
402 if (NumSuccessors == 0)
405 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
407 if (!DT->dominates(getEntry(), *PI))
410 Region *R = RI->getRegionFor(exit);
412 if (R->getEntry() != exit) {
413 if (exit->getTerminator()->getNumSuccessors() == 1)
414 return new Region(getEntry(), *succ_begin(exit), RI, DT);
419 while (R->getParent() && R->getParent()->getEntry() == exit)
422 if (!DT->dominates(getEntry(), R->getExit()))
423 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
425 if (!DT->dominates(R->getExit(), *PI))
428 return new Region(getEntry(), R->getExit(), RI, DT);
431 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
432 enum PrintStyle Style) const {
434 OS.indent(level*2) << "[" << level << "] " << getNameStr();
436 OS.indent(level*2) << getNameStr();
441 if (Style != PrintNone) {
442 OS.indent(level*2) << "{\n";
443 OS.indent(level*2 + 2);
445 if (Style == PrintBB) {
446 for (const auto &BB : blocks())
447 OS << BB->getName() << ", "; // TODO: remove the last ","
448 } else if (Style == PrintRN) {
449 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
450 OS << **I << ", "; // TODO: remove the last ",
457 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
458 (*RI)->print(OS, print_tree, level+1, Style);
460 if (Style != PrintNone)
461 OS.indent(level*2) << "} \n";
464 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
465 void Region::dump() const {
466 print(dbgs(), true, getDepth(), printStyle.getValue());
470 void Region::clearNodeCache() {
471 // Free the cached nodes.
472 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
473 IE = BBNodeMap.end(); I != IE; ++I)
477 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
478 (*RI)->clearNodeCache();
481 //===----------------------------------------------------------------------===//
482 // RegionInfo implementation
485 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
486 BasicBlock *exit) const {
487 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
489 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
495 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
496 assert(entry && exit && "entry and exit must not be null!");
497 typedef DominanceFrontier::DomSetType DST;
499 DST *entrySuccs = &DF->find(entry)->second;
501 // Exit is the header of a loop that contains the entry. In this case,
502 // the dominance frontier must only contain the exit.
503 if (!DT->dominates(entry, exit)) {
504 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
506 if (*SI != exit && *SI != entry)
512 DST *exitSuccs = &DF->find(exit)->second;
514 // Do not allow edges leaving the region.
515 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
517 if (*SI == exit || *SI == entry)
519 if (exitSuccs->find(*SI) == exitSuccs->end())
521 if (!isCommonDomFrontier(*SI, entry, exit))
525 // Do not allow edges pointing into the region.
526 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
528 if (DT->properlyDominates(entry, *SI) && *SI != exit)
535 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
536 BBtoBBMap *ShortCut) const {
537 assert(entry && exit && "entry and exit must not be null!");
539 BBtoBBMap::iterator e = ShortCut->find(exit);
541 if (e == ShortCut->end())
542 // No further region at exit available.
543 (*ShortCut)[entry] = exit;
545 // We found a region e that starts at exit. Therefore (entry, e->second)
546 // is also a region, that is larger than (entry, exit). Insert the
548 BasicBlock *BB = e->second;
549 (*ShortCut)[entry] = BB;
553 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
554 BBtoBBMap *ShortCut) const {
555 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
557 if (e == ShortCut->end())
560 return PDT->getNode(e->second)->getIDom();
563 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
564 assert(entry && exit && "entry and exit must not be null!");
566 unsigned num_successors = succ_end(entry) - succ_begin(entry);
568 if (num_successors <= 1 && exit == *(succ_begin(entry)))
574 void RegionInfo::updateStatistics(Region *R) {
577 // TODO: Slow. Should only be enabled if -stats is used.
578 if (R->isSimple()) ++numSimpleRegions;
581 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
582 assert(entry && exit && "entry and exit must not be null!");
584 if (isTrivialRegion(entry, exit))
587 Region *region = new Region(entry, exit, this, DT);
588 BBtoRegion.insert(std::make_pair(entry, region));
591 region->verifyRegion();
593 DEBUG(region->verifyRegion());
596 updateStatistics(region);
600 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
603 DomTreeNode *N = PDT->getNode(entry);
608 Region *lastRegion= nullptr;
609 BasicBlock *lastExit = entry;
611 // As only a BasicBlock that postdominates entry can finish a region, walk the
612 // post dominance tree upwards.
613 while ((N = getNextPostDom(N, ShortCut))) {
614 BasicBlock *exit = N->getBlock();
619 if (isRegion(entry, exit)) {
620 Region *newRegion = createRegion(entry, exit);
623 newRegion->addSubRegion(lastRegion);
625 lastRegion = newRegion;
629 // This can never be a region, so stop the search.
630 if (!DT->dominates(entry, exit))
634 // Tried to create regions from entry to lastExit. Next time take a
635 // shortcut from entry to lastExit.
636 if (lastExit != entry)
637 insertShortCut(entry, lastExit, ShortCut);
640 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
641 BasicBlock *entry = &(F.getEntryBlock());
642 DomTreeNode *N = DT->getNode(entry);
644 // Iterate over the dominance tree in post order to start with the small
645 // regions from the bottom of the dominance tree. If the small regions are
646 // detected first, detection of bigger regions is faster, as we can jump
647 // over the small regions.
648 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
650 findRegionsWithEntry(FI->getBlock(), ShortCut);
654 Region *RegionInfo::getTopMostParent(Region *region) {
655 while (region->parent)
656 region = region->getParent();
661 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
662 BasicBlock *BB = N->getBlock();
664 // Passed region exit
665 while (BB == region->getExit())
666 region = region->getParent();
668 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
670 // This basic block is a start block of a region. It is already in the
671 // BBtoRegion relation. Only the child basic blocks have to be updated.
672 if (it != BBtoRegion.end()) {
673 Region *newRegion = it->second;
674 region->addSubRegion(getTopMostParent(newRegion));
677 BBtoRegion[BB] = region;
680 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
681 buildRegionsTree(*CI, region);
684 void RegionInfo::releaseMemory() {
687 delete TopLevelRegion;
688 TopLevelRegion = nullptr;
691 RegionInfo::RegionInfo() : FunctionPass(ID) {
692 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
693 TopLevelRegion = nullptr;
696 RegionInfo::~RegionInfo() {
700 void RegionInfo::Calculate(Function &F) {
701 // ShortCut a function where for every BB the exit of the largest region
702 // starting with BB is stored. These regions can be threated as single BBS.
703 // This improves performance on linear CFGs.
706 scanForRegions(F, &ShortCut);
707 BasicBlock *BB = &F.getEntryBlock();
708 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
711 bool RegionInfo::runOnFunction(Function &F) {
714 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
715 PDT = &getAnalysis<PostDominatorTree>();
716 DF = &getAnalysis<DominanceFrontier>();
718 TopLevelRegion = new Region(&F.getEntryBlock(), nullptr, this, DT, nullptr);
719 updateStatistics(TopLevelRegion);
726 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
727 AU.setPreservesAll();
728 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
729 AU.addRequired<PostDominatorTree>();
730 AU.addRequired<DominanceFrontier>();
733 void RegionInfo::print(raw_ostream &OS, const Module *) const {
734 OS << "Region tree:\n";
735 TopLevelRegion->print(OS, true, 0, printStyle.getValue());
736 OS << "End region tree\n";
739 void RegionInfo::verifyAnalysis() const {
740 // Only do verification when user wants to, otherwise this expensive check
741 // will be invoked by PMDataManager::verifyPreservedAnalysis when
742 // a regionpass (marked PreservedAll) finish.
743 if (!VerifyRegionInfo) return;
745 TopLevelRegion->verifyRegionNest();
748 // Region pass manager support.
749 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
750 BBtoRegionMap::const_iterator I=
752 return I != BBtoRegion.end() ? I->second : nullptr;
755 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
759 Region *RegionInfo::operator[](BasicBlock *BB) const {
760 return getRegionFor(BB);
763 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
764 BasicBlock *Exit = nullptr;
767 // Get largest region that starts at BB.
768 Region *R = getRegionFor(BB);
769 while (R && R->getParent() && R->getParent()->getEntry() == BB)
772 // Get the single exit of BB.
773 if (R && R->getEntry() == BB)
775 else if (++succ_begin(BB) == succ_end(BB))
776 Exit = *succ_begin(BB);
777 else // No single exit exists.
780 // Get largest region that starts at Exit.
781 Region *ExitR = getRegionFor(Exit);
782 while (ExitR && ExitR->getParent()
783 && ExitR->getParent()->getEntry() == Exit)
784 ExitR = ExitR->getParent();
786 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
788 if (!R->contains(*PI) && !ExitR->contains(*PI))
791 // This stops infinite cycles.
792 if (DT->dominates(Exit, BB))
802 RegionInfo::getCommonRegion(Region *A, Region *B) const {
803 assert (A && B && "One of the Regions is NULL");
805 if (A->contains(B)) return A;
807 while (!B->contains(A))
814 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
815 Region* ret = Regions.back();
818 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
819 E = Regions.end(); I != E; ++I)
820 ret = getCommonRegion(ret, *I);
826 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
827 Region* ret = getRegionFor(BBs.back());
830 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
831 E = BBs.end(); I != E; ++I)
832 ret = getCommonRegion(ret, getRegionFor(*I));
837 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
839 Region *R = getRegionFor(OldBB);
841 setRegionFor(NewBB, R);
843 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
844 R->replaceEntry(NewBB);
848 setRegionFor(OldBB, R);
851 char RegionInfo::ID = 0;
852 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
853 "Detect single entry single exit regions", true, true)
854 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
855 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
856 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
857 INITIALIZE_PASS_END(RegionInfo, "regions",
858 "Detect single entry single exit regions", true, true)
860 // Create methods available outside of this file, to use them
861 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
862 // the link time optimization.
865 FunctionPass *createRegionInfoPass() {
866 return new RegionInfo();