1 //===- CallGraph.cpp - CallGraph analysis for MLIR ------------------------===//
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 // This file contains interfaces and analyses for defining a nested callgraph.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Analysis/CallGraph.h"
14 #include "mlir/IR/Operation.h"
15 #include "mlir/IR/SymbolTable.h"
16 #include "mlir/Interfaces/CallInterfaces.h"
17 #include "llvm/ADT/PointerUnion.h"
18 #include "llvm/ADT/SCCIterator.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 using namespace mlir;
22 
23 //===----------------------------------------------------------------------===//
24 // CallGraphNode
25 //===----------------------------------------------------------------------===//
26 
27 /// Returns if this node refers to the indirect/external node.
28 bool CallGraphNode::isExternal() const { return !callableRegion; }
29 
30 /// Return the callable region this node represents. This can only be called
31 /// on non-external nodes.
32 Region *CallGraphNode::getCallableRegion() const {
33   assert(!isExternal() && "the external node has no callable region");
34   return callableRegion;
35 }
36 
37 /// Adds an reference edge to the given node. This is only valid on the
38 /// external node.
39 void CallGraphNode::addAbstractEdge(CallGraphNode *node) {
40   assert(isExternal() && "abstract edges are only valid on external nodes");
41   addEdge(node, Edge::Kind::Abstract);
42 }
43 
44 /// Add an outgoing call edge from this node.
45 void CallGraphNode::addCallEdge(CallGraphNode *node) {
46   addEdge(node, Edge::Kind::Call);
47 }
48 
49 /// Adds a reference edge to the given child node.
50 void CallGraphNode::addChildEdge(CallGraphNode *child) {
51   addEdge(child, Edge::Kind::Child);
52 }
53 
54 /// Returns true if this node has any child edges.
55 bool CallGraphNode::hasChildren() const {
56   return llvm::any_of(edges, [](const Edge &edge) { return edge.isChild(); });
57 }
58 
59 /// Add an edge to 'node' with the given kind.
60 void CallGraphNode::addEdge(CallGraphNode *node, Edge::Kind kind) {
61   edges.insert({node, kind});
62 }
63 
64 //===----------------------------------------------------------------------===//
65 // CallGraph
66 //===----------------------------------------------------------------------===//
67 
68 /// Recursively compute the callgraph edges for the given operation. Computed
69 /// edges are placed into the given callgraph object.
70 static void computeCallGraph(Operation *op, CallGraph &cg,
71                              CallGraphNode *parentNode, bool resolveCalls) {
72   if (CallOpInterface call = dyn_cast<CallOpInterface>(op)) {
73     // If there is no parent node, we ignore this operation. Even if this
74     // operation was a call, there would be no callgraph node to attribute it
75     // to.
76     if (resolveCalls && parentNode)
77       parentNode->addCallEdge(cg.resolveCallable(call));
78     return;
79   }
80 
81   // Compute the callgraph nodes and edges for each of the nested operations.
82   if (CallableOpInterface callable = dyn_cast<CallableOpInterface>(op)) {
83     if (auto *callableRegion = callable.getCallableRegion())
84       parentNode = cg.getOrAddNode(callableRegion, parentNode);
85     else
86       return;
87   }
88 
89   for (Region &region : op->getRegions())
90     for (Block &block : region)
91       for (Operation &nested : block)
92         computeCallGraph(&nested, cg, parentNode, resolveCalls);
93 }
94 
95 CallGraph::CallGraph(Operation *op) : externalNode(/*callableRegion=*/nullptr) {
96   // Make two passes over the graph, one to compute the callables and one to
97   // resolve the calls. We split these up as we may have nested callable objects
98   // that need to be reserved before the calls.
99   computeCallGraph(op, *this, /*parentNode=*/nullptr, /*resolveCalls=*/false);
100   computeCallGraph(op, *this, /*parentNode=*/nullptr, /*resolveCalls=*/true);
101 }
102 
103 /// Get or add a call graph node for the given region.
104 CallGraphNode *CallGraph::getOrAddNode(Region *region,
105                                        CallGraphNode *parentNode) {
106   assert(region && isa<CallableOpInterface>(region->getParentOp()) &&
107          "expected parent operation to be callable");
108   std::unique_ptr<CallGraphNode> &node = nodes[region];
109   if (!node) {
110     node.reset(new CallGraphNode(region));
111 
112     // Add this node to the given parent node if necessary.
113     if (parentNode)
114       parentNode->addChildEdge(node.get());
115     else
116       // Otherwise, connect all callable nodes to the external node, this allows
117       // for conservatively including all callable nodes within the graph.
118       // FIXME(riverriddle) This isn't correct, this is only necessary for
119       // callable nodes that *could* be called from external sources. This
120       // requires extending the interface for callables to check if they may be
121       // referenced externally.
122       externalNode.addAbstractEdge(node.get());
123   }
124   return node.get();
125 }
126 
127 /// Lookup a call graph node for the given region, or nullptr if none is
128 /// registered.
129 CallGraphNode *CallGraph::lookupNode(Region *region) const {
130   auto it = nodes.find(region);
131   return it == nodes.end() ? nullptr : it->second.get();
132 }
133 
134 /// Resolve the callable for given callee to a node in the callgraph, or the
135 /// external node if a valid node was not resolved.
136 CallGraphNode *CallGraph::resolveCallable(CallOpInterface call) const {
137   Operation *callable = call.resolveCallable();
138   if (auto callableOp = dyn_cast_or_null<CallableOpInterface>(callable))
139     if (auto *node = lookupNode(callableOp.getCallableRegion()))
140       return node;
141 
142   // If we don't have a valid direct region, this is an external call.
143   return getExternalNode();
144 }
145 
146 //===----------------------------------------------------------------------===//
147 // Printing
148 
149 /// Dump the graph in a human readable format.
150 void CallGraph::dump() const { print(llvm::errs()); }
151 void CallGraph::print(raw_ostream &os) const {
152   os << "// ---- CallGraph ----\n";
153 
154   // Functor used to output the name for the given node.
155   auto emitNodeName = [&](const CallGraphNode *node) {
156     if (node->isExternal()) {
157       os << "<External-Node>";
158       return;
159     }
160 
161     auto *callableRegion = node->getCallableRegion();
162     auto *parentOp = callableRegion->getParentOp();
163     os << "'" << callableRegion->getParentOp()->getName() << "' - Region #"
164        << callableRegion->getRegionNumber();
165     if (auto attrs = parentOp->getAttrList().getDictionary())
166       os << " : " << attrs;
167   };
168 
169   for (auto &nodeIt : nodes) {
170     const CallGraphNode *node = nodeIt.second.get();
171 
172     // Dump the header for this node.
173     os << "// - Node : ";
174     emitNodeName(node);
175     os << "\n";
176 
177     // Emit each of the edges.
178     for (auto &edge : *node) {
179       os << "// -- ";
180       if (edge.isCall())
181         os << "Call";
182       else if (edge.isChild())
183         os << "Child";
184 
185       os << "-Edge : ";
186       emitNodeName(edge.getTarget());
187       os << "\n";
188     }
189     os << "//\n";
190   }
191 
192   os << "// -- SCCs --\n";
193 
194   for (auto &scc : make_range(llvm::scc_begin(this), llvm::scc_end(this))) {
195     os << "// - SCC : \n";
196     for (auto &node : scc) {
197       os << "// -- Node :";
198       emitNodeName(node);
199       os << "\n";
200     }
201     os << "\n";
202   }
203 
204   os << "// -------------------\n";
205 }
206