LLVM 23.0.0git
PostOrderIterator.h
Go to the documentation of this file.
1//===- llvm/ADT/PostOrderIterator.h - PostOrder iterator --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file builds on the ADT/GraphTraits.h file to build a generic graph
11/// post order iterator. This should work over any graph type that has a
12/// GraphTraits specialization.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_POSTORDERITERATOR_H
17#define LLVM_ADT_POSTORDERITERATOR_H
18
23#include <iterator>
24#include <optional>
25#include <set>
26#include <type_traits>
27#include <utility>
28
29namespace llvm {
30
31// The po_iterator_storage template provides access to the set of already
32// visited nodes during the po_iterator's depth-first traversal.
33//
34// The default implementation simply contains a set of visited nodes, while
35// the External=true version uses a reference to an external set.
36//
37// It is possible to prune the depth-first traversal in several ways:
38//
39// - When providing an external set that already contains some graph nodes,
40// those nodes won't be visited again. This is useful for restarting a
41// post-order traversal on a graph with nodes that aren't dominated by a
42// single node.
43//
44// - By providing a custom SetType class, unwanted graph nodes can be excluded
45// by having the insert() function return false. This could for example
46// confine a CFG traversal to blocks in a specific loop.
47//
48// - Finally, by specializing the po_iterator_storage template itself, graph
49// edges can be pruned by returning false in the insertEdge() function. This
50// could be used to remove loop back-edges from the CFG seen by po_iterator.
51//
52// A specialized po_iterator_storage class can observe both the pre-order and
53// the post-order. The insertEdge() function is called in a pre-order, while
54// the finishPostorder() function is called just before the po_iterator moves
55// on to the next node.
56
57/// Default po_iterator_storage implementation with an internal set object.
58template<class SetType, bool External>
60 SetType Visited;
61
62public:
63 // Return true if edge destination should be visited.
64 template <typename NodeRef>
65 bool insertEdge(std::optional<NodeRef> From, NodeRef To) {
66 return Visited.insert(To).second;
67 }
68
69 // Called after all children of BB have been visited.
70 template <typename NodeRef> void finishPostorder(NodeRef BB) {}
71};
72
73/// Specialization of po_iterator_storage that references an external set.
74template<class SetType>
75class po_iterator_storage<SetType, true> {
76 SetType &Visited;
77
78public:
79 po_iterator_storage(SetType &VSet) : Visited(VSet) {}
80 po_iterator_storage(const po_iterator_storage &S) : Visited(S.Visited) {}
81
82 // Return true if edge destination should be visited, called with From = 0 for
83 // the root node.
84 // Graph edges can be pruned by specializing this function.
85 template <class NodeRef>
86 bool insertEdge(std::optional<NodeRef> From, NodeRef To) {
87 return Visited.insert(To).second;
88 }
89
90 // Called after all children of BB have been visited.
91 template <class NodeRef> void finishPostorder(NodeRef BB) {}
92};
93
94namespace po_detail {
95
96template <typename NodeRef> class NumberSet {
98
99public:
100 void reserve(size_t Size) {
101 if (Size < Data.size())
102 Data.resize(Size, false);
103 }
104
105 std::pair<std::nullopt_t, bool> insert(NodeRef Node) {
107 if (Idx >= Data.size())
108 Data.resize(Idx + 1);
109 bool Inserted = !Data[Idx];
110 Data[Idx] = true;
111 return {std::nullopt, Inserted};
112 }
113};
114
115template <typename GraphT>
117 std::conditional_t<GraphHasNodeNumbers<GraphT>,
120
121} // namespace po_detail
122
123template <class GraphT, class SetType = po_detail::DefaultSet<GraphT>,
124 bool ExtStorage = false, class GT = GraphTraits<GraphT>>
125class po_iterator : public po_iterator_storage<SetType, ExtStorage> {
126public:
127 // When External storage is used we are not multi-pass safe.
129 std::conditional_t<ExtStorage, std::input_iterator_tag,
130 std::forward_iterator_tag>;
131 using value_type = typename GT::NodeRef;
132 using difference_type = std::ptrdiff_t;
134 using reference = const value_type &;
135
136private:
137 using NodeRef = typename GT::NodeRef;
138 using ChildItTy = typename GT::ChildIteratorType;
139
140 /// Used to maintain the ordering.
141 /// First element is basic block pointer, second is iterator for the next
142 /// child to visit, third is the end iterator.
144
145 po_iterator(NodeRef BB) {
146 this->insertEdge(std::optional<NodeRef>(), BB);
147 VisitStack.emplace_back(BB, GT::child_begin(BB), GT::child_end(BB));
148 traverseChild();
149 }
150
151 po_iterator() = default; // End is when stack is empty.
152
153 po_iterator(NodeRef BB, SetType &S)
154 : po_iterator_storage<SetType, ExtStorage>(S) {
155 if (this->insertEdge(std::optional<NodeRef>(), BB)) {
156 VisitStack.emplace_back(BB, GT::child_begin(BB), GT::child_end(BB));
157 traverseChild();
158 }
159 }
160
161 po_iterator(SetType &S)
162 : po_iterator_storage<SetType, ExtStorage>(S) {
163 } // End is when stack is empty.
164
165 void traverseChild() {
166 while (true) {
167 auto &Entry = VisitStack.back();
168 if (std::get<1>(Entry) == std::get<2>(Entry))
169 break;
170 NodeRef BB = *std::get<1>(Entry)++;
171 if (this->insertEdge(std::optional<NodeRef>(std::get<0>(Entry)), BB)) {
172 // If the block is not visited...
173 VisitStack.emplace_back(BB, GT::child_begin(BB), GT::child_end(BB));
174 }
175 }
176 }
177
178public:
179 // Provide static "constructors"...
180 static po_iterator begin(const GraphT &G) {
181 return po_iterator(GT::getEntryNode(G));
182 }
183 static po_iterator end(const GraphT &G) { return po_iterator(); }
184
185 static po_iterator begin(const GraphT &G, SetType &S) {
186 return po_iterator(GT::getEntryNode(G), S);
187 }
188 static po_iterator end(const GraphT &G, SetType &S) { return po_iterator(S); }
189
190 bool operator==(const po_iterator &x) const {
191 return VisitStack == x.VisitStack;
192 }
193 bool operator!=(const po_iterator &x) const { return !(*this == x); }
194
195 reference operator*() const { return std::get<0>(VisitStack.back()); }
196
197 // This is a nonstandard operator-> that dereferences the pointer an extra
198 // time... so that you can actually call methods ON the BasicBlock, because
199 // the contained type is a pointer. This allows BBIt->getTerminator() f.e.
200 //
201 NodeRef operator->() const { return **this; }
202
203 po_iterator &operator++() { // Preincrement
204 this->finishPostorder(std::get<0>(VisitStack.back()));
205 VisitStack.pop_back();
206 if (!VisitStack.empty())
207 traverseChild();
208 return *this;
209 }
210
211 po_iterator operator++(int) { // Postincrement
212 po_iterator tmp = *this;
213 ++*this;
214 return tmp;
215 }
216};
217
218// Provide global constructors that automatically figure out correct types...
219//
220template <class T>
222template <class T>
224
225template <class T> iterator_range<po_iterator<T>> post_order(const T &G) {
226 return make_range(po_begin(G), po_end(G));
227}
228
229// Provide global definitions of external postorder iterators...
230template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>>
231struct po_ext_iterator : po_iterator<T, SetType, true> {
232 po_ext_iterator(const po_iterator<T, SetType, true> &V) :
233 po_iterator<T, SetType, true>(V) {}
234};
235
236template <class T, class SetType>
240
241template <class T, class SetType>
245
246template <class T, class SetType>
250
251// Provide global definitions of inverse post order iterators...
252template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>,
253 bool External = false>
254struct ipo_iterator : po_iterator<Inverse<T>, SetType, External> {
255 ipo_iterator(const po_iterator<Inverse<T>, SetType, External> &V) :
256 po_iterator<Inverse<T>, SetType, External> (V) {}
257};
258
259template <class T>
263
264template <class T>
266 return ipo_iterator<T>::end(G);
267}
268
269template <class T>
273
274// Provide global definitions of external inverse postorder iterators...
275template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>>
276struct ipo_ext_iterator : ipo_iterator<T, SetType, true> {
279 ipo_ext_iterator(const po_iterator<Inverse<T>, SetType, true> &V) :
280 ipo_iterator<T, SetType, true>(V) {}
281};
282
283template <class T, class SetType>
287
288template <class T, class SetType>
292
293template <class T, class SetType>
295inverse_post_order_ext(const T &G, SetType &S) {
296 return make_range(ipo_ext_begin(G, S), ipo_ext_end(G, S));
297}
298
299//===--------------------------------------------------------------------===//
300// Reverse Post Order CFG iterator code
301//===--------------------------------------------------------------------===//
302//
303// This is used to visit basic blocks in a method in reverse post order. This
304// class is awkward to use because I don't know a good incremental algorithm to
305// computer RPO from a graph. Because of this, the construction of the
306// ReversePostOrderTraversal object is expensive (it must walk the entire graph
307// with a postorder iterator to build the data structures). The moral of this
308// story is: Don't create more ReversePostOrderTraversal classes than necessary.
309//
310// Because it does the traversal in its constructor, it won't invalidate when
311// BasicBlocks are removed, *but* it may contain erased blocks. Some places
312// rely on this behavior (i.e. GVN).
313//
314// This class should be used like this:
315// {
316// ReversePostOrderTraversal<Function*> RPOT(FuncPtr); // Expensive to create
317// for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
318// ...
319// }
320// for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
321// ...
322// }
323// }
324//
325
326template<class GraphT, class GT = GraphTraits<GraphT>>
328 using NodeRef = typename GT::NodeRef;
329
330 using VecTy = SmallVector<NodeRef, 8>;
331 VecTy Blocks; // Block list in normal PO order
332
333 void Initialize(const GraphT &G) {
334 std::copy(po_begin(G), po_end(G), std::back_inserter(Blocks));
335 }
336
337public:
340
341 ReversePostOrderTraversal(const GraphT &G) { Initialize(G); }
342
343 // Because we want a reverse post order, use reverse iterators from the vector
344 rpo_iterator begin() { return Blocks.rbegin(); }
345 const_rpo_iterator begin() const { return Blocks.rbegin(); }
346 rpo_iterator end() { return Blocks.rend(); }
347 const_rpo_iterator end() const { return Blocks.rend(); }
348};
349
350} // end namespace llvm
351
352#endif // LLVM_ADT_POSTORDERITERATOR_H
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
#define G(x, y, z)
Definition MD5.cpp:55
#define T
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
const_rpo_iterator end() const
const_rpo_iterator begin() const
typename VecTy::reverse_iterator rpo_iterator
typename VecTy::const_reverse_iterator const_rpo_iterator
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
std::reverse_iterator< const_iterator > const_reverse_iterator
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A range adaptor for a pair of iterators.
std::pair< std::nullopt_t, bool > insert(NodeRef Node)
po_iterator_storage(const po_iterator_storage &S)
bool insertEdge(std::optional< NodeRef > From, NodeRef To)
Default po_iterator_storage implementation with an internal set object.
bool insertEdge(std::optional< NodeRef > From, NodeRef To)
void finishPostorder(NodeRef BB)
static po_iterator end(const GraphT &G, SetType &S)
reference operator*() const
std::ptrdiff_t difference_type
static po_iterator end(const GraphT &G)
const value_type & reference
NodeRef operator->() const
typename GT::NodeRef value_type
static po_iterator begin(const GraphT &G)
po_iterator & operator++()
po_iterator operator++(int)
std::conditional_t< ExtStorage, std::input_iterator_tag, std::forward_iterator_tag > iterator_category
bool operator==(const po_iterator &x) const
bool operator!=(const po_iterator &x) const
static po_iterator begin(const GraphT &G, SetType &S)
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
@ Entry
Definition COFF.h:862
std::conditional_t< GraphHasNodeNumbers< GraphT >, NumberSet< typename GraphTraits< GraphT >::NodeRef >, SmallPtrSet< typename GraphTraits< GraphT >::NodeRef, 8 > > DefaultSet
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
ipo_iterator< T > ipo_end(const T &G)
iterator_range< po_ext_iterator< T, SetType > > post_order_ext(const T &G, SetType &S)
iterator_range< ipo_ext_iterator< T, SetType > > inverse_post_order_ext(const T &G, SetType &S)
ipo_ext_iterator< T, SetType > ipo_ext_begin(const T &G, SetType &S)
iterator_range< ipo_iterator< T > > inverse_post_order(const T &G)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< po_iterator< T > > post_order(const T &G)
po_iterator< T > po_begin(const T &G)
ipo_ext_iterator< T, SetType > ipo_ext_end(const T &G, SetType &S)
ipo_iterator< T > ipo_begin(const T &G)
po_ext_iterator< T, SetType > po_ext_begin(const T &G, SetType &S)
po_ext_iterator< T, SetType > po_ext_end(const T &G, SetType &S)
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
po_iterator< T > po_end(const T &G)
ipo_ext_iterator(const ipo_iterator< T, SetType, true > &V)
ipo_ext_iterator(const po_iterator< Inverse< T >, SetType, true > &V)
ipo_iterator(const po_iterator< Inverse< T >, SetType, External > &V)
po_ext_iterator(const po_iterator< T, SetType, true > &V)