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