Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:16

0001 //===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // Calculate a program structure tree built out of single entry single exit
0010 // regions.
0011 // The basic ideas are taken from "The Program Structure Tree - Richard Johnson,
0012 // David Pearson, Keshav Pingali - 1994", however enriched with ideas from "The
0013 // Refined Process Structure Tree - Jussi Vanhatalo, Hagen Voelyer, Jana
0014 // Koehler - 2009".
0015 // The algorithm to calculate these data structures however is completely
0016 // different, as it takes advantage of existing information already available
0017 // in (Post)dominace tree and dominance frontier passes. This leads to a simpler
0018 // and in practice hopefully better performing algorithm. The runtime of the
0019 // algorithms described in the papers above are both linear in graph size,
0020 // O(V+E), whereas this algorithm is not, as the dominance frontier information
0021 // itself is not, but in practice runtime seems to be in the order of magnitude
0022 // of dominance tree calculation.
0023 //
0024 // WARNING: LLVM is generally very concerned about compile time such that
0025 //          the use of additional analysis passes in the default
0026 //          optimization sequence is avoided as much as possible.
0027 //          Specifically, if you do not need the RegionInfo, but dominance
0028 //          information could be sufficient please base your work only on
0029 //          the dominator tree. Most passes maintain it, such that using
0030 //          it has often near zero cost. In contrast RegionInfo is by
0031 //          default not available, is not maintained by existing
0032 //          transformations and there is no intention to do so.
0033 //
0034 //===----------------------------------------------------------------------===//
0035 
0036 #ifndef LLVM_ANALYSIS_REGIONINFO_H
0037 #define LLVM_ANALYSIS_REGIONINFO_H
0038 
0039 #include "llvm/ADT/DenseMap.h"
0040 #include "llvm/ADT/DepthFirstIterator.h"
0041 #include "llvm/ADT/GraphTraits.h"
0042 #include "llvm/ADT/PointerIntPair.h"
0043 #include "llvm/ADT/iterator_range.h"
0044 #include "llvm/IR/Dominators.h"
0045 #include "llvm/IR/PassManager.h"
0046 #include "llvm/Pass.h"
0047 #include <algorithm>
0048 #include <cassert>
0049 #include <map>
0050 #include <memory>
0051 #include <set>
0052 #include <string>
0053 #include <type_traits>
0054 #include <vector>
0055 
0056 namespace llvm {
0057 
0058 class DominanceFrontier;
0059 class Loop;
0060 class LoopInfo;
0061 class PostDominatorTree;
0062 class Region;
0063 template <class RegionTr> class RegionBase;
0064 class RegionInfo;
0065 template <class RegionTr> class RegionInfoBase;
0066 class RegionNode;
0067 class raw_ostream;
0068 
0069 // Class to be specialized for different users of RegionInfo
0070 // (i.e. BasicBlocks or MachineBasicBlocks). This is only to avoid needing to
0071 // pass around an unreasonable number of template parameters.
0072 template <class FuncT_>
0073 struct RegionTraits {
0074   // FuncT
0075   // BlockT
0076   // RegionT
0077   // RegionNodeT
0078   // RegionInfoT
0079   using BrokenT = typename FuncT_::UnknownRegionTypeError;
0080 };
0081 
0082 template <>
0083 struct RegionTraits<Function> {
0084   using FuncT = Function;
0085   using BlockT = BasicBlock;
0086   using RegionT = Region;
0087   using RegionNodeT = RegionNode;
0088   using RegionInfoT = RegionInfo;
0089   using DomTreeT = DominatorTree;
0090   using DomTreeNodeT = DomTreeNode;
0091   using DomFrontierT = DominanceFrontier;
0092   using PostDomTreeT = PostDominatorTree;
0093   using InstT = Instruction;
0094   using LoopT = Loop;
0095   using LoopInfoT = LoopInfo;
0096 
0097   static unsigned getNumSuccessors(BasicBlock *BB) {
0098     return BB->getTerminator()->getNumSuccessors();
0099   }
0100 };
0101 
0102 /// Marker class to iterate over the elements of a Region in flat mode.
0103 ///
0104 /// The class is used to either iterate in Flat mode or by not using it to not
0105 /// iterate in Flat mode.  During a Flat mode iteration all Regions are entered
0106 /// and the iteration returns every BasicBlock.  If the Flat mode is not
0107 /// selected for SubRegions just one RegionNode containing the subregion is
0108 /// returned.
0109 template <class GraphType>
0110 class FlatIt {};
0111 
0112 /// A RegionNode represents a subregion or a BasicBlock that is part of a
0113 /// Region.
0114 template <class Tr>
0115 class RegionNodeBase {
0116   friend class RegionBase<Tr>;
0117 
0118 public:
0119   using BlockT = typename Tr::BlockT;
0120   using RegionT = typename Tr::RegionT;
0121 
0122 private:
0123   /// This is the entry basic block that starts this region node.  If this is a
0124   /// BasicBlock RegionNode, then entry is just the basic block, that this
0125   /// RegionNode represents.  Otherwise it is the entry of this (Sub)RegionNode.
0126   ///
0127   /// In the BBtoRegionNode map of the parent of this node, BB will always map
0128   /// to this node no matter which kind of node this one is.
0129   ///
0130   /// The node can hold either a Region or a BasicBlock.
0131   /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
0132   /// RegionNode.
0133   PointerIntPair<BlockT *, 1, bool> entry;
0134 
0135   /// The parent Region of this RegionNode.
0136   /// @see getParent()
0137   RegionT *parent;
0138 
0139 protected:
0140   /// Create a RegionNode.
0141   ///
0142   /// @param Parent      The parent of this RegionNode.
0143   /// @param Entry       The entry BasicBlock of the RegionNode.  If this
0144   ///                    RegionNode represents a BasicBlock, this is the
0145   ///                    BasicBlock itself.  If it represents a subregion, this
0146   ///                    is the entry BasicBlock of the subregion.
0147   /// @param isSubRegion If this RegionNode represents a SubRegion.
0148   inline RegionNodeBase(RegionT *Parent, BlockT *Entry,
0149                         bool isSubRegion = false)
0150       : entry(Entry, isSubRegion), parent(Parent) {}
0151 
0152 public:
0153   RegionNodeBase(const RegionNodeBase &) = delete;
0154   RegionNodeBase &operator=(const RegionNodeBase &) = delete;
0155 
0156   /// Get the parent Region of this RegionNode.
0157   ///
0158   /// The parent Region is the Region this RegionNode belongs to. If for
0159   /// example a BasicBlock is element of two Regions, there exist two
0160   /// RegionNodes for this BasicBlock. Each with the getParent() function
0161   /// pointing to the Region this RegionNode belongs to.
0162   ///
0163   /// @return Get the parent Region of this RegionNode.
0164   inline RegionT *getParent() const { return parent; }
0165 
0166   /// Get the entry BasicBlock of this RegionNode.
0167   ///
0168   /// If this RegionNode represents a BasicBlock this is just the BasicBlock
0169   /// itself, otherwise we return the entry BasicBlock of the Subregion
0170   ///
0171   /// @return The entry BasicBlock of this RegionNode.
0172   inline BlockT *getEntry() const { return entry.getPointer(); }
0173 
0174   /// Get the content of this RegionNode.
0175   ///
0176   /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
0177   /// check the type of the content with the isSubRegion() function call.
0178   ///
0179   /// @return The content of this RegionNode.
0180   template <class T> inline T *getNodeAs() const;
0181 
0182   /// Is this RegionNode a subregion?
0183   ///
0184   /// @return True if it contains a subregion. False if it contains a
0185   ///         BasicBlock.
0186   inline bool isSubRegion() const { return entry.getInt(); }
0187 };
0188 
0189 //===----------------------------------------------------------------------===//
0190 /// A single entry single exit Region.
0191 ///
0192 /// A Region is a connected subgraph of a control flow graph that has exactly
0193 /// two connections to the remaining graph. It can be used to analyze or
0194 /// optimize parts of the control flow graph.
0195 ///
0196 /// A <em> simple Region </em> is connected to the remaining graph by just two
0197 /// edges. One edge entering the Region and another one leaving the Region.
0198 ///
0199 /// An <em> extended Region </em> (or just Region) is a subgraph that can be
0200 /// transform into a simple Region. The transformation is done by adding
0201 /// BasicBlocks that merge several entry or exit edges so that after the merge
0202 /// just one entry and one exit edge exists.
0203 ///
0204 /// The \e Entry of a Region is the first BasicBlock that is passed after
0205 /// entering the Region. It is an element of the Region. The entry BasicBlock
0206 /// dominates all BasicBlocks in the Region.
0207 ///
0208 /// The \e Exit of a Region is the first BasicBlock that is passed after
0209 /// leaving the Region. It is not an element of the Region. The exit BasicBlock,
0210 /// postdominates all BasicBlocks in the Region.
0211 ///
0212 /// A <em> canonical Region </em> cannot be constructed by combining smaller
0213 /// Regions.
0214 ///
0215 /// Region A is the \e parent of Region B, if B is completely contained in A.
0216 ///
0217 /// Two canonical Regions either do not intersect at all or one is
0218 /// the parent of the other.
0219 ///
0220 /// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
0221 /// Regions in the control flow graph and E is the \e parent relation of these
0222 /// Regions.
0223 ///
0224 /// Example:
0225 ///
0226 /// \verbatim
0227 /// A simple control flow graph, that contains two regions.
0228 ///
0229 ///        1
0230 ///       / |
0231 ///      2   |
0232 ///     / \   3
0233 ///    4   5  |
0234 ///    |   |  |
0235 ///    6   7  8
0236 ///     \  | /
0237 ///      \ |/       Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
0238 ///        9        Region B: 2 -> 9 {2,4,5,6,7}
0239 /// \endverbatim
0240 ///
0241 /// You can obtain more examples by either calling
0242 ///
0243 /// <tt> "opt -passes='print<regions>' anyprogram.ll" </tt>
0244 /// or
0245 /// <tt> "opt -view-regions-only anyprogram.ll" </tt>
0246 ///
0247 /// on any LLVM file you are interested in.
0248 ///
0249 /// The first call returns a textual representation of the program structure
0250 /// tree, the second one creates a graphical representation using graphviz.
0251 template <class Tr>
0252 class RegionBase : public RegionNodeBase<Tr> {
0253   friend class RegionInfoBase<Tr>;
0254 
0255   using FuncT = typename Tr::FuncT;
0256   using BlockT = typename Tr::BlockT;
0257   using RegionInfoT = typename Tr::RegionInfoT;
0258   using RegionT = typename Tr::RegionT;
0259   using RegionNodeT = typename Tr::RegionNodeT;
0260   using DomTreeT = typename Tr::DomTreeT;
0261   using LoopT = typename Tr::LoopT;
0262   using LoopInfoT = typename Tr::LoopInfoT;
0263   using InstT = typename Tr::InstT;
0264 
0265   using BlockTraits = GraphTraits<BlockT *>;
0266   using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
0267   using SuccIterTy = typename BlockTraits::ChildIteratorType;
0268   using PredIterTy = typename InvBlockTraits::ChildIteratorType;
0269 
0270   // Information necessary to manage this Region.
0271   RegionInfoT *RI;
0272   DomTreeT *DT;
0273 
0274   // The exit BasicBlock of this region.
0275   // (The entry BasicBlock is part of RegionNode)
0276   BlockT *exit;
0277 
0278   using RegionSet = std::vector<std::unique_ptr<RegionT>>;
0279 
0280   // The subregions of this region.
0281   RegionSet children;
0282 
0283   using BBNodeMapT = std::map<BlockT *, std::unique_ptr<RegionNodeT>>;
0284 
0285   // Save the BasicBlock RegionNodes that are element of this Region.
0286   mutable BBNodeMapT BBNodeMap;
0287 
0288   /// Check if a BB is in this Region. This check also works
0289   /// if the region is incorrectly built. (EXPENSIVE!)
0290   void verifyBBInRegion(BlockT *BB) const;
0291 
0292   /// Walk over all the BBs of the region starting from BB and
0293   /// verify that all reachable basic blocks are elements of the region.
0294   /// (EXPENSIVE!)
0295   void verifyWalk(BlockT *BB, std::set<BlockT *> *visitedBB) const;
0296 
0297   /// Verify if the region and its children are valid regions (EXPENSIVE!)
0298   void verifyRegionNest() const;
0299 
0300 public:
0301   /// Create a new region.
0302   ///
0303   /// @param Entry  The entry basic block of the region.
0304   /// @param Exit   The exit basic block of the region.
0305   /// @param RI     The region info object that is managing this region.
0306   /// @param DT     The dominator tree of the current function.
0307   /// @param Parent The surrounding region or NULL if this is a top level
0308   ///               region.
0309   RegionBase(BlockT *Entry, BlockT *Exit, RegionInfoT *RI, DomTreeT *DT,
0310              RegionT *Parent = nullptr);
0311 
0312   RegionBase(const RegionBase &) = delete;
0313   RegionBase &operator=(const RegionBase &) = delete;
0314 
0315   /// Delete the Region and all its subregions.
0316   ~RegionBase();
0317 
0318   /// Get the entry BasicBlock of the Region.
0319   /// @return The entry BasicBlock of the region.
0320   BlockT *getEntry() const {
0321     return RegionNodeBase<Tr>::getEntry();
0322   }
0323 
0324   /// Replace the entry basic block of the region with the new basic
0325   ///        block.
0326   ///
0327   /// @param BB  The new entry basic block of the region.
0328   void replaceEntry(BlockT *BB);
0329 
0330   /// Replace the exit basic block of the region with the new basic
0331   ///        block.
0332   ///
0333   /// @param BB  The new exit basic block of the region.
0334   void replaceExit(BlockT *BB);
0335 
0336   /// Recursively replace the entry basic block of the region.
0337   ///
0338   /// This function replaces the entry basic block with a new basic block. It
0339   /// also updates all child regions that have the same entry basic block as
0340   /// this region.
0341   ///
0342   /// @param NewEntry The new entry basic block.
0343   void replaceEntryRecursive(BlockT *NewEntry);
0344 
0345   /// Recursively replace the exit basic block of the region.
0346   ///
0347   /// This function replaces the exit basic block with a new basic block. It
0348   /// also updates all child regions that have the same exit basic block as
0349   /// this region.
0350   ///
0351   /// @param NewExit The new exit basic block.
0352   void replaceExitRecursive(BlockT *NewExit);
0353 
0354   /// Get the exit BasicBlock of the Region.
0355   /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
0356   ///         Region.
0357   BlockT *getExit() const { return exit; }
0358 
0359   /// Get the parent of the Region.
0360   /// @return The parent of the Region or NULL if this is a top level
0361   ///         Region.
0362   RegionT *getParent() const {
0363     return RegionNodeBase<Tr>::getParent();
0364   }
0365 
0366   /// Get the RegionNode representing the current Region.
0367   /// @return The RegionNode representing the current Region.
0368   RegionNodeT *getNode() const {
0369     return const_cast<RegionNodeT *>(
0370         reinterpret_cast<const RegionNodeT *>(this));
0371   }
0372 
0373   /// Get the nesting level of this Region.
0374   ///
0375   /// An toplevel Region has depth 0.
0376   ///
0377   /// @return The depth of the region.
0378   unsigned getDepth() const;
0379 
0380   /// Check if a Region is the TopLevel region.
0381   ///
0382   /// The toplevel region represents the whole function.
0383   bool isTopLevelRegion() const { return exit == nullptr; }
0384 
0385   /// Return a new (non-canonical) region, that is obtained by joining
0386   ///        this region with its predecessors.
0387   ///
0388   /// @return A region also starting at getEntry(), but reaching to the next
0389   ///         basic block that forms with getEntry() a (non-canonical) region.
0390   ///         NULL if such a basic block does not exist.
0391   RegionT *getExpandedRegion() const;
0392 
0393   /// Return the first block of this region's single entry edge,
0394   ///        if existing.
0395   ///
0396   /// @return The BasicBlock starting this region's single entry edge,
0397   ///         else NULL.
0398   BlockT *getEnteringBlock() const;
0399 
0400   /// Return the first block of this region's single exit edge,
0401   ///        if existing.
0402   ///
0403   /// @return The BasicBlock starting this region's single exit edge,
0404   ///         else NULL.
0405   BlockT *getExitingBlock() const;
0406 
0407   /// Collect all blocks of this region's single exit edge, if existing.
0408   ///
0409   /// @return True if this region contains all the predecessors of the exit.
0410   bool getExitingBlocks(SmallVectorImpl<BlockT *> &Exitings) const;
0411 
0412   /// Is this a simple region?
0413   ///
0414   /// A region is simple if it has exactly one exit and one entry edge.
0415   ///
0416   /// @return True if the Region is simple.
0417   bool isSimple() const;
0418 
0419   /// Returns the name of the Region.
0420   /// @return The Name of the Region.
0421   std::string getNameStr() const;
0422 
0423   /// Return the RegionInfo object, that belongs to this Region.
0424   RegionInfoT *getRegionInfo() const { return RI; }
0425 
0426   /// PrintStyle - Print region in difference ways.
0427   enum PrintStyle { PrintNone, PrintBB, PrintRN };
0428 
0429   /// Print the region.
0430   ///
0431   /// @param OS The output stream the Region is printed to.
0432   /// @param printTree Print also the tree of subregions.
0433   /// @param level The indentation level used for printing.
0434   void print(raw_ostream &OS, bool printTree = true, unsigned level = 0,
0435              PrintStyle Style = PrintNone) const;
0436 
0437 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
0438   /// Print the region to stderr.
0439   void dump() const;
0440 #endif
0441 
0442   /// Check if the region contains a BasicBlock.
0443   ///
0444   /// @param BB The BasicBlock that might be contained in this Region.
0445   /// @return True if the block is contained in the region otherwise false.
0446   bool contains(const BlockT *BB) const;
0447 
0448   /// Check if the region contains another region.
0449   ///
0450   /// @param SubRegion The region that might be contained in this Region.
0451   /// @return True if SubRegion is contained in the region otherwise false.
0452   bool contains(const RegionT *SubRegion) const {
0453     // Toplevel Region.
0454     if (!getExit())
0455       return true;
0456 
0457     return contains(SubRegion->getEntry()) &&
0458            (contains(SubRegion->getExit()) ||
0459             SubRegion->getExit() == getExit());
0460   }
0461 
0462   /// Check if the region contains an Instruction.
0463   ///
0464   /// @param Inst The Instruction that might be contained in this region.
0465   /// @return True if the Instruction is contained in the region otherwise
0466   /// false.
0467   bool contains(const InstT *Inst) const { return contains(Inst->getParent()); }
0468 
0469   /// Check if the region contains a loop.
0470   ///
0471   /// @param L The loop that might be contained in this region.
0472   /// @return True if the loop is contained in the region otherwise false.
0473   ///         In case a NULL pointer is passed to this function the result
0474   ///         is false, except for the region that describes the whole function.
0475   ///         In that case true is returned.
0476   bool contains(const LoopT *L) const;
0477 
0478   /// Get the outermost loop in the region that contains a loop.
0479   ///
0480   /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
0481   /// and is itself contained in the region.
0482   ///
0483   /// @param L The loop the lookup is started.
0484   /// @return The outermost loop in the region, NULL if such a loop does not
0485   ///         exist or if the region describes the whole function.
0486   LoopT *outermostLoopInRegion(LoopT *L) const;
0487 
0488   /// Get the outermost loop in the region that contains a basic block.
0489   ///
0490   /// Find for a basic block BB the outermost loop L that contains BB and is
0491   /// itself contained in the region.
0492   ///
0493   /// @param LI A pointer to a LoopInfo analysis.
0494   /// @param BB The basic block surrounded by the loop.
0495   /// @return The outermost loop in the region, NULL if such a loop does not
0496   ///         exist or if the region describes the whole function.
0497   LoopT *outermostLoopInRegion(LoopInfoT *LI, BlockT *BB) const;
0498 
0499   /// Get the subregion that starts at a BasicBlock
0500   ///
0501   /// @param BB The BasicBlock the subregion should start.
0502   /// @return The Subregion if available, otherwise NULL.
0503   RegionT *getSubRegionNode(BlockT *BB) const;
0504 
0505   /// Get the RegionNode for a BasicBlock
0506   ///
0507   /// @param BB The BasicBlock at which the RegionNode should start.
0508   /// @return If available, the RegionNode that represents the subregion
0509   ///         starting at BB. If no subregion starts at BB, the RegionNode
0510   ///         representing BB.
0511   RegionNodeT *getNode(BlockT *BB) const;
0512 
0513   /// Get the BasicBlock RegionNode for a BasicBlock
0514   ///
0515   /// @param BB The BasicBlock for which the RegionNode is requested.
0516   /// @return The RegionNode representing the BB.
0517   RegionNodeT *getBBNode(BlockT *BB) const;
0518 
0519   /// Add a new subregion to this Region.
0520   ///
0521   /// @param SubRegion The new subregion that will be added.
0522   /// @param moveChildren Move the children of this region, that are also
0523   ///                     contained in SubRegion into SubRegion.
0524   void addSubRegion(RegionT *SubRegion, bool moveChildren = false);
0525 
0526   /// Remove a subregion from this Region.
0527   ///
0528   /// The subregion is not deleted, as it will probably be inserted into another
0529   /// region.
0530   /// @param SubRegion The SubRegion that will be removed.
0531   RegionT *removeSubRegion(RegionT *SubRegion);
0532 
0533   /// Move all direct child nodes of this Region to another Region.
0534   ///
0535   /// @param To The Region the child nodes will be transferred to.
0536   void transferChildrenTo(RegionT *To);
0537 
0538   /// Verify if the region is a correct region.
0539   ///
0540   /// Check if this is a correctly build Region. This is an expensive check, as
0541   /// the complete CFG of the Region will be walked.
0542   void verifyRegion() const;
0543 
0544   /// Clear the cache for BB RegionNodes.
0545   ///
0546   /// After calling this function the BasicBlock RegionNodes will be stored at
0547   /// different memory locations. RegionNodes obtained before this function is
0548   /// called are therefore not comparable to RegionNodes abtained afterwords.
0549   void clearNodeCache();
0550 
0551   /// @name Subregion Iterators
0552   ///
0553   /// These iterators iterator over all subregions of this Region.
0554   //@{
0555   using iterator = typename RegionSet::iterator;
0556   using const_iterator = typename RegionSet::const_iterator;
0557 
0558   iterator begin() { return children.begin(); }
0559   iterator end() { return children.end(); }
0560 
0561   const_iterator begin() const { return children.begin(); }
0562   const_iterator end() const { return children.end(); }
0563   //@}
0564 
0565   /// @name BasicBlock Iterators
0566   ///
0567   /// These iterators iterate over all BasicBlocks that are contained in this
0568   /// Region. The iterator also iterates over BasicBlocks that are elements of
0569   /// a subregion of this Region. It is therefore called a flat iterator.
0570   //@{
0571   template <bool IsConst>
0572   class block_iterator_wrapper
0573       : public df_iterator<
0574             std::conditional_t<IsConst, const BlockT, BlockT> *> {
0575     using super =
0576         df_iterator<std::conditional_t<IsConst, const BlockT, BlockT> *>;
0577 
0578   public:
0579     using Self = block_iterator_wrapper<IsConst>;
0580     using value_type = typename super::value_type;
0581 
0582     // Construct the begin iterator.
0583     block_iterator_wrapper(value_type Entry, value_type Exit)
0584         : super(df_begin(Entry)) {
0585       // Mark the exit of the region as visited, so that the children of the
0586       // exit and the exit itself, i.e. the block outside the region will never
0587       // be visited.
0588       super::Visited.insert(Exit);
0589     }
0590 
0591     // Construct the end iterator.
0592     block_iterator_wrapper() : super(df_end<value_type>((BlockT *)nullptr)) {}
0593 
0594     /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
0595 
0596     // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
0597     //        This was introduced for backwards compatibility, but should
0598     //        be removed as soon as all users are fixed.
0599     BlockT *operator*() const {
0600       return const_cast<BlockT *>(super::operator*());
0601     }
0602   };
0603 
0604   using block_iterator = block_iterator_wrapper<false>;
0605   using const_block_iterator = block_iterator_wrapper<true>;
0606 
0607   block_iterator block_begin() { return block_iterator(getEntry(), getExit()); }
0608 
0609   block_iterator block_end() { return block_iterator(); }
0610 
0611   const_block_iterator block_begin() const {
0612     return const_block_iterator(getEntry(), getExit());
0613   }
0614   const_block_iterator block_end() const { return const_block_iterator(); }
0615 
0616   using block_range = iterator_range<block_iterator>;
0617   using const_block_range = iterator_range<const_block_iterator>;
0618 
0619   /// Returns a range view of the basic blocks in the region.
0620   inline block_range blocks() {
0621     return block_range(block_begin(), block_end());
0622   }
0623 
0624   /// Returns a range view of the basic blocks in the region.
0625   ///
0626   /// This is the 'const' version of the range view.
0627   inline const_block_range blocks() const {
0628     return const_block_range(block_begin(), block_end());
0629   }
0630   //@}
0631 
0632   /// @name Element Iterators
0633   ///
0634   /// These iterators iterate over all BasicBlock and subregion RegionNodes that
0635   /// are direct children of this Region. It does not iterate over any
0636   /// RegionNodes that are also element of a subregion of this Region.
0637   //@{
0638   using element_iterator =
0639       df_iterator<RegionNodeT *, df_iterator_default_set<RegionNodeT *>, false,
0640                   GraphTraits<RegionNodeT *>>;
0641 
0642   using const_element_iterator =
0643       df_iterator<const RegionNodeT *,
0644                   df_iterator_default_set<const RegionNodeT *>, false,
0645                   GraphTraits<const RegionNodeT *>>;
0646 
0647   element_iterator element_begin();
0648   element_iterator element_end();
0649   iterator_range<element_iterator> elements() {
0650     return make_range(element_begin(), element_end());
0651   }
0652 
0653   const_element_iterator element_begin() const;
0654   const_element_iterator element_end() const;
0655   iterator_range<const_element_iterator> elements() const {
0656     return make_range(element_begin(), element_end());
0657   }
0658   //@}
0659 };
0660 
0661 /// Print a RegionNode.
0662 template <class Tr>
0663 inline raw_ostream &operator<<(raw_ostream &OS, const RegionNodeBase<Tr> &Node);
0664 
0665 //===----------------------------------------------------------------------===//
0666 /// Analysis that detects all canonical Regions.
0667 ///
0668 /// The RegionInfo pass detects all canonical regions in a function. The Regions
0669 /// are connected using the parent relation. This builds a Program Structure
0670 /// Tree.
0671 template <class Tr>
0672 class RegionInfoBase {
0673   friend class RegionInfo;
0674   friend class MachineRegionInfo;
0675 
0676   using BlockT = typename Tr::BlockT;
0677   using FuncT = typename Tr::FuncT;
0678   using RegionT = typename Tr::RegionT;
0679   using RegionInfoT = typename Tr::RegionInfoT;
0680   using DomTreeT = typename Tr::DomTreeT;
0681   using DomTreeNodeT = typename Tr::DomTreeNodeT;
0682   using PostDomTreeT = typename Tr::PostDomTreeT;
0683   using DomFrontierT = typename Tr::DomFrontierT;
0684   using BlockTraits = GraphTraits<BlockT *>;
0685   using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
0686   using SuccIterTy = typename BlockTraits::ChildIteratorType;
0687   using PredIterTy = typename InvBlockTraits::ChildIteratorType;
0688 
0689   using BBtoBBMap = DenseMap<BlockT *, BlockT *>;
0690   using BBtoRegionMap = DenseMap<BlockT *, RegionT *>;
0691 
0692   RegionInfoBase();
0693 
0694   RegionInfoBase(RegionInfoBase &&Arg)
0695     : DT(std::move(Arg.DT)), PDT(std::move(Arg.PDT)), DF(std::move(Arg.DF)),
0696       TopLevelRegion(std::move(Arg.TopLevelRegion)),
0697       BBtoRegion(std::move(Arg.BBtoRegion)) {
0698     Arg.wipe();
0699   }
0700 
0701   RegionInfoBase &operator=(RegionInfoBase &&RHS) {
0702     DT = std::move(RHS.DT);
0703     PDT = std::move(RHS.PDT);
0704     DF = std::move(RHS.DF);
0705     TopLevelRegion = std::move(RHS.TopLevelRegion);
0706     BBtoRegion = std::move(RHS.BBtoRegion);
0707     RHS.wipe();
0708     return *this;
0709   }
0710 
0711   virtual ~RegionInfoBase();
0712 
0713   DomTreeT *DT;
0714   PostDomTreeT *PDT;
0715   DomFrontierT *DF;
0716 
0717   /// The top level region.
0718   RegionT *TopLevelRegion = nullptr;
0719 
0720   /// Map every BB to the smallest region, that contains BB.
0721   BBtoRegionMap BBtoRegion;
0722 
0723 protected:
0724   /// Update refences to a RegionInfoT held by the RegionT managed here
0725   ///
0726   /// This is a post-move helper. Regions hold references to the owning
0727   /// RegionInfo object. After a move these need to be fixed.
0728   template<typename TheRegionT>
0729   void updateRegionTree(RegionInfoT &RI, TheRegionT *R) {
0730     if (!R)
0731       return;
0732     R->RI = &RI;
0733     for (auto &SubR : *R)
0734       updateRegionTree(RI, SubR.get());
0735   }
0736 
0737 private:
0738   /// Wipe this region tree's state without releasing any resources.
0739   ///
0740   /// This is essentially a post-move helper only. It leaves the object in an
0741   /// assignable and destroyable state, but otherwise invalid.
0742   void wipe() {
0743     DT = nullptr;
0744     PDT = nullptr;
0745     DF = nullptr;
0746     TopLevelRegion = nullptr;
0747     BBtoRegion.clear();
0748   }
0749 
0750   // Check whether the entries of BBtoRegion for the BBs of region
0751   // SR are correct. Triggers an assertion if not. Calls itself recursively for
0752   // subregions.
0753   void verifyBBMap(const RegionT *SR) const;
0754 
0755   // Returns true if BB is in the dominance frontier of
0756   // entry, because it was inherited from exit. In the other case there is an
0757   // edge going from entry to BB without passing exit.
0758   bool isCommonDomFrontier(BlockT *BB, BlockT *entry, BlockT *exit) const;
0759 
0760   // Check if entry and exit surround a valid region, based on
0761   // dominance tree and dominance frontier.
0762   bool isRegion(BlockT *entry, BlockT *exit) const;
0763 
0764   // Saves a shortcut pointing from entry to exit.
0765   // This function may extend this shortcut if possible.
0766   void insertShortCut(BlockT *entry, BlockT *exit, BBtoBBMap *ShortCut) const;
0767 
0768   // Returns the next BB that postdominates N, while skipping
0769   // all post dominators that cannot finish a canonical region.
0770   DomTreeNodeT *getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const;
0771 
0772   // A region is trivial, if it contains only one BB.
0773   bool isTrivialRegion(BlockT *entry, BlockT *exit) const;
0774 
0775   // Creates a single entry single exit region.
0776   RegionT *createRegion(BlockT *entry, BlockT *exit);
0777 
0778   // Detect all regions starting with bb 'entry'.
0779   void findRegionsWithEntry(BlockT *entry, BBtoBBMap *ShortCut);
0780 
0781   // Detects regions in F.
0782   void scanForRegions(FuncT &F, BBtoBBMap *ShortCut);
0783 
0784   // Get the top most parent with the same entry block.
0785   RegionT *getTopMostParent(RegionT *region);
0786 
0787   // Build the region hierarchy after all region detected.
0788   void buildRegionsTree(DomTreeNodeT *N, RegionT *region);
0789 
0790   // Update statistic about created regions.
0791   virtual void updateStatistics(RegionT *R) = 0;
0792 
0793   // Detect all regions in function and build the region tree.
0794   void calculate(FuncT &F);
0795 
0796 public:
0797   RegionInfoBase(const RegionInfoBase &) = delete;
0798   RegionInfoBase &operator=(const RegionInfoBase &) = delete;
0799 
0800   static bool VerifyRegionInfo;
0801   static typename RegionT::PrintStyle printStyle;
0802 
0803   void print(raw_ostream &OS) const;
0804 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
0805   void dump() const;
0806 #endif
0807 
0808   void releaseMemory();
0809 
0810   /// Get the smallest region that contains a BasicBlock.
0811   ///
0812   /// @param BB The basic block.
0813   /// @return The smallest region, that contains BB or NULL, if there is no
0814   /// region containing BB.
0815   RegionT *getRegionFor(BlockT *BB) const;
0816 
0817   ///  Set the smallest region that surrounds a basic block.
0818   ///
0819   /// @param BB The basic block surrounded by a region.
0820   /// @param R The smallest region that surrounds BB.
0821   void setRegionFor(BlockT *BB, RegionT *R);
0822 
0823   /// A shortcut for getRegionFor().
0824   ///
0825   /// @param BB The basic block.
0826   /// @return The smallest region, that contains BB or NULL, if there is no
0827   /// region containing BB.
0828   RegionT *operator[](BlockT *BB) const;
0829 
0830   /// Return the exit of the maximal refined region, that starts at a
0831   /// BasicBlock.
0832   ///
0833   /// @param BB The BasicBlock the refined region starts.
0834   BlockT *getMaxRegionExit(BlockT *BB) const;
0835 
0836   /// Find the smallest region that contains two regions.
0837   ///
0838   /// @param A The first region.
0839   /// @param B The second region.
0840   /// @return The smallest region containing A and B.
0841   RegionT *getCommonRegion(RegionT *A, RegionT *B) const;
0842 
0843   /// Find the smallest region that contains two basic blocks.
0844   ///
0845   /// @param A The first basic block.
0846   /// @param B The second basic block.
0847   /// @return The smallest region that contains A and B.
0848   RegionT *getCommonRegion(BlockT *A, BlockT *B) const {
0849     return getCommonRegion(getRegionFor(A), getRegionFor(B));
0850   }
0851 
0852   /// Find the smallest region that contains a set of regions.
0853   ///
0854   /// @param Regions A vector of regions.
0855   /// @return The smallest region that contains all regions in Regions.
0856   RegionT *getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const;
0857 
0858   /// Find the smallest region that contains a set of basic blocks.
0859   ///
0860   /// @param BBs A vector of basic blocks.
0861   /// @return The smallest region that contains all basic blocks in BBS.
0862   RegionT *getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const;
0863 
0864   RegionT *getTopLevelRegion() const { return TopLevelRegion; }
0865 
0866   /// Clear the Node Cache for all Regions.
0867   ///
0868   /// @see Region::clearNodeCache()
0869   void clearNodeCache() {
0870     if (TopLevelRegion)
0871       TopLevelRegion->clearNodeCache();
0872   }
0873 
0874   void verifyAnalysis() const;
0875 };
0876 
0877 class RegionNode : public RegionNodeBase<RegionTraits<Function>> {
0878 public:
0879   inline RegionNode(Region *Parent, BasicBlock *Entry, bool isSubRegion = false)
0880       : RegionNodeBase<RegionTraits<Function>>(Parent, Entry, isSubRegion) {}
0881 
0882   bool operator==(const Region &RN) const {
0883     return this == reinterpret_cast<const RegionNode *>(&RN);
0884   }
0885 };
0886 
0887 class Region : public RegionBase<RegionTraits<Function>> {
0888 public:
0889   Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo *RI, DominatorTree *DT,
0890          Region *Parent = nullptr);
0891   ~Region();
0892 
0893   bool operator==(const RegionNode &RN) const {
0894     return &RN == reinterpret_cast<const RegionNode *>(this);
0895   }
0896 };
0897 
0898 class RegionInfo : public RegionInfoBase<RegionTraits<Function>> {
0899 public:
0900   using Base = RegionInfoBase<RegionTraits<Function>>;
0901 
0902   explicit RegionInfo();
0903 
0904   RegionInfo(RegionInfo &&Arg) : Base(std::move(static_cast<Base &>(Arg))) {
0905     updateRegionTree(*this, TopLevelRegion);
0906   }
0907 
0908   RegionInfo &operator=(RegionInfo &&RHS) {
0909     Base::operator=(std::move(static_cast<Base &>(RHS)));
0910     updateRegionTree(*this, TopLevelRegion);
0911     return *this;
0912   }
0913 
0914   ~RegionInfo() override;
0915 
0916   /// Handle invalidation explicitly.
0917   bool invalidate(Function &F, const PreservedAnalyses &PA,
0918                   FunctionAnalysisManager::Invalidator &);
0919 
0920   // updateStatistics - Update statistic about created regions.
0921   void updateStatistics(Region *R) final;
0922 
0923   void recalculate(Function &F, DominatorTree *DT, PostDominatorTree *PDT,
0924                    DominanceFrontier *DF);
0925 
0926 #ifndef NDEBUG
0927   /// Opens a viewer to show the GraphViz visualization of the regions.
0928   ///
0929   /// Useful during debugging as an alternative to dump().
0930   void view();
0931 
0932   /// Opens a viewer to show the GraphViz visualization of this region
0933   /// without instructions in the BasicBlocks.
0934   ///
0935   /// Useful during debugging as an alternative to dump().
0936   void viewOnly();
0937 #endif
0938 };
0939 
0940 class RegionInfoPass : public FunctionPass {
0941   RegionInfo RI;
0942 
0943 public:
0944   static char ID;
0945 
0946   explicit RegionInfoPass();
0947   ~RegionInfoPass() override;
0948 
0949   RegionInfo &getRegionInfo() { return RI; }
0950 
0951   const RegionInfo &getRegionInfo() const { return RI; }
0952 
0953   /// @name FunctionPass interface
0954   //@{
0955   bool runOnFunction(Function &F) override;
0956   void releaseMemory() override;
0957   void verifyAnalysis() const override;
0958   void getAnalysisUsage(AnalysisUsage &AU) const override;
0959   void print(raw_ostream &OS, const Module *) const override;
0960   void dump() const;
0961   //@}
0962 };
0963 
0964 /// Analysis pass that exposes the \c RegionInfo for a function.
0965 class RegionInfoAnalysis : public AnalysisInfoMixin<RegionInfoAnalysis> {
0966   friend AnalysisInfoMixin<RegionInfoAnalysis>;
0967 
0968   static AnalysisKey Key;
0969 
0970 public:
0971   using Result = RegionInfo;
0972 
0973   RegionInfo run(Function &F, FunctionAnalysisManager &AM);
0974 };
0975 
0976 /// Printer pass for the \c RegionInfo.
0977 class RegionInfoPrinterPass : public PassInfoMixin<RegionInfoPrinterPass> {
0978   raw_ostream &OS;
0979 
0980 public:
0981   explicit RegionInfoPrinterPass(raw_ostream &OS);
0982 
0983   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
0984 
0985   static bool isRequired() { return true; }
0986 };
0987 
0988 /// Verifier pass for the \c RegionInfo.
0989 struct RegionInfoVerifierPass : PassInfoMixin<RegionInfoVerifierPass> {
0990   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
0991   static bool isRequired() { return true; }
0992 };
0993 
0994 template <>
0995 template <>
0996 inline BasicBlock *
0997 RegionNodeBase<RegionTraits<Function>>::getNodeAs<BasicBlock>() const {
0998   assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
0999   return getEntry();
1000 }
1001 
1002 template <>
1003 template <>
1004 inline Region *
1005 RegionNodeBase<RegionTraits<Function>>::getNodeAs<Region>() const {
1006   assert(isSubRegion() && "This is not a subregion RegionNode!");
1007   auto Unconst = const_cast<RegionNodeBase<RegionTraits<Function>> *>(this);
1008   return reinterpret_cast<Region *>(Unconst);
1009 }
1010 
1011 template <class Tr>
1012 inline raw_ostream &operator<<(raw_ostream &OS,
1013                                const RegionNodeBase<Tr> &Node) {
1014   using BlockT = typename Tr::BlockT;
1015   using RegionT = typename Tr::RegionT;
1016 
1017   if (Node.isSubRegion())
1018     return OS << Node.template getNodeAs<RegionT>()->getNameStr();
1019   else
1020     return OS << Node.template getNodeAs<BlockT>()->getName();
1021 }
1022 
1023 extern template class RegionBase<RegionTraits<Function>>;
1024 extern template class RegionNodeBase<RegionTraits<Function>>;
1025 extern template class RegionInfoBase<RegionTraits<Function>>;
1026 
1027 } // end namespace llvm
1028 
1029 #endif // LLVM_ANALYSIS_REGIONINFO_H