LLVM  3.7.0
RegionInfo.h
Go to the documentation of this file.
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 
42 #include "llvm/IR/CFG.h"
43 #include "llvm/IR/Dominators.h"
44 #include <map>
45 #include <memory>
46 #include <set>
47 
48 namespace llvm {
49 
50 // RegionTraits - Class to be specialized for different users of RegionInfo
51 // (i.e. BasicBlocks or MachineBasicBlocks). This is only to avoid needing to
52 // pass around an unreasonable number of template parameters.
53 template <class FuncT_>
54 struct RegionTraits {
55  // FuncT
56  // BlockT
57  // RegionT
58  // RegionNodeT
59  // RegionInfoT
60  typedef typename FuncT_::UnknownRegionTypeError BrokenT;
61 };
62 
63 class DominatorTree;
64 class DominanceFrontier;
65 class Loop;
66 class LoopInfo;
67 struct PostDominatorTree;
68 class raw_ostream;
69 class Region;
70 template <class RegionTr>
71 class RegionBase;
72 class RegionNode;
73 class RegionInfo;
74 template <class RegionTr>
76 
77 template <>
79  typedef Function FuncT;
80  typedef BasicBlock BlockT;
81  typedef Region RegionT;
88  typedef Instruction InstT;
89  typedef Loop LoopT;
91 
92  static unsigned getNumSuccessors(BasicBlock *BB) {
93  return BB->getTerminator()->getNumSuccessors();
94  }
95 };
96 
97 /// @brief Marker class to iterate over the elements of a Region in flat mode.
98 ///
99 /// The class is used to either iterate in Flat mode or by not using it to not
100 /// iterate in Flat mode. During a Flat mode iteration all Regions are entered
101 /// and the iteration returns every BasicBlock. If the Flat mode is not
102 /// selected for SubRegions just one RegionNode containing the subregion is
103 /// returned.
104 template <class GraphType>
105 class FlatIt {};
106 
107 /// @brief A RegionNode represents a subregion or a BasicBlock that is part of a
108 /// Region.
109 template <class Tr>
111  friend class RegionBase<Tr>;
112 
113 public:
114  typedef typename Tr::BlockT BlockT;
115  typedef typename Tr::RegionT RegionT;
116 
117 private:
118  RegionNodeBase(const RegionNodeBase &) = delete;
119  const RegionNodeBase &operator=(const RegionNodeBase &) = delete;
120 
121  /// This is the entry basic block that starts this region node. If this is a
122  /// BasicBlock RegionNode, then entry is just the basic block, that this
123  /// RegionNode represents. Otherwise it is the entry of this (Sub)RegionNode.
124  ///
125  /// In the BBtoRegionNode map of the parent of this node, BB will always map
126  /// to this node no matter which kind of node this one is.
127  ///
128  /// The node can hold either a Region or a BasicBlock.
129  /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
130  /// RegionNode.
132 
133  /// @brief The parent Region of this RegionNode.
134  /// @see getParent()
135  RegionT *parent;
136 
137 protected:
138  /// @brief Create a RegionNode.
139  ///
140  /// @param Parent The parent of this RegionNode.
141  /// @param Entry The entry BasicBlock of the RegionNode. If this
142  /// RegionNode represents a BasicBlock, this is the
143  /// BasicBlock itself. If it represents a subregion, this
144  /// is the entry BasicBlock of the subregion.
145  /// @param isSubRegion If this RegionNode represents a SubRegion.
146  inline RegionNodeBase(RegionT *Parent, BlockT *Entry,
147  bool isSubRegion = false)
148  : entry(Entry, isSubRegion), parent(Parent) {}
149 
150 public:
151  /// @brief Get the parent Region of this RegionNode.
152  ///
153  /// The parent Region is the Region this RegionNode belongs to. If for
154  /// example a BasicBlock is element of two Regions, there exist two
155  /// RegionNodes for this BasicBlock. Each with the getParent() function
156  /// pointing to the Region this RegionNode belongs to.
157  ///
158  /// @return Get the parent Region of this RegionNode.
159  inline RegionT *getParent() const { return parent; }
160 
161  /// @brief Get the entry BasicBlock of this RegionNode.
162  ///
163  /// If this RegionNode represents a BasicBlock this is just the BasicBlock
164  /// itself, otherwise we return the entry BasicBlock of the Subregion
165  ///
166  /// @return The entry BasicBlock of this RegionNode.
167  inline BlockT *getEntry() const { return entry.getPointer(); }
168 
169  /// @brief Get the content of this RegionNode.
170  ///
171  /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
172  /// check the type of the content with the isSubRegion() function call.
173  ///
174  /// @return The content of this RegionNode.
175  template <class T> inline T *getNodeAs() const;
176 
177  /// @brief Is this RegionNode a subregion?
178  ///
179  /// @return True if it contains a subregion. False if it contains a
180  /// BasicBlock.
181  inline bool isSubRegion() const { return entry.getInt(); }
182 };
183 
184 //===----------------------------------------------------------------------===//
185 /// @brief A single entry single exit Region.
186 ///
187 /// A Region is a connected subgraph of a control flow graph that has exactly
188 /// two connections to the remaining graph. It can be used to analyze or
189 /// optimize parts of the control flow graph.
190 ///
191 /// A <em> simple Region </em> is connected to the remaining graph by just two
192 /// edges. One edge entering the Region and another one leaving the Region.
193 ///
194 /// An <em> extended Region </em> (or just Region) is a subgraph that can be
195 /// transform into a simple Region. The transformation is done by adding
196 /// BasicBlocks that merge several entry or exit edges so that after the merge
197 /// just one entry and one exit edge exists.
198 ///
199 /// The \e Entry of a Region is the first BasicBlock that is passed after
200 /// entering the Region. It is an element of the Region. The entry BasicBlock
201 /// dominates all BasicBlocks in the Region.
202 ///
203 /// The \e Exit of a Region is the first BasicBlock that is passed after
204 /// leaving the Region. It is not an element of the Region. The exit BasicBlock,
205 /// postdominates all BasicBlocks in the Region.
206 ///
207 /// A <em> canonical Region </em> cannot be constructed by combining smaller
208 /// Regions.
209 ///
210 /// Region A is the \e parent of Region B, if B is completely contained in A.
211 ///
212 /// Two canonical Regions either do not intersect at all or one is
213 /// the parent of the other.
214 ///
215 /// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
216 /// Regions in the control flow graph and E is the \e parent relation of these
217 /// Regions.
218 ///
219 /// Example:
220 ///
221 /// \verbatim
222 /// A simple control flow graph, that contains two regions.
223 ///
224 /// 1
225 /// / |
226 /// 2 |
227 /// / \ 3
228 /// 4 5 |
229 /// | | |
230 /// 6 7 8
231 /// \ | /
232 /// \ |/ Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
233 /// 9 Region B: 2 -> 9 {2,4,5,6,7}
234 /// \endverbatim
235 ///
236 /// You can obtain more examples by either calling
237 ///
238 /// <tt> "opt -regions -analyze anyprogram.ll" </tt>
239 /// or
240 /// <tt> "opt -view-regions-only anyprogram.ll" </tt>
241 ///
242 /// on any LLVM file you are interested in.
243 ///
244 /// The first call returns a textual representation of the program structure
245 /// tree, the second one creates a graphical representation using graphviz.
246 template <class Tr>
247 class RegionBase : public RegionNodeBase<Tr> {
248  typedef typename Tr::FuncT FuncT;
249  typedef typename Tr::BlockT BlockT;
250  typedef typename Tr::RegionInfoT RegionInfoT;
251  typedef typename Tr::RegionT RegionT;
252  typedef typename Tr::RegionNodeT RegionNodeT;
253  typedef typename Tr::DomTreeT DomTreeT;
254  typedef typename Tr::LoopT LoopT;
255  typedef typename Tr::LoopInfoT LoopInfoT;
256  typedef typename Tr::InstT InstT;
257 
258  typedef GraphTraits<BlockT *> BlockTraits;
259  typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
260  typedef typename BlockTraits::ChildIteratorType SuccIterTy;
261  typedef typename InvBlockTraits::ChildIteratorType PredIterTy;
262 
263  friend class RegionInfoBase<Tr>;
264  RegionBase(const RegionBase &) = delete;
265  const RegionBase &operator=(const RegionBase &) = delete;
266 
267  // Information necessary to manage this Region.
268  RegionInfoT *RI;
269  DomTreeT *DT;
270 
271  // The exit BasicBlock of this region.
272  // (The entry BasicBlock is part of RegionNode)
273  BlockT *exit;
274 
275  typedef std::vector<std::unique_ptr<RegionT>> RegionSet;
276 
277  // The subregions of this region.
278  RegionSet children;
279 
280  typedef std::map<BlockT *, RegionNodeT *> BBNodeMapT;
281 
282  // Save the BasicBlock RegionNodes that are element of this Region.
283  mutable BBNodeMapT BBNodeMap;
284 
285  /// verifyBBInRegion - Check if a BB is in this Region. This check also works
286  /// if the region is incorrectly built. (EXPENSIVE!)
287  void verifyBBInRegion(BlockT *BB) const;
288 
289  /// verifyWalk - Walk over all the BBs of the region starting from BB and
290  /// verify that all reachable basic blocks are elements of the region.
291  /// (EXPENSIVE!)
292  void verifyWalk(BlockT *BB, std::set<BlockT *> *visitedBB) const;
293 
294  /// verifyRegionNest - Verify if the region and its children are valid
295  /// regions (EXPENSIVE!)
296  void verifyRegionNest() const;
297 
298 public:
299  /// @brief Create a new region.
300  ///
301  /// @param Entry The entry basic block of the region.
302  /// @param Exit The exit basic block of the region.
303  /// @param RI The region info object that is managing this region.
304  /// @param DT The dominator tree of the current function.
305  /// @param Parent The surrounding region or NULL if this is a top level
306  /// region.
307  RegionBase(BlockT *Entry, BlockT *Exit, RegionInfoT *RI, DomTreeT *DT,
308  RegionT *Parent = nullptr);
309 
310  /// Delete the Region and all its subregions.
311  ~RegionBase();
312 
313  /// @brief Get the entry BasicBlock of the Region.
314  /// @return The entry BasicBlock of the region.
315  BlockT *getEntry() const {
317  }
318 
319  /// @brief Replace the entry basic block of the region with the new basic
320  /// block.
321  ///
322  /// @param BB The new entry basic block of the region.
323  void replaceEntry(BlockT *BB);
324 
325  /// @brief Replace the exit basic block of the region with the new basic
326  /// block.
327  ///
328  /// @param BB The new exit basic block of the region.
329  void replaceExit(BlockT *BB);
330 
331  /// @brief Recursively replace the entry basic block of the region.
332  ///
333  /// This function replaces the entry basic block with a new basic block. It
334  /// also updates all child regions that have the same entry basic block as
335  /// this region.
336  ///
337  /// @param NewEntry The new entry basic block.
338  void replaceEntryRecursive(BlockT *NewEntry);
339 
340  /// @brief Recursively replace the exit basic block of the region.
341  ///
342  /// This function replaces the exit basic block with a new basic block. It
343  /// also updates all child regions that have the same exit basic block as
344  /// this region.
345  ///
346  /// @param NewExit The new exit basic block.
347  void replaceExitRecursive(BlockT *NewExit);
348 
349  /// @brief Get the exit BasicBlock of the Region.
350  /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
351  /// Region.
352  BlockT *getExit() const { return exit; }
353 
354  /// @brief Get the parent of the Region.
355  /// @return The parent of the Region or NULL if this is a top level
356  /// Region.
357  RegionT *getParent() const {
359  }
360 
361  /// @brief Get the RegionNode representing the current Region.
362  /// @return The RegionNode representing the current Region.
363  RegionNodeT *getNode() const {
364  return const_cast<RegionNodeT *>(
365  reinterpret_cast<const RegionNodeT *>(this));
366  }
367 
368  /// @brief Get the nesting level of this Region.
369  ///
370  /// An toplevel Region has depth 0.
371  ///
372  /// @return The depth of the region.
373  unsigned getDepth() const;
374 
375  /// @brief Check if a Region is the TopLevel region.
376  ///
377  /// The toplevel region represents the whole function.
378  bool isTopLevelRegion() const { return exit == nullptr; }
379 
380  /// @brief Return a new (non-canonical) region, that is obtained by joining
381  /// this region with its predecessors.
382  ///
383  /// @return A region also starting at getEntry(), but reaching to the next
384  /// basic block that forms with getEntry() a (non-canonical) region.
385  /// NULL if such a basic block does not exist.
386  RegionT *getExpandedRegion() const;
387 
388  /// @brief Return the first block of this region's single entry edge,
389  /// if existing.
390  ///
391  /// @return The BasicBlock starting this region's single entry edge,
392  /// else NULL.
393  BlockT *getEnteringBlock() const;
394 
395  /// @brief Return the first block of this region's single exit edge,
396  /// if existing.
397  ///
398  /// @return The BasicBlock starting this region's single exit edge,
399  /// else NULL.
400  BlockT *getExitingBlock() const;
401 
402  /// @brief Is this a simple region?
403  ///
404  /// A region is simple if it has exactly one exit and one entry edge.
405  ///
406  /// @return True if the Region is simple.
407  bool isSimple() const;
408 
409  /// @brief Returns the name of the Region.
410  /// @return The Name of the Region.
411  std::string getNameStr() const;
412 
413  /// @brief Return the RegionInfo object, that belongs to this Region.
414  RegionInfoT *getRegionInfo() const { return RI; }
415 
416  /// PrintStyle - Print region in difference ways.
418 
419  /// @brief Print the region.
420  ///
421  /// @param OS The output stream the Region is printed to.
422  /// @param printTree Print also the tree of subregions.
423  /// @param level The indentation level used for printing.
424  void print(raw_ostream &OS, bool printTree = true, unsigned level = 0,
425  PrintStyle Style = PrintNone) const;
426 
427 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
428  /// @brief Print the region to stderr.
429  void dump() const;
430 #endif
431 
432  /// @brief Check if the region contains a BasicBlock.
433  ///
434  /// @param BB The BasicBlock that might be contained in this Region.
435  /// @return True if the block is contained in the region otherwise false.
436  bool contains(const BlockT *BB) const;
437 
438  /// @brief Check if the region contains another region.
439  ///
440  /// @param SubRegion The region that might be contained in this Region.
441  /// @return True if SubRegion is contained in the region otherwise false.
442  bool contains(const RegionT *SubRegion) const {
443  // Toplevel Region.
444  if (!getExit())
445  return true;
446 
447  return contains(SubRegion->getEntry()) &&
448  (contains(SubRegion->getExit()) ||
449  SubRegion->getExit() == getExit());
450  }
451 
452  /// @brief Check if the region contains an Instruction.
453  ///
454  /// @param Inst The Instruction that might be contained in this region.
455  /// @return True if the Instruction is contained in the region otherwise
456  /// false.
457  bool contains(const InstT *Inst) const { return contains(Inst->getParent()); }
458 
459  /// @brief Check if the region contains a loop.
460  ///
461  /// @param L The loop that might be contained in this region.
462  /// @return True if the loop is contained in the region otherwise false.
463  /// In case a NULL pointer is passed to this function the result
464  /// is false, except for the region that describes the whole function.
465  /// In that case true is returned.
466  bool contains(const LoopT *L) const;
467 
468  /// @brief Get the outermost loop in the region that contains a loop.
469  ///
470  /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
471  /// and is itself contained in the region.
472  ///
473  /// @param L The loop the lookup is started.
474  /// @return The outermost loop in the region, NULL if such a loop does not
475  /// exist or if the region describes the whole function.
476  LoopT *outermostLoopInRegion(LoopT *L) const;
477 
478  /// @brief Get the outermost loop in the region that contains a basic block.
479  ///
480  /// Find for a basic block BB the outermost loop L that contains BB and is
481  /// itself contained in the region.
482  ///
483  /// @param LI A pointer to a LoopInfo analysis.
484  /// @param BB The basic block surrounded by the loop.
485  /// @return The outermost loop in the region, NULL if such a loop does not
486  /// exist or if the region describes the whole function.
487  LoopT *outermostLoopInRegion(LoopInfoT *LI, BlockT *BB) const;
488 
489  /// @brief Get the subregion that starts at a BasicBlock
490  ///
491  /// @param BB The BasicBlock the subregion should start.
492  /// @return The Subregion if available, otherwise NULL.
493  RegionT *getSubRegionNode(BlockT *BB) const;
494 
495  /// @brief Get the RegionNode for a BasicBlock
496  ///
497  /// @param BB The BasicBlock at which the RegionNode should start.
498  /// @return If available, the RegionNode that represents the subregion
499  /// starting at BB. If no subregion starts at BB, the RegionNode
500  /// representing BB.
501  RegionNodeT *getNode(BlockT *BB) const;
502 
503  /// @brief Get the BasicBlock RegionNode for a BasicBlock
504  ///
505  /// @param BB The BasicBlock for which the RegionNode is requested.
506  /// @return The RegionNode representing the BB.
507  RegionNodeT *getBBNode(BlockT *BB) const;
508 
509  /// @brief Add a new subregion to this Region.
510  ///
511  /// @param SubRegion The new subregion that will be added.
512  /// @param moveChildren Move the children of this region, that are also
513  /// contained in SubRegion into SubRegion.
514  void addSubRegion(RegionT *SubRegion, bool moveChildren = false);
515 
516  /// @brief Remove a subregion from this Region.
517  ///
518  /// The subregion is not deleted, as it will probably be inserted into another
519  /// region.
520  /// @param SubRegion The SubRegion that will be removed.
521  RegionT *removeSubRegion(RegionT *SubRegion);
522 
523  /// @brief Move all direct child nodes of this Region to another Region.
524  ///
525  /// @param To The Region the child nodes will be transferred to.
526  void transferChildrenTo(RegionT *To);
527 
528  /// @brief Verify if the region is a correct region.
529  ///
530  /// Check if this is a correctly build Region. This is an expensive check, as
531  /// the complete CFG of the Region will be walked.
532  void verifyRegion() const;
533 
534  /// @brief Clear the cache for BB RegionNodes.
535  ///
536  /// After calling this function the BasicBlock RegionNodes will be stored at
537  /// different memory locations. RegionNodes obtained before this function is
538  /// called are therefore not comparable to RegionNodes abtained afterwords.
539  void clearNodeCache();
540 
541  /// @name Subregion Iterators
542  ///
543  /// These iterators iterator over all subregions of this Region.
544  //@{
545  typedef typename RegionSet::iterator iterator;
546  typedef typename RegionSet::const_iterator const_iterator;
547 
548  iterator begin() { return children.begin(); }
549  iterator end() { return children.end(); }
550 
551  const_iterator begin() const { return children.begin(); }
552  const_iterator end() const { return children.end(); }
553  //@}
554 
555  /// @name BasicBlock Iterators
556  ///
557  /// These iterators iterate over all BasicBlocks that are contained in this
558  /// Region. The iterator also iterates over BasicBlocks that are elements of
559  /// a subregion of this Region. It is therefore called a flat iterator.
560  //@{
561  template <bool IsConst>
563  : public df_iterator<
564  typename std::conditional<IsConst, const BlockT, BlockT>::type *> {
565  typedef df_iterator<
566  typename std::conditional<IsConst, const BlockT, BlockT>::type *> super;
567 
568  public:
570  typedef typename super::pointer pointer;
571 
572  // Construct the begin iterator.
574  : super(df_begin(Entry)) {
575  // Mark the exit of the region as visited, so that the children of the
576  // exit and the exit itself, i.e. the block outside the region will never
577  // be visited.
578  super::Visited.insert(Exit);
579  }
580 
581  // Construct the end iterator.
583 
584  /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
585 
586  // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
587  // This was introduced for backwards compatibility, but should
588  // be removed as soon as all users are fixed.
589  BlockT *operator*() const {
590  return const_cast<BlockT *>(super::operator*());
591  }
592  };
593 
594  typedef block_iterator_wrapper<false> block_iterator;
595  typedef block_iterator_wrapper<true> const_block_iterator;
596 
598 
600 
603  }
605 
608 
609  /// @brief Returns a range view of the basic blocks in the region.
610  inline block_range blocks() {
611  return block_range(block_begin(), block_end());
612  }
613 
614  /// @brief Returns a range view of the basic blocks in the region.
615  ///
616  /// This is the 'const' version of the range view.
617  inline const_block_range blocks() const {
619  }
620  //@}
621 
622  /// @name Element Iterators
623  ///
624  /// These iterators iterate over all BasicBlock and subregion RegionNodes that
625  /// are direct children of this Region. It does not iterate over any
626  /// RegionNodes that are also element of a subregion of this Region.
627  //@{
630 
632  false,
634 
637 
640  //@}
641 };
642 
643 /// Print a RegionNode.
644 template <class Tr>
645 inline raw_ostream &operator<<(raw_ostream &OS, const RegionNodeBase<Tr> &Node);
646 
647 //===----------------------------------------------------------------------===//
648 /// @brief Analysis that detects all canonical Regions.
649 ///
650 /// The RegionInfo pass detects all canonical regions in a function. The Regions
651 /// are connected using the parent relation. This builds a Program Structure
652 /// Tree.
653 template <class Tr>
654 class RegionInfoBase {
655  typedef typename Tr::BlockT BlockT;
656  typedef typename Tr::FuncT FuncT;
657  typedef typename Tr::RegionT RegionT;
658  typedef typename Tr::RegionInfoT RegionInfoT;
659  typedef typename Tr::DomTreeT DomTreeT;
660  typedef typename Tr::DomTreeNodeT DomTreeNodeT;
661  typedef typename Tr::PostDomTreeT PostDomTreeT;
662  typedef typename Tr::DomFrontierT DomFrontierT;
663  typedef GraphTraits<BlockT *> BlockTraits;
664  typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
665  typedef typename BlockTraits::ChildIteratorType SuccIterTy;
666  typedef typename InvBlockTraits::ChildIteratorType PredIterTy;
667 
668  friend class RegionInfo;
669  friend class MachineRegionInfo;
673 
674  RegionInfoBase();
675  virtual ~RegionInfoBase();
676 
677  RegionInfoBase(const RegionInfoBase &) = delete;
678  const RegionInfoBase &operator=(const RegionInfoBase &) = delete;
679 
680  DomTreeT *DT;
681  PostDomTreeT *PDT;
682  DomFrontierT *DF;
683 
684  /// The top level region.
685  RegionT *TopLevelRegion;
686 
687 private:
688  /// Map every BB to the smallest region, that contains BB.
689  BBtoRegionMap BBtoRegion;
690 
691  // isCommonDomFrontier - Returns true if BB is in the dominance frontier of
692  // entry, because it was inherited from exit. In the other case there is an
693  // edge going from entry to BB without passing exit.
694  bool isCommonDomFrontier(BlockT *BB, BlockT *entry, BlockT *exit) const;
695 
696  // isRegion - Check if entry and exit surround a valid region, based on
697  // dominance tree and dominance frontier.
698  bool isRegion(BlockT *entry, BlockT *exit) const;
699 
700  // insertShortCut - Saves a shortcut pointing from entry to exit.
701  // This function may extend this shortcut if possible.
702  void insertShortCut(BlockT *entry, BlockT *exit, BBtoBBMap *ShortCut) const;
703 
704  // getNextPostDom - Returns the next BB that postdominates N, while skipping
705  // all post dominators that cannot finish a canonical region.
706  DomTreeNodeT *getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const;
707 
708  // isTrivialRegion - A region is trivial, if it contains only one BB.
709  bool isTrivialRegion(BlockT *entry, BlockT *exit) const;
710 
711  // createRegion - Creates a single entry single exit region.
712  RegionT *createRegion(BlockT *entry, BlockT *exit);
713 
714  // findRegionsWithEntry - Detect all regions starting with bb 'entry'.
715  void findRegionsWithEntry(BlockT *entry, BBtoBBMap *ShortCut);
716 
717  // scanForRegions - Detects regions in F.
718  void scanForRegions(FuncT &F, BBtoBBMap *ShortCut);
719 
720  // getTopMostParent - Get the top most parent with the same entry block.
721  RegionT *getTopMostParent(RegionT *region);
722 
723  // buildRegionsTree - build the region hierarchy after all region detected.
724  void buildRegionsTree(DomTreeNodeT *N, RegionT *region);
725 
726  // updateStatistics - Update statistic about created regions.
727  virtual void updateStatistics(RegionT *R) = 0;
728 
729  // calculate - detect all regions in function and build the region tree.
730  void calculate(FuncT &F);
731 
732 public:
733  static bool VerifyRegionInfo;
734  static typename RegionT::PrintStyle printStyle;
735 
736  void print(raw_ostream &OS) const;
737 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
738  void dump() const;
739 #endif
740 
741  void releaseMemory();
742 
743  /// @brief Get the smallest region that contains a BasicBlock.
744  ///
745  /// @param BB The basic block.
746  /// @return The smallest region, that contains BB or NULL, if there is no
747  /// region containing BB.
748  RegionT *getRegionFor(BlockT *BB) const;
749 
750  /// @brief Set the smallest region that surrounds a basic block.
751  ///
752  /// @param BB The basic block surrounded by a region.
753  /// @param R The smallest region that surrounds BB.
754  void setRegionFor(BlockT *BB, RegionT *R);
755 
756  /// @brief A shortcut for getRegionFor().
757  ///
758  /// @param BB The basic block.
759  /// @return The smallest region, that contains BB or NULL, if there is no
760  /// region containing BB.
761  RegionT *operator[](BlockT *BB) const;
762 
763  /// @brief Return the exit of the maximal refined region, that starts at a
764  /// BasicBlock.
765  ///
766  /// @param BB The BasicBlock the refined region starts.
767  BlockT *getMaxRegionExit(BlockT *BB) const;
768 
769  /// @brief Find the smallest region that contains two regions.
770  ///
771  /// @param A The first region.
772  /// @param B The second region.
773  /// @return The smallest region containing A and B.
774  RegionT *getCommonRegion(RegionT *A, RegionT *B) const;
775 
776  /// @brief Find the smallest region that contains two basic blocks.
777  ///
778  /// @param A The first basic block.
779  /// @param B The second basic block.
780  /// @return The smallest region that contains A and B.
781  RegionT *getCommonRegion(BlockT *A, BlockT *B) const {
783  }
784 
785  /// @brief Find the smallest region that contains a set of regions.
786  ///
787  /// @param Regions A vector of regions.
788  /// @return The smallest region that contains all regions in Regions.
789  RegionT *getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const;
790 
791  /// @brief Find the smallest region that contains a set of basic blocks.
792  ///
793  /// @param BBs A vector of basic blocks.
794  /// @return The smallest region that contains all basic blocks in BBS.
795  RegionT *getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const;
796 
797  RegionT *getTopLevelRegion() const { return TopLevelRegion; }
798 
799  /// @brief Update RegionInfo after a basic block was split.
800  ///
801  /// @param NewBB The basic block that was created before OldBB.
802  /// @param OldBB The old basic block.
803  void splitBlock(BlockT *NewBB, BlockT *OldBB);
804 
805  /// @brief Clear the Node Cache for all Regions.
806  ///
807  /// @see Region::clearNodeCache()
808  void clearNodeCache() {
809  if (TopLevelRegion)
810  TopLevelRegion->clearNodeCache();
811  }
812 
813  void verifyAnalysis() const;
814 };
815 
816 class Region;
817 
818 class RegionNode : public RegionNodeBase<RegionTraits<Function>> {
819 public:
820  inline RegionNode(Region *Parent, BasicBlock *Entry, bool isSubRegion = false)
821  : RegionNodeBase<RegionTraits<Function>>(Parent, Entry, isSubRegion) {}
822 
823  bool operator==(const Region &RN) const {
824  return this == reinterpret_cast<const RegionNode *>(&RN);
825  }
826 };
827 
828 class Region : public RegionBase<RegionTraits<Function>> {
829 public:
830  Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo *RI, DominatorTree *DT,
831  Region *Parent = nullptr);
832  ~Region();
833 
834  bool operator==(const RegionNode &RN) const {
835  return &RN == reinterpret_cast<const RegionNode *>(this);
836  }
837 };
838 
839 class RegionInfo : public RegionInfoBase<RegionTraits<Function>> {
840 public:
841  explicit RegionInfo();
842 
843  ~RegionInfo() override;
844 
845  // updateStatistics - Update statistic about created regions.
846  void updateStatistics(Region *R) final;
847 
849  DominanceFrontier *DF);
850 };
851 
852 class RegionInfoPass : public FunctionPass {
853  RegionInfo RI;
854 
855 public:
856  static char ID;
857  explicit RegionInfoPass();
858 
859  ~RegionInfoPass() override;
860 
861  RegionInfo &getRegionInfo() { return RI; }
862 
863  const RegionInfo &getRegionInfo() const { return RI; }
864 
865  /// @name FunctionPass interface
866  //@{
867  bool runOnFunction(Function &F) override;
868  void releaseMemory() override;
869  void verifyAnalysis() const override;
870  void getAnalysisUsage(AnalysisUsage &AU) const override;
871  void print(raw_ostream &OS, const Module *) const override;
872  void dump() const;
873  //@}
874 };
875 
876 template <>
877 template <>
878 inline BasicBlock *
879 RegionNodeBase<RegionTraits<Function>>::getNodeAs<BasicBlock>() const {
880  assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
881  return getEntry();
882 }
883 
884 template <>
885 template <>
886 inline Region *
887 RegionNodeBase<RegionTraits<Function>>::getNodeAs<Region>() const {
888  assert(isSubRegion() && "This is not a subregion RegionNode!");
889  auto Unconst = const_cast<RegionNodeBase<RegionTraits<Function>> *>(this);
890  return reinterpret_cast<Region *>(Unconst);
891 }
892 
893 template <class Tr>
895  const RegionNodeBase<Tr> &Node) {
896  typedef typename Tr::BlockT BlockT;
897  typedef typename Tr::RegionT RegionT;
898 
899  if (Node.isSubRegion())
900  return OS << Node.template getNodeAs<RegionT>()->getNameStr();
901  else
902  return OS << Node.template getNodeAs<BlockT>()->getName();
903 }
904 
905 extern template class RegionBase<RegionTraits<Function>>;
906 extern template class RegionNodeBase<RegionTraits<Function>>;
907 extern template class RegionInfoBase<RegionTraits<Function>>;
908 
909 } // End llvm namespace
910 #endif
RegionT * getCommonRegion(BlockT *A, BlockT *B) const
Find the smallest region that contains two basic blocks.
Definition: RegionInfo.h:781
iterator begin()
Definition: RegionInfo.h:548
std::string getNameStr() const
Returns the name of the Region.
block_iterator_wrapper< false > block_iterator
Definition: RegionInfo.h:594
RegionNodeT * getNode() const
Get the RegionNode representing the current Region.
Definition: RegionInfo.h:363
Various leaf nodes.
Definition: ISDOpcodes.h:60
Tr::RegionT RegionT
Definition: RegionInfo.h:115
bool isSimple() const
Is this a simple region?
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: GraphTraits.h:27
static RegionT::PrintStyle printStyle
Definition: RegionInfo.h:734
const RegionInfo & getRegionInfo() const
Definition: RegionInfo.h:863
void print(raw_ostream &OS, bool printTree=true, unsigned level=0, PrintStyle Style=PrintNone) const
Print the region.
pointer operator*() const
BlockT * getExitingBlock() const
Return the first block of this region's single exit edge, if existing.
void print(raw_ostream &OS, const Module *) const override
print - Print out the internal state of the pass.
Definition: RegionInfo.cpp:144
RegionNodeBase(RegionT *Parent, BlockT *Entry, bool isSubRegion=false)
Create a RegionNode.
Definition: RegionInfo.h:146
block_iterator_wrapper(pointer Entry, pointer Exit)
Definition: RegionInfo.h:573
bool contains(const InstT *Inst) const
Check if the region contains an Instruction.
Definition: RegionInfo.h:457
bool contains(const RegionT *SubRegion) const
Check if the region contains another region.
Definition: RegionInfo.h:442
BlockT * getEntry() const
Get the entry BasicBlock of this RegionNode.
Definition: RegionInfo.h:167
bool isSubRegion() const
Is this RegionNode a subregion?
Definition: RegionInfo.h:181
F(f)
void setRegionFor(BlockT *BB, RegionT *R)
Set the smallest region that surrounds a basic block.
RegionT * getTopLevelRegion() const
Definition: RegionInfo.h:797
void recalculate(Function &F, DominatorTree *DT, PostDominatorTree *PDT, DominanceFrontier *DF)
Definition: RegionInfo.cpp:94
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: RegionInfo.cpp:137
T * getNodeAs() const
Get the content of this RegionNode.
Analysis that detects all canonical Regions.
Definition: RegionInfo.h:75
RegionT * getRegionFor(BlockT *BB) const
Get the smallest region that contains a BasicBlock.
RegionInfoT * getRegionInfo() const
Return the RegionInfo object, that belongs to this Region.
Definition: RegionInfo.h:414
iterator_range< const_block_iterator > const_block_range
Definition: RegionInfo.h:607
unsigned getDepth() const
Get the nesting level of this Region.
LoopT * outermostLoopInRegion(LoopT *L) const
Get the outermost loop in the region that contains a loop.
void clearNodeCache()
Clear the cache for BB RegionNodes.
A RegionNode represents a subregion or a BasicBlock that is part of a Region.
Definition: RegionInfo.h:110
block_iterator_wrapper< true > const_block_iterator
Definition: RegionInfo.h:595
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APInt.h:33
RegionT * getParent() const
Get the parent of the Region.
Definition: RegionInfo.h:357
static StringRef getName(Value *V)
RegionInfo & getRegionInfo()
Definition: RegionInfo.h:861
block_range blocks()
Returns a range view of the basic blocks in the region.
Definition: RegionInfo.h:610
RegionNodeT * getBBNode(BlockT *BB) const
Get the BasicBlock RegionNode for a BasicBlock.
void print(raw_ostream &OS) const
super::pointer pointer
BlockT * getMaxRegionExit(BlockT *BB) const
Return the exit of the maximal refined region, that starts at a BasicBlock.
PrintStyle
PrintStyle - Print region in difference ways.
Definition: RegionInfo.h:417
void verifyAnalysis() const
RegionSet::iterator iterator
Definition: RegionInfo.h:545
Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo *RI, DominatorTree *DT, Region *Parent=nullptr)
Definition: RegionInfo.cpp:64
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
Definition: RegionInfo.cpp:133
~RegionInfo() override
Definition: RegionInfo.cpp:82
Base class for the actual dominator tree node.
void dump() const
Definition: RegionInfo.cpp:149
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:67
iterator end()
Definition: RegionInfo.h:549
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Definition: InstrTypes.h:57
const_block_iterator block_begin() const
Definition: RegionInfo.h:601
df_iterator< RegionNodeT *, SmallPtrSet< RegionNodeT *, 8 >, false, GraphTraits< RegionNodeT * > > element_iterator
Definition: RegionInfo.h:629
RegionT * getParent() const
Get the parent Region of this RegionNode.
Definition: RegionInfo.h:159
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
void dump() const
Print the region to stderr.
df_iterator< T > df_end(const T &G)
PostDominatorTree PostDomTreeT
Definition: RegionInfo.h:87
void addSubRegion(RegionT *SubRegion, bool moveChildren=false)
Add a new subregion to this Region.
void replaceExit(BlockT *BB)
Replace the exit basic block of the region with the new basic block.
element_iterator element_end()
const_iterator begin() const
Definition: RegionInfo.h:551
bool operator==(const RegionNode &RN) const
Definition: RegionInfo.h:834
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
void transferChildrenTo(RegionT *To)
Move all direct child nodes of this Region to another Region.
IntType getInt() const
iterator_range< block_iterator > block_range
Definition: RegionInfo.h:606
const_block_range blocks() const
Returns a range view of the basic blocks in the region.
Definition: RegionInfo.h:617
block_iterator_wrapper< IsConst > Self
Definition: RegionInfo.h:569
PointerTy getPointer() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
df_iterator< const RegionNodeT *, SmallPtrSet< const RegionNodeT *, 8 >, false, GraphTraits< const RegionNodeT * > > const_element_iterator
Definition: RegionInfo.h:633
~RegionInfoPass() override
Definition: RegionInfo.cpp:114
void replaceEntryRecursive(BlockT *NewEntry)
Recursively replace the entry basic block of the region.
RegionT * getSubRegionNode(BlockT *BB) const
Get the subregion that starts at a BasicBlock.
RegionT * getExpandedRegion() const
Return a new (non-canonical) region, that is obtained by joining this region with its predecessors...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: RegionInfo.cpp:129
A single entry single exit Region.
Definition: RegionInfo.h:71
void replaceEntry(BlockT *BB)
Replace the entry basic block of the region with the new basic block.
df_iterator< T > df_begin(const T &G)
A range adaptor for a pair of iterators.
element_iterator element_begin()
void splitBlock(BlockT *NewBB, BlockT *OldBB)
Update RegionInfo after a basic block was split.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
FuncT_::UnknownRegionTypeError BrokenT
Definition: RegionInfo.h:60
block_iterator block_begin()
Definition: RegionInfo.h:597
DominanceFrontier DomFrontierT
Definition: RegionInfo.h:86
block_iterator block_end()
Definition: RegionInfo.h:599
void replaceExitRecursive(BlockT *NewExit)
Recursively replace the exit basic block of the region.
BlockT * getEnteringBlock() const
Return the first block of this region's single entry edge, if existing.
bool operator==(const Region &RN) const
Definition: RegionInfo.h:823
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
RegionNode(Region *Parent, BasicBlock *Entry, bool isSubRegion=false)
Definition: RegionInfo.h:820
void verifyRegion() const
Verify if the region is a correct region.
Marker class to iterate over the elements of a Region in flat mode.
Definition: RegionInfo.h:105
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:1738
RegionSet::const_iterator const_iterator
Definition: RegionInfo.h:546
~RegionBase()
Delete the Region and all its subregions.
BlockT * getExit() const
Get the exit BasicBlock of the Region.
Definition: RegionInfo.h:352
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Definition: RegionInfo.cpp:118
RegionT * operator[](BlockT *BB) const
A shortcut for getRegionFor().
void clearNodeCache()
Clear the Node Cache for all Regions.
Definition: RegionInfo.h:808
RegionT * getCommonRegion(RegionT *A, RegionT *B) const
Find the smallest region that contains two regions.
BlockT * getEntry() const
Get the entry BasicBlock of the Region.
Definition: RegionInfo.h:315
bool contains(const BlockT *BB) const
Check if the region contains a BasicBlock.
const_block_iterator block_end() const
Definition: RegionInfo.h:604
static bool VerifyRegionInfo
Definition: RegionInfo.h:733
void updateStatistics(Region *R) final
Definition: RegionInfo.cpp:86
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
const_iterator end() const
Definition: RegionInfo.h:552
RegionT * removeSubRegion(RegionT *SubRegion)
Remove a subregion from this Region.
static unsigned getNumSuccessors(BasicBlock *BB)
Definition: RegionInfo.h:92
bool isTopLevelRegion() const
Check if a Region is the TopLevel region.
Definition: RegionInfo.h:378