RegionInfo.h 32 KB

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