GenericCycleInfo.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- GenericCycleInfo.h - Info for Cycles in any IR ------*- 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. /// \file
  15. /// \brief Find all cycles in a control-flow graph, including irreducible loops.
  16. ///
  17. /// See docs/CycleTerminology.rst for a formal definition of cycles.
  18. ///
  19. /// Briefly:
  20. /// - A cycle is a generalization of a loop which can represent
  21. /// irreducible control flow.
  22. /// - Cycles identified in a program are implementation defined,
  23. /// depending on the DFS traversal chosen.
  24. /// - Cycles are well-nested, and form a forest with a parent-child
  25. /// relationship.
  26. /// - In any choice of DFS, every natural loop L is represented by a
  27. /// unique cycle C which is a superset of L.
  28. /// - In the absence of irreducible control flow, the cycles are
  29. /// exactly the natural loops in the program.
  30. ///
  31. //===----------------------------------------------------------------------===//
  32. #ifndef LLVM_ADT_GENERICCYCLEINFO_H
  33. #define LLVM_ADT_GENERICCYCLEINFO_H
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/DenseMap.h"
  36. #include "llvm/ADT/GenericSSAContext.h"
  37. #include "llvm/ADT/GraphTraits.h"
  38. #include "llvm/ADT/SmallVector.h"
  39. #include "llvm/ADT/iterator.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/Printable.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include <vector>
  44. namespace llvm {
  45. template <typename ContextT> class GenericCycleInfo;
  46. template <typename ContextT> class GenericCycleInfoCompute;
  47. /// A possibly irreducible generalization of a \ref Loop.
  48. template <typename ContextT> class GenericCycle {
  49. public:
  50. using BlockT = typename ContextT::BlockT;
  51. using FunctionT = typename ContextT::FunctionT;
  52. template <typename> friend class GenericCycleInfo;
  53. template <typename> friend class GenericCycleInfoCompute;
  54. private:
  55. /// The parent cycle. Is null for the root "cycle". Top-level cycles point
  56. /// at the root.
  57. GenericCycle *ParentCycle = nullptr;
  58. /// The entry block(s) of the cycle. The header is the only entry if
  59. /// this is a loop. Is empty for the root "cycle", to avoid
  60. /// unnecessary memory use.
  61. SmallVector<BlockT *, 1> Entries;
  62. /// Child cycles, if any.
  63. std::vector<std::unique_ptr<GenericCycle>> Children;
  64. /// Basic blocks that are contained in the cycle, including entry blocks,
  65. /// and including blocks that are part of a child cycle.
  66. std::vector<BlockT *> Blocks;
  67. /// Depth of the cycle in the tree. The root "cycle" is at depth 0.
  68. ///
  69. /// \note Depths are not necessarily contiguous. However, child loops always
  70. /// have strictly greater depth than their parents, and sibling loops
  71. /// always have the same depth.
  72. unsigned Depth = 0;
  73. void clear() {
  74. Entries.clear();
  75. Children.clear();
  76. Blocks.clear();
  77. Depth = 0;
  78. ParentCycle = nullptr;
  79. }
  80. void appendEntry(BlockT *Block) { Entries.push_back(Block); }
  81. void appendBlock(BlockT *Block) { Blocks.push_back(Block); }
  82. GenericCycle(const GenericCycle &) = delete;
  83. GenericCycle &operator=(const GenericCycle &) = delete;
  84. GenericCycle(GenericCycle &&Rhs) = delete;
  85. GenericCycle &operator=(GenericCycle &&Rhs) = delete;
  86. public:
  87. GenericCycle() = default;
  88. /// \brief Whether the cycle is a natural loop.
  89. bool isReducible() const { return Entries.size() == 1; }
  90. BlockT *getHeader() const { return Entries[0]; }
  91. /// \brief Return whether \p Block is an entry block of the cycle.
  92. bool isEntry(BlockT *Block) const { return is_contained(Entries, Block); }
  93. /// \brief Return whether \p Block is contained in the cycle.
  94. bool contains(const BlockT *Block) const {
  95. return is_contained(Blocks, Block);
  96. }
  97. /// \brief Returns true iff this cycle contains \p C.
  98. ///
  99. /// Note: Non-strict containment check, i.e. returns true if C is the
  100. /// same cycle.
  101. bool contains(const GenericCycle *C) const;
  102. const GenericCycle *getParentCycle() const { return ParentCycle; }
  103. GenericCycle *getParentCycle() { return ParentCycle; }
  104. unsigned getDepth() const { return Depth; }
  105. /// Return all of the successor blocks of this cycle.
  106. ///
  107. /// These are the blocks _outside of the current cycle_ which are
  108. /// branched to.
  109. void getExitBlocks(SmallVectorImpl<BlockT *> &TmpStorage) const;
  110. /// Iteration over child cycles.
  111. //@{
  112. using const_child_iterator_base =
  113. typename std::vector<std::unique_ptr<GenericCycle>>::const_iterator;
  114. struct const_child_iterator
  115. : iterator_adaptor_base<const_child_iterator, const_child_iterator_base> {
  116. using Base =
  117. iterator_adaptor_base<const_child_iterator, const_child_iterator_base>;
  118. const_child_iterator() = default;
  119. explicit const_child_iterator(const_child_iterator_base I) : Base(I) {}
  120. const const_child_iterator_base &wrapped() { return Base::wrapped(); }
  121. GenericCycle *operator*() const { return Base::I->get(); }
  122. };
  123. const_child_iterator child_begin() const {
  124. return const_child_iterator{Children.begin()};
  125. }
  126. const_child_iterator child_end() const {
  127. return const_child_iterator{Children.end()};
  128. }
  129. size_t getNumChildren() const { return Children.size(); }
  130. iterator_range<const_child_iterator> children() const {
  131. return llvm::make_range(const_child_iterator{Children.begin()},
  132. const_child_iterator{Children.end()});
  133. }
  134. //@}
  135. /// Iteration over blocks in the cycle (including entry blocks).
  136. //@{
  137. using const_block_iterator = typename std::vector<BlockT *>::const_iterator;
  138. const_block_iterator block_begin() const {
  139. return const_block_iterator{Blocks.begin()};
  140. }
  141. const_block_iterator block_end() const {
  142. return const_block_iterator{Blocks.end()};
  143. }
  144. size_t getNumBlocks() const { return Blocks.size(); }
  145. iterator_range<const_block_iterator> blocks() const {
  146. return llvm::make_range(block_begin(), block_end());
  147. }
  148. //@}
  149. /// Iteration over entry blocks.
  150. //@{
  151. using const_entry_iterator =
  152. typename SmallVectorImpl<BlockT *>::const_iterator;
  153. size_t getNumEntries() const { return Entries.size(); }
  154. iterator_range<const_entry_iterator> entries() const {
  155. return llvm::make_range(Entries.begin(), Entries.end());
  156. }
  157. Printable printEntries(const ContextT &Ctx) const {
  158. return Printable([this, &Ctx](raw_ostream &Out) {
  159. bool First = true;
  160. for (auto *Entry : Entries) {
  161. if (!First)
  162. Out << ' ';
  163. First = false;
  164. Out << Ctx.print(Entry);
  165. }
  166. });
  167. }
  168. Printable print(const ContextT &Ctx) const {
  169. return Printable([this, &Ctx](raw_ostream &Out) {
  170. Out << "depth=" << Depth << ": entries(" << printEntries(Ctx) << ')';
  171. for (auto *Block : Blocks) {
  172. if (isEntry(Block))
  173. continue;
  174. Out << ' ' << Ctx.print(Block);
  175. }
  176. });
  177. }
  178. };
  179. /// \brief Cycle information for a function.
  180. template <typename ContextT> class GenericCycleInfo {
  181. public:
  182. using BlockT = typename ContextT::BlockT;
  183. using CycleT = GenericCycle<ContextT>;
  184. using FunctionT = typename ContextT::FunctionT;
  185. template <typename> friend class GenericCycle;
  186. template <typename> friend class GenericCycleInfoCompute;
  187. private:
  188. ContextT Context;
  189. /// Map basic blocks to their inner-most containing loop.
  190. DenseMap<BlockT *, CycleT *> BlockMap;
  191. /// Outermost cycles discovered by any DFS.
  192. ///
  193. /// Note: The implementation treats the nullptr as the parent of
  194. /// every top-level cycle. See \ref contains for an example.
  195. std::vector<std::unique_ptr<CycleT>> TopLevelCycles;
  196. public:
  197. GenericCycleInfo() = default;
  198. GenericCycleInfo(GenericCycleInfo &&) = default;
  199. GenericCycleInfo &operator=(GenericCycleInfo &&) = default;
  200. void clear();
  201. void compute(FunctionT &F);
  202. FunctionT *getFunction() const { return Context.getFunction(); }
  203. const ContextT &getSSAContext() const { return Context; }
  204. CycleT *getCycle(const BlockT *Block) const;
  205. CycleT *getTopLevelParentCycle(const BlockT *Block) const;
  206. /// Move \p Child to \p NewParent by manipulating Children vectors.
  207. ///
  208. /// Note: This is an incomplete operation that does not update the
  209. /// list of blocks in the new parent or the depth of the subtree.
  210. void moveToNewParent(CycleT *NewParent, CycleT *Child);
  211. /// Methods for debug and self-test.
  212. //@{
  213. bool validateTree() const;
  214. void print(raw_ostream &Out) const;
  215. void dump() const { print(dbgs()); }
  216. //@}
  217. /// Iteration over top-level cycles.
  218. //@{
  219. using const_toplevel_iterator_base =
  220. typename std::vector<std::unique_ptr<CycleT>>::const_iterator;
  221. struct const_toplevel_iterator
  222. : iterator_adaptor_base<const_toplevel_iterator,
  223. const_toplevel_iterator_base> {
  224. using Base = iterator_adaptor_base<const_toplevel_iterator,
  225. const_toplevel_iterator_base>;
  226. const_toplevel_iterator() = default;
  227. explicit const_toplevel_iterator(const_toplevel_iterator_base I)
  228. : Base(I) {}
  229. const const_toplevel_iterator_base &wrapped() { return Base::wrapped(); }
  230. CycleT *operator*() const { return Base::I->get(); }
  231. };
  232. const_toplevel_iterator toplevel_begin() const {
  233. return const_toplevel_iterator{TopLevelCycles.begin()};
  234. }
  235. const_toplevel_iterator toplevel_end() const {
  236. return const_toplevel_iterator{TopLevelCycles.end()};
  237. }
  238. iterator_range<const_toplevel_iterator> toplevel_cycles() const {
  239. return llvm::make_range(const_toplevel_iterator{TopLevelCycles.begin()},
  240. const_toplevel_iterator{TopLevelCycles.end()});
  241. }
  242. //@}
  243. };
  244. /// \brief GraphTraits for iterating over a sub-tree of the CycleT tree.
  245. template <typename CycleRefT, typename ChildIteratorT> struct CycleGraphTraits {
  246. using NodeRef = CycleRefT;
  247. using nodes_iterator = ChildIteratorT;
  248. using ChildIteratorType = nodes_iterator;
  249. static NodeRef getEntryNode(NodeRef Graph) { return Graph; }
  250. static ChildIteratorType child_begin(NodeRef Ref) {
  251. return Ref->child_begin();
  252. }
  253. static ChildIteratorType child_end(NodeRef Ref) { return Ref->child_end(); }
  254. // Not implemented:
  255. // static nodes_iterator nodes_begin(GraphType *G)
  256. // static nodes_iterator nodes_end (GraphType *G)
  257. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  258. // typedef EdgeRef - Type of Edge token in the graph, which should
  259. // be cheap to copy.
  260. // typedef ChildEdgeIteratorType - Type used to iterate over children edges in
  261. // graph, dereference to a EdgeRef.
  262. // static ChildEdgeIteratorType child_edge_begin(NodeRef)
  263. // static ChildEdgeIteratorType child_edge_end(NodeRef)
  264. // Return iterators that point to the beginning and ending of the
  265. // edge list for the given callgraph node.
  266. //
  267. // static NodeRef edge_dest(EdgeRef)
  268. // Return the destination node of an edge.
  269. // static unsigned size (GraphType *G)
  270. // Return total number of nodes in the graph
  271. };
  272. template <typename BlockT>
  273. struct GraphTraits<const GenericCycle<BlockT> *>
  274. : CycleGraphTraits<const GenericCycle<BlockT> *,
  275. typename GenericCycle<BlockT>::const_child_iterator> {};
  276. template <typename BlockT>
  277. struct GraphTraits<GenericCycle<BlockT> *>
  278. : CycleGraphTraits<GenericCycle<BlockT> *,
  279. typename GenericCycle<BlockT>::const_child_iterator> {};
  280. } // namespace llvm
  281. #endif // LLVM_ADT_GENERICCYCLEINFO_H
  282. #ifdef __GNUC__
  283. #pragma GCC diagnostic pop
  284. #endif