LLVM 24.0.0git
DependenceGraphBuilder.cpp
Go to the documentation of this file.
1//===- DependenceGraphBuilder.cpp ------------------------------------------==//
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// This file implements common steps of the build algorithm for construction
9// of dependence graphs such as DDG and PDG.
10//===----------------------------------------------------------------------===//
11
17#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/DDG.h"
19
20using namespace llvm;
21
22#define DEBUG_TYPE "dgb"
23
24STATISTIC(TotalGraphs, "Number of dependence graphs created.");
25STATISTIC(TotalDefUseEdges, "Number of def-use edges created.");
26STATISTIC(TotalMemoryEdges, "Number of memory dependence edges created.");
27STATISTIC(TotalFineGrainedNodes, "Number of fine-grained nodes created.");
28STATISTIC(TotalPiBlockNodes, "Number of pi-block nodes created.");
29STATISTIC(TotalConfusedEdges,
30 "Number of confused memory dependencies between two nodes.");
31STATISTIC(TotalEdgeReversals,
32 "Number of times the source and sink of dependence was reversed to "
33 "expose cycles in the graph.");
34
36
37//===--------------------------------------------------------------------===//
38// AbstractDependenceGraphBuilder implementation
39//===--------------------------------------------------------------------===//
40
41template <class G>
43 // The BBList is expected to be in program order.
44 size_t NextOrdinal = 1;
45 for (auto *BB : BBList)
46 for (auto &I : *BB)
47 InstOrdinalMap.insert(std::make_pair(&I, NextOrdinal++));
48}
49
50template <class G>
52 ++TotalGraphs;
53 assert(IMap.empty() && "Expected empty instruction map at start");
54 for (BasicBlock *BB : BBList)
55 for (Instruction &I : *BB) {
56 auto &NewNode = createFineGrainedNode(I);
57 IMap.insert(std::make_pair(&I, &NewNode));
58 NodeOrdinalMap.insert(std::make_pair(&NewNode, getOrdinal(I)));
59 ++TotalFineGrainedNodes;
60 }
61}
62
63template <class G>
65 // Create a root node that connects to every connected component of the graph.
66 // This is done to allow graph iterators to visit all the disjoint components
67 // of the graph, in a single walk.
68 //
69 // This algorithm works by going through each node of the graph and for each
70 // node N, do a DFS starting from N. A rooted edge is established between the
71 // root node and N (if N is not yet visited). All the nodes reachable from N
72 // are marked as visited and are skipped in the DFS of subsequent nodes.
73 //
74 // Note: This algorithm tries to limit the number of edges out of the root
75 // node to some extent, but there may be redundant edges created depending on
76 // the iteration order. For example for a graph {A -> B}, an edge from the
77 // root node is added to both nodes if B is visited before A. While it does
78 // not result in minimal number of edges, this approach saves compile-time
79 // while keeping the number of edges in check.
80 auto &RootNode = createRootNode();
82 for (auto *N : Graph) {
83 if (*N == RootNode)
84 continue;
85 for (auto I : depth_first_ext(N, Visited))
86 if (I == N)
87 createRootedEdge(RootNode, *N);
88 }
89}
90
93 return;
94
95 LLVM_DEBUG(dbgs() << "==== Start of Creation of Pi-Blocks ===\n");
96
97 // The overall algorithm is as follows:
98 // 1. Identify SCCs and for each SCC create a pi-block node containing all
99 // the nodes in that SCC.
100 // 2. Identify incoming edges incident to the nodes inside of the SCC and
101 // reconnect them to the pi-block node.
102 // 3. Identify outgoing edges from the nodes inside of the SCC to nodes
103 // outside of it and reconnect them so that the edges are coming out of the
104 // SCC node instead.
105
106 // Adding nodes as we iterate through the SCCs cause the SCC
107 // iterators to get invalidated. To prevent this invalidation, we first
108 // collect a list of nodes that are part of an SCC, and then iterate over
109 // those lists to create the pi-block nodes. Each element of the list is a
110 // list of nodes in an SCC. Note: trivial SCCs containing a single node are
111 // ignored.
113 for (auto &SCC : make_range(scc_begin(&Graph), scc_end(&Graph))) {
114 if (SCC.size() > 1)
115 ListOfSCCs.emplace_back(SCC.begin(), SCC.end());
116 }
117
118 for (NodeListType &NL : ListOfSCCs) {
119 LLVM_DEBUG(dbgs() << "Creating pi-block node with " << NL.size()
120 << " nodes in it.\n");
121
122 // SCC iterator may put the nodes in an order that's different from the
123 // program order. To preserve original program order, we sort the list of
124 // nodes based on ordinal numbers computed earlier.
125 llvm::sort(NL, [&](NodeType *LHS, NodeType *RHS) {
126 return getOrdinal(*LHS) < getOrdinal(*RHS);
127 });
128
129 NodeType &PiNode = createPiBlock(NL);
130 ++TotalPiBlockNodes;
131
132 // Build a set to speed up the lookup for edges whose targets
133 // are inside the SCC.
135
136 // We have the set of nodes in the SCC. We go through the set of nodes
137 // that are outside of the SCC and look for edges that cross the two sets.
138 for (NodeType *N : Graph) {
139
140 // Skip the SCC node and all the nodes inside of it.
141 if (*N == PiNode || NodesInSCC.count(N))
142 continue;
143
144 enum Direction {
145 Incoming, // Incoming edges to the SCC
146 Outgoing, // Edges going ot of the SCC
147 DirectionCount // To make the enum usable as an array index.
148 };
149
150 // Use these flags to help us avoid creating redundant edges. If there
151 // are more than one edges from an outside node to inside nodes, we only
152 // keep one edge from that node to the pi-block node. Similarly, if
153 // there are more than one edges from inside nodes to an outside node,
154 // we only keep one edge from the pi-block node to the outside node.
155 // There is a flag defined for each direction (incoming vs outgoing) and
156 // for each type of edge supported, using a two-dimensional boolean
157 // array.
158 using EdgeKind = typename EdgeType::EdgeKind;
159 EnumeratedArray<bool, EdgeKind> EdgeAlreadyCreated[DirectionCount]{false,
160 false};
161
162 auto createEdgeOfKind = [this](NodeType &Src, NodeType &Dst,
163 const EdgeKind K) {
164 switch (K) {
165 case EdgeKind::RegisterDefUse:
166 createDefUseEdge(Src, Dst);
167 break;
168 case EdgeKind::MemoryDependence:
169 createMemoryEdge(Src, Dst);
170 break;
171 case EdgeKind::Rooted:
172 createRootedEdge(Src, Dst);
173 break;
174 default:
175 llvm_unreachable("Unsupported type of edge.");
176 }
177 };
178
179 auto reconnectEdges = [&](NodeType *Src, NodeType *Dst, NodeType *New,
180 const Direction Dir) {
181 if (!Src->hasEdgeTo(*Dst))
182 return;
184 dbgs() << "reconnecting("
185 << (Dir == Direction::Incoming ? "incoming)" : "outgoing)")
186 << ":\nSrc:" << *Src << "\nDst:" << *Dst << "\nNew:" << *New
187 << "\n");
188 assert((Dir == Direction::Incoming || Dir == Direction::Outgoing) &&
189 "Invalid direction.");
190
192 Src->findEdgesTo(*Dst, EL);
193 for (EdgeType *OldEdge : EL) {
194 EdgeKind Kind = OldEdge->getKind();
195 if (!EdgeAlreadyCreated[Dir][Kind]) {
196 if (Dir == Direction::Incoming) {
197 createEdgeOfKind(*Src, *New, Kind);
198 LLVM_DEBUG(dbgs() << "created edge from Src to New.\n");
199 } else if (Dir == Direction::Outgoing) {
200 createEdgeOfKind(*New, *Dst, Kind);
201 LLVM_DEBUG(dbgs() << "created edge from New to Dst.\n");
202 }
203 EdgeAlreadyCreated[Dir][Kind] = true;
204 }
205 Src->removeEdge(*OldEdge);
206 destroyEdge(*OldEdge);
207 LLVM_DEBUG(dbgs() << "removed old edge between Src and Dst.\n\n");
208 }
209 };
210
211 for (NodeType *SCCNode : NL) {
212 // Process incoming edges incident to the pi-block node.
213 reconnectEdges(N, SCCNode, &PiNode, Direction::Incoming);
214
215 // Process edges that are coming out of the pi-block node.
216 reconnectEdges(SCCNode, N, &PiNode, Direction::Outgoing);
217 }
218 }
219 }
220
221 // Ordinal maps are no longer needed.
222 InstOrdinalMap.clear();
223 NodeOrdinalMap.clear();
224
225 LLVM_DEBUG(dbgs() << "==== End of Creation of Pi-Blocks ===\n");
226}
227
229 for (NodeType *N : Graph) {
230 InstructionListType SrcIList;
231 N->collectInstructions([](const Instruction *I) { return true; }, SrcIList);
232
233 // Use a set to mark the targets that we link to N, so we don't add
234 // duplicate def-use edges when more than one instruction in a target node
235 // use results of instructions that are contained in N.
236 SmallPtrSet<NodeType *, 4> VisitedTargets;
237
238 for (Instruction *II : SrcIList) {
239 for (Instruction *UI : II->users()) {
240 NodeType *DstNode = IMap.lookup(UI);
241
242 // In the case of loops, the scope of the subgraph is all the
243 // basic blocks (and instructions within them) belonging to the loop. We
244 // simply ignore all the edges coming from (or going into) instructions
245 // or basic blocks outside of this range.
246 if (!DstNode) {
248 dbgs()
249 << "skipped def-use edge since the sink" << *UI
250 << " is outside the range of instructions being considered.\n");
251 continue;
252 }
253
254 // Self dependencies are ignored because they are redundant and
255 // uninteresting.
256 if (DstNode == N) {
258 << "skipped def-use edge since the sink and the source ("
259 << N << ") are the same.\n");
260 continue;
261 }
262
263 if (VisitedTargets.insert(DstNode).second) {
264 createDefUseEdge(*N, *DstNode);
265 ++TotalDefUseEdges;
266 }
267 }
268 }
269 }
270}
271
272template <class G>
274 using DGIterator = typename G::iterator;
275 auto isMemoryAccess = [](const Instruction *I) {
276 return I->mayReadOrWriteMemory();
277 };
278 for (DGIterator SrcIt = Graph.begin(), E = Graph.end(); SrcIt != E; ++SrcIt) {
279 InstructionListType SrcIList;
280 (*SrcIt)->collectInstructions(isMemoryAccess, SrcIList);
281 if (SrcIList.empty())
282 continue;
283
284 for (DGIterator DstIt = SrcIt; DstIt != E; ++DstIt) {
285 if (**SrcIt == **DstIt)
286 continue;
287 InstructionListType DstIList;
288 (*DstIt)->collectInstructions(isMemoryAccess, DstIList);
289 if (DstIList.empty())
290 continue;
291 bool ForwardEdgeCreated = false;
292 bool BackwardEdgeCreated = false;
293 for (Instruction *ISrc : SrcIList) {
294 for (Instruction *IDst : DstIList) {
295 auto D = DI.depends(ISrc, IDst);
296 if (!D)
297 continue;
298
299 // If we have a dependence with its left-most non-'=' direction
300 // being '>' we need to reverse the direction of the edge, because
301 // the source of the dependence cannot occur after the sink. For
302 // confused dependencies, we will create edges in both directions to
303 // represent the possibility of a cycle.
304
305 auto createConfusedEdges = [&](NodeType &Src, NodeType &Dst) {
306 if (!ForwardEdgeCreated) {
307 createMemoryEdge(Src, Dst);
308 ++TotalMemoryEdges;
309 }
310 if (!BackwardEdgeCreated) {
311 createMemoryEdge(Dst, Src);
312 ++TotalMemoryEdges;
313 }
314 ForwardEdgeCreated = BackwardEdgeCreated = true;
315 ++TotalConfusedEdges;
316 };
317
318 auto createForwardEdge = [&](NodeType &Src, NodeType &Dst) {
319 if (!ForwardEdgeCreated) {
320 createMemoryEdge(Src, Dst);
321 ++TotalMemoryEdges;
322 }
323 ForwardEdgeCreated = true;
324 };
325
326 auto createBackwardEdge = [&](NodeType &Src, NodeType &Dst) {
327 if (!BackwardEdgeCreated) {
328 createMemoryEdge(Dst, Src);
329 ++TotalMemoryEdges;
330 }
331 BackwardEdgeCreated = true;
332 };
333
334 if (D->isConfused())
335 createConfusedEdges(**SrcIt, **DstIt);
336 else if (D->isOrdered() && !D->isLoopIndependent()) {
337 bool ReversedEdge = false;
338 for (unsigned Level = 1; Level <= D->getLevels(); ++Level) {
339 if (D->getDirection(Level) == Dependence::DVEntry::EQ)
340 continue;
341 else if (D->getDirection(Level) == Dependence::DVEntry::GT) {
342 createBackwardEdge(**SrcIt, **DstIt);
343 ReversedEdge = true;
344 ++TotalEdgeReversals;
345 break;
346 } else if (D->getDirection(Level) == Dependence::DVEntry::LT)
347 break;
348 else {
349 createConfusedEdges(**SrcIt, **DstIt);
350 break;
351 }
352 }
353 if (!ReversedEdge)
354 createForwardEdge(**SrcIt, **DstIt);
355 } else
356 createForwardEdge(**SrcIt, **DstIt);
357
358 // Avoid creating duplicate edges.
359 if (ForwardEdgeCreated && BackwardEdgeCreated)
360 break;
361 }
362
363 // If we've created edges in both directions, there is no more
364 // unique edge that we can create between these two nodes, so we
365 // can exit early.
366 if (ForwardEdgeCreated && BackwardEdgeCreated)
367 break;
368 }
369 }
370 }
371}
372
374 if (!shouldSimplify())
375 return;
376 LLVM_DEBUG(dbgs() << "==== Start of Graph Simplification ===\n");
377
378 // This algorithm works by first collecting a set of candidate nodes that have
379 // an out-degree of one (in terms of def-use edges), and then ignoring those
380 // whose targets have an in-degree more than one. Each node in the resulting
381 // set can then be merged with its corresponding target and put back into the
382 // worklist until no further merge candidates are available.
383 SmallPtrSet<NodeType *, 32> CandidateSourceNodes;
384
385 // A mapping between nodes and their in-degree. To save space, this map
386 // only contains nodes that are targets of nodes in the CandidateSourceNodes.
387 DenseMap<NodeType *, unsigned> TargetInDegreeMap;
388
389 for (NodeType *N : Graph) {
390 if (N->getEdges().size() != 1)
391 continue;
392 EdgeType &Edge = N->back();
393 if (!Edge.isDefUse())
394 continue;
395 CandidateSourceNodes.insert(N);
396
397 // Insert an element into the in-degree map and initialize to zero. The
398 // count will get updated in the next step.
399 TargetInDegreeMap.insert({&Edge.getTargetNode(), 0});
400 }
401
402 LLVM_DEBUG({
403 dbgs() << "Size of candidate src node list:" << CandidateSourceNodes.size()
404 << "\nNode with single outgoing def-use edge:\n";
405 for (NodeType *N : CandidateSourceNodes) {
406 dbgs() << N << "\n";
407 }
408 });
409
410 for (NodeType *N : Graph) {
411 for (EdgeType *E : *N) {
412 NodeType *Tgt = &E->getTargetNode();
413 auto TgtIT = TargetInDegreeMap.find(Tgt);
414 if (TgtIT != TargetInDegreeMap.end())
415 ++(TgtIT->second);
416 }
417 }
418
419 LLVM_DEBUG({
420 dbgs() << "Size of target in-degree map:" << TargetInDegreeMap.size()
421 << "\nContent of in-degree map:\n";
422 for (auto &I : TargetInDegreeMap) {
423 dbgs() << I.first << " --> " << I.second << "\n";
424 }
425 });
426
427 SmallVector<NodeType *, 32> Worklist(CandidateSourceNodes.begin(),
428 CandidateSourceNodes.end());
429 while (!Worklist.empty()) {
430 NodeType &Src = *Worklist.pop_back_val();
431 // As nodes get merged, we need to skip any node that has been removed from
432 // the candidate set (see below).
433 if (!CandidateSourceNodes.erase(&Src))
434 continue;
435
436 assert(Src.getEdges().size() == 1 &&
437 "Expected a single edge from the candidate src node.");
438 NodeType &Tgt = Src.back().getTargetNode();
439 assert(TargetInDegreeMap.find(&Tgt) != TargetInDegreeMap.end() &&
440 "Expected target to be in the in-degree map.");
441
442 if (TargetInDegreeMap[&Tgt] != 1)
443 continue;
444
445 if (!areNodesMergeable(Src, Tgt))
446 continue;
447
448 // Do not merge if there is also an edge from target to src (immediate
449 // cycle).
450 if (Tgt.hasEdgeTo(Src))
451 continue;
452
453 LLVM_DEBUG(dbgs() << "Merging:" << Src << "\nWith:" << Tgt << "\n");
454
455 mergeNodes(Src, Tgt);
456
457 // If the target node is in the candidate set itself, we need to put the
458 // src node back into the worklist again so it gives the target a chance
459 // to get merged into it. For example if we have:
460 // {(a)->(b), (b)->(c), (c)->(d), ...} and the worklist is initially {b, a},
461 // then after merging (a) and (b) together, we need to put (a,b) back in
462 // the worklist so that (c) can get merged in as well resulting in
463 // {(a,b,c) -> d}
464 // We also need to remove the old target (b), from the worklist. We first
465 // remove it from the candidate set here, and skip any item from the
466 // worklist that is not in the set.
467 if (CandidateSourceNodes.erase(&Tgt)) {
468 Worklist.push_back(&Src);
469 CandidateSourceNodes.insert(&Src);
470 LLVM_DEBUG(dbgs() << "Putting " << &Src << " back in the worklist.\n");
471 }
472 }
473 LLVM_DEBUG(dbgs() << "=== End of Graph Simplification ===\n");
474}
475
476template <class G>
478
479 // If we don't create pi-blocks, then we may not have a DAG.
481 return;
482
484 using NodeKind = typename NodeType::NodeKind;
485 for (NodeType *N : post_order(&Graph)) {
486 if (N->getKind() == NodeKind::PiBlock) {
487 // Put members of the pi-block right after the pi-block itself, for
488 // convenience.
489 const NodeListType &PiBlockMembers = getNodesInPiBlock(*N);
490 llvm::append_range(NodesInPO, PiBlockMembers);
491 }
492 NodesInPO.push_back(N);
493 }
494
495 size_t OldSize = Graph.Nodes.size();
496 Graph.Nodes.clear();
497 append_range(Graph.Nodes, reverse(NodesInPO));
498 if (Graph.Nodes.size() != OldSize)
499 assert(false &&
500 "Expected the number of nodes to stay the same after the sort");
501}
502
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
SmallVector< Instruction *, 2 > InstructionListType
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
This file defines an array type that can be indexed using scoped enum values.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:249
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This abstract builder class defines a set of high-level steps for creating DDG-like graphs.
void createAndConnectRootNode()
Create a root node and add edges such that each node in the graph is reachable from the root.
void computeInstructionOrdinals()
Compute ordinal numbers for each instruction and store them in a map for future look up.
virtual const NodeListType & getNodesInPiBlock(const NodeType &N)=0
Given a pi-block node, return a vector of all the nodes contained within it.
virtual EdgeType & createMemoryEdge(NodeType &Src, NodeType &Tgt)=0
Create a memory dependence edge going from Src to Tgt.
virtual bool shouldSimplify() const
Return true if graph simplification step is requested, and false otherwise.
void sortNodesTopologically()
Topologically sort the graph nodes.
virtual NodeType & createFineGrainedNode(Instruction &I)=0
Create an atomic node in the graph given a single instruction.
virtual EdgeType & createRootedEdge(NodeType &Src, NodeType &Tgt)=0
void createFineGrainedNodes()
Create fine grained nodes.
InstToOrdinalMap InstOrdinalMap
A mapping from each instruction to an ordinal number.
virtual EdgeType & createDefUseEdge(NodeType &Src, NodeType &Tgt)=0
Create a def-use edge going from Src to Tgt.
void createMemoryDependencyEdges()
Analyze data dependencies that exist between memory loads or stores, in the graph nodes and create ed...
virtual void mergeNodes(NodeType &A, NodeType &B)=0
Append the content of node B into node A and remove B and the edge between A and B from the graph.
DependenceInfo & DI
Dependence information used to create memory dependence edges in the graph.
void simplify()
Go through all the nodes in the graph and collapse any two nodes 'a' and 'b' if all of the following ...
const BasicBlockListType & BBList
The list of basic blocks to consider when building the graph.
InstToNodeMap IMap
A mapping from instructions to the corresponding nodes in the graph.
size_t getOrdinal(Instruction &I)
Given an instruction I return its associated ordinal number.
SmallVector< NodeType *, 4 > NodeListType
void createDefUseEdges()
Analyze the def-use chains and create edges from the nodes containing definitions to the nodes contai...
NodeToOrdinalMap NodeOrdinalMap
A mapping from nodes to an ordinal number.
virtual bool areNodesMergeable(const NodeType &A, const NodeType &B) const =0
Return true if it's safe to merge the two nodes.
void createPiBlocks()
Apply graph abstraction to groups of nodes that belong to a strongly connected component of the graph...
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Encapsulate some common data and functionality needed for different variations of data dependence gra...
Definition DDG.h:252
size_type size() const
bool erase(PtrType Ptr)
Remove pointer from the set.
iterator end() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto post_order(const T &G)
Post-order traversal of a graph.
scc_iterator< T > scc_end(const T &G)
Construct the end iterator for a deduced graph type T.
#define N
Determine the kind of a node from its type.