anijain2305 commented on a change in pull request #4922: [Relay][pass] call 
graph for relay
URL: https://github.com/apache/incubator-tvm/pull/4922#discussion_r384183704
 
 

 ##########
 File path: src/relay/pass/call_graph.cc
 ##########
 @@ -0,0 +1,339 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/relay/pass/call_graph.cc
+ * \brief Implementation of APIs to handle the call graph of a Relay module.
+ */
+
+#include "call_graph.h"
+
+#include <tvm/relay/expr_functor.h>
+#include <tvm/runtime/object.h>
+#include <algorithm>
+#include <memory>
+#include <sstream>
+#include <unordered_set>
+#include <vector>
+
+namespace tvm {
+namespace relay {
+
+CallGraph::CallGraph(IRModule module) {
+  auto n = make_object<CallGraphNode>();
+  n->module = std::move(module);
+  auto gvar_funcs = n->module->functions;
+  for (const auto& it : gvar_funcs) {
+    if (const auto* fn = it.second.as<FunctionNode>()) {
+      auto func = GetRef<Function>(fn);
+      // Add the global function to gradually build up the call graph.
+      n->AddToCallGraph(it.first, func);
+    }
+  }
+  data_ = std::move(n);
+}
+
+void CallGraphNode::AddToCallGraph(const GlobalVar& gv, const Function& func) {
+  CHECK(func.defined() && gv.defined());
+  // Add the current global function as an entry to the call grpah.
+  CallGraphEntry* cg_node = LookupGlobalVar(gv);
+
+  // Only GlobalVar nodes need to be handled in a function. It indicates that
+  // the global function of a callee is called by the function that is being
+  // processed. An edge will be added from the current global function, 
cg_node,
+  // to the node that contains the found callee GlobalVarNode.
+  //
+  // This is the major overhead for constructing a call graph because the
+  // post-order visitor will visit each AST node of the current function to
+  // figure out the dependencies between functions.
+  PostOrderVisit(func, [&](const Expr& expr) {
+    if (const GlobalVarNode* gvn = expr.as<GlobalVarNode>()) {
+      auto callee = GetRef<GlobalVar>(gvn);
+      cg_node->AddCalledGlobal(LookupGlobalVar(callee));
+    }
+  });
+}
+
+const CallGraphEntry* CallGraphNode::operator[](const GlobalVar& gv) const {
+  const_iterator cit = call_graph_.find(gv);
+  CHECK(cit != call_graph_.end())
+      << "GlobalVar " << gv->name_hint << " not found in the call graph!";
+  return cit->second.get();
+}
+
+CallGraphEntry* CallGraphNode::operator[](const GlobalVar& gv) {
+  const_iterator cit = call_graph_.find(gv);
+  CHECK(cit != call_graph_.end())
+      << "GlobalVar " << gv->name_hint << " not found in the call graph!";
+  return cit->second.get();
+}
+
+// Query the existence of a GlobalVar in the call graph. It creates an entry if
+// there is no such a node available.
+CallGraphEntry* CallGraphNode::LookupGlobalVar(const GlobalVar& gv) {
+  CHECK(gv.defined());
+
+  // This inserts an element to the call graph if it is not there yet.
+  auto& call_graph_node = call_graph_[gv];
+  if (call_graph_node) return call_graph_node.get();
+
+  CHECK(module->ContainGlobalVar(gv->name_hint))
+      << "GlobalVar " << gv->name_hint << " not found in the current ir 
module";
+
+  // Create the node for the inserted entry.
+  call_graph_node = std::unique_ptr<CallGraphEntry>(new CallGraphEntry(gv));
+  return call_graph_node.get();
+}
+
+void CallGraphNode::Print(std::ostream& os) const {
+  // Print the call graph in the topological order.
+  std::vector<CallGraphEntry*> nodes = TopologicalOrder();
+  for (const auto* cgn : nodes) {
+    cgn->Print(os);
+  }
+}
+
+GlobalVar CallGraphNode::RemoveGlobalVarFromModule(CallGraphEntry* cg_node,
+                                                   bool update_call_graph) {
+  CHECK(cg_node->empty() || (cg_node->IsRecursive() && cg_node->size() == 1))
+      << "Cannot remove global var " << cg_node->GetNameHint()
+      << " from call graph, because it still calls "
+      << cg_node->size() << " other global functions";
+
+  if (update_call_graph) {
+    // Update the call graph by removing all edges that point to the node
+    // `cg_node`.
+    for (auto& it : *this) {
+      it.second->RemoveAllCallTo(cg_node);
+    }
+  }
+  GlobalVar gv = cg_node->GetGlobalVar();
+  call_graph_.erase(gv);
+  // Update the IR module.
+  module->Remove(gv);
+  return gv;
+}
+
+std::vector<CallGraphEntry*> CallGraphNode::GetEntryGlobals() const {
+  std::vector<CallGraphEntry*> ret;
+  // An entry function in Relay is a function that never called by other
+  // functions or only called by itself.
+  for (const auto& it : *this) {
+    if (it.second->GetRefCount() == 0 || it.second->IsRecursiveEntry()) {
+      ret.push_back(it.second.get());
+    }
+  }
+  return ret;
+}
+
+std::vector<CallGraphEntry*> CallGraphNode::TopologicalOrder() const {
+  std::vector<CallGraphEntry*> ret;
+  // Collect all entry nodes.
+  std::vector<CallGraphEntry*> entries = GetEntryGlobals();
+  CallGraphEntry::CallGraphEntrySet visited;
+
+  for (const auto& it : entries) {
+    // Keep tracking the nodes that have been visited.
+    auto topo = it->TopologicalOrder(&visited);
+    // Preprend the collected items. The intermeidate nodes that are shared by
+    // multiple entries are guaranteed to be collected when visiting the
+    // previous entries. Therefore, topological order remains.
+    ret.insert(ret.begin(), topo.begin(), topo.end());
+  }
+
+  // Find out the missing global functions if there are any to help debugging.
+  if (ret.size() != module->functions.size()) {
+    for (auto it : module->functions) {
+      if (visited.find((*this)[it.first]) == visited.end()) {
+        LOG(WARNING) << "Missing global:" << it.first->name_hint
+                     << " with # refs = " << (*this)[it.first]->GetRefCount();
+      }
+    }
+    LOG(FATAL) << "Expected " << module->functions.size()
+               << " globals, but received "
+               << ret.size();
+  }
+
+  return ret;
+}
+
+// A BSF traverser is used to collect the nodes in a CallGraphEntry. The nodes
+// that are visited by previous CallGraphEntry entries can be memoized. This
+// helps us to make sure no entry will be visited multiple times when 
collecting
+// the nodes for an entir call graph.
 
 Review comment:
   entir -> entire

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to