LLVM 23.0.0git
SCCIterator.h
Go to the documentation of this file.
1//===- ADT/SCCIterator.h - Strongly Connected Comp. Iter. -------*- 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/// \file
9///
10/// This builds on the llvm/ADT/GraphTraits.h file to find the strongly
11/// connected components (SCCs) of a graph in O(N+E) time using Tarjan's DFS
12/// algorithm.
13///
14/// The SCC iterator has the important property that if a node in SCC S1 has an
15/// edge to a node in SCC S2, then it visits S1 *after* S2.
16///
17/// To visit S1 *before* S2, use the scc_iterator on the Inverse graph. (NOTE:
18/// This requires some simple wrappers and is not supported yet.)
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_ADT_SCCITERATOR_H
23#define LLVM_ADT_SCCITERATOR_H
24
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/iterator.h"
30#include <cassert>
31#include <cstddef>
32#include <iterator>
33#include <queue>
34#include <set>
35#include <vector>
36
37namespace llvm {
38
39/// Enumerate the SCCs of a directed graph in reverse topological order
40/// of the SCC DAG.
41///
42/// This is implemented using Tarjan's DFS algorithm using an internal stack to
43/// build up a vector of nodes in a particular SCC. Note that it is a forward
44/// iterator and thus you cannot backtrack or re-visit nodes.
45template <class GraphT, class GT = GraphTraits<GraphT>>
46class scc_iterator : public iterator_facade_base<
47 scc_iterator<GraphT, GT>, std::forward_iterator_tag,
48 const std::vector<typename GT::NodeRef>, ptrdiff_t> {
49 using NodeRef = typename GT::NodeRef;
50 using ChildItTy = typename GT::ChildIteratorType;
51 using SccTy = std::vector<NodeRef>;
52 using reference = typename scc_iterator::reference;
53
54 /// Element of VisitStack during DFS.
55 struct StackElement {
56 NodeRef Node; ///< The current node pointer.
57 ChildItTy NextChild; ///< The next child, modified inplace during DFS.
58 unsigned MinVisited; ///< Minimum uplink value of all children of Node.
59
60 StackElement(NodeRef Node, const ChildItTy &Child, unsigned Min)
61 : Node(Node), NextChild(Child), MinVisited(Min) {}
62
63 bool operator==(const StackElement &Other) const {
64 return Node == Other.Node &&
65 NextChild == Other.NextChild &&
66 MinVisited == Other.MinVisited;
67 }
68 };
69
70 /// The visit counters used to detect when a complete SCC is on the stack.
71 /// visitNum is the global counter.
72 ///
73 /// nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
74 unsigned visitNum;
75 DenseMap<NodeRef, unsigned> nodeVisitNumbers;
76
77 /// Stack holding nodes of the SCC.
78 std::vector<NodeRef> SCCNodeStack;
79
80 /// The current SCC, retrieved using operator*().
81 SccTy CurrentSCC;
82
83 /// DFS stack, Used to maintain the ordering. The top contains the current
84 /// node, the next child to visit, and the minimum uplink value of all child
85 std::vector<StackElement> VisitStack;
86
87 /// A single "visit" within the non-recursive DFS traversal.
88 void DFSVisitOne(NodeRef N);
89
90 /// The stack-based DFS traversal; defined below.
91 void DFSVisitChildren();
92
93 /// Compute the next SCC using the DFS traversal.
94 void GetNextSCC();
95
96 scc_iterator(NodeRef entryN) : visitNum(0) {
97 DFSVisitOne(entryN);
98 GetNextSCC();
99 }
100
101 /// End is when the DFS stack is empty.
102 scc_iterator() = default;
103
104public:
105 static scc_iterator begin(const GraphT &G) {
106 return scc_iterator(GT::getEntryNode(G));
107 }
108 static scc_iterator end(const GraphT &) { return scc_iterator(); }
109
110 /// Direct loop termination test which is more efficient than
111 /// comparison with \c end().
112 bool isAtEnd() const {
113 assert(!CurrentSCC.empty() || VisitStack.empty());
114 return CurrentSCC.empty();
115 }
116
117 bool operator==(const scc_iterator &x) const {
118 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
119 }
120
121 scc_iterator &operator++() {
122 GetNextSCC();
123 return *this;
124 }
125
126 reference operator*() const {
127 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
128 return CurrentSCC;
129 }
130
131 /// Test if the current SCC has a cycle.
132 ///
133 /// If the SCC has more than one node, this is trivially true. If not, it may
134 /// still contain a cycle if the node has an edge back to itself.
135 bool hasCycle() const;
136
137 /// This informs the \c scc_iterator that the specified \c Old node
138 /// has been deleted, and \c New is to be used in its place.
139 void ReplaceNode(NodeRef Old, NodeRef New) {
140 assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
141 // Do the assignment in two steps, in case 'New' is not yet in the map, and
142 // inserting it causes the map to grow.
143 auto tempVal = nodeVisitNumbers[Old];
144 nodeVisitNumbers[New] = tempVal;
145 nodeVisitNumbers.erase(Old);
146 }
147};
148
149template <class GraphT, class GT>
150void scc_iterator<GraphT, GT>::DFSVisitOne(NodeRef N) {
151 ++visitNum;
152 nodeVisitNumbers[N] = visitNum;
153 SCCNodeStack.push_back(N);
154 VisitStack.push_back(StackElement(N, GT::child_begin(N), visitNum));
155#if 0 // Enable if needed when debugging.
156 dbgs() << "TarjanSCC: Node " << N <<
157 " : visitNum = " << visitNum << "\n";
158#endif
159}
160
161template <class GraphT, class GT>
162void scc_iterator<GraphT, GT>::DFSVisitChildren() {
163 assert(!VisitStack.empty());
164 while (VisitStack.back().NextChild != GT::child_end(VisitStack.back().Node)) {
165 // TOS has at least one more child so continue DFS
166 NodeRef childN = *VisitStack.back().NextChild++;
167 auto Visited = nodeVisitNumbers.find(childN);
168 if (Visited == nodeVisitNumbers.end()) {
169 // this node has never been seen.
170 DFSVisitOne(childN);
171 continue;
172 }
173
174 unsigned childNum = Visited->second;
175 if (VisitStack.back().MinVisited > childNum)
176 VisitStack.back().MinVisited = childNum;
177 }
178}
179
180template <class GraphT, class GT> void scc_iterator<GraphT, GT>::GetNextSCC() {
181 CurrentSCC.clear(); // Prepare to compute the next SCC
182 while (!VisitStack.empty()) {
183 DFSVisitChildren();
184
185 // Pop the leaf on top of the VisitStack.
186 NodeRef visitingN = VisitStack.back().Node;
187 unsigned minVisitNum = VisitStack.back().MinVisited;
188 assert(VisitStack.back().NextChild == GT::child_end(visitingN));
189 VisitStack.pop_back();
190
191 // Propagate MinVisitNum to parent so we can detect the SCC starting node.
192 if (!VisitStack.empty() && VisitStack.back().MinVisited > minVisitNum)
193 VisitStack.back().MinVisited = minVisitNum;
194
195#if 0 // Enable if needed when debugging.
196 dbgs() << "TarjanSCC: Popped node " << visitingN <<
197 " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
198 nodeVisitNumbers[visitingN] << "\n";
199#endif
200
201 if (minVisitNum != nodeVisitNumbers[visitingN])
202 continue;
203
204 // A full SCC is on the SCCNodeStack! It includes all nodes below
205 // visitingN on the stack. Copy those nodes to CurrentSCC,
206 // reset their minVisit values, and return (this suspends
207 // the DFS traversal till the next ++).
208 do {
209 CurrentSCC.push_back(SCCNodeStack.back());
210 SCCNodeStack.pop_back();
211 nodeVisitNumbers[CurrentSCC.back()] = ~0U;
212 } while (CurrentSCC.back() != visitingN);
213 return;
214 }
215}
216
217template <class GraphT, class GT>
219 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
220 if (CurrentSCC.size() > 1)
221 return true;
222 NodeRef N = CurrentSCC.front();
223 for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
224 ++CI)
225 if (*CI == N)
226 return true;
227 return false;
228 }
229
230/// Construct the begin iterator for a deduced graph type T.
231template <class T> scc_iterator<T> scc_begin(const T &G) {
233}
234
235/// Construct the end iterator for a deduced graph type T.
236template <class T> scc_iterator<T> scc_end(const T &G) {
237 return scc_iterator<T>::end(G);
238}
239
240/// Sort the nodes of a directed SCC in the decreasing order of the edge
241/// weights. The instantiating GraphT type should have weighted edge type
242/// declared in its graph traits in order to use this iterator.
243///
244/// This is implemented using Kruskal's minimal spanning tree algorithm followed
245/// by Kahn's algorithm to compute a topological order on the MST. First a
246/// maximum spanning tree (forest) is built based on all edges within the SCC
247/// collection. Then a topological walk is initiated on tree nodes that do not
248/// have a predecessor and then applied to all nodes of the SCC. Such order
249/// ensures that high-weighted edges are visited first during the traversal.
250template <class GraphT, class GT = GraphTraits<GraphT>>
252 using NodeType = typename GT::NodeType;
253 using EdgeType = typename GT::EdgeType;
254 using NodesType = std::vector<NodeType *>;
255
256 // Auxilary node information used during the MST calculation.
257 struct NodeInfo {
258 NodeInfo *Group = this;
259 uint32_t Rank = 0;
260 bool Visited = false;
261 DenseSet<const EdgeType *> IncomingMSTEdges;
262 };
263
264 // Find the root group of the node and compress the path from node to the
265 // root.
266 NodeInfo *find(NodeInfo *Node) {
267 if (Node->Group != Node)
268 Node->Group = find(Node->Group);
269 return Node->Group;
270 }
271
272 // Union the source and target node into the same group and return true.
273 // Returns false if they are already in the same group.
274 bool unionGroups(const EdgeType *Edge) {
275 NodeInfo *G1 = find(&NodeInfoMap[Edge->Source]);
276 NodeInfo *G2 = find(&NodeInfoMap[Edge->Target]);
277
278 // If the edge forms a cycle, do not add it to MST
279 if (G1 == G2)
280 return false;
281
282 // Make the smaller rank tree a direct child of high rank tree.
283 if (G1->Rank < G2->Rank)
284 G1->Group = G2;
285 else {
286 G2->Group = G1;
287 // If the ranks are the same, increment root of one tree by one.
288 if (G1->Rank == G2->Rank)
289 G1->Rank++;
290 }
291 return true;
292 }
293
295 NodesType Nodes;
296
297public:
298 scc_member_iterator(const NodesType &InputNodes);
299
300 NodesType &operator*() { return Nodes; }
301};
302
303template <class GraphT, class GT>
305 const NodesType &InputNodes) {
306 if (InputNodes.size() <= 1) {
307 Nodes = InputNodes;
308 return;
309 }
310
311 // Initialize auxilary node information.
312 NodeInfoMap.clear();
313 NodeInfoMap.reserve(InputNodes.size());
314 for (auto *Node : InputNodes) {
315 // Construct a `NodeInfo` object in place. `insert()` would involve a copy
316 // construction, invalidating the initial value of the `Group` field, which
317 // should be `this`.
318 NodeInfoMap.try_emplace(Node);
319 }
320
321 // Sort edges by weights.
322 struct EdgeComparer {
323 bool operator()(const EdgeType *L, const EdgeType *R) const {
324 return L->Weight > R->Weight;
325 }
326 };
327
328 std::multiset<const EdgeType *, EdgeComparer> SortedEdges;
329 for (auto *Node : InputNodes) {
330 for (auto &Edge : Node->Edges) {
331 if (NodeInfoMap.count(Edge.Target))
332 SortedEdges.insert(&Edge);
333 }
334 }
335
336 // Traverse all the edges and compute the Maximum Weight Spanning Tree
337 // using Kruskal's algorithm.
339 for (auto *Edge : SortedEdges) {
340 if (unionGroups(Edge))
341 MSTEdges.insert(Edge);
342 }
343
344 // Run Kahn's algorithm on MST to compute a topological traversal order.
345 // The algorithm starts from nodes that have no incoming edge. These nodes are
346 // "roots" of the MST forest. This ensures that nodes are visited before their
347 // descendants are, thus ensures hot edges are processed before cold edges,
348 // based on how MST is computed.
349 std::queue<NodeType *> Queue;
350 for (const auto *Edge : MSTEdges)
351 NodeInfoMap[Edge->Target].IncomingMSTEdges.insert(Edge);
352
353 // Walk through SortedEdges to initialize the queue, instead of using NodeInfoMap
354 // to ensure an ordered deterministic push.
355 for (auto *Edge : SortedEdges) {
356 auto &Info = NodeInfoMap[Edge->Source];
357 if (!Info.Visited && Info.IncomingMSTEdges.empty()) {
358 Queue.push(Edge->Source);
359 Info.Visited = true;
360 }
361 }
362
363 while (!Queue.empty()) {
364 auto *Node = Queue.front();
365 Queue.pop();
366 Nodes.push_back(Node);
367 for (auto &Edge : Node->Edges) {
368 // Edges to nodes outside the SCC carry no MST state; skip them instead
369 // of inserting a fresh entry (the map must not grow at this point).
370 auto It = NodeInfoMap.find(Edge.Target);
371 if (It == NodeInfoMap.end())
372 continue;
373 NodeInfo &Info = It->second;
374 Info.IncomingMSTEdges.erase(&Edge);
375 if (MSTEdges.count(&Edge) && Info.IncomingMSTEdges.empty()) {
376 Queue.push(Edge.Target);
377 }
378 }
379 }
380
381 assert(InputNodes.size() == Nodes.size() && "missing nodes in MST");
382 std::reverse(Nodes.begin(), Nodes.end());
383}
384} // end namespace llvm
385
386#endif // LLVM_ADT_SCCITERATOR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
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.
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Definition SCCIterator.h:48
scc_iterator & operator++()
static scc_iterator begin(const GraphT &G)
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
static scc_iterator end(const GraphT &)
bool operator==(const scc_iterator &x) const
void ReplaceNode(NodeRef Old, NodeRef New)
This informs the scc_iterator that the specified Old node has been deleted, and New is to be used in ...
bool hasCycle() const
Test if the current SCC has a cycle.
reference operator*() const
scc_member_iterator(const NodesType &InputNodes)
std::pair< NodeId, LaneBitmask > NodeRef
Definition RDFLiveness.h:35
This is an optimization pass for GlobalISel generic memory operations.
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ Other
Any other memory.
Definition ModRef.h:68
scc_iterator< T > scc_end(const T &G)
Construct the end iterator for a deduced graph type T.
#define N