blob: 75ca61f67c7346736acc96b1d272f59d231fb807 [file] [log] [blame]
Tobias Grosserf96b0062010-07-22 07:46:31 +00001//===- RegionInfo.cpp - SESE region detection analysis --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// Detects single entry single exit regions in the control flow graph.
10//===----------------------------------------------------------------------===//
11
12#include "llvm/Analysis/RegionInfo.h"
13#include "llvm/Analysis/RegionIterator.h"
14
15#include "llvm/ADT/PostOrderIterator.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/raw_ostream.h"
Tobias Grosser082d5872010-07-27 04:17:13 +000020#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserf96b0062010-07-22 07:46:31 +000021
22#define DEBUG_TYPE "region"
23#include "llvm/Support/Debug.h"
24
25#include <set>
26#include <algorithm>
27
28using namespace llvm;
29
30// Always verify if expensive checking is enabled.
31#ifdef XDEBUG
Dan Gohman811edc12010-08-02 18:50:06 +000032static bool VerifyRegionInfo = true;
Tobias Grosserf96b0062010-07-22 07:46:31 +000033#else
Dan Gohman811edc12010-08-02 18:50:06 +000034static bool VerifyRegionInfo = false;
Tobias Grosserf96b0062010-07-22 07:46:31 +000035#endif
36
37static cl::opt<bool,true>
38VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
39 cl::desc("Verify region info (time consuming)"));
40
41STATISTIC(numRegions, "The # of regions");
42STATISTIC(numSimpleRegions, "The # of simple regions");
43
44//===----------------------------------------------------------------------===//
45/// PrintStyle - Print region in difference ways.
46enum PrintStyle { PrintNone, PrintBB, PrintRN };
47
48cl::opt<enum PrintStyle> printStyle("print-region-style", cl::Hidden,
49 cl::desc("style of printing regions"),
50 cl::values(
51 clEnumValN(PrintNone, "none", "print no details"),
52 clEnumValN(PrintBB, "bb", "print regions in detail with block_iterator"),
53 clEnumValN(PrintRN, "rn", "print regions in detail with element_iterator"),
54 clEnumValEnd));
55//===----------------------------------------------------------------------===//
56/// Region Implementation
57Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
58 DominatorTree *dt, Region *Parent)
59 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
60
61Region::~Region() {
Daniel Dunbar329878f2010-07-28 20:28:50 +000062 // Free the cached nodes.
63 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
64 ie = BBNodeMap.end(); it != ie; ++it)
65 delete it->second;
66
Tobias Grosserf96b0062010-07-22 07:46:31 +000067 // Only clean the cache for this Region. Caches of child Regions will be
68 // cleaned when the child Regions are deleted.
69 BBNodeMap.clear();
70
71 for (iterator I = begin(), E = end(); I != E; ++I)
72 delete *I;
73}
74
75bool Region::contains(const BasicBlock *B) const {
76 BasicBlock *BB = const_cast<BasicBlock*>(B);
77
78 assert(DT->getNode(BB) && "BB not part of the dominance tree");
79
80 BasicBlock *entry = getEntry(), *exit = getExit();
81
82 // Toplevel region.
83 if (!exit)
84 return true;
85
86 return (DT->dominates(entry, BB)
87 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
88}
89
Tobias Grosser082d5872010-07-27 04:17:13 +000090bool Region::contains(const Loop *L) const {
91 // BBs that are not part of any loop are element of the Loop
92 // described by the NULL pointer. This loop is not part of any region,
93 // except if the region describes the whole function.
94 if (L == 0)
95 return getExit() == 0;
96
97 if (!contains(L->getHeader()))
98 return false;
99
100 SmallVector<BasicBlock *, 8> ExitingBlocks;
101 L->getExitingBlocks(ExitingBlocks);
102
103 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
104 BE = ExitingBlocks.end(); BI != BE; ++BI)
105 if (!contains(*BI))
106 return false;
107
108 return true;
109}
110
111Loop *Region::outermostLoopInRegion(Loop *L) const {
112 if (!contains(L))
113 return 0;
114
115 while (L && contains(L->getParentLoop())) {
116 L = L->getParentLoop();
117 }
118
119 return L;
120}
121
122Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
123 assert(LI && BB && "LI and BB cannot be null!");
124 Loop *L = LI->getLoopFor(BB);
125 return outermostLoopInRegion(L);
126}
127
Tobias Grosserf96b0062010-07-22 07:46:31 +0000128bool Region::isSimple() const {
129 bool isSimple = true;
130 bool found = false;
131
132 BasicBlock *entry = getEntry(), *exit = getExit();
133
134 // TopLevelRegion
135 if (!exit)
136 return false;
137
138 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
Tobias Grosser73362c82010-08-10 09:54:35 +0000139 ++PI) {
140 BasicBlock *Pred = *PI;
141 if (DT->getNode(Pred) && !contains(Pred)) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000142 if (found) {
143 isSimple = false;
144 break;
145 }
146 found = true;
147 }
Tobias Grosser73362c82010-08-10 09:54:35 +0000148 }
Tobias Grosserf96b0062010-07-22 07:46:31 +0000149
150 found = false;
151
152 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
153 ++PI)
154 if (contains(*PI)) {
155 if (found) {
156 isSimple = false;
157 break;
158 }
159 found = true;
160 }
161
162 return isSimple;
163}
164
Tobias Grosser082d5872010-07-27 04:17:13 +0000165std::string Region::getNameStr() const {
166 std::string exitName;
167 std::string entryName;
168
169 if (getEntry()->getName().empty()) {
170 raw_string_ostream OS(entryName);
171
172 WriteAsOperand(OS, getEntry(), false);
173 entryName = OS.str();
174 } else
175 entryName = getEntry()->getNameStr();
176
177 if (getExit()) {
178 if (getExit()->getName().empty()) {
179 raw_string_ostream OS(exitName);
180
181 WriteAsOperand(OS, getExit(), false);
182 exitName = OS.str();
183 } else
184 exitName = getExit()->getNameStr();
185 } else
186 exitName = "<Function Return>";
187
188 return entryName + " => " + exitName;
189}
190
Tobias Grosserf96b0062010-07-22 07:46:31 +0000191void Region::verifyBBInRegion(BasicBlock *BB) const {
192 if (!contains(BB))
193 llvm_unreachable("Broken region found!");
194
195 BasicBlock *entry = getEntry(), *exit = getExit();
196
197 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
198 if (!contains(*SI) && exit != *SI)
199 llvm_unreachable("Broken region found!");
200
201 if (entry != BB)
202 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
203 if (!contains(*SI))
204 llvm_unreachable("Broken region found!");
205}
206
207void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
208 BasicBlock *exit = getExit();
209
210 visited->insert(BB);
211
212 verifyBBInRegion(BB);
213
214 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
215 if (*SI != exit && visited->find(*SI) == visited->end())
216 verifyWalk(*SI, visited);
217}
218
219void Region::verifyRegion() const {
220 // Only do verification when user wants to, otherwise this expensive
221 // check will be invoked by PassManager.
222 if (!VerifyRegionInfo) return;
223
224 std::set<BasicBlock*> visited;
225 verifyWalk(getEntry(), &visited);
226}
227
228void Region::verifyRegionNest() const {
229 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
230 (*RI)->verifyRegionNest();
231
232 verifyRegion();
233}
234
235Region::block_iterator Region::block_begin() {
236 return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
237}
238
239Region::block_iterator Region::block_end() {
240 return GraphTraits<FlatIt<Region*> >::nodes_end(this);
241}
242
243Region::const_block_iterator Region::block_begin() const {
244 return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
245}
246
247Region::const_block_iterator Region::block_end() const {
248 return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
249}
250
251Region::element_iterator Region::element_begin() {
252 return GraphTraits<Region*>::nodes_begin(this);
253}
254
255Region::element_iterator Region::element_end() {
256 return GraphTraits<Region*>::nodes_end(this);
257}
258
259Region::const_element_iterator Region::element_begin() const {
260 return GraphTraits<const Region*>::nodes_begin(this);
261}
262
263Region::const_element_iterator Region::element_end() const {
264 return GraphTraits<const Region*>::nodes_end(this);
265}
266
267Region* Region::getSubRegionNode(BasicBlock *BB) const {
268 Region *R = RI->getRegionFor(BB);
269
270 if (!R || R == this)
271 return 0;
272
273 // If we pass the BB out of this region, that means our code is broken.
274 assert(contains(R) && "BB not in current region!");
275
276 while (contains(R->getParent()) && R->getParent() != this)
277 R = R->getParent();
278
279 if (R->getEntry() != BB)
280 return 0;
281
282 return R;
283}
284
285RegionNode* Region::getBBNode(BasicBlock *BB) const {
286 assert(contains(BB) && "Can get BB node out of this region!");
287
288 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
289
290 if (at != BBNodeMap.end())
291 return at->second;
292
293 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
294 BBNodeMap.insert(std::make_pair(BB, NewNode));
295 return NewNode;
296}
297
298RegionNode* Region::getNode(BasicBlock *BB) const {
299 assert(contains(BB) && "Can get BB node out of this region!");
300 if (Region* Child = getSubRegionNode(BB))
301 return Child->getNode();
302
303 return getBBNode(BB);
304}
305
306void Region::transferChildrenTo(Region *To) {
307 for (iterator I = begin(), E = end(); I != E; ++I) {
308 (*I)->parent = To;
309 To->children.push_back(*I);
310 }
311 children.clear();
312}
313
Tobias Grosser96493902010-10-13 05:54:09 +0000314void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000315 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
Tobias Grosser96493902010-10-13 05:54:09 +0000316 assert(std::find(begin(), end(), SubRegion) == children.end()
317 && "Subregion already exists!");
318
Tobias Grosserf96b0062010-07-22 07:46:31 +0000319 SubRegion->parent = this;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000320 children.push_back(SubRegion);
Tobias Grosser96493902010-10-13 05:54:09 +0000321
322 if (!moveChildren)
323 return;
324
325 assert(SubRegion->children.size() == 0
326 && "SubRegions that contain children are not supported");
327
328 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
329 if (!(*I)->isSubRegion()) {
330 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
331
332 if (SubRegion->contains(BB))
333 RI->setRegionFor(BB, SubRegion);
334 }
335
336 std::vector<Region*> Keep;
337 for (iterator I = begin(), E = end(); I != E; ++I)
338 if (SubRegion->contains(*I) && *I != SubRegion) {
339 SubRegion->children.push_back(*I);
340 (*I)->parent = SubRegion;
341 } else
342 Keep.push_back(*I);
343
344 children.clear();
345 children.insert(children.begin(), Keep.begin(), Keep.end());
Tobias Grosserf96b0062010-07-22 07:46:31 +0000346}
347
348
349Region *Region::removeSubRegion(Region *Child) {
350 assert(Child->parent == this && "Child is not a child of this region!");
351 Child->parent = 0;
352 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
353 assert(I != children.end() && "Region does not exit. Unable to remove.");
354 children.erase(children.begin()+(I-begin()));
355 return Child;
356}
357
358unsigned Region::getDepth() const {
359 unsigned Depth = 0;
360
361 for (Region *R = parent; R != 0; R = R->parent)
362 ++Depth;
363
364 return Depth;
365}
366
367void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
368 if (print_tree)
369 OS.indent(level*2) << "[" << level << "] " << getNameStr();
370 else
371 OS.indent(level*2) << getNameStr();
372
373 OS << "\n";
374
375
376 if (printStyle != PrintNone) {
377 OS.indent(level*2) << "{\n";
378 OS.indent(level*2 + 2);
379
380 if (printStyle == PrintBB) {
381 for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
382 OS << **I << ", "; // TODO: remove the last ","
383 } else if (printStyle == PrintRN) {
384 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
385 OS << **I << ", "; // TODO: remove the last ",
386 }
387
388 OS << "\n";
389 }
390
391 if (print_tree)
392 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
393 (*RI)->print(OS, print_tree, level+1);
394
395 if (printStyle != PrintNone)
396 OS.indent(level*2) << "} \n";
397}
398
399void Region::dump() const {
400 print(dbgs(), true, getDepth());
401}
402
403void Region::clearNodeCache() {
Tobias Grosser67be08a2010-10-13 00:07:59 +0000404 // Free the cached nodes.
405 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
406 IE = BBNodeMap.end(); I != IE; ++IE)
407 delete I->second;
408
Tobias Grosserf96b0062010-07-22 07:46:31 +0000409 BBNodeMap.clear();
410 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
411 (*RI)->clearNodeCache();
412}
413
414//===----------------------------------------------------------------------===//
415// RegionInfo implementation
416//
417
418bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
419 BasicBlock *exit) const {
Gabor Greif3d8586e2010-07-22 11:07:46 +0000420 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
421 BasicBlock *P = *PI;
422 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
Tobias Grosserf96b0062010-07-22 07:46:31 +0000423 return false;
Gabor Greif3d8586e2010-07-22 11:07:46 +0000424 }
Tobias Grosserf96b0062010-07-22 07:46:31 +0000425 return true;
426}
427
428bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
429 assert(entry && exit && "entry and exit must not be null!");
430 typedef DominanceFrontier::DomSetType DST;
431
Gabor Greif11aa60d2010-07-22 11:12:32 +0000432 DST *entrySuccs = &DF->find(entry)->second;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000433
434 // Exit is the header of a loop that contains the entry. In this case,
435 // the dominance frontier must only contain the exit.
436 if (!DT->dominates(entry, exit)) {
437 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
438 SI != SE; ++SI)
439 if (*SI != exit && *SI != entry)
440 return false;
441
442 return true;
443 }
444
Gabor Greif11aa60d2010-07-22 11:12:32 +0000445 DST *exitSuccs = &DF->find(exit)->second;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000446
447 // Do not allow edges leaving the region.
448 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
449 SI != SE; ++SI) {
450 if (*SI == exit || *SI == entry)
451 continue;
452 if (exitSuccs->find(*SI) == exitSuccs->end())
453 return false;
454 if (!isCommonDomFrontier(*SI, entry, exit))
455 return false;
456 }
457
458 // Do not allow edges pointing into the region.
459 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
460 SI != SE; ++SI)
Dan Gohmana29dbd22010-07-26 17:34:05 +0000461 if (DT->properlyDominates(entry, *SI) && *SI != exit)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000462 return false;
463
464
465 return true;
466}
467
468void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
469 BBtoBBMap *ShortCut) const {
470 assert(entry && exit && "entry and exit must not be null!");
471
472 BBtoBBMap::iterator e = ShortCut->find(exit);
473
474 if (e == ShortCut->end())
475 // No further region at exit available.
476 (*ShortCut)[entry] = exit;
477 else {
478 // We found a region e that starts at exit. Therefore (entry, e->second)
479 // is also a region, that is larger than (entry, exit). Insert the
480 // larger one.
481 BasicBlock *BB = e->second;
482 (*ShortCut)[entry] = BB;
483 }
484}
485
486DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
487 BBtoBBMap *ShortCut) const {
488 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
489
490 if (e == ShortCut->end())
491 return N->getIDom();
492
493 return PDT->getNode(e->second)->getIDom();
494}
495
496bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
497 assert(entry && exit && "entry and exit must not be null!");
498
499 unsigned num_successors = succ_end(entry) - succ_begin(entry);
500
501 if (num_successors <= 1 && exit == *(succ_begin(entry)))
502 return true;
503
504 return false;
505}
506
507void RegionInfo::updateStatistics(Region *R) {
508 ++numRegions;
509
510 // TODO: Slow. Should only be enabled if -stats is used.
511 if (R->isSimple()) ++numSimpleRegions;
512}
513
514Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
515 assert(entry && exit && "entry and exit must not be null!");
516
517 if (isTrivialRegion(entry, exit))
518 return 0;
519
520 Region *region = new Region(entry, exit, this, DT);
521 BBtoRegion.insert(std::make_pair(entry, region));
522
523 #ifdef XDEBUG
524 region->verifyRegion();
525 #else
526 DEBUG(region->verifyRegion());
527 #endif
528
529 updateStatistics(region);
530 return region;
531}
532
533void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
534 assert(entry);
535
536 DomTreeNode *N = PDT->getNode(entry);
537
538 if (!N)
539 return;
540
541 Region *lastRegion= 0;
542 BasicBlock *lastExit = entry;
543
544 // As only a BasicBlock that postdominates entry can finish a region, walk the
545 // post dominance tree upwards.
546 while ((N = getNextPostDom(N, ShortCut))) {
547 BasicBlock *exit = N->getBlock();
548
549 if (!exit)
550 break;
551
552 if (isRegion(entry, exit)) {
553 Region *newRegion = createRegion(entry, exit);
554
555 if (lastRegion)
556 newRegion->addSubRegion(lastRegion);
557
558 lastRegion = newRegion;
559 lastExit = exit;
560 }
561
562 // This can never be a region, so stop the search.
563 if (!DT->dominates(entry, exit))
564 break;
565 }
566
567 // Tried to create regions from entry to lastExit. Next time take a
568 // shortcut from entry to lastExit.
569 if (lastExit != entry)
570 insertShortCut(entry, lastExit, ShortCut);
571}
572
573void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
574 BasicBlock *entry = &(F.getEntryBlock());
575 DomTreeNode *N = DT->getNode(entry);
576
577 // Iterate over the dominance tree in post order to start with the small
578 // regions from the bottom of the dominance tree. If the small regions are
579 // detected first, detection of bigger regions is faster, as we can jump
580 // over the small regions.
581 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
582 ++FI) {
Gabor Greiff95eef62010-07-22 13:49:27 +0000583 findRegionsWithEntry(FI->getBlock(), ShortCut);
Tobias Grosserf96b0062010-07-22 07:46:31 +0000584 }
585}
586
587Region *RegionInfo::getTopMostParent(Region *region) {
588 while (region->parent)
589 region = region->getParent();
590
591 return region;
592}
593
594void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
595 BasicBlock *BB = N->getBlock();
596
597 // Passed region exit
598 while (BB == region->getExit())
599 region = region->getParent();
600
601 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
602
603 // This basic block is a start block of a region. It is already in the
604 // BBtoRegion relation. Only the child basic blocks have to be updated.
605 if (it != BBtoRegion.end()) {
606 Region *newRegion = it->second;;
607 region->addSubRegion(getTopMostParent(newRegion));
608 region = newRegion;
609 } else {
610 BBtoRegion[BB] = region;
611 }
612
613 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
614 buildRegionsTree(*CI, region);
615}
616
617void RegionInfo::releaseMemory() {
618 BBtoRegion.clear();
619 if (TopLevelRegion)
620 delete TopLevelRegion;
621 TopLevelRegion = 0;
622}
623
Owen Anderson90c579d2010-08-06 18:33:48 +0000624RegionInfo::RegionInfo() : FunctionPass(ID) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000625 TopLevelRegion = 0;
626}
627
628RegionInfo::~RegionInfo() {
629 releaseMemory();
630}
631
632void RegionInfo::Calculate(Function &F) {
633 // ShortCut a function where for every BB the exit of the largest region
634 // starting with BB is stored. These regions can be threated as single BBS.
635 // This improves performance on linear CFGs.
636 BBtoBBMap ShortCut;
637
638 scanForRegions(F, &ShortCut);
639 BasicBlock *BB = &F.getEntryBlock();
640 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
641}
642
643bool RegionInfo::runOnFunction(Function &F) {
644 releaseMemory();
645
646 DT = &getAnalysis<DominatorTree>();
647 PDT = &getAnalysis<PostDominatorTree>();
648 DF = &getAnalysis<DominanceFrontier>();
649
650 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
651 updateStatistics(TopLevelRegion);
652
653 Calculate(F);
654
655 return false;
656}
657
658void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
659 AU.setPreservesAll();
660 AU.addRequiredTransitive<DominatorTree>();
661 AU.addRequired<PostDominatorTree>();
662 AU.addRequired<DominanceFrontier>();
663}
664
665void RegionInfo::print(raw_ostream &OS, const Module *) const {
666 OS << "Region tree:\n";
667 TopLevelRegion->print(OS, true, 0);
668 OS << "End region tree\n";
669}
670
671void RegionInfo::verifyAnalysis() const {
672 // Only do verification when user wants to, otherwise this expensive check
673 // will be invoked by PMDataManager::verifyPreservedAnalysis when
674 // a regionpass (marked PreservedAll) finish.
675 if (!VerifyRegionInfo) return;
676
677 TopLevelRegion->verifyRegionNest();
678}
679
680// Region pass manager support.
681Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
682 BBtoRegionMap::const_iterator I=
683 BBtoRegion.find(BB);
684 return I != BBtoRegion.end() ? I->second : 0;
685}
686
Tobias Grosser9ee5c502010-10-13 05:54:07 +0000687void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
688 BBtoRegion[BB] = R;
689}
690
Tobias Grosserf96b0062010-07-22 07:46:31 +0000691Region *RegionInfo::operator[](BasicBlock *BB) const {
692 return getRegionFor(BB);
693}
694
Tobias Grosser0e6fcf42010-07-27 08:39:43 +0000695BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
696 BasicBlock *Exit = NULL;
697
698 while (true) {
699 // Get largest region that starts at BB.
700 Region *R = getRegionFor(BB);
701 while (R && R->getParent() && R->getParent()->getEntry() == BB)
702 R = R->getParent();
703
704 // Get the single exit of BB.
705 if (R && R->getEntry() == BB)
706 Exit = R->getExit();
707 else if (++succ_begin(BB) == succ_end(BB))
708 Exit = *succ_begin(BB);
709 else // No single exit exists.
710 return Exit;
711
712 // Get largest region that starts at Exit.
713 Region *ExitR = getRegionFor(Exit);
714 while (ExitR && ExitR->getParent()
715 && ExitR->getParent()->getEntry() == Exit)
716 ExitR = ExitR->getParent();
717
718 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
719 ++PI)
720 if (!R->contains(*PI) && !ExitR->contains(*PI))
721 break;
722
723 // This stops infinite cycles.
724 if (DT->dominates(Exit, BB))
725 break;
726
727 BB = Exit;
728 }
729
730 return Exit;
731}
732
Tobias Grosserf96b0062010-07-22 07:46:31 +0000733Region*
734RegionInfo::getCommonRegion(Region *A, Region *B) const {
735 assert (A && B && "One of the Regions is NULL");
736
737 if (A->contains(B)) return A;
738
739 while (!B->contains(A))
740 B = B->getParent();
741
742 return B;
743}
744
745Region*
746RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
747 Region* ret = Regions.back();
748 Regions.pop_back();
749
750 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
751 E = Regions.end(); I != E; ++I)
752 ret = getCommonRegion(ret, *I);
753
754 return ret;
755}
756
757Region*
758RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
759 Region* ret = getRegionFor(BBs.back());
760 BBs.pop_back();
761
762 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
763 E = BBs.end(); I != E; ++I)
764 ret = getCommonRegion(ret, getRegionFor(*I));
765
766 return ret;
767}
768
769char RegionInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000770INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
771 "Detect single entry single exit regions", true, true)
772INITIALIZE_PASS_DEPENDENCY(DominatorTree)
773INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
774INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
775INITIALIZE_PASS_END(RegionInfo, "regions",
Owen Andersonce665bd2010-10-07 22:25:06 +0000776 "Detect single entry single exit regions", true, true)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000777
778// Create methods available outside of this file, to use them
779// "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
780// the link time optimization.
781
782namespace llvm {
783 FunctionPass *createRegionInfoPass() {
784 return new RegionInfo();
785 }
786}
787