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