blob: 2622c8966cd1f2b86a162433306267a2b78c122f [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
Tobias Grosser4bcc0222010-10-13 05:54:10 +000075void Region::replaceEntry(BasicBlock *BB) {
76 entry.setPointer(BB);
77}
78
79void Region::replaceExit(BasicBlock *BB) {
80 assert(exit && "No exit to replace!");
81 exit = BB;
82}
83
Tobias Grosserf96b0062010-07-22 07:46:31 +000084bool Region::contains(const BasicBlock *B) const {
85 BasicBlock *BB = const_cast<BasicBlock*>(B);
86
87 assert(DT->getNode(BB) && "BB not part of the dominance tree");
88
89 BasicBlock *entry = getEntry(), *exit = getExit();
90
91 // Toplevel region.
92 if (!exit)
93 return true;
94
95 return (DT->dominates(entry, BB)
96 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
97}
98
Tobias Grosser082d5872010-07-27 04:17:13 +000099bool Region::contains(const Loop *L) const {
100 // BBs that are not part of any loop are element of the Loop
101 // described by the NULL pointer. This loop is not part of any region,
102 // except if the region describes the whole function.
103 if (L == 0)
104 return getExit() == 0;
105
106 if (!contains(L->getHeader()))
107 return false;
108
109 SmallVector<BasicBlock *, 8> ExitingBlocks;
110 L->getExitingBlocks(ExitingBlocks);
111
112 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
113 BE = ExitingBlocks.end(); BI != BE; ++BI)
114 if (!contains(*BI))
115 return false;
116
117 return true;
118}
119
120Loop *Region::outermostLoopInRegion(Loop *L) const {
121 if (!contains(L))
122 return 0;
123
124 while (L && contains(L->getParentLoop())) {
125 L = L->getParentLoop();
126 }
127
128 return L;
129}
130
131Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
132 assert(LI && BB && "LI and BB cannot be null!");
133 Loop *L = LI->getLoopFor(BB);
134 return outermostLoopInRegion(L);
135}
136
Tobias Grosserf96b0062010-07-22 07:46:31 +0000137bool Region::isSimple() const {
138 bool isSimple = true;
139 bool found = false;
140
141 BasicBlock *entry = getEntry(), *exit = getExit();
142
Tobias Grosserb2279302010-10-13 11:02:44 +0000143 if (isTopLevelRegion())
Tobias Grosserf96b0062010-07-22 07:46:31 +0000144 return false;
145
146 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
Tobias Grosser73362c82010-08-10 09:54:35 +0000147 ++PI) {
148 BasicBlock *Pred = *PI;
149 if (DT->getNode(Pred) && !contains(Pred)) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000150 if (found) {
151 isSimple = false;
152 break;
153 }
154 found = true;
155 }
Tobias Grosser73362c82010-08-10 09:54:35 +0000156 }
Tobias Grosserf96b0062010-07-22 07:46:31 +0000157
158 found = false;
159
160 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
161 ++PI)
162 if (contains(*PI)) {
163 if (found) {
164 isSimple = false;
165 break;
166 }
167 found = true;
168 }
169
170 return isSimple;
171}
172
Tobias Grosser082d5872010-07-27 04:17:13 +0000173std::string Region::getNameStr() const {
174 std::string exitName;
175 std::string entryName;
176
177 if (getEntry()->getName().empty()) {
178 raw_string_ostream OS(entryName);
179
180 WriteAsOperand(OS, getEntry(), false);
181 entryName = OS.str();
182 } else
183 entryName = getEntry()->getNameStr();
184
185 if (getExit()) {
186 if (getExit()->getName().empty()) {
187 raw_string_ostream OS(exitName);
188
189 WriteAsOperand(OS, getExit(), false);
190 exitName = OS.str();
191 } else
192 exitName = getExit()->getNameStr();
193 } else
194 exitName = "<Function Return>";
195
196 return entryName + " => " + exitName;
197}
198
Tobias Grosserf96b0062010-07-22 07:46:31 +0000199void Region::verifyBBInRegion(BasicBlock *BB) const {
200 if (!contains(BB))
201 llvm_unreachable("Broken region found!");
202
203 BasicBlock *entry = getEntry(), *exit = getExit();
204
205 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
206 if (!contains(*SI) && exit != *SI)
207 llvm_unreachable("Broken region found!");
208
209 if (entry != BB)
210 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
211 if (!contains(*SI))
212 llvm_unreachable("Broken region found!");
213}
214
215void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
216 BasicBlock *exit = getExit();
217
218 visited->insert(BB);
219
220 verifyBBInRegion(BB);
221
222 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
223 if (*SI != exit && visited->find(*SI) == visited->end())
224 verifyWalk(*SI, visited);
225}
226
227void Region::verifyRegion() const {
228 // Only do verification when user wants to, otherwise this expensive
229 // check will be invoked by PassManager.
230 if (!VerifyRegionInfo) return;
231
232 std::set<BasicBlock*> visited;
233 verifyWalk(getEntry(), &visited);
234}
235
236void Region::verifyRegionNest() const {
237 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
238 (*RI)->verifyRegionNest();
239
240 verifyRegion();
241}
242
243Region::block_iterator Region::block_begin() {
244 return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
245}
246
247Region::block_iterator Region::block_end() {
248 return GraphTraits<FlatIt<Region*> >::nodes_end(this);
249}
250
251Region::const_block_iterator Region::block_begin() const {
252 return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
253}
254
255Region::const_block_iterator Region::block_end() const {
256 return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
257}
258
259Region::element_iterator Region::element_begin() {
260 return GraphTraits<Region*>::nodes_begin(this);
261}
262
263Region::element_iterator Region::element_end() {
264 return GraphTraits<Region*>::nodes_end(this);
265}
266
267Region::const_element_iterator Region::element_begin() const {
268 return GraphTraits<const Region*>::nodes_begin(this);
269}
270
271Region::const_element_iterator Region::element_end() const {
272 return GraphTraits<const Region*>::nodes_end(this);
273}
274
275Region* Region::getSubRegionNode(BasicBlock *BB) const {
276 Region *R = RI->getRegionFor(BB);
277
278 if (!R || R == this)
279 return 0;
280
281 // If we pass the BB out of this region, that means our code is broken.
282 assert(contains(R) && "BB not in current region!");
283
284 while (contains(R->getParent()) && R->getParent() != this)
285 R = R->getParent();
286
287 if (R->getEntry() != BB)
288 return 0;
289
290 return R;
291}
292
293RegionNode* Region::getBBNode(BasicBlock *BB) const {
294 assert(contains(BB) && "Can get BB node out of this region!");
295
296 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
297
298 if (at != BBNodeMap.end())
299 return at->second;
300
301 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
302 BBNodeMap.insert(std::make_pair(BB, NewNode));
303 return NewNode;
304}
305
306RegionNode* Region::getNode(BasicBlock *BB) const {
307 assert(contains(BB) && "Can get BB node out of this region!");
308 if (Region* Child = getSubRegionNode(BB))
309 return Child->getNode();
310
311 return getBBNode(BB);
312}
313
314void Region::transferChildrenTo(Region *To) {
315 for (iterator I = begin(), E = end(); I != E; ++I) {
316 (*I)->parent = To;
317 To->children.push_back(*I);
318 }
319 children.clear();
320}
321
Tobias Grosser96493902010-10-13 05:54:09 +0000322void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000323 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
Tobias Grosser96493902010-10-13 05:54:09 +0000324 assert(std::find(begin(), end(), SubRegion) == children.end()
325 && "Subregion already exists!");
326
Tobias Grosserf96b0062010-07-22 07:46:31 +0000327 SubRegion->parent = this;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000328 children.push_back(SubRegion);
Tobias Grosser96493902010-10-13 05:54:09 +0000329
330 if (!moveChildren)
331 return;
332
333 assert(SubRegion->children.size() == 0
334 && "SubRegions that contain children are not supported");
335
336 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
337 if (!(*I)->isSubRegion()) {
338 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
339
340 if (SubRegion->contains(BB))
341 RI->setRegionFor(BB, SubRegion);
342 }
343
344 std::vector<Region*> Keep;
345 for (iterator I = begin(), E = end(); I != E; ++I)
346 if (SubRegion->contains(*I) && *I != SubRegion) {
347 SubRegion->children.push_back(*I);
348 (*I)->parent = SubRegion;
349 } else
350 Keep.push_back(*I);
351
352 children.clear();
353 children.insert(children.begin(), Keep.begin(), Keep.end());
Tobias Grosserf96b0062010-07-22 07:46:31 +0000354}
355
356
357Region *Region::removeSubRegion(Region *Child) {
358 assert(Child->parent == this && "Child is not a child of this region!");
359 Child->parent = 0;
360 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
361 assert(I != children.end() && "Region does not exit. Unable to remove.");
362 children.erase(children.begin()+(I-begin()));
363 return Child;
364}
365
366unsigned Region::getDepth() const {
367 unsigned Depth = 0;
368
369 for (Region *R = parent; R != 0; R = R->parent)
370 ++Depth;
371
372 return Depth;
373}
374
Tobias Grosserc69bd732010-10-13 05:54:11 +0000375Region *Region::getExpandedRegion() const {
376 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
377
378 if (NumSuccessors == 0)
379 return NULL;
380
381 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
382 PI != PE; ++PI)
383 if (!DT->dominates(getEntry(), *PI))
384 return NULL;
385
386 Region *R = RI->getRegionFor(exit);
387
388 if (R->getEntry() != exit) {
389 if (exit->getTerminator()->getNumSuccessors() == 1)
390 return new Region(getEntry(), *succ_begin(exit), RI, DT);
391 else
392 return NULL;
393 }
394
395 while (R->getParent() && R->getParent()->getEntry() == exit)
396 R = R->getParent();
397
398 if (!DT->dominates(getEntry(), R->getExit()))
399 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
400 PI != PE; ++PI)
401 if (!DT->dominates(R->getExit(), *PI))
402 return NULL;
403
404 return new Region(getEntry(), R->getExit(), RI, DT);
405}
406
Tobias Grosserf96b0062010-07-22 07:46:31 +0000407void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
408 if (print_tree)
409 OS.indent(level*2) << "[" << level << "] " << getNameStr();
410 else
411 OS.indent(level*2) << getNameStr();
412
413 OS << "\n";
414
415
416 if (printStyle != PrintNone) {
417 OS.indent(level*2) << "{\n";
418 OS.indent(level*2 + 2);
419
420 if (printStyle == PrintBB) {
421 for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
422 OS << **I << ", "; // TODO: remove the last ","
423 } else if (printStyle == PrintRN) {
424 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
425 OS << **I << ", "; // TODO: remove the last ",
426 }
427
428 OS << "\n";
429 }
430
431 if (print_tree)
432 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
433 (*RI)->print(OS, print_tree, level+1);
434
435 if (printStyle != PrintNone)
436 OS.indent(level*2) << "} \n";
437}
438
439void Region::dump() const {
440 print(dbgs(), true, getDepth());
441}
442
443void Region::clearNodeCache() {
Tobias Grosser67be08a2010-10-13 00:07:59 +0000444 // Free the cached nodes.
445 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
Tobias Grosserc5021012010-10-13 08:00:53 +0000446 IE = BBNodeMap.end(); I != IE; ++I)
Tobias Grosser67be08a2010-10-13 00:07:59 +0000447 delete I->second;
448
Tobias Grosserf96b0062010-07-22 07:46:31 +0000449 BBNodeMap.clear();
450 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
451 (*RI)->clearNodeCache();
452}
453
454//===----------------------------------------------------------------------===//
455// RegionInfo implementation
456//
457
458bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
459 BasicBlock *exit) const {
Gabor Greif3d8586e2010-07-22 11:07:46 +0000460 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
461 BasicBlock *P = *PI;
462 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
Tobias Grosserf96b0062010-07-22 07:46:31 +0000463 return false;
Gabor Greif3d8586e2010-07-22 11:07:46 +0000464 }
Tobias Grosserf96b0062010-07-22 07:46:31 +0000465 return true;
466}
467
468bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
469 assert(entry && exit && "entry and exit must not be null!");
470 typedef DominanceFrontier::DomSetType DST;
471
Gabor Greif11aa60d2010-07-22 11:12:32 +0000472 DST *entrySuccs = &DF->find(entry)->second;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000473
474 // Exit is the header of a loop that contains the entry. In this case,
475 // the dominance frontier must only contain the exit.
476 if (!DT->dominates(entry, exit)) {
477 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
478 SI != SE; ++SI)
479 if (*SI != exit && *SI != entry)
480 return false;
481
482 return true;
483 }
484
Gabor Greif11aa60d2010-07-22 11:12:32 +0000485 DST *exitSuccs = &DF->find(exit)->second;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000486
487 // Do not allow edges leaving the region.
488 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
489 SI != SE; ++SI) {
490 if (*SI == exit || *SI == entry)
491 continue;
492 if (exitSuccs->find(*SI) == exitSuccs->end())
493 return false;
494 if (!isCommonDomFrontier(*SI, entry, exit))
495 return false;
496 }
497
498 // Do not allow edges pointing into the region.
499 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
500 SI != SE; ++SI)
Dan Gohmana29dbd22010-07-26 17:34:05 +0000501 if (DT->properlyDominates(entry, *SI) && *SI != exit)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000502 return false;
503
504
505 return true;
506}
507
508void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
509 BBtoBBMap *ShortCut) const {
510 assert(entry && exit && "entry and exit must not be null!");
511
512 BBtoBBMap::iterator e = ShortCut->find(exit);
513
514 if (e == ShortCut->end())
515 // No further region at exit available.
516 (*ShortCut)[entry] = exit;
517 else {
518 // We found a region e that starts at exit. Therefore (entry, e->second)
519 // is also a region, that is larger than (entry, exit). Insert the
520 // larger one.
521 BasicBlock *BB = e->second;
522 (*ShortCut)[entry] = BB;
523 }
524}
525
526DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
527 BBtoBBMap *ShortCut) const {
528 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
529
530 if (e == ShortCut->end())
531 return N->getIDom();
532
533 return PDT->getNode(e->second)->getIDom();
534}
535
536bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
537 assert(entry && exit && "entry and exit must not be null!");
538
539 unsigned num_successors = succ_end(entry) - succ_begin(entry);
540
541 if (num_successors <= 1 && exit == *(succ_begin(entry)))
542 return true;
543
544 return false;
545}
546
547void RegionInfo::updateStatistics(Region *R) {
548 ++numRegions;
549
550 // TODO: Slow. Should only be enabled if -stats is used.
551 if (R->isSimple()) ++numSimpleRegions;
552}
553
554Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
555 assert(entry && exit && "entry and exit must not be null!");
556
557 if (isTrivialRegion(entry, exit))
558 return 0;
559
560 Region *region = new Region(entry, exit, this, DT);
561 BBtoRegion.insert(std::make_pair(entry, region));
562
563 #ifdef XDEBUG
564 region->verifyRegion();
565 #else
566 DEBUG(region->verifyRegion());
567 #endif
568
569 updateStatistics(region);
570 return region;
571}
572
573void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
574 assert(entry);
575
576 DomTreeNode *N = PDT->getNode(entry);
577
578 if (!N)
579 return;
580
581 Region *lastRegion= 0;
582 BasicBlock *lastExit = entry;
583
584 // As only a BasicBlock that postdominates entry can finish a region, walk the
585 // post dominance tree upwards.
586 while ((N = getNextPostDom(N, ShortCut))) {
587 BasicBlock *exit = N->getBlock();
588
589 if (!exit)
590 break;
591
592 if (isRegion(entry, exit)) {
593 Region *newRegion = createRegion(entry, exit);
594
595 if (lastRegion)
596 newRegion->addSubRegion(lastRegion);
597
598 lastRegion = newRegion;
599 lastExit = exit;
600 }
601
602 // This can never be a region, so stop the search.
603 if (!DT->dominates(entry, exit))
604 break;
605 }
606
607 // Tried to create regions from entry to lastExit. Next time take a
608 // shortcut from entry to lastExit.
609 if (lastExit != entry)
610 insertShortCut(entry, lastExit, ShortCut);
611}
612
613void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
614 BasicBlock *entry = &(F.getEntryBlock());
615 DomTreeNode *N = DT->getNode(entry);
616
617 // Iterate over the dominance tree in post order to start with the small
618 // regions from the bottom of the dominance tree. If the small regions are
619 // detected first, detection of bigger regions is faster, as we can jump
620 // over the small regions.
621 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
622 ++FI) {
Gabor Greiff95eef62010-07-22 13:49:27 +0000623 findRegionsWithEntry(FI->getBlock(), ShortCut);
Tobias Grosserf96b0062010-07-22 07:46:31 +0000624 }
625}
626
627Region *RegionInfo::getTopMostParent(Region *region) {
628 while (region->parent)
629 region = region->getParent();
630
631 return region;
632}
633
634void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
635 BasicBlock *BB = N->getBlock();
636
637 // Passed region exit
638 while (BB == region->getExit())
639 region = region->getParent();
640
641 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
642
643 // This basic block is a start block of a region. It is already in the
644 // BBtoRegion relation. Only the child basic blocks have to be updated.
645 if (it != BBtoRegion.end()) {
646 Region *newRegion = it->second;;
647 region->addSubRegion(getTopMostParent(newRegion));
648 region = newRegion;
649 } else {
650 BBtoRegion[BB] = region;
651 }
652
653 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
654 buildRegionsTree(*CI, region);
655}
656
657void RegionInfo::releaseMemory() {
658 BBtoRegion.clear();
659 if (TopLevelRegion)
660 delete TopLevelRegion;
661 TopLevelRegion = 0;
662}
663
Owen Anderson90c579d2010-08-06 18:33:48 +0000664RegionInfo::RegionInfo() : FunctionPass(ID) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000665 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
Tobias Grosserf96b0062010-07-22 07:46:31 +0000666 TopLevelRegion = 0;
667}
668
669RegionInfo::~RegionInfo() {
670 releaseMemory();
671}
672
673void RegionInfo::Calculate(Function &F) {
674 // ShortCut a function where for every BB the exit of the largest region
675 // starting with BB is stored. These regions can be threated as single BBS.
676 // This improves performance on linear CFGs.
677 BBtoBBMap ShortCut;
678
679 scanForRegions(F, &ShortCut);
680 BasicBlock *BB = &F.getEntryBlock();
681 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
682}
683
684bool RegionInfo::runOnFunction(Function &F) {
685 releaseMemory();
686
687 DT = &getAnalysis<DominatorTree>();
688 PDT = &getAnalysis<PostDominatorTree>();
689 DF = &getAnalysis<DominanceFrontier>();
690
691 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
692 updateStatistics(TopLevelRegion);
693
694 Calculate(F);
695
696 return false;
697}
698
699void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
700 AU.setPreservesAll();
701 AU.addRequiredTransitive<DominatorTree>();
702 AU.addRequired<PostDominatorTree>();
703 AU.addRequired<DominanceFrontier>();
704}
705
706void RegionInfo::print(raw_ostream &OS, const Module *) const {
707 OS << "Region tree:\n";
708 TopLevelRegion->print(OS, true, 0);
709 OS << "End region tree\n";
710}
711
712void RegionInfo::verifyAnalysis() const {
713 // Only do verification when user wants to, otherwise this expensive check
714 // will be invoked by PMDataManager::verifyPreservedAnalysis when
715 // a regionpass (marked PreservedAll) finish.
716 if (!VerifyRegionInfo) return;
717
718 TopLevelRegion->verifyRegionNest();
719}
720
721// Region pass manager support.
722Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
723 BBtoRegionMap::const_iterator I=
724 BBtoRegion.find(BB);
725 return I != BBtoRegion.end() ? I->second : 0;
726}
727
Tobias Grosser9ee5c502010-10-13 05:54:07 +0000728void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
729 BBtoRegion[BB] = R;
730}
731
Tobias Grosserf96b0062010-07-22 07:46:31 +0000732Region *RegionInfo::operator[](BasicBlock *BB) const {
733 return getRegionFor(BB);
734}
735
Tobias Grosser0e6fcf42010-07-27 08:39:43 +0000736BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
737 BasicBlock *Exit = NULL;
738
739 while (true) {
740 // Get largest region that starts at BB.
741 Region *R = getRegionFor(BB);
742 while (R && R->getParent() && R->getParent()->getEntry() == BB)
743 R = R->getParent();
744
745 // Get the single exit of BB.
746 if (R && R->getEntry() == BB)
747 Exit = R->getExit();
748 else if (++succ_begin(BB) == succ_end(BB))
749 Exit = *succ_begin(BB);
750 else // No single exit exists.
751 return Exit;
752
753 // Get largest region that starts at Exit.
754 Region *ExitR = getRegionFor(Exit);
755 while (ExitR && ExitR->getParent()
756 && ExitR->getParent()->getEntry() == Exit)
757 ExitR = ExitR->getParent();
758
759 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
760 ++PI)
761 if (!R->contains(*PI) && !ExitR->contains(*PI))
762 break;
763
764 // This stops infinite cycles.
765 if (DT->dominates(Exit, BB))
766 break;
767
768 BB = Exit;
769 }
770
771 return Exit;
772}
773
Tobias Grosserf96b0062010-07-22 07:46:31 +0000774Region*
775RegionInfo::getCommonRegion(Region *A, Region *B) const {
776 assert (A && B && "One of the Regions is NULL");
777
778 if (A->contains(B)) return A;
779
780 while (!B->contains(A))
781 B = B->getParent();
782
783 return B;
784}
785
786Region*
787RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
788 Region* ret = Regions.back();
789 Regions.pop_back();
790
791 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
792 E = Regions.end(); I != E; ++I)
793 ret = getCommonRegion(ret, *I);
794
795 return ret;
796}
797
798Region*
799RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
800 Region* ret = getRegionFor(BBs.back());
801 BBs.pop_back();
802
803 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
804 E = BBs.end(); I != E; ++I)
805 ret = getCommonRegion(ret, getRegionFor(*I));
806
807 return ret;
808}
809
Tobias Grosser592316c2010-10-13 05:54:13 +0000810void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
811{
812 Region *R = getRegionFor(OldBB);
Tobias Grosserb2279302010-10-13 11:02:44 +0000813
Tobias Grosser592316c2010-10-13 05:54:13 +0000814 setRegionFor(NewBB, R);
815
Tobias Grosserb2279302010-10-13 11:02:44 +0000816 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
Tobias Grosser592316c2010-10-13 05:54:13 +0000817 R->replaceEntry(NewBB);
818 R = R->getParent();
819 }
820
821 setRegionFor(OldBB, R);
822}
823
Tobias Grosserf96b0062010-07-22 07:46:31 +0000824char RegionInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000825INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
826 "Detect single entry single exit regions", true, true)
827INITIALIZE_PASS_DEPENDENCY(DominatorTree)
828INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
829INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
830INITIALIZE_PASS_END(RegionInfo, "regions",
Owen Andersonce665bd2010-10-07 22:25:06 +0000831 "Detect single entry single exit regions", true, true)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000832
833// Create methods available outside of this file, to use them
834// "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
835// the link time optimization.
836
837namespace llvm {
838 FunctionPass *createRegionInfoPass() {
839 return new RegionInfo();
840 }
841}
842