blob: fad5074086ce6c4e324e03e181fe77f6a8f036eb [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"
Tobias Grosserf96b0062010-07-22 07:46:31 +000013#include "llvm/ADT/PostOrderIterator.h"
14#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm/Analysis/LoopInfo.h"
16#include "llvm/Analysis/RegionIterator.h"
17#include "llvm/Assembly/Writer.h"
Tobias Grosserf96b0062010-07-22 07:46:31 +000018#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/ErrorHandling.h"
Tobias Grosserf96b0062010-07-22 07:46:31 +000020
21#define DEBUG_TYPE "region"
22#include "llvm/Support/Debug.h"
23
24#include <set>
25#include <algorithm>
26
27using namespace llvm;
28
29// Always verify if expensive checking is enabled.
30#ifdef XDEBUG
Dan Gohman811edc12010-08-02 18:50:06 +000031static bool VerifyRegionInfo = true;
Tobias Grosserf96b0062010-07-22 07:46:31 +000032#else
Dan Gohman811edc12010-08-02 18:50:06 +000033static bool VerifyRegionInfo = false;
Tobias Grosserf96b0062010-07-22 07:46:31 +000034#endif
35
36static cl::opt<bool,true>
37VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
38 cl::desc("Verify region info (time consuming)"));
39
40STATISTIC(numRegions, "The # of regions");
41STATISTIC(numSimpleRegions, "The # of simple regions");
42
Tobias Grossercc5d9922011-04-04 07:19:18 +000043static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
44 cl::Hidden,
Tobias Grosserf96b0062010-07-22 07:46:31 +000045 cl::desc("style of printing regions"),
46 cl::values(
Tobias Grossercc5d9922011-04-04 07:19:18 +000047 clEnumValN(Region::PrintNone, "none", "print no details"),
48 clEnumValN(Region::PrintBB, "bb",
Hongbin Zheng23a22a22012-08-27 13:49:24 +000049 "print regions in detail with block_iterator"),
Tobias Grossercc5d9922011-04-04 07:19:18 +000050 clEnumValN(Region::PrintRN, "rn",
51 "print regions in detail with element_iterator"),
Tobias Grosserf96b0062010-07-22 07:46:31 +000052 clEnumValEnd));
53//===----------------------------------------------------------------------===//
54/// Region Implementation
55Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
56 DominatorTree *dt, Region *Parent)
57 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
58
59Region::~Region() {
Daniel Dunbar329878f2010-07-28 20:28:50 +000060 // Free the cached nodes.
61 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
62 ie = BBNodeMap.end(); it != ie; ++it)
63 delete it->second;
64
Tobias Grosserf96b0062010-07-22 07:46:31 +000065 // Only clean the cache for this Region. Caches of child Regions will be
66 // cleaned when the child Regions are deleted.
67 BBNodeMap.clear();
68
69 for (iterator I = begin(), E = end(); I != E; ++I)
70 delete *I;
71}
72
Tobias Grosser4bcc0222010-10-13 05:54:10 +000073void Region::replaceEntry(BasicBlock *BB) {
74 entry.setPointer(BB);
75}
76
77void Region::replaceExit(BasicBlock *BB) {
78 assert(exit && "No exit to replace!");
79 exit = BB;
80}
81
Tobias Grosserf96b0062010-07-22 07:46:31 +000082bool Region::contains(const BasicBlock *B) const {
83 BasicBlock *BB = const_cast<BasicBlock*>(B);
84
85 assert(DT->getNode(BB) && "BB not part of the dominance tree");
86
87 BasicBlock *entry = getEntry(), *exit = getExit();
88
89 // Toplevel region.
90 if (!exit)
91 return true;
92
93 return (DT->dominates(entry, BB)
94 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
95}
96
Tobias Grosser082d5872010-07-27 04:17:13 +000097bool Region::contains(const Loop *L) const {
98 // BBs that are not part of any loop are element of the Loop
99 // described by the NULL pointer. This loop is not part of any region,
100 // except if the region describes the whole function.
101 if (L == 0)
102 return getExit() == 0;
103
104 if (!contains(L->getHeader()))
105 return false;
106
107 SmallVector<BasicBlock *, 8> ExitingBlocks;
108 L->getExitingBlocks(ExitingBlocks);
109
110 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
111 BE = ExitingBlocks.end(); BI != BE; ++BI)
112 if (!contains(*BI))
113 return false;
114
115 return true;
116}
117
118Loop *Region::outermostLoopInRegion(Loop *L) const {
119 if (!contains(L))
120 return 0;
121
122 while (L && contains(L->getParentLoop())) {
123 L = L->getParentLoop();
124 }
125
126 return L;
127}
128
129Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
130 assert(LI && BB && "LI and BB cannot be null!");
131 Loop *L = LI->getLoopFor(BB);
132 return outermostLoopInRegion(L);
133}
134
Tobias Grosser21d842c2011-01-13 23:18:04 +0000135BasicBlock *Region::getEnteringBlock() const {
136 BasicBlock *entry = getEntry();
137 BasicBlock *Pred;
138 BasicBlock *enteringBlock = 0;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000139
140 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
Tobias Grosser73362c82010-08-10 09:54:35 +0000141 ++PI) {
Tobias Grosser21d842c2011-01-13 23:18:04 +0000142 Pred = *PI;
Tobias Grosser73362c82010-08-10 09:54:35 +0000143 if (DT->getNode(Pred) && !contains(Pred)) {
Tobias Grosser21d842c2011-01-13 23:18:04 +0000144 if (enteringBlock)
145 return 0;
146
147 enteringBlock = Pred;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000148 }
Tobias Grosser73362c82010-08-10 09:54:35 +0000149 }
Tobias Grosserf96b0062010-07-22 07:46:31 +0000150
Tobias Grosser21d842c2011-01-13 23:18:04 +0000151 return enteringBlock;
152}
153
154BasicBlock *Region::getExitingBlock() const {
155 BasicBlock *exit = getExit();
156 BasicBlock *Pred;
157 BasicBlock *exitingBlock = 0;
158
159 if (!exit)
160 return 0;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000161
162 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
Tobias Grosser21d842c2011-01-13 23:18:04 +0000163 ++PI) {
164 Pred = *PI;
165 if (contains(Pred)) {
166 if (exitingBlock)
167 return 0;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000168
Tobias Grosser21d842c2011-01-13 23:18:04 +0000169 exitingBlock = Pred;
170 }
171 }
172
173 return exitingBlock;
174}
175
176bool Region::isSimple() const {
177 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
Tobias Grosserf96b0062010-07-22 07:46:31 +0000178}
179
Tobias Grosser082d5872010-07-27 04:17:13 +0000180std::string Region::getNameStr() const {
181 std::string exitName;
182 std::string entryName;
183
184 if (getEntry()->getName().empty()) {
185 raw_string_ostream OS(entryName);
186
187 WriteAsOperand(OS, getEntry(), false);
Tobias Grosser082d5872010-07-27 04:17:13 +0000188 } else
Benjamin Kramer2774dc02011-11-15 18:30:06 +0000189 entryName = getEntry()->getName();
Tobias Grosser082d5872010-07-27 04:17:13 +0000190
191 if (getExit()) {
192 if (getExit()->getName().empty()) {
193 raw_string_ostream OS(exitName);
194
195 WriteAsOperand(OS, getExit(), false);
Tobias Grosser082d5872010-07-27 04:17:13 +0000196 } else
Benjamin Kramer2774dc02011-11-15 18:30:06 +0000197 exitName = getExit()->getName();
Tobias Grosser082d5872010-07-27 04:17:13 +0000198 } else
199 exitName = "<Function Return>";
200
201 return entryName + " => " + exitName;
202}
203
Tobias Grosserf96b0062010-07-22 07:46:31 +0000204void Region::verifyBBInRegion(BasicBlock *BB) const {
205 if (!contains(BB))
206 llvm_unreachable("Broken region found!");
207
208 BasicBlock *entry = getEntry(), *exit = getExit();
209
210 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
211 if (!contains(*SI) && exit != *SI)
212 llvm_unreachable("Broken region found!");
213
214 if (entry != BB)
215 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
216 if (!contains(*SI))
217 llvm_unreachable("Broken region found!");
218}
219
220void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
221 BasicBlock *exit = getExit();
222
223 visited->insert(BB);
224
225 verifyBBInRegion(BB);
226
227 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
228 if (*SI != exit && visited->find(*SI) == visited->end())
229 verifyWalk(*SI, visited);
230}
231
232void Region::verifyRegion() const {
233 // Only do verification when user wants to, otherwise this expensive
234 // check will be invoked by PassManager.
235 if (!VerifyRegionInfo) return;
236
237 std::set<BasicBlock*> visited;
238 verifyWalk(getEntry(), &visited);
239}
240
241void Region::verifyRegionNest() const {
242 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
243 (*RI)->verifyRegionNest();
244
245 verifyRegion();
246}
247
Tobias Grosserf96b0062010-07-22 07:46:31 +0000248Region::element_iterator Region::element_begin() {
249 return GraphTraits<Region*>::nodes_begin(this);
250}
251
252Region::element_iterator Region::element_end() {
253 return GraphTraits<Region*>::nodes_end(this);
254}
255
256Region::const_element_iterator Region::element_begin() const {
257 return GraphTraits<const Region*>::nodes_begin(this);
258}
259
260Region::const_element_iterator Region::element_end() const {
261 return GraphTraits<const Region*>::nodes_end(this);
262}
263
264Region* Region::getSubRegionNode(BasicBlock *BB) const {
265 Region *R = RI->getRegionFor(BB);
266
267 if (!R || R == this)
268 return 0;
269
270 // If we pass the BB out of this region, that means our code is broken.
271 assert(contains(R) && "BB not in current region!");
272
273 while (contains(R->getParent()) && R->getParent() != this)
274 R = R->getParent();
275
276 if (R->getEntry() != BB)
277 return 0;
278
279 return R;
280}
281
282RegionNode* Region::getBBNode(BasicBlock *BB) const {
283 assert(contains(BB) && "Can get BB node out of this region!");
284
285 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
286
287 if (at != BBNodeMap.end())
288 return at->second;
289
290 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
291 BBNodeMap.insert(std::make_pair(BB, NewNode));
292 return NewNode;
293}
294
295RegionNode* Region::getNode(BasicBlock *BB) const {
296 assert(contains(BB) && "Can get BB node out of this region!");
297 if (Region* Child = getSubRegionNode(BB))
298 return Child->getNode();
299
300 return getBBNode(BB);
301}
302
303void Region::transferChildrenTo(Region *To) {
304 for (iterator I = begin(), E = end(); I != E; ++I) {
305 (*I)->parent = To;
306 To->children.push_back(*I);
307 }
308 children.clear();
309}
310
Tobias Grosser96493902010-10-13 05:54:09 +0000311void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000312 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
Tobias Grosser96493902010-10-13 05:54:09 +0000313 assert(std::find(begin(), end(), SubRegion) == children.end()
314 && "Subregion already exists!");
315
Tobias Grosserf96b0062010-07-22 07:46:31 +0000316 SubRegion->parent = this;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000317 children.push_back(SubRegion);
Tobias Grosser96493902010-10-13 05:54:09 +0000318
319 if (!moveChildren)
320 return;
321
322 assert(SubRegion->children.size() == 0
323 && "SubRegions that contain children are not supported");
324
325 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
326 if (!(*I)->isSubRegion()) {
327 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
328
329 if (SubRegion->contains(BB))
330 RI->setRegionFor(BB, SubRegion);
331 }
332
333 std::vector<Region*> Keep;
334 for (iterator I = begin(), E = end(); I != E; ++I)
335 if (SubRegion->contains(*I) && *I != SubRegion) {
336 SubRegion->children.push_back(*I);
337 (*I)->parent = SubRegion;
338 } else
339 Keep.push_back(*I);
340
341 children.clear();
342 children.insert(children.begin(), Keep.begin(), Keep.end());
Tobias Grosserf96b0062010-07-22 07:46:31 +0000343}
344
345
346Region *Region::removeSubRegion(Region *Child) {
347 assert(Child->parent == this && "Child is not a child of this region!");
348 Child->parent = 0;
349 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
350 assert(I != children.end() && "Region does not exit. Unable to remove.");
351 children.erase(children.begin()+(I-begin()));
352 return Child;
353}
354
355unsigned Region::getDepth() const {
356 unsigned Depth = 0;
357
358 for (Region *R = parent; R != 0; R = R->parent)
359 ++Depth;
360
361 return Depth;
362}
363
Tobias Grosserc69bd732010-10-13 05:54:11 +0000364Region *Region::getExpandedRegion() const {
365 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
366
367 if (NumSuccessors == 0)
368 return NULL;
369
370 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
371 PI != PE; ++PI)
372 if (!DT->dominates(getEntry(), *PI))
373 return NULL;
374
375 Region *R = RI->getRegionFor(exit);
376
377 if (R->getEntry() != exit) {
378 if (exit->getTerminator()->getNumSuccessors() == 1)
379 return new Region(getEntry(), *succ_begin(exit), RI, DT);
380 else
381 return NULL;
382 }
383
384 while (R->getParent() && R->getParent()->getEntry() == exit)
385 R = R->getParent();
386
387 if (!DT->dominates(getEntry(), R->getExit()))
388 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
389 PI != PE; ++PI)
390 if (!DT->dominates(R->getExit(), *PI))
391 return NULL;
392
393 return new Region(getEntry(), R->getExit(), RI, DT);
394}
395
Tobias Grossercc5d9922011-04-04 07:19:18 +0000396void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
397 enum PrintStyle Style) const {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000398 if (print_tree)
399 OS.indent(level*2) << "[" << level << "] " << getNameStr();
400 else
401 OS.indent(level*2) << getNameStr();
402
403 OS << "\n";
404
405
Tobias Grossercc5d9922011-04-04 07:19:18 +0000406 if (Style != PrintNone) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000407 OS.indent(level*2) << "{\n";
408 OS.indent(level*2 + 2);
409
Tobias Grossercc5d9922011-04-04 07:19:18 +0000410 if (Style == PrintBB) {
Hongbin Zheng23a22a22012-08-27 13:49:24 +0000411 for (const_block_iterator I = block_begin(), E = block_end(); I != E; ++I)
412 OS << (*I)->getName() << ", "; // TODO: remove the last ","
Tobias Grossercc5d9922011-04-04 07:19:18 +0000413 } else if (Style == PrintRN) {
Tobias Grosserf96b0062010-07-22 07:46:31 +0000414 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
415 OS << **I << ", "; // TODO: remove the last ",
416 }
417
418 OS << "\n";
419 }
420
421 if (print_tree)
422 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
Tobias Grossercc5d9922011-04-04 07:19:18 +0000423 (*RI)->print(OS, print_tree, level+1, Style);
Tobias Grosserf96b0062010-07-22 07:46:31 +0000424
Tobias Grossercc5d9922011-04-04 07:19:18 +0000425 if (Style != PrintNone)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000426 OS.indent(level*2) << "} \n";
427}
428
Manman Ren286c4dc2012-09-12 05:06:18 +0000429#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000430void Region::dump() const {
Tobias Grossercc5d9922011-04-04 07:19:18 +0000431 print(dbgs(), true, getDepth(), printStyle.getValue());
Tobias Grosserf96b0062010-07-22 07:46:31 +0000432}
Manman Rencc77eec2012-09-06 19:55:56 +0000433#endif
Tobias Grosserf96b0062010-07-22 07:46:31 +0000434
435void Region::clearNodeCache() {
Tobias Grosser67be08a2010-10-13 00:07:59 +0000436 // Free the cached nodes.
437 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
Tobias Grosserc5021012010-10-13 08:00:53 +0000438 IE = BBNodeMap.end(); I != IE; ++I)
Tobias Grosser67be08a2010-10-13 00:07:59 +0000439 delete I->second;
440
Tobias Grosserf96b0062010-07-22 07:46:31 +0000441 BBNodeMap.clear();
442 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
443 (*RI)->clearNodeCache();
444}
445
446//===----------------------------------------------------------------------===//
447// RegionInfo implementation
448//
449
450bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
451 BasicBlock *exit) const {
Gabor Greif3d8586e2010-07-22 11:07:46 +0000452 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
453 BasicBlock *P = *PI;
454 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
Tobias Grosserf96b0062010-07-22 07:46:31 +0000455 return false;
Gabor Greif3d8586e2010-07-22 11:07:46 +0000456 }
Tobias Grosserf96b0062010-07-22 07:46:31 +0000457 return true;
458}
459
460bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
461 assert(entry && exit && "entry and exit must not be null!");
462 typedef DominanceFrontier::DomSetType DST;
463
Gabor Greif11aa60d2010-07-22 11:12:32 +0000464 DST *entrySuccs = &DF->find(entry)->second;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000465
466 // Exit is the header of a loop that contains the entry. In this case,
467 // the dominance frontier must only contain the exit.
468 if (!DT->dominates(entry, exit)) {
469 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
470 SI != SE; ++SI)
471 if (*SI != exit && *SI != entry)
472 return false;
473
474 return true;
475 }
476
Gabor Greif11aa60d2010-07-22 11:12:32 +0000477 DST *exitSuccs = &DF->find(exit)->second;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000478
479 // Do not allow edges leaving the region.
480 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
481 SI != SE; ++SI) {
482 if (*SI == exit || *SI == entry)
483 continue;
484 if (exitSuccs->find(*SI) == exitSuccs->end())
485 return false;
486 if (!isCommonDomFrontier(*SI, entry, exit))
487 return false;
488 }
489
490 // Do not allow edges pointing into the region.
491 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
492 SI != SE; ++SI)
Dan Gohmana29dbd22010-07-26 17:34:05 +0000493 if (DT->properlyDominates(entry, *SI) && *SI != exit)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000494 return false;
495
496
497 return true;
498}
499
500void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
501 BBtoBBMap *ShortCut) const {
502 assert(entry && exit && "entry and exit must not be null!");
503
504 BBtoBBMap::iterator e = ShortCut->find(exit);
505
506 if (e == ShortCut->end())
507 // No further region at exit available.
508 (*ShortCut)[entry] = exit;
509 else {
510 // We found a region e that starts at exit. Therefore (entry, e->second)
511 // is also a region, that is larger than (entry, exit). Insert the
512 // larger one.
513 BasicBlock *BB = e->second;
514 (*ShortCut)[entry] = BB;
515 }
516}
517
518DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
519 BBtoBBMap *ShortCut) const {
520 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
521
522 if (e == ShortCut->end())
523 return N->getIDom();
524
525 return PDT->getNode(e->second)->getIDom();
526}
527
528bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
529 assert(entry && exit && "entry and exit must not be null!");
530
531 unsigned num_successors = succ_end(entry) - succ_begin(entry);
532
533 if (num_successors <= 1 && exit == *(succ_begin(entry)))
534 return true;
535
536 return false;
537}
538
539void RegionInfo::updateStatistics(Region *R) {
540 ++numRegions;
541
542 // TODO: Slow. Should only be enabled if -stats is used.
543 if (R->isSimple()) ++numSimpleRegions;
544}
545
546Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
547 assert(entry && exit && "entry and exit must not be null!");
548
549 if (isTrivialRegion(entry, exit))
550 return 0;
551
552 Region *region = new Region(entry, exit, this, DT);
553 BBtoRegion.insert(std::make_pair(entry, region));
554
555 #ifdef XDEBUG
556 region->verifyRegion();
557 #else
558 DEBUG(region->verifyRegion());
559 #endif
560
561 updateStatistics(region);
562 return region;
563}
564
565void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
566 assert(entry);
567
568 DomTreeNode *N = PDT->getNode(entry);
569
570 if (!N)
571 return;
572
573 Region *lastRegion= 0;
574 BasicBlock *lastExit = entry;
575
576 // As only a BasicBlock that postdominates entry can finish a region, walk the
577 // post dominance tree upwards.
578 while ((N = getNextPostDom(N, ShortCut))) {
579 BasicBlock *exit = N->getBlock();
580
581 if (!exit)
582 break;
583
584 if (isRegion(entry, exit)) {
585 Region *newRegion = createRegion(entry, exit);
586
587 if (lastRegion)
588 newRegion->addSubRegion(lastRegion);
589
590 lastRegion = newRegion;
591 lastExit = exit;
592 }
593
594 // This can never be a region, so stop the search.
595 if (!DT->dominates(entry, exit))
596 break;
597 }
598
599 // Tried to create regions from entry to lastExit. Next time take a
600 // shortcut from entry to lastExit.
601 if (lastExit != entry)
602 insertShortCut(entry, lastExit, ShortCut);
603}
604
605void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
606 BasicBlock *entry = &(F.getEntryBlock());
607 DomTreeNode *N = DT->getNode(entry);
608
609 // Iterate over the dominance tree in post order to start with the small
610 // regions from the bottom of the dominance tree. If the small regions are
611 // detected first, detection of bigger regions is faster, as we can jump
612 // over the small regions.
613 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
614 ++FI) {
Gabor Greiff95eef62010-07-22 13:49:27 +0000615 findRegionsWithEntry(FI->getBlock(), ShortCut);
Tobias Grosserf96b0062010-07-22 07:46:31 +0000616 }
617}
618
619Region *RegionInfo::getTopMostParent(Region *region) {
620 while (region->parent)
621 region = region->getParent();
622
623 return region;
624}
625
626void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
627 BasicBlock *BB = N->getBlock();
628
629 // Passed region exit
630 while (BB == region->getExit())
631 region = region->getParent();
632
633 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
634
635 // This basic block is a start block of a region. It is already in the
636 // BBtoRegion relation. Only the child basic blocks have to be updated.
637 if (it != BBtoRegion.end()) {
Chad Rosier90f20042012-02-22 17:25:00 +0000638 Region *newRegion = it->second;
Tobias Grosserf96b0062010-07-22 07:46:31 +0000639 region->addSubRegion(getTopMostParent(newRegion));
640 region = newRegion;
641 } else {
642 BBtoRegion[BB] = region;
643 }
644
645 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
646 buildRegionsTree(*CI, region);
647}
648
649void RegionInfo::releaseMemory() {
650 BBtoRegion.clear();
651 if (TopLevelRegion)
652 delete TopLevelRegion;
653 TopLevelRegion = 0;
654}
655
Owen Anderson90c579d2010-08-06 18:33:48 +0000656RegionInfo::RegionInfo() : FunctionPass(ID) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000657 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
Tobias Grosserf96b0062010-07-22 07:46:31 +0000658 TopLevelRegion = 0;
659}
660
661RegionInfo::~RegionInfo() {
662 releaseMemory();
663}
664
665void RegionInfo::Calculate(Function &F) {
666 // ShortCut a function where for every BB the exit of the largest region
667 // starting with BB is stored. These regions can be threated as single BBS.
668 // This improves performance on linear CFGs.
669 BBtoBBMap ShortCut;
670
671 scanForRegions(F, &ShortCut);
672 BasicBlock *BB = &F.getEntryBlock();
673 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
674}
675
676bool RegionInfo::runOnFunction(Function &F) {
677 releaseMemory();
678
679 DT = &getAnalysis<DominatorTree>();
680 PDT = &getAnalysis<PostDominatorTree>();
681 DF = &getAnalysis<DominanceFrontier>();
682
683 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
684 updateStatistics(TopLevelRegion);
685
686 Calculate(F);
687
688 return false;
689}
690
691void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
692 AU.setPreservesAll();
693 AU.addRequiredTransitive<DominatorTree>();
694 AU.addRequired<PostDominatorTree>();
695 AU.addRequired<DominanceFrontier>();
696}
697
698void RegionInfo::print(raw_ostream &OS, const Module *) const {
699 OS << "Region tree:\n";
Tobias Grossercc5d9922011-04-04 07:19:18 +0000700 TopLevelRegion->print(OS, true, 0, printStyle.getValue());
Tobias Grosserf96b0062010-07-22 07:46:31 +0000701 OS << "End region tree\n";
702}
703
704void RegionInfo::verifyAnalysis() const {
705 // Only do verification when user wants to, otherwise this expensive check
706 // will be invoked by PMDataManager::verifyPreservedAnalysis when
707 // a regionpass (marked PreservedAll) finish.
708 if (!VerifyRegionInfo) return;
709
710 TopLevelRegion->verifyRegionNest();
711}
712
713// Region pass manager support.
714Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
715 BBtoRegionMap::const_iterator I=
716 BBtoRegion.find(BB);
717 return I != BBtoRegion.end() ? I->second : 0;
718}
719
Tobias Grosser9ee5c502010-10-13 05:54:07 +0000720void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
721 BBtoRegion[BB] = R;
722}
723
Tobias Grosserf96b0062010-07-22 07:46:31 +0000724Region *RegionInfo::operator[](BasicBlock *BB) const {
725 return getRegionFor(BB);
726}
727
Tobias Grosser0e6fcf42010-07-27 08:39:43 +0000728BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
729 BasicBlock *Exit = NULL;
730
731 while (true) {
732 // Get largest region that starts at BB.
733 Region *R = getRegionFor(BB);
734 while (R && R->getParent() && R->getParent()->getEntry() == BB)
735 R = R->getParent();
736
737 // Get the single exit of BB.
738 if (R && R->getEntry() == BB)
739 Exit = R->getExit();
740 else if (++succ_begin(BB) == succ_end(BB))
741 Exit = *succ_begin(BB);
742 else // No single exit exists.
743 return Exit;
744
745 // Get largest region that starts at Exit.
746 Region *ExitR = getRegionFor(Exit);
747 while (ExitR && ExitR->getParent()
748 && ExitR->getParent()->getEntry() == Exit)
749 ExitR = ExitR->getParent();
750
751 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
752 ++PI)
753 if (!R->contains(*PI) && !ExitR->contains(*PI))
754 break;
755
756 // This stops infinite cycles.
757 if (DT->dominates(Exit, BB))
758 break;
759
760 BB = Exit;
761 }
762
763 return Exit;
764}
765
Tobias Grosserf96b0062010-07-22 07:46:31 +0000766Region*
767RegionInfo::getCommonRegion(Region *A, Region *B) const {
768 assert (A && B && "One of the Regions is NULL");
769
770 if (A->contains(B)) return A;
771
772 while (!B->contains(A))
773 B = B->getParent();
774
775 return B;
776}
777
778Region*
779RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
780 Region* ret = Regions.back();
781 Regions.pop_back();
782
783 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
784 E = Regions.end(); I != E; ++I)
785 ret = getCommonRegion(ret, *I);
786
787 return ret;
788}
789
790Region*
791RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
792 Region* ret = getRegionFor(BBs.back());
793 BBs.pop_back();
794
795 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
796 E = BBs.end(); I != E; ++I)
797 ret = getCommonRegion(ret, getRegionFor(*I));
798
799 return ret;
800}
801
Tobias Grosser592316c2010-10-13 05:54:13 +0000802void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
803{
804 Region *R = getRegionFor(OldBB);
Tobias Grosserb2279302010-10-13 11:02:44 +0000805
Tobias Grosser592316c2010-10-13 05:54:13 +0000806 setRegionFor(NewBB, R);
807
Tobias Grosserb2279302010-10-13 11:02:44 +0000808 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
Tobias Grosser592316c2010-10-13 05:54:13 +0000809 R->replaceEntry(NewBB);
810 R = R->getParent();
811 }
812
813 setRegionFor(OldBB, R);
814}
815
Tobias Grosserf96b0062010-07-22 07:46:31 +0000816char RegionInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000817INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
818 "Detect single entry single exit regions", true, true)
819INITIALIZE_PASS_DEPENDENCY(DominatorTree)
820INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
821INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
822INITIALIZE_PASS_END(RegionInfo, "regions",
Owen Andersonce665bd2010-10-07 22:25:06 +0000823 "Detect single entry single exit regions", true, true)
Tobias Grosserf96b0062010-07-22 07:46:31 +0000824
825// Create methods available outside of this file, to use them
826// "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
827// the link time optimization.
828
829namespace llvm {
830 FunctionPass *createRegionInfoPass() {
831 return new RegionInfo();
832 }
833}
834