RegionInfo.h 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Calculate a program structure tree built out of single entry single exit
  15. // regions.
  16. // The basic ideas are taken from "The Program Structure Tree - Richard Johnson,
  17. // David Pearson, Keshav Pingali - 1994", however enriched with ideas from "The
  18. // Refined Process Structure Tree - Jussi Vanhatalo, Hagen Voelyer, Jana
  19. // Koehler - 2009".
  20. // The algorithm to calculate these data structures however is completely
  21. // different, as it takes advantage of existing information already available
  22. // in (Post)dominace tree and dominance frontier passes. This leads to a simpler
  23. // and in practice hopefully better performing algorithm. The runtime of the
  24. // algorithms described in the papers above are both linear in graph size,
  25. // O(V+E), whereas this algorithm is not, as the dominance frontier information
  26. // itself is not, but in practice runtime seems to be in the order of magnitude
  27. // of dominance tree calculation.
  28. //
  29. // WARNING: LLVM is generally very concerned about compile time such that
  30. // the use of additional analysis passes in the default
  31. // optimization sequence is avoided as much as possible.
  32. // Specifically, if you do not need the RegionInfo, but dominance
  33. // information could be sufficient please base your work only on
  34. // the dominator tree. Most passes maintain it, such that using
  35. // it has often near zero cost. In contrast RegionInfo is by
  36. // default not available, is not maintained by existing
  37. // transformations and there is no intention to do so.
  38. //
  39. //===----------------------------------------------------------------------===//
  40. #ifndef LLVM_ANALYSIS_REGIONINFO_H
  41. #define LLVM_ANALYSIS_REGIONINFO_H
  42. #include "llvm/ADT/DenseMap.h"
  43. #include "llvm/ADT/DepthFirstIterator.h"
  44. #include "llvm/ADT/GraphTraits.h"
  45. #include "llvm/ADT/PointerIntPair.h"
  46. #include "llvm/ADT/iterator_range.h"
  47. #include "llvm/Config/llvm-config.h"
  48. #include "llvm/IR/BasicBlock.h"
  49. #include "llvm/IR/Dominators.h"
  50. #include "llvm/IR/PassManager.h"
  51. #include "llvm/Pass.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include <algorithm>
  54. #include <cassert>
  55. #include <map>
  56. #include <memory>
  57. #include <set>
  58. #include <string>
  59. #include <type_traits>
  60. #include <vector>
  61. namespace llvm {
  62. class DominanceFrontier;
  63. class Loop;
  64. class LoopInfo;
  65. class PostDominatorTree;
  66. class Region;
  67. template <class RegionTr> class RegionBase;
  68. class RegionInfo;
  69. template <class RegionTr> class RegionInfoBase;
  70. class RegionNode;
  71. // Class to be specialized for different users of RegionInfo
  72. // (i.e. BasicBlocks or MachineBasicBlocks). This is only to avoid needing to
  73. // pass around an unreasonable number of template parameters.
  74. template <class FuncT_>
  75. struct RegionTraits {
  76. // FuncT
  77. // BlockT
  78. // RegionT
  79. // RegionNodeT
  80. // RegionInfoT
  81. using BrokenT = typename FuncT_::UnknownRegionTypeError;
  82. };
  83. template <>
  84. struct RegionTraits<Function> {
  85. using FuncT = Function;
  86. using BlockT = BasicBlock;
  87. using RegionT = Region;
  88. using RegionNodeT = RegionNode;
  89. using RegionInfoT = RegionInfo;
  90. using DomTreeT = DominatorTree;
  91. using DomTreeNodeT = DomTreeNode;
  92. using DomFrontierT = DominanceFrontier;
  93. using PostDomTreeT = PostDominatorTree;
  94. using InstT = Instruction;
  95. using LoopT = Loop;
  96. using LoopInfoT = LoopInfo;
  97. static unsigned getNumSuccessors(BasicBlock *BB) {
  98. return BB->getTerminator()->getNumSuccessors();
  99. }
  100. };
  101. /// Marker class to iterate over the elements of a Region in flat mode.
  102. ///
  103. /// The class is used to either iterate in Flat mode or by not using it to not
  104. /// iterate in Flat mode. During a Flat mode iteration all Regions are entered
  105. /// and the iteration returns every BasicBlock. If the Flat mode is not
  106. /// selected for SubRegions just one RegionNode containing the subregion is
  107. /// returned.
  108. template <class GraphType>
  109. class FlatIt {};
  110. /// A RegionNode represents a subregion or a BasicBlock that is part of a
  111. /// Region.
  112. template <class Tr>
  113. class RegionNodeBase {
  114. friend class RegionBase<Tr>;
  115. public:
  116. using BlockT = typename Tr::BlockT;
  117. using RegionT = typename Tr::RegionT;
  118. private:
  119. /// This is the entry basic block that starts this region node. If this is a
  120. /// BasicBlock RegionNode, then entry is just the basic block, that this
  121. /// RegionNode represents. Otherwise it is the entry of this (Sub)RegionNode.
  122. ///
  123. /// In the BBtoRegionNode map of the parent of this node, BB will always map
  124. /// to this node no matter which kind of node this one is.
  125. ///
  126. /// The node can hold either a Region or a BasicBlock.
  127. /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
  128. /// RegionNode.
  129. PointerIntPair<BlockT *, 1, bool> entry;
  130. /// The parent Region of this RegionNode.
  131. /// @see getParent()
  132. RegionT *parent;
  133. protected:
  134. /// Create a RegionNode.
  135. ///
  136. /// @param Parent The parent of this RegionNode.
  137. /// @param Entry The entry BasicBlock of the RegionNode. If this
  138. /// RegionNode represents a BasicBlock, this is the
  139. /// BasicBlock itself. If it represents a subregion, this
  140. /// is the entry BasicBlock of the subregion.
  141. /// @param isSubRegion If this RegionNode represents a SubRegion.
  142. inline RegionNodeBase(RegionT *Parent, BlockT *Entry,
  143. bool isSubRegion = false)
  144. : entry(Entry, isSubRegion), parent(Parent) {}
  145. public:
  146. RegionNodeBase(const RegionNodeBase &) = delete;
  147. RegionNodeBase &operator=(const RegionNodeBase &) = delete;
  148. /// Get the parent Region of this RegionNode.
  149. ///
  150. /// The parent Region is the Region this RegionNode belongs to. If for
  151. /// example a BasicBlock is element of two Regions, there exist two
  152. /// RegionNodes for this BasicBlock. Each with the getParent() function
  153. /// pointing to the Region this RegionNode belongs to.
  154. ///
  155. /// @return Get the parent Region of this RegionNode.
  156. inline RegionT *getParent() const { return parent; }
  157. /// Get the entry BasicBlock of this RegionNode.
  158. ///
  159. /// If this RegionNode represents a BasicBlock this is just the BasicBlock
  160. /// itself, otherwise we return the entry BasicBlock of the Subregion
  161. ///
  162. /// @return The entry BasicBlock of this RegionNode.
  163. inline BlockT *getEntry() const { return entry.getPointer(); }
  164. /// Get the content of this RegionNode.
  165. ///
  166. /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
  167. /// check the type of the content with the isSubRegion() function call.
  168. ///
  169. /// @return The content of this RegionNode.
  170. template <class T> inline T *getNodeAs() const;
  171. /// Is this RegionNode a subregion?
  172. ///
  173. /// @return True if it contains a subregion. False if it contains a
  174. /// BasicBlock.
  175. inline bool isSubRegion() const { return entry.getInt(); }
  176. };
  177. //===----------------------------------------------------------------------===//
  178. /// A single entry single exit Region.
  179. ///
  180. /// A Region is a connected subgraph of a control flow graph that has exactly
  181. /// two connections to the remaining graph. It can be used to analyze or
  182. /// optimize parts of the control flow graph.
  183. ///
  184. /// A <em> simple Region </em> is connected to the remaining graph by just two
  185. /// edges. One edge entering the Region and another one leaving the Region.
  186. ///
  187. /// An <em> extended Region </em> (or just Region) is a subgraph that can be
  188. /// transform into a simple Region. The transformation is done by adding
  189. /// BasicBlocks that merge several entry or exit edges so that after the merge
  190. /// just one entry and one exit edge exists.
  191. ///
  192. /// The \e Entry of a Region is the first BasicBlock that is passed after
  193. /// entering the Region. It is an element of the Region. The entry BasicBlock
  194. /// dominates all BasicBlocks in the Region.
  195. ///
  196. /// The \e Exit of a Region is the first BasicBlock that is passed after
  197. /// leaving the Region. It is not an element of the Region. The exit BasicBlock,
  198. /// postdominates all BasicBlocks in the Region.
  199. ///
  200. /// A <em> canonical Region </em> cannot be constructed by combining smaller
  201. /// Regions.
  202. ///
  203. /// Region A is the \e parent of Region B, if B is completely contained in A.
  204. ///
  205. /// Two canonical Regions either do not intersect at all or one is
  206. /// the parent of the other.
  207. ///
  208. /// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
  209. /// Regions in the control flow graph and E is the \e parent relation of these
  210. /// Regions.
  211. ///
  212. /// Example:
  213. ///
  214. /// \verbatim
  215. /// A simple control flow graph, that contains two regions.
  216. ///
  217. /// 1
  218. /// / |
  219. /// 2 |
  220. /// / \ 3
  221. /// 4 5 |
  222. /// | | |
  223. /// 6 7 8
  224. /// \ | /
  225. /// \ |/ Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
  226. /// 9 Region B: 2 -> 9 {2,4,5,6,7}
  227. /// \endverbatim
  228. ///
  229. /// You can obtain more examples by either calling
  230. ///
  231. /// <tt> "opt -regions -analyze anyprogram.ll" </tt>
  232. /// or
  233. /// <tt> "opt -view-regions-only anyprogram.ll" </tt>
  234. ///
  235. /// on any LLVM file you are interested in.
  236. ///
  237. /// The first call returns a textual representation of the program structure
  238. /// tree, the second one creates a graphical representation using graphviz.
  239. template <class Tr>
  240. class RegionBase : public RegionNodeBase<Tr> {
  241. friend class RegionInfoBase<Tr>;
  242. using FuncT = typename Tr::FuncT;
  243. using BlockT = typename Tr::BlockT;
  244. using RegionInfoT = typename Tr::RegionInfoT;
  245. using RegionT = typename Tr::RegionT;
  246. using RegionNodeT = typename Tr::RegionNodeT;
  247. using DomTreeT = typename Tr::DomTreeT;
  248. using LoopT = typename Tr::LoopT;
  249. using LoopInfoT = typename Tr::LoopInfoT;
  250. using InstT = typename Tr::InstT;
  251. using BlockTraits = GraphTraits<BlockT *>;
  252. using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
  253. using SuccIterTy = typename BlockTraits::ChildIteratorType;
  254. using PredIterTy = typename InvBlockTraits::ChildIteratorType;
  255. // Information necessary to manage this Region.
  256. RegionInfoT *RI;
  257. DomTreeT *DT;
  258. // The exit BasicBlock of this region.
  259. // (The entry BasicBlock is part of RegionNode)
  260. BlockT *exit;
  261. using RegionSet = std::vector<std::unique_ptr<RegionT>>;
  262. // The subregions of this region.
  263. RegionSet children;
  264. using BBNodeMapT = std::map<BlockT *, std::unique_ptr<RegionNodeT>>;
  265. // Save the BasicBlock RegionNodes that are element of this Region.
  266. mutable BBNodeMapT BBNodeMap;
  267. /// Check if a BB is in this Region. This check also works
  268. /// if the region is incorrectly built. (EXPENSIVE!)
  269. void verifyBBInRegion(BlockT *BB) const;
  270. /// Walk over all the BBs of the region starting from BB and
  271. /// verify that all reachable basic blocks are elements of the region.
  272. /// (EXPENSIVE!)
  273. void verifyWalk(BlockT *BB, std::set<BlockT *> *visitedBB) const;
  274. /// Verify if the region and its children are valid regions (EXPENSIVE!)
  275. void verifyRegionNest() const;
  276. public:
  277. /// Create a new region.
  278. ///
  279. /// @param Entry The entry basic block of the region.
  280. /// @param Exit The exit basic block of the region.
  281. /// @param RI The region info object that is managing this region.
  282. /// @param DT The dominator tree of the current function.
  283. /// @param Parent The surrounding region or NULL if this is a top level
  284. /// region.
  285. RegionBase(BlockT *Entry, BlockT *Exit, RegionInfoT *RI, DomTreeT *DT,
  286. RegionT *Parent = nullptr);
  287. RegionBase(const RegionBase &) = delete;
  288. RegionBase &operator=(const RegionBase &) = delete;
  289. /// Delete the Region and all its subregions.
  290. ~RegionBase();
  291. /// Get the entry BasicBlock of the Region.
  292. /// @return The entry BasicBlock of the region.
  293. BlockT *getEntry() const {
  294. return RegionNodeBase<Tr>::getEntry();
  295. }
  296. /// Replace the entry basic block of the region with the new basic
  297. /// block.
  298. ///
  299. /// @param BB The new entry basic block of the region.
  300. void replaceEntry(BlockT *BB);
  301. /// Replace the exit basic block of the region with the new basic
  302. /// block.
  303. ///
  304. /// @param BB The new exit basic block of the region.
  305. void replaceExit(BlockT *BB);
  306. /// Recursively replace the entry basic block of the region.
  307. ///
  308. /// This function replaces the entry basic block with a new basic block. It
  309. /// also updates all child regions that have the same entry basic block as
  310. /// this region.
  311. ///
  312. /// @param NewEntry The new entry basic block.
  313. void replaceEntryRecursive(BlockT *NewEntry);
  314. /// Recursively replace the exit basic block of the region.
  315. ///
  316. /// This function replaces the exit basic block with a new basic block. It
  317. /// also updates all child regions that have the same exit basic block as
  318. /// this region.
  319. ///
  320. /// @param NewExit The new exit basic block.
  321. void replaceExitRecursive(BlockT *NewExit);
  322. /// Get the exit BasicBlock of the Region.
  323. /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
  324. /// Region.
  325. BlockT *getExit() const { return exit; }
  326. /// Get the parent of the Region.
  327. /// @return The parent of the Region or NULL if this is a top level
  328. /// Region.
  329. RegionT *getParent() const {
  330. return RegionNodeBase<Tr>::getParent();
  331. }
  332. /// Get the RegionNode representing the current Region.
  333. /// @return The RegionNode representing the current Region.
  334. RegionNodeT *getNode() const {
  335. return const_cast<RegionNodeT *>(
  336. reinterpret_cast<const RegionNodeT *>(this));
  337. }
  338. /// Get the nesting level of this Region.
  339. ///
  340. /// An toplevel Region has depth 0.
  341. ///
  342. /// @return The depth of the region.
  343. unsigned getDepth() const;
  344. /// Check if a Region is the TopLevel region.
  345. ///
  346. /// The toplevel region represents the whole function.
  347. bool isTopLevelRegion() const { return exit == nullptr; }
  348. /// Return a new (non-canonical) region, that is obtained by joining
  349. /// this region with its predecessors.
  350. ///
  351. /// @return A region also starting at getEntry(), but reaching to the next
  352. /// basic block that forms with getEntry() a (non-canonical) region.
  353. /// NULL if such a basic block does not exist.
  354. RegionT *getExpandedRegion() const;
  355. /// Return the first block of this region's single entry edge,
  356. /// if existing.
  357. ///
  358. /// @return The BasicBlock starting this region's single entry edge,
  359. /// else NULL.
  360. BlockT *getEnteringBlock() const;
  361. /// Return the first block of this region's single exit edge,
  362. /// if existing.
  363. ///
  364. /// @return The BasicBlock starting this region's single exit edge,
  365. /// else NULL.
  366. BlockT *getExitingBlock() const;
  367. /// Collect all blocks of this region's single exit edge, if existing.
  368. ///
  369. /// @return True if this region contains all the predecessors of the exit.
  370. bool getExitingBlocks(SmallVectorImpl<BlockT *> &Exitings) const;
  371. /// Is this a simple region?
  372. ///
  373. /// A region is simple if it has exactly one exit and one entry edge.
  374. ///
  375. /// @return True if the Region is simple.
  376. bool isSimple() const;
  377. /// Returns the name of the Region.
  378. /// @return The Name of the Region.
  379. std::string getNameStr() const;
  380. /// Return the RegionInfo object, that belongs to this Region.
  381. RegionInfoT *getRegionInfo() const { return RI; }
  382. /// PrintStyle - Print region in difference ways.
  383. enum PrintStyle { PrintNone, PrintBB, PrintRN };
  384. /// Print the region.
  385. ///
  386. /// @param OS The output stream the Region is printed to.
  387. /// @param printTree Print also the tree of subregions.
  388. /// @param level The indentation level used for printing.
  389. void print(raw_ostream &OS, bool printTree = true, unsigned level = 0,
  390. PrintStyle Style = PrintNone) const;
  391. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  392. /// Print the region to stderr.
  393. void dump() const;
  394. #endif
  395. /// Check if the region contains a BasicBlock.
  396. ///
  397. /// @param BB The BasicBlock that might be contained in this Region.
  398. /// @return True if the block is contained in the region otherwise false.
  399. bool contains(const BlockT *BB) const;
  400. /// Check if the region contains another region.
  401. ///
  402. /// @param SubRegion The region that might be contained in this Region.
  403. /// @return True if SubRegion is contained in the region otherwise false.
  404. bool contains(const RegionT *SubRegion) const {
  405. // Toplevel Region.
  406. if (!getExit())
  407. return true;
  408. return contains(SubRegion->getEntry()) &&
  409. (contains(SubRegion->getExit()) ||
  410. SubRegion->getExit() == getExit());
  411. }
  412. /// Check if the region contains an Instruction.
  413. ///
  414. /// @param Inst The Instruction that might be contained in this region.
  415. /// @return True if the Instruction is contained in the region otherwise
  416. /// false.
  417. bool contains(const InstT *Inst) const { return contains(Inst->getParent()); }
  418. /// Check if the region contains a loop.
  419. ///
  420. /// @param L The loop that might be contained in this region.
  421. /// @return True if the loop is contained in the region otherwise false.
  422. /// In case a NULL pointer is passed to this function the result
  423. /// is false, except for the region that describes the whole function.
  424. /// In that case true is returned.
  425. bool contains(const LoopT *L) const;
  426. /// Get the outermost loop in the region that contains a loop.
  427. ///
  428. /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
  429. /// and is itself contained in the region.
  430. ///
  431. /// @param L The loop the lookup is started.
  432. /// @return The outermost loop in the region, NULL if such a loop does not
  433. /// exist or if the region describes the whole function.
  434. LoopT *outermostLoopInRegion(LoopT *L) const;
  435. /// Get the outermost loop in the region that contains a basic block.
  436. ///
  437. /// Find for a basic block BB the outermost loop L that contains BB and is
  438. /// itself contained in the region.
  439. ///
  440. /// @param LI A pointer to a LoopInfo analysis.
  441. /// @param BB The basic block surrounded by the loop.
  442. /// @return The outermost loop in the region, NULL if such a loop does not
  443. /// exist or if the region describes the whole function.
  444. LoopT *outermostLoopInRegion(LoopInfoT *LI, BlockT *BB) const;
  445. /// Get the subregion that starts at a BasicBlock
  446. ///
  447. /// @param BB The BasicBlock the subregion should start.
  448. /// @return The Subregion if available, otherwise NULL.
  449. RegionT *getSubRegionNode(BlockT *BB) const;
  450. /// Get the RegionNode for a BasicBlock
  451. ///
  452. /// @param BB The BasicBlock at which the RegionNode should start.
  453. /// @return If available, the RegionNode that represents the subregion
  454. /// starting at BB. If no subregion starts at BB, the RegionNode
  455. /// representing BB.
  456. RegionNodeT *getNode(BlockT *BB) const;
  457. /// Get the BasicBlock RegionNode for a BasicBlock
  458. ///
  459. /// @param BB The BasicBlock for which the RegionNode is requested.
  460. /// @return The RegionNode representing the BB.
  461. RegionNodeT *getBBNode(BlockT *BB) const;
  462. /// Add a new subregion to this Region.
  463. ///
  464. /// @param SubRegion The new subregion that will be added.
  465. /// @param moveChildren Move the children of this region, that are also
  466. /// contained in SubRegion into SubRegion.
  467. void addSubRegion(RegionT *SubRegion, bool moveChildren = false);
  468. /// Remove a subregion from this Region.
  469. ///
  470. /// The subregion is not deleted, as it will probably be inserted into another
  471. /// region.
  472. /// @param SubRegion The SubRegion that will be removed.
  473. RegionT *removeSubRegion(RegionT *SubRegion);
  474. /// Move all direct child nodes of this Region to another Region.
  475. ///
  476. /// @param To The Region the child nodes will be transferred to.
  477. void transferChildrenTo(RegionT *To);
  478. /// Verify if the region is a correct region.
  479. ///
  480. /// Check if this is a correctly build Region. This is an expensive check, as
  481. /// the complete CFG of the Region will be walked.
  482. void verifyRegion() const;
  483. /// Clear the cache for BB RegionNodes.
  484. ///
  485. /// After calling this function the BasicBlock RegionNodes will be stored at
  486. /// different memory locations. RegionNodes obtained before this function is
  487. /// called are therefore not comparable to RegionNodes abtained afterwords.
  488. void clearNodeCache();
  489. /// @name Subregion Iterators
  490. ///
  491. /// These iterators iterator over all subregions of this Region.
  492. //@{
  493. using iterator = typename RegionSet::iterator;
  494. using const_iterator = typename RegionSet::const_iterator;
  495. iterator begin() { return children.begin(); }
  496. iterator end() { return children.end(); }
  497. const_iterator begin() const { return children.begin(); }
  498. const_iterator end() const { return children.end(); }
  499. //@}
  500. /// @name BasicBlock Iterators
  501. ///
  502. /// These iterators iterate over all BasicBlocks that are contained in this
  503. /// Region. The iterator also iterates over BasicBlocks that are elements of
  504. /// a subregion of this Region. It is therefore called a flat iterator.
  505. //@{
  506. template <bool IsConst>
  507. class block_iterator_wrapper
  508. : public df_iterator<
  509. std::conditional_t<IsConst, const BlockT, BlockT> *> {
  510. using super =
  511. df_iterator<std::conditional_t<IsConst, const BlockT, BlockT> *>;
  512. public:
  513. using Self = block_iterator_wrapper<IsConst>;
  514. using value_type = typename super::value_type;
  515. // Construct the begin iterator.
  516. block_iterator_wrapper(value_type Entry, value_type Exit)
  517. : super(df_begin(Entry)) {
  518. // Mark the exit of the region as visited, so that the children of the
  519. // exit and the exit itself, i.e. the block outside the region will never
  520. // be visited.
  521. super::Visited.insert(Exit);
  522. }
  523. // Construct the end iterator.
  524. block_iterator_wrapper() : super(df_end<value_type>((BlockT *)nullptr)) {}
  525. /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
  526. // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
  527. // This was introduced for backwards compatibility, but should
  528. // be removed as soon as all users are fixed.
  529. BlockT *operator*() const {
  530. return const_cast<BlockT *>(super::operator*());
  531. }
  532. };
  533. using block_iterator = block_iterator_wrapper<false>;
  534. using const_block_iterator = block_iterator_wrapper<true>;
  535. block_iterator block_begin() { return block_iterator(getEntry(), getExit()); }
  536. block_iterator block_end() { return block_iterator(); }
  537. const_block_iterator block_begin() const {
  538. return const_block_iterator(getEntry(), getExit());
  539. }
  540. const_block_iterator block_end() const { return const_block_iterator(); }
  541. using block_range = iterator_range<block_iterator>;
  542. using const_block_range = iterator_range<const_block_iterator>;
  543. /// Returns a range view of the basic blocks in the region.
  544. inline block_range blocks() {
  545. return block_range(block_begin(), block_end());
  546. }
  547. /// Returns a range view of the basic blocks in the region.
  548. ///
  549. /// This is the 'const' version of the range view.
  550. inline const_block_range blocks() const {
  551. return const_block_range(block_begin(), block_end());
  552. }
  553. //@}
  554. /// @name Element Iterators
  555. ///
  556. /// These iterators iterate over all BasicBlock and subregion RegionNodes that
  557. /// are direct children of this Region. It does not iterate over any
  558. /// RegionNodes that are also element of a subregion of this Region.
  559. //@{
  560. using element_iterator =
  561. df_iterator<RegionNodeT *, df_iterator_default_set<RegionNodeT *>, false,
  562. GraphTraits<RegionNodeT *>>;
  563. using const_element_iterator =
  564. df_iterator<const RegionNodeT *,
  565. df_iterator_default_set<const RegionNodeT *>, false,
  566. GraphTraits<const RegionNodeT *>>;
  567. element_iterator element_begin();
  568. element_iterator element_end();
  569. iterator_range<element_iterator> elements() {
  570. return make_range(element_begin(), element_end());
  571. }
  572. const_element_iterator element_begin() const;
  573. const_element_iterator element_end() const;
  574. iterator_range<const_element_iterator> elements() const {
  575. return make_range(element_begin(), element_end());
  576. }
  577. //@}
  578. };
  579. /// Print a RegionNode.
  580. template <class Tr>
  581. inline raw_ostream &operator<<(raw_ostream &OS, const RegionNodeBase<Tr> &Node);
  582. //===----------------------------------------------------------------------===//
  583. /// Analysis that detects all canonical Regions.
  584. ///
  585. /// The RegionInfo pass detects all canonical regions in a function. The Regions
  586. /// are connected using the parent relation. This builds a Program Structure
  587. /// Tree.
  588. template <class Tr>
  589. class RegionInfoBase {
  590. friend class RegionInfo;
  591. friend class MachineRegionInfo;
  592. using BlockT = typename Tr::BlockT;
  593. using FuncT = typename Tr::FuncT;
  594. using RegionT = typename Tr::RegionT;
  595. using RegionInfoT = typename Tr::RegionInfoT;
  596. using DomTreeT = typename Tr::DomTreeT;
  597. using DomTreeNodeT = typename Tr::DomTreeNodeT;
  598. using PostDomTreeT = typename Tr::PostDomTreeT;
  599. using DomFrontierT = typename Tr::DomFrontierT;
  600. using BlockTraits = GraphTraits<BlockT *>;
  601. using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
  602. using SuccIterTy = typename BlockTraits::ChildIteratorType;
  603. using PredIterTy = typename InvBlockTraits::ChildIteratorType;
  604. using BBtoBBMap = DenseMap<BlockT *, BlockT *>;
  605. using BBtoRegionMap = DenseMap<BlockT *, RegionT *>;
  606. RegionInfoBase();
  607. RegionInfoBase(RegionInfoBase &&Arg)
  608. : DT(std::move(Arg.DT)), PDT(std::move(Arg.PDT)), DF(std::move(Arg.DF)),
  609. TopLevelRegion(std::move(Arg.TopLevelRegion)),
  610. BBtoRegion(std::move(Arg.BBtoRegion)) {
  611. Arg.wipe();
  612. }
  613. RegionInfoBase &operator=(RegionInfoBase &&RHS) {
  614. DT = std::move(RHS.DT);
  615. PDT = std::move(RHS.PDT);
  616. DF = std::move(RHS.DF);
  617. TopLevelRegion = std::move(RHS.TopLevelRegion);
  618. BBtoRegion = std::move(RHS.BBtoRegion);
  619. RHS.wipe();
  620. return *this;
  621. }
  622. virtual ~RegionInfoBase();
  623. DomTreeT *DT;
  624. PostDomTreeT *PDT;
  625. DomFrontierT *DF;
  626. /// The top level region.
  627. RegionT *TopLevelRegion = nullptr;
  628. /// Map every BB to the smallest region, that contains BB.
  629. BBtoRegionMap BBtoRegion;
  630. protected:
  631. /// Update refences to a RegionInfoT held by the RegionT managed here
  632. ///
  633. /// This is a post-move helper. Regions hold references to the owning
  634. /// RegionInfo object. After a move these need to be fixed.
  635. template<typename TheRegionT>
  636. void updateRegionTree(RegionInfoT &RI, TheRegionT *R) {
  637. if (!R)
  638. return;
  639. R->RI = &RI;
  640. for (auto &SubR : *R)
  641. updateRegionTree(RI, SubR.get());
  642. }
  643. private:
  644. /// Wipe this region tree's state without releasing any resources.
  645. ///
  646. /// This is essentially a post-move helper only. It leaves the object in an
  647. /// assignable and destroyable state, but otherwise invalid.
  648. void wipe() {
  649. DT = nullptr;
  650. PDT = nullptr;
  651. DF = nullptr;
  652. TopLevelRegion = nullptr;
  653. BBtoRegion.clear();
  654. }
  655. // Check whether the entries of BBtoRegion for the BBs of region
  656. // SR are correct. Triggers an assertion if not. Calls itself recursively for
  657. // subregions.
  658. void verifyBBMap(const RegionT *SR) const;
  659. // Returns true if BB is in the dominance frontier of
  660. // entry, because it was inherited from exit. In the other case there is an
  661. // edge going from entry to BB without passing exit.
  662. bool isCommonDomFrontier(BlockT *BB, BlockT *entry, BlockT *exit) const;
  663. // Check if entry and exit surround a valid region, based on
  664. // dominance tree and dominance frontier.
  665. bool isRegion(BlockT *entry, BlockT *exit) const;
  666. // Saves a shortcut pointing from entry to exit.
  667. // This function may extend this shortcut if possible.
  668. void insertShortCut(BlockT *entry, BlockT *exit, BBtoBBMap *ShortCut) const;
  669. // Returns the next BB that postdominates N, while skipping
  670. // all post dominators that cannot finish a canonical region.
  671. DomTreeNodeT *getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const;
  672. // A region is trivial, if it contains only one BB.
  673. bool isTrivialRegion(BlockT *entry, BlockT *exit) const;
  674. // Creates a single entry single exit region.
  675. RegionT *createRegion(BlockT *entry, BlockT *exit);
  676. // Detect all regions starting with bb 'entry'.
  677. void findRegionsWithEntry(BlockT *entry, BBtoBBMap *ShortCut);
  678. // Detects regions in F.
  679. void scanForRegions(FuncT &F, BBtoBBMap *ShortCut);
  680. // Get the top most parent with the same entry block.
  681. RegionT *getTopMostParent(RegionT *region);
  682. // Build the region hierarchy after all region detected.
  683. void buildRegionsTree(DomTreeNodeT *N, RegionT *region);
  684. // Update statistic about created regions.
  685. virtual void updateStatistics(RegionT *R) = 0;
  686. // Detect all regions in function and build the region tree.
  687. void calculate(FuncT &F);
  688. public:
  689. RegionInfoBase(const RegionInfoBase &) = delete;
  690. RegionInfoBase &operator=(const RegionInfoBase &) = delete;
  691. static bool VerifyRegionInfo;
  692. static typename RegionT::PrintStyle printStyle;
  693. void print(raw_ostream &OS) const;
  694. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  695. void dump() const;
  696. #endif
  697. void releaseMemory();
  698. /// Get the smallest region that contains a BasicBlock.
  699. ///
  700. /// @param BB The basic block.
  701. /// @return The smallest region, that contains BB or NULL, if there is no
  702. /// region containing BB.
  703. RegionT *getRegionFor(BlockT *BB) const;
  704. /// Set the smallest region that surrounds a basic block.
  705. ///
  706. /// @param BB The basic block surrounded by a region.
  707. /// @param R The smallest region that surrounds BB.
  708. void setRegionFor(BlockT *BB, RegionT *R);
  709. /// A shortcut for getRegionFor().
  710. ///
  711. /// @param BB The basic block.
  712. /// @return The smallest region, that contains BB or NULL, if there is no
  713. /// region containing BB.
  714. RegionT *operator[](BlockT *BB) const;
  715. /// Return the exit of the maximal refined region, that starts at a
  716. /// BasicBlock.
  717. ///
  718. /// @param BB The BasicBlock the refined region starts.
  719. BlockT *getMaxRegionExit(BlockT *BB) const;
  720. /// Find the smallest region that contains two regions.
  721. ///
  722. /// @param A The first region.
  723. /// @param B The second region.
  724. /// @return The smallest region containing A and B.
  725. RegionT *getCommonRegion(RegionT *A, RegionT *B) const;
  726. /// Find the smallest region that contains two basic blocks.
  727. ///
  728. /// @param A The first basic block.
  729. /// @param B The second basic block.
  730. /// @return The smallest region that contains A and B.
  731. RegionT *getCommonRegion(BlockT *A, BlockT *B) const {
  732. return getCommonRegion(getRegionFor(A), getRegionFor(B));
  733. }
  734. /// Find the smallest region that contains a set of regions.
  735. ///
  736. /// @param Regions A vector of regions.
  737. /// @return The smallest region that contains all regions in Regions.
  738. RegionT *getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const;
  739. /// Find the smallest region that contains a set of basic blocks.
  740. ///
  741. /// @param BBs A vector of basic blocks.
  742. /// @return The smallest region that contains all basic blocks in BBS.
  743. RegionT *getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const;
  744. RegionT *getTopLevelRegion() const { return TopLevelRegion; }
  745. /// Clear the Node Cache for all Regions.
  746. ///
  747. /// @see Region::clearNodeCache()
  748. void clearNodeCache() {
  749. if (TopLevelRegion)
  750. TopLevelRegion->clearNodeCache();
  751. }
  752. void verifyAnalysis() const;
  753. };
  754. class RegionNode : public RegionNodeBase<RegionTraits<Function>> {
  755. public:
  756. inline RegionNode(Region *Parent, BasicBlock *Entry, bool isSubRegion = false)
  757. : RegionNodeBase<RegionTraits<Function>>(Parent, Entry, isSubRegion) {}
  758. bool operator==(const Region &RN) const {
  759. return this == reinterpret_cast<const RegionNode *>(&RN);
  760. }
  761. };
  762. class Region : public RegionBase<RegionTraits<Function>> {
  763. public:
  764. Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo *RI, DominatorTree *DT,
  765. Region *Parent = nullptr);
  766. ~Region();
  767. bool operator==(const RegionNode &RN) const {
  768. return &RN == reinterpret_cast<const RegionNode *>(this);
  769. }
  770. };
  771. class RegionInfo : public RegionInfoBase<RegionTraits<Function>> {
  772. public:
  773. using Base = RegionInfoBase<RegionTraits<Function>>;
  774. explicit RegionInfo();
  775. RegionInfo(RegionInfo &&Arg) : Base(std::move(static_cast<Base &>(Arg))) {
  776. updateRegionTree(*this, TopLevelRegion);
  777. }
  778. RegionInfo &operator=(RegionInfo &&RHS) {
  779. Base::operator=(std::move(static_cast<Base &>(RHS)));
  780. updateRegionTree(*this, TopLevelRegion);
  781. return *this;
  782. }
  783. ~RegionInfo() override;
  784. /// Handle invalidation explicitly.
  785. bool invalidate(Function &F, const PreservedAnalyses &PA,
  786. FunctionAnalysisManager::Invalidator &);
  787. // updateStatistics - Update statistic about created regions.
  788. void updateStatistics(Region *R) final;
  789. void recalculate(Function &F, DominatorTree *DT, PostDominatorTree *PDT,
  790. DominanceFrontier *DF);
  791. #ifndef NDEBUG
  792. /// Opens a viewer to show the GraphViz visualization of the regions.
  793. ///
  794. /// Useful during debugging as an alternative to dump().
  795. void view();
  796. /// Opens a viewer to show the GraphViz visualization of this region
  797. /// without instructions in the BasicBlocks.
  798. ///
  799. /// Useful during debugging as an alternative to dump().
  800. void viewOnly();
  801. #endif
  802. };
  803. class RegionInfoPass : public FunctionPass {
  804. RegionInfo RI;
  805. public:
  806. static char ID;
  807. explicit RegionInfoPass();
  808. ~RegionInfoPass() override;
  809. RegionInfo &getRegionInfo() { return RI; }
  810. const RegionInfo &getRegionInfo() const { return RI; }
  811. /// @name FunctionPass interface
  812. //@{
  813. bool runOnFunction(Function &F) override;
  814. void releaseMemory() override;
  815. void verifyAnalysis() const override;
  816. void getAnalysisUsage(AnalysisUsage &AU) const override;
  817. void print(raw_ostream &OS, const Module *) const override;
  818. void dump() const;
  819. //@}
  820. };
  821. /// Analysis pass that exposes the \c RegionInfo for a function.
  822. class RegionInfoAnalysis : public AnalysisInfoMixin<RegionInfoAnalysis> {
  823. friend AnalysisInfoMixin<RegionInfoAnalysis>;
  824. static AnalysisKey Key;
  825. public:
  826. using Result = RegionInfo;
  827. RegionInfo run(Function &F, FunctionAnalysisManager &AM);
  828. };
  829. /// Printer pass for the \c RegionInfo.
  830. class RegionInfoPrinterPass : public PassInfoMixin<RegionInfoPrinterPass> {
  831. raw_ostream &OS;
  832. public:
  833. explicit RegionInfoPrinterPass(raw_ostream &OS);
  834. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  835. };
  836. /// Verifier pass for the \c RegionInfo.
  837. struct RegionInfoVerifierPass : PassInfoMixin<RegionInfoVerifierPass> {
  838. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  839. };
  840. template <>
  841. template <>
  842. inline BasicBlock *
  843. RegionNodeBase<RegionTraits<Function>>::getNodeAs<BasicBlock>() const {
  844. assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
  845. return getEntry();
  846. }
  847. template <>
  848. template <>
  849. inline Region *
  850. RegionNodeBase<RegionTraits<Function>>::getNodeAs<Region>() const {
  851. assert(isSubRegion() && "This is not a subregion RegionNode!");
  852. auto Unconst = const_cast<RegionNodeBase<RegionTraits<Function>> *>(this);
  853. return reinterpret_cast<Region *>(Unconst);
  854. }
  855. template <class Tr>
  856. inline raw_ostream &operator<<(raw_ostream &OS,
  857. const RegionNodeBase<Tr> &Node) {
  858. using BlockT = typename Tr::BlockT;
  859. using RegionT = typename Tr::RegionT;
  860. if (Node.isSubRegion())
  861. return OS << Node.template getNodeAs<RegionT>()->getNameStr();
  862. else
  863. return OS << Node.template getNodeAs<BlockT>()->getName();
  864. }
  865. extern template class RegionBase<RegionTraits<Function>>;
  866. extern template class RegionNodeBase<RegionTraits<Function>>;
  867. extern template class RegionInfoBase<RegionTraits<Function>>;
  868. } // end namespace llvm
  869. #endif // LLVM_ANALYSIS_REGIONINFO_H
  870. #ifdef __GNUC__
  871. #pragma GCC diagnostic pop
  872. #endif