RegionInfo.h revision d03fdfb97c1a693101bfef5800c262237f5d382f
1//===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
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//
10// Calculate a program structure tree built out of single entry single exit
11// regions.
12// The basic ideas are taken from "The Program Structure Tree - Richard Johnson,
13// David Pearson, Keshav Pingali - 1994", however enriched with ideas from "The
14// Refined Process Structure Tree - Jussi Vanhatalo, Hagen Voelyer, Jana
15// Koehler - 2009".
16// The algorithm to calculate these data structures however is completely
17// different, as it takes advantage of existing information already available
18// in (Post)dominace tree and dominance frontier passes. This leads to a simpler
19// and in practice hopefully better performing algorithm. The runtime of the
20// algorithms described in the papers above are both linear in graph size,
21// O(V+E), whereas this algorithm is not, as the dominance frontier information
22// itself is not, but in practice runtime seems to be in the order of magnitude
23// of dominance tree calculation.
24//
25//===----------------------------------------------------------------------===//
26
27#ifndef LLVM_ANALYSIS_REGIONINFO_H
28#define LLVM_ANALYSIS_REGIONINFO_H
29
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/Analysis/DominanceFrontier.h"
32#include "llvm/Analysis/PostDominators.h"
33#include "llvm/Support/Allocator.h"
34#include <map>
35
36namespace llvm {
37
38class Region;
39class RegionInfo;
40class raw_ostream;
41class Loop;
42class LoopInfo;
43
44/// @brief Marker class to iterate over the elements of a Region in flat mode.
45///
46/// The class is used to either iterate in Flat mode or by not using it to not
47/// iterate in Flat mode.  During a Flat mode iteration all Regions are entered
48/// and the iteration returns every BasicBlock.  If the Flat mode is not
49/// selected for SubRegions just one RegionNode containing the subregion is
50/// returned.
51template <class GraphType>
52class FlatIt {};
53
54/// @brief A RegionNode represents a subregion or a BasicBlock that is part of a
55/// Region.
56class RegionNode {
57  RegionNode(const RegionNode &) LLVM_DELETED_FUNCTION;
58  const RegionNode &operator=(const RegionNode &) LLVM_DELETED_FUNCTION;
59
60protected:
61  /// This is the entry basic block that starts this region node.  If this is a
62  /// BasicBlock RegionNode, then entry is just the basic block, that this
63  /// RegionNode represents.  Otherwise it is the entry of this (Sub)RegionNode.
64  ///
65  /// In the BBtoRegionNode map of the parent of this node, BB will always map
66  /// to this node no matter which kind of node this one is.
67  ///
68  /// The node can hold either a Region or a BasicBlock.
69  /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
70  /// RegionNode.
71  PointerIntPair<BasicBlock*, 1, bool> entry;
72
73  /// @brief The parent Region of this RegionNode.
74  /// @see getParent()
75  Region* parent;
76
77public:
78  /// @brief Create a RegionNode.
79  ///
80  /// @param Parent      The parent of this RegionNode.
81  /// @param Entry       The entry BasicBlock of the RegionNode.  If this
82  ///                    RegionNode represents a BasicBlock, this is the
83  ///                    BasicBlock itself.  If it represents a subregion, this
84  ///                    is the entry BasicBlock of the subregion.
85  /// @param isSubRegion If this RegionNode represents a SubRegion.
86  inline RegionNode(Region* Parent, BasicBlock* Entry, bool isSubRegion = 0)
87    : entry(Entry, isSubRegion), parent(Parent) {}
88
89  /// @brief Get the parent Region of this RegionNode.
90  ///
91  /// The parent Region is the Region this RegionNode belongs to. If for
92  /// example a BasicBlock is element of two Regions, there exist two
93  /// RegionNodes for this BasicBlock. Each with the getParent() function
94  /// pointing to the Region this RegionNode belongs to.
95  ///
96  /// @return Get the parent Region of this RegionNode.
97  inline Region* getParent() const { return parent; }
98
99  /// @brief Get the entry BasicBlock of this RegionNode.
100  ///
101  /// If this RegionNode represents a BasicBlock this is just the BasicBlock
102  /// itself, otherwise we return the entry BasicBlock of the Subregion
103  ///
104  /// @return The entry BasicBlock of this RegionNode.
105  inline BasicBlock* getEntry() const { return entry.getPointer(); }
106
107  /// @brief Get the content of this RegionNode.
108  ///
109  /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
110  /// check the type of the content with the isSubRegion() function call.
111  ///
112  /// @return The content of this RegionNode.
113  template<class T>
114  inline T* getNodeAs() const;
115
116  /// @brief Is this RegionNode a subregion?
117  ///
118  /// @return True if it contains a subregion. False if it contains a
119  ///         BasicBlock.
120  inline bool isSubRegion() const {
121    return entry.getInt();
122  }
123};
124
125/// Print a RegionNode.
126inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node);
127
128template<>
129inline BasicBlock* RegionNode::getNodeAs<BasicBlock>() const {
130  assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
131  return getEntry();
132}
133
134template<>
135inline Region* RegionNode::getNodeAs<Region>() const {
136  assert(isSubRegion() && "This is not a subregion RegionNode!");
137  return reinterpret_cast<Region*>(const_cast<RegionNode*>(this));
138}
139
140//===----------------------------------------------------------------------===//
141/// @brief A single entry single exit Region.
142///
143/// A Region is a connected subgraph of a control flow graph that has exactly
144/// two connections to the remaining graph. It can be used to analyze or
145/// optimize parts of the control flow graph.
146///
147/// A <em> simple Region </em> is connected to the remaining graph by just two
148/// edges. One edge entering the Region and another one leaving the Region.
149///
150/// An <em> extended Region </em> (or just Region) is a subgraph that can be
151/// transform into a simple Region. The transformation is done by adding
152/// BasicBlocks that merge several entry or exit edges so that after the merge
153/// just one entry and one exit edge exists.
154///
155/// The \e Entry of a Region is the first BasicBlock that is passed after
156/// entering the Region. It is an element of the Region. The entry BasicBlock
157/// dominates all BasicBlocks in the Region.
158///
159/// The \e Exit of a Region is the first BasicBlock that is passed after
160/// leaving the Region. It is not an element of the Region. The exit BasicBlock,
161/// postdominates all BasicBlocks in the Region.
162///
163/// A <em> canonical Region </em> cannot be constructed by combining smaller
164/// Regions.
165///
166/// Region A is the \e parent of Region B, if B is completely contained in A.
167///
168/// Two canonical Regions either do not intersect at all or one is
169/// the parent of the other.
170///
171/// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
172/// Regions in the control flow graph and E is the \e parent relation of these
173/// Regions.
174///
175/// Example:
176///
177/// \verbatim
178/// A simple control flow graph, that contains two regions.
179///
180///        1
181///       / |
182///      2   |
183///     / \   3
184///    4   5  |
185///    |   |  |
186///    6   7  8
187///     \  | /
188///      \ |/       Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
189///        9        Region B: 2 -> 9 {2,4,5,6,7}
190/// \endverbatim
191///
192/// You can obtain more examples by either calling
193///
194/// <tt> "opt -regions -analyze anyprogram.ll" </tt>
195/// or
196/// <tt> "opt -view-regions-only anyprogram.ll" </tt>
197///
198/// on any LLVM file you are interested in.
199///
200/// The first call returns a textual representation of the program structure
201/// tree, the second one creates a graphical representation using graphviz.
202class Region : public RegionNode {
203  friend class RegionInfo;
204  Region(const Region &) LLVM_DELETED_FUNCTION;
205  const Region &operator=(const Region &) LLVM_DELETED_FUNCTION;
206
207  // Information necessary to manage this Region.
208  RegionInfo* RI;
209  DominatorTree *DT;
210
211  // The exit BasicBlock of this region.
212  // (The entry BasicBlock is part of RegionNode)
213  BasicBlock *exit;
214
215  typedef std::vector<Region*> RegionSet;
216
217  // The subregions of this region.
218  RegionSet children;
219
220  typedef std::map<BasicBlock*, RegionNode*> BBNodeMapT;
221
222  // Save the BasicBlock RegionNodes that are element of this Region.
223  mutable BBNodeMapT BBNodeMap;
224
225  /// verifyBBInRegion - Check if a BB is in this Region. This check also works
226  /// if the region is incorrectly built. (EXPENSIVE!)
227  void verifyBBInRegion(BasicBlock* BB) const;
228
229  /// verifyWalk - Walk over all the BBs of the region starting from BB and
230  /// verify that all reachable basic blocks are elements of the region.
231  /// (EXPENSIVE!)
232  void verifyWalk(BasicBlock* BB, std::set<BasicBlock*>* visitedBB) const;
233
234  /// verifyRegionNest - Verify if the region and its children are valid
235  /// regions (EXPENSIVE!)
236  void verifyRegionNest() const;
237
238public:
239  /// @brief Create a new region.
240  ///
241  /// @param Entry  The entry basic block of the region.
242  /// @param Exit   The exit basic block of the region.
243  /// @param RI     The region info object that is managing this region.
244  /// @param DT     The dominator tree of the current function.
245  /// @param Parent The surrounding region or NULL if this is a top level
246  ///               region.
247  Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI,
248         DominatorTree *DT, Region *Parent = 0);
249
250  /// Delete the Region and all its subregions.
251  ~Region();
252
253  /// @brief Get the entry BasicBlock of the Region.
254  /// @return The entry BasicBlock of the region.
255  BasicBlock *getEntry() const { return RegionNode::getEntry(); }
256
257  /// @brief Replace the entry basic block of the region with the new basic
258  ///        block.
259  ///
260  /// @param BB  The new entry basic block of the region.
261  void replaceEntry(BasicBlock *BB);
262
263  /// @brief Replace the exit basic block of the region with the new basic
264  ///        block.
265  ///
266  /// @param BB  The new exit basic block of the region.
267  void replaceExit(BasicBlock *BB);
268
269  /// @brief Recursively replace the entry basic block of the region.
270  ///
271  /// This function replaces the entry basic block with a new basic block. It
272  /// also updates all child regions that have the same entry basic block as
273  /// this region.
274  ///
275  /// @param NewEntry The new entry basic block.
276  void replaceEntryRecursive(BasicBlock *NewEntry);
277
278  /// @brief Recursively replace the exit basic block of the region.
279  ///
280  /// This function replaces the exit basic block with a new basic block. It
281  /// also updates all child regions that have the same exit basic block as
282  /// this region.
283  ///
284  /// @param NewExit The new exit basic block.
285  void replaceExitRecursive(BasicBlock *NewExit);
286
287  /// @brief Get the exit BasicBlock of the Region.
288  /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
289  ///         Region.
290  BasicBlock *getExit() const { return exit; }
291
292  /// @brief Get the parent of the Region.
293  /// @return The parent of the Region or NULL if this is a top level
294  ///         Region.
295  Region *getParent() const { return RegionNode::getParent(); }
296
297  /// @brief Get the RegionNode representing the current Region.
298  /// @return The RegionNode representing the current Region.
299  RegionNode* getNode() const {
300    return const_cast<RegionNode*>(reinterpret_cast<const RegionNode*>(this));
301  }
302
303  /// @brief Get the nesting level of this Region.
304  ///
305  /// An toplevel Region has depth 0.
306  ///
307  /// @return The depth of the region.
308  unsigned getDepth() const;
309
310  /// @brief Check if a Region is the TopLevel region.
311  ///
312  /// The toplevel region represents the whole function.
313  bool isTopLevelRegion() const { return exit == NULL; }
314
315  /// @brief Return a new (non canonical) region, that is obtained by joining
316  ///        this region with its predecessors.
317  ///
318  /// @return A region also starting at getEntry(), but reaching to the next
319  ///         basic block that forms with getEntry() a (non canonical) region.
320  ///         NULL if such a basic block does not exist.
321  Region *getExpandedRegion() const;
322
323  /// @brief Return the first block of this region's single entry edge,
324  ///        if existing.
325  ///
326  /// @return The BasicBlock starting this region's single entry edge,
327  ///         else NULL.
328  BasicBlock *getEnteringBlock() const;
329
330  /// @brief Return the first block of this region's single exit edge,
331  ///        if existing.
332  ///
333  /// @return The BasicBlock starting this region's single exit edge,
334  ///         else NULL.
335  BasicBlock *getExitingBlock() const;
336
337  /// @brief Is this a simple region?
338  ///
339  /// A region is simple if it has exactly one exit and one entry edge.
340  ///
341  /// @return True if the Region is simple.
342  bool isSimple() const;
343
344  /// @brief Returns the name of the Region.
345  /// @return The Name of the Region.
346  std::string getNameStr() const;
347
348  /// @brief Return the RegionInfo object, that belongs to this Region.
349  RegionInfo *getRegionInfo() const {
350    return RI;
351  }
352
353  /// PrintStyle - Print region in difference ways.
354  enum PrintStyle { PrintNone, PrintBB, PrintRN  };
355
356  /// @brief Print the region.
357  ///
358  /// @param OS The output stream the Region is printed to.
359  /// @param printTree Print also the tree of subregions.
360  /// @param level The indentation level used for printing.
361  void print(raw_ostream& OS, bool printTree = true, unsigned level = 0,
362             enum PrintStyle Style = PrintNone) const;
363
364  /// @brief Print the region to stderr.
365  void dump() const;
366
367  /// @brief Check if the region contains a BasicBlock.
368  ///
369  /// @param BB The BasicBlock that might be contained in this Region.
370  /// @return True if the block is contained in the region otherwise false.
371  bool contains(const BasicBlock *BB) const;
372
373  /// @brief Check if the region contains another region.
374  ///
375  /// @param SubRegion The region that might be contained in this Region.
376  /// @return True if SubRegion is contained in the region otherwise false.
377  bool contains(const Region *SubRegion) const {
378    // Toplevel Region.
379    if (!getExit())
380      return true;
381
382    return contains(SubRegion->getEntry())
383      && (contains(SubRegion->getExit()) || SubRegion->getExit() == getExit());
384  }
385
386  /// @brief Check if the region contains an Instruction.
387  ///
388  /// @param Inst The Instruction that might be contained in this region.
389  /// @return True if the Instruction is contained in the region otherwise false.
390  bool contains(const Instruction *Inst) const {
391    return contains(Inst->getParent());
392  }
393
394  /// @brief Check if the region contains a loop.
395  ///
396  /// @param L The loop that might be contained in this region.
397  /// @return True if the loop is contained in the region otherwise false.
398  ///         In case a NULL pointer is passed to this function the result
399  ///         is false, except for the region that describes the whole function.
400  ///         In that case true is returned.
401  bool contains(const Loop *L) const;
402
403  /// @brief Get the outermost loop in the region that contains a loop.
404  ///
405  /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
406  /// and is itself contained in the region.
407  ///
408  /// @param L The loop the lookup is started.
409  /// @return The outermost loop in the region, NULL if such a loop does not
410  ///         exist or if the region describes the whole function.
411  Loop *outermostLoopInRegion(Loop *L) const;
412
413  /// @brief Get the outermost loop in the region that contains a basic block.
414  ///
415  /// Find for a basic block BB the outermost loop L that contains BB and is
416  /// itself contained in the region.
417  ///
418  /// @param LI A pointer to a LoopInfo analysis.
419  /// @param BB The basic block surrounded by the loop.
420  /// @return The outermost loop in the region, NULL if such a loop does not
421  ///         exist or if the region describes the whole function.
422  Loop *outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const;
423
424  /// @brief Get the subregion that starts at a BasicBlock
425  ///
426  /// @param BB The BasicBlock the subregion should start.
427  /// @return The Subregion if available, otherwise NULL.
428  Region* getSubRegionNode(BasicBlock *BB) const;
429
430  /// @brief Get the RegionNode for a BasicBlock
431  ///
432  /// @param BB The BasicBlock at which the RegionNode should start.
433  /// @return If available, the RegionNode that represents the subregion
434  ///         starting at BB. If no subregion starts at BB, the RegionNode
435  ///         representing BB.
436  RegionNode* getNode(BasicBlock *BB) const;
437
438  /// @brief Get the BasicBlock RegionNode for a BasicBlock
439  ///
440  /// @param BB The BasicBlock for which the RegionNode is requested.
441  /// @return The RegionNode representing the BB.
442  RegionNode* getBBNode(BasicBlock *BB) const;
443
444  /// @brief Add a new subregion to this Region.
445  ///
446  /// @param SubRegion The new subregion that will be added.
447  /// @param moveChildren Move the children of this region, that are also
448  ///                     contained in SubRegion into SubRegion.
449  void addSubRegion(Region *SubRegion, bool moveChildren = false);
450
451  /// @brief Remove a subregion from this Region.
452  ///
453  /// The subregion is not deleted, as it will probably be inserted into another
454  /// region.
455  /// @param SubRegion The SubRegion that will be removed.
456  Region *removeSubRegion(Region *SubRegion);
457
458  /// @brief Move all direct child nodes of this Region to another Region.
459  ///
460  /// @param To The Region the child nodes will be transferred to.
461  void transferChildrenTo(Region *To);
462
463  /// @brief Verify if the region is a correct region.
464  ///
465  /// Check if this is a correctly build Region. This is an expensive check, as
466  /// the complete CFG of the Region will be walked.
467  void verifyRegion() const;
468
469  /// @brief Clear the cache for BB RegionNodes.
470  ///
471  /// After calling this function the BasicBlock RegionNodes will be stored at
472  /// different memory locations. RegionNodes obtained before this function is
473  /// called are therefore not comparable to RegionNodes abtained afterwords.
474  void clearNodeCache();
475
476  /// @name Subregion Iterators
477  ///
478  /// These iterators iterator over all subregions of this Region.
479  //@{
480  typedef RegionSet::iterator iterator;
481  typedef RegionSet::const_iterator const_iterator;
482
483  iterator begin() { return children.begin(); }
484  iterator end() { return children.end(); }
485
486  const_iterator begin() const { return children.begin(); }
487  const_iterator end() const { return children.end(); }
488  //@}
489
490  /// @name BasicBlock Iterators
491  ///
492  /// These iterators iterate over all BasicBlocks that are contained in this
493  /// Region. The iterator also iterates over BasicBlocks that are elements of
494  /// a subregion of this Region. It is therefore called a flat iterator.
495  //@{
496  template <bool IsConst>
497  class block_iterator_wrapper
498    : public df_iterator<typename conditional<IsConst,
499                                              const BasicBlock,
500                                              BasicBlock>::type*> {
501    typedef df_iterator<typename conditional<IsConst,
502                                             const BasicBlock,
503                                             BasicBlock>::type*>
504      super;
505  public:
506    typedef block_iterator_wrapper<IsConst> Self;
507    typedef typename super::pointer pointer;
508
509    // Construct the begin iterator.
510    block_iterator_wrapper(pointer Entry, pointer Exit) : super(df_begin(Entry))
511    {
512      // Mark the exit of the region as visited, so that the children of the
513      // exit and the exit itself, i.e. the block outside the region will never
514      // be visited.
515      super::Visited.insert(Exit);
516    }
517
518    // Construct the end iterator.
519    block_iterator_wrapper() : super(df_end<pointer>((BasicBlock *)0)) {}
520
521    /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
522
523    // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
524    //        This was introduced for backwards compatibility, but should
525    //        be removed as soon as all users are fixed.
526    BasicBlock *operator*() const {
527      return const_cast<BasicBlock*>(super::operator*());
528    }
529  };
530
531  typedef block_iterator_wrapper<false> block_iterator;
532  typedef block_iterator_wrapper<true>  const_block_iterator;
533
534  block_iterator block_begin() {
535   return block_iterator(getEntry(), getExit());
536  }
537
538  block_iterator block_end() {
539   return block_iterator();
540  }
541
542  const_block_iterator block_begin() const {
543    return const_block_iterator(getEntry(), getExit());
544  }
545  const_block_iterator block_end() const {
546    return const_block_iterator();
547  }
548  //@}
549
550  /// @name Element Iterators
551  ///
552  /// These iterators iterate over all BasicBlock and subregion RegionNodes that
553  /// are direct children of this Region. It does not iterate over any
554  /// RegionNodes that are also element of a subregion of this Region.
555  //@{
556  typedef df_iterator<RegionNode*, SmallPtrSet<RegionNode*, 8>, false,
557                      GraphTraits<RegionNode*> > element_iterator;
558
559  typedef df_iterator<const RegionNode*, SmallPtrSet<const RegionNode*, 8>,
560                      false, GraphTraits<const RegionNode*> >
561            const_element_iterator;
562
563  element_iterator element_begin();
564  element_iterator element_end();
565
566  const_element_iterator element_begin() const;
567  const_element_iterator element_end() const;
568  //@}
569};
570
571//===----------------------------------------------------------------------===//
572/// @brief Analysis that detects all canonical Regions.
573///
574/// The RegionInfo pass detects all canonical regions in a function. The Regions
575/// are connected using the parent relation. This builds a Program Structure
576/// Tree.
577class RegionInfo : public FunctionPass {
578  typedef DenseMap<BasicBlock*,BasicBlock*> BBtoBBMap;
579  typedef DenseMap<BasicBlock*, Region*> BBtoRegionMap;
580  typedef SmallPtrSet<Region*, 4> RegionSet;
581
582  RegionInfo(const RegionInfo &) LLVM_DELETED_FUNCTION;
583  const RegionInfo &operator=(const RegionInfo &) LLVM_DELETED_FUNCTION;
584
585  DominatorTree *DT;
586  PostDominatorTree *PDT;
587  DominanceFrontier *DF;
588
589  /// The top level region.
590  Region *TopLevelRegion;
591
592  /// Map every BB to the smallest region, that contains BB.
593  BBtoRegionMap BBtoRegion;
594
595  // isCommonDomFrontier - Returns true if BB is in the dominance frontier of
596  // entry, because it was inherited from exit. In the other case there is an
597  // edge going from entry to BB without passing exit.
598  bool isCommonDomFrontier(BasicBlock* BB, BasicBlock* entry,
599                           BasicBlock* exit) const;
600
601  // isRegion - Check if entry and exit surround a valid region, based on
602  // dominance tree and dominance frontier.
603  bool isRegion(BasicBlock* entry, BasicBlock* exit) const;
604
605  // insertShortCut - Saves a shortcut pointing from entry to exit.
606  // This function may extend this shortcut if possible.
607  void insertShortCut(BasicBlock* entry, BasicBlock* exit,
608                      BBtoBBMap* ShortCut) const;
609
610  // getNextPostDom - Returns the next BB that postdominates N, while skipping
611  // all post dominators that cannot finish a canonical region.
612  DomTreeNode *getNextPostDom(DomTreeNode* N, BBtoBBMap *ShortCut) const;
613
614  // isTrivialRegion - A region is trivial, if it contains only one BB.
615  bool isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const;
616
617  // createRegion - Creates a single entry single exit region.
618  Region *createRegion(BasicBlock *entry, BasicBlock *exit);
619
620  // findRegionsWithEntry - Detect all regions starting with bb 'entry'.
621  void findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut);
622
623  // scanForRegions - Detects regions in F.
624  void scanForRegions(Function &F, BBtoBBMap *ShortCut);
625
626  // getTopMostParent - Get the top most parent with the same entry block.
627  Region *getTopMostParent(Region *region);
628
629  // buildRegionsTree - build the region hierarchy after all region detected.
630  void buildRegionsTree(DomTreeNode *N, Region *region);
631
632  // Calculate - detecte all regions in function and build the region tree.
633  void Calculate(Function& F);
634
635  void releaseMemory();
636
637  // updateStatistics - Update statistic about created regions.
638  void updateStatistics(Region *R);
639
640  // isSimple - Check if a region is a simple region with exactly one entry
641  // edge and exactly one exit edge.
642  bool isSimple(Region* R) const;
643
644public:
645  static char ID;
646  explicit RegionInfo();
647
648  ~RegionInfo();
649
650  /// @name FunctionPass interface
651  //@{
652  virtual bool runOnFunction(Function &F);
653  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
654  virtual void print(raw_ostream &OS, const Module *) const;
655  virtual void verifyAnalysis() const;
656  //@}
657
658  /// @brief Get the smallest region that contains a BasicBlock.
659  ///
660  /// @param BB The basic block.
661  /// @return The smallest region, that contains BB or NULL, if there is no
662  /// region containing BB.
663  Region *getRegionFor(BasicBlock *BB) const;
664
665  /// @brief  Set the smallest region that surrounds a basic block.
666  ///
667  /// @param BB The basic block surrounded by a region.
668  /// @param R The smallest region that surrounds BB.
669  void setRegionFor(BasicBlock *BB, Region *R);
670
671  /// @brief A shortcut for getRegionFor().
672  ///
673  /// @param BB The basic block.
674  /// @return The smallest region, that contains BB or NULL, if there is no
675  /// region containing BB.
676  Region *operator[](BasicBlock *BB) const;
677
678  /// @brief Return the exit of the maximal refined region, that starts at a
679  /// BasicBlock.
680  ///
681  /// @param BB The BasicBlock the refined region starts.
682  BasicBlock *getMaxRegionExit(BasicBlock *BB) const;
683
684  /// @brief Find the smallest region that contains two regions.
685  ///
686  /// @param A The first region.
687  /// @param B The second region.
688  /// @return The smallest region containing A and B.
689  Region *getCommonRegion(Region* A, Region *B) const;
690
691  /// @brief Find the smallest region that contains two basic blocks.
692  ///
693  /// @param A The first basic block.
694  /// @param B The second basic block.
695  /// @return The smallest region that contains A and B.
696  Region* getCommonRegion(BasicBlock* A, BasicBlock *B) const {
697    return getCommonRegion(getRegionFor(A), getRegionFor(B));
698  }
699
700  /// @brief Find the smallest region that contains a set of regions.
701  ///
702  /// @param Regions A vector of regions.
703  /// @return The smallest region that contains all regions in Regions.
704  Region* getCommonRegion(SmallVectorImpl<Region*> &Regions) const;
705
706  /// @brief Find the smallest region that contains a set of basic blocks.
707  ///
708  /// @param BBs A vector of basic blocks.
709  /// @return The smallest region that contains all basic blocks in BBS.
710  Region* getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const;
711
712  Region *getTopLevelRegion() const {
713    return TopLevelRegion;
714  }
715
716  /// @brief Update RegionInfo after a basic block was split.
717  ///
718  /// @param NewBB The basic block that was created before OldBB.
719  /// @param OldBB The old basic block.
720  void splitBlock(BasicBlock* NewBB, BasicBlock *OldBB);
721
722  /// @brief Clear the Node Cache for all Regions.
723  ///
724  /// @see Region::clearNodeCache()
725  void clearNodeCache() {
726    if (TopLevelRegion)
727      TopLevelRegion->clearNodeCache();
728  }
729};
730
731inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node) {
732  if (Node.isSubRegion())
733    return OS << Node.getNodeAs<Region>()->getNameStr();
734  else
735    return OS << Node.getNodeAs<BasicBlock>()->getName();
736}
737} // End llvm namespace
738#endif
739
740