DepthFirstIterator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/DepthFirstIterator.h - Depth First iterator -----*- 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. // This file builds on the ADT/GraphTraits.h file to build generic depth
  15. // first graph iterator. This file exposes the following functions/types:
  16. //
  17. // df_begin/df_end/df_iterator
  18. // * Normal depth-first iteration - visit a node and then all of its children.
  19. //
  20. // idf_begin/idf_end/idf_iterator
  21. // * Depth-first iteration on the 'inverse' graph.
  22. //
  23. // df_ext_begin/df_ext_end/df_ext_iterator
  24. // * Normal depth-first iteration - visit a node and then all of its children.
  25. // This iterator stores the 'visited' set in an external set, which allows
  26. // it to be more efficient, and allows external clients to use the set for
  27. // other purposes.
  28. //
  29. // idf_ext_begin/idf_ext_end/idf_ext_iterator
  30. // * Depth-first iteration on the 'inverse' graph.
  31. // This iterator stores the 'visited' set in an external set, which allows
  32. // it to be more efficient, and allows external clients to use the set for
  33. // other purposes.
  34. //
  35. //===----------------------------------------------------------------------===//
  36. #ifndef LLVM_ADT_DEPTHFIRSTITERATOR_H
  37. #define LLVM_ADT_DEPTHFIRSTITERATOR_H
  38. #include "llvm/ADT/GraphTraits.h"
  39. #include "llvm/ADT/None.h"
  40. #include "llvm/ADT/Optional.h"
  41. #include "llvm/ADT/SmallPtrSet.h"
  42. #include "llvm/ADT/iterator_range.h"
  43. #include <iterator>
  44. #include <set>
  45. #include <utility>
  46. #include <vector>
  47. namespace llvm {
  48. // df_iterator_storage - A private class which is used to figure out where to
  49. // store the visited set.
  50. template<class SetType, bool External> // Non-external set
  51. class df_iterator_storage {
  52. public:
  53. SetType Visited;
  54. };
  55. template<class SetType>
  56. class df_iterator_storage<SetType, true> {
  57. public:
  58. df_iterator_storage(SetType &VSet) : Visited(VSet) {}
  59. df_iterator_storage(const df_iterator_storage &S) : Visited(S.Visited) {}
  60. SetType &Visited;
  61. };
  62. // The visited stated for the iteration is a simple set augmented with
  63. // one more method, completed, which is invoked when all children of a
  64. // node have been processed. It is intended to distinguish of back and
  65. // cross edges in the spanning tree but is not used in the common case.
  66. template <typename NodeRef, unsigned SmallSize=8>
  67. struct df_iterator_default_set : public SmallPtrSet<NodeRef, SmallSize> {
  68. using BaseSet = SmallPtrSet<NodeRef, SmallSize>;
  69. using iterator = typename BaseSet::iterator;
  70. std::pair<iterator,bool> insert(NodeRef N) { return BaseSet::insert(N); }
  71. template <typename IterT>
  72. void insert(IterT Begin, IterT End) { BaseSet::insert(Begin,End); }
  73. void completed(NodeRef) {}
  74. };
  75. // Generic Depth First Iterator
  76. template <class GraphT,
  77. class SetType =
  78. df_iterator_default_set<typename GraphTraits<GraphT>::NodeRef>,
  79. bool ExtStorage = false, class GT = GraphTraits<GraphT>>
  80. class df_iterator
  81. : public std::iterator<std::forward_iterator_tag, typename GT::NodeRef>,
  82. public df_iterator_storage<SetType, ExtStorage> {
  83. using super = std::iterator<std::forward_iterator_tag, typename GT::NodeRef>;
  84. using NodeRef = typename GT::NodeRef;
  85. using ChildItTy = typename GT::ChildIteratorType;
  86. // First element is node reference, second is the 'next child' to visit.
  87. // The second child is initialized lazily to pick up graph changes during the
  88. // DFS.
  89. using StackElement = std::pair<NodeRef, Optional<ChildItTy>>;
  90. // VisitStack - Used to maintain the ordering. Top = current block
  91. std::vector<StackElement> VisitStack;
  92. private:
  93. inline df_iterator(NodeRef Node) {
  94. this->Visited.insert(Node);
  95. VisitStack.push_back(StackElement(Node, None));
  96. }
  97. inline df_iterator() = default; // End is when stack is empty
  98. inline df_iterator(NodeRef Node, SetType &S)
  99. : df_iterator_storage<SetType, ExtStorage>(S) {
  100. if (this->Visited.insert(Node).second)
  101. VisitStack.push_back(StackElement(Node, None));
  102. }
  103. inline df_iterator(SetType &S)
  104. : df_iterator_storage<SetType, ExtStorage>(S) {
  105. // End is when stack is empty
  106. }
  107. inline void toNext() {
  108. do {
  109. NodeRef Node = VisitStack.back().first;
  110. Optional<ChildItTy> &Opt = VisitStack.back().second;
  111. if (!Opt)
  112. Opt.emplace(GT::child_begin(Node));
  113. // Notice that we directly mutate *Opt here, so that
  114. // VisitStack.back().second actually gets updated as the iterator
  115. // increases.
  116. while (*Opt != GT::child_end(Node)) {
  117. NodeRef Next = *(*Opt)++;
  118. // Has our next sibling been visited?
  119. if (this->Visited.insert(Next).second) {
  120. // No, do it now.
  121. VisitStack.push_back(StackElement(Next, None));
  122. return;
  123. }
  124. }
  125. this->Visited.completed(Node);
  126. // Oops, ran out of successors... go up a level on the stack.
  127. VisitStack.pop_back();
  128. } while (!VisitStack.empty());
  129. }
  130. public:
  131. using pointer = typename super::pointer;
  132. // Provide static begin and end methods as our public "constructors"
  133. static df_iterator begin(const GraphT &G) {
  134. return df_iterator(GT::getEntryNode(G));
  135. }
  136. static df_iterator end(const GraphT &G) { return df_iterator(); }
  137. // Static begin and end methods as our public ctors for external iterators
  138. static df_iterator begin(const GraphT &G, SetType &S) {
  139. return df_iterator(GT::getEntryNode(G), S);
  140. }
  141. static df_iterator end(const GraphT &G, SetType &S) { return df_iterator(S); }
  142. bool operator==(const df_iterator &x) const {
  143. return VisitStack == x.VisitStack;
  144. }
  145. bool operator!=(const df_iterator &x) const { return !(*this == x); }
  146. const NodeRef &operator*() const { return VisitStack.back().first; }
  147. // This is a nonstandard operator-> that dereferences the pointer an extra
  148. // time... so that you can actually call methods ON the Node, because
  149. // the contained type is a pointer. This allows BBIt->getTerminator() f.e.
  150. //
  151. NodeRef operator->() const { return **this; }
  152. df_iterator &operator++() { // Preincrement
  153. toNext();
  154. return *this;
  155. }
  156. /// Skips all children of the current node and traverses to next node
  157. ///
  158. /// Note: This function takes care of incrementing the iterator. If you
  159. /// always increment and call this function, you risk walking off the end.
  160. df_iterator &skipChildren() {
  161. VisitStack.pop_back();
  162. if (!VisitStack.empty())
  163. toNext();
  164. return *this;
  165. }
  166. df_iterator operator++(int) { // Postincrement
  167. df_iterator tmp = *this;
  168. ++*this;
  169. return tmp;
  170. }
  171. // nodeVisited - return true if this iterator has already visited the
  172. // specified node. This is public, and will probably be used to iterate over
  173. // nodes that a depth first iteration did not find: ie unreachable nodes.
  174. //
  175. bool nodeVisited(NodeRef Node) const {
  176. return this->Visited.contains(Node);
  177. }
  178. /// getPathLength - Return the length of the path from the entry node to the
  179. /// current node, counting both nodes.
  180. unsigned getPathLength() const { return VisitStack.size(); }
  181. /// getPath - Return the n'th node in the path from the entry node to the
  182. /// current node.
  183. NodeRef getPath(unsigned n) const { return VisitStack[n].first; }
  184. };
  185. // Provide global constructors that automatically figure out correct types...
  186. //
  187. template <class T>
  188. df_iterator<T> df_begin(const T& G) {
  189. return df_iterator<T>::begin(G);
  190. }
  191. template <class T>
  192. df_iterator<T> df_end(const T& G) {
  193. return df_iterator<T>::end(G);
  194. }
  195. // Provide an accessor method to use them in range-based patterns.
  196. template <class T>
  197. iterator_range<df_iterator<T>> depth_first(const T& G) {
  198. return make_range(df_begin(G), df_end(G));
  199. }
  200. // Provide global definitions of external depth first iterators...
  201. template <class T, class SetTy = std::set<typename GraphTraits<T>::NodeRef>>
  202. struct df_ext_iterator : public df_iterator<T, SetTy, true> {
  203. df_ext_iterator(const df_iterator<T, SetTy, true> &V)
  204. : df_iterator<T, SetTy, true>(V) {}
  205. };
  206. template <class T, class SetTy>
  207. df_ext_iterator<T, SetTy> df_ext_begin(const T& G, SetTy &S) {
  208. return df_ext_iterator<T, SetTy>::begin(G, S);
  209. }
  210. template <class T, class SetTy>
  211. df_ext_iterator<T, SetTy> df_ext_end(const T& G, SetTy &S) {
  212. return df_ext_iterator<T, SetTy>::end(G, S);
  213. }
  214. template <class T, class SetTy>
  215. iterator_range<df_ext_iterator<T, SetTy>> depth_first_ext(const T& G,
  216. SetTy &S) {
  217. return make_range(df_ext_begin(G, S), df_ext_end(G, S));
  218. }
  219. // Provide global definitions of inverse depth first iterators...
  220. template <class T,
  221. class SetTy =
  222. df_iterator_default_set<typename GraphTraits<T>::NodeRef>,
  223. bool External = false>
  224. struct idf_iterator : public df_iterator<Inverse<T>, SetTy, External> {
  225. idf_iterator(const df_iterator<Inverse<T>, SetTy, External> &V)
  226. : df_iterator<Inverse<T>, SetTy, External>(V) {}
  227. };
  228. template <class T>
  229. idf_iterator<T> idf_begin(const T& G) {
  230. return idf_iterator<T>::begin(Inverse<T>(G));
  231. }
  232. template <class T>
  233. idf_iterator<T> idf_end(const T& G){
  234. return idf_iterator<T>::end(Inverse<T>(G));
  235. }
  236. // Provide an accessor method to use them in range-based patterns.
  237. template <class T>
  238. iterator_range<idf_iterator<T>> inverse_depth_first(const T& G) {
  239. return make_range(idf_begin(G), idf_end(G));
  240. }
  241. // Provide global definitions of external inverse depth first iterators...
  242. template <class T, class SetTy = std::set<typename GraphTraits<T>::NodeRef>>
  243. struct idf_ext_iterator : public idf_iterator<T, SetTy, true> {
  244. idf_ext_iterator(const idf_iterator<T, SetTy, true> &V)
  245. : idf_iterator<T, SetTy, true>(V) {}
  246. idf_ext_iterator(const df_iterator<Inverse<T>, SetTy, true> &V)
  247. : idf_iterator<T, SetTy, true>(V) {}
  248. };
  249. template <class T, class SetTy>
  250. idf_ext_iterator<T, SetTy> idf_ext_begin(const T& G, SetTy &S) {
  251. return idf_ext_iterator<T, SetTy>::begin(Inverse<T>(G), S);
  252. }
  253. template <class T, class SetTy>
  254. idf_ext_iterator<T, SetTy> idf_ext_end(const T& G, SetTy &S) {
  255. return idf_ext_iterator<T, SetTy>::end(Inverse<T>(G), S);
  256. }
  257. template <class T, class SetTy>
  258. iterator_range<idf_ext_iterator<T, SetTy>> inverse_depth_first_ext(const T& G,
  259. SetTy &S) {
  260. return make_range(idf_ext_begin(G, S), idf_ext_end(G, S));
  261. }
  262. } // end namespace llvm
  263. #endif // LLVM_ADT_DEPTHFIRSTITERATOR_H
  264. #ifdef __GNUC__
  265. #pragma GCC diagnostic pop
  266. #endif