Lunderberg commented on code in PR #16184:
URL: https://github.com/apache/tvm/pull/16184#discussion_r1432190263


##########
src/tir/transforms/inline_private_functions.cc:
##########
@@ -0,0 +1,273 @@
+/*
+ * 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 inline_private_functions.cc
+ * \brief Inline private functions to their callsite
+ */
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/builtin.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt.h>
+#include <tvm/tir/stmt_functor.h>
+#include <tvm/tir/transform.h>
+
+namespace tvm {
+namespace tir {
+namespace transform {
+
+namespace {
+
+template <typename T>
+using PSet = std::unordered_set<T, ObjectPtrHash, ObjectPtrEqual>;
+
+template <typename T, typename U>
+using PMap = std::unordered_map<T, U, ObjectPtrHash, ObjectPtrEqual>;
+
+PMap<GlobalVar, PSet<GlobalVar>> CollectCallMap(const IRModule& mod) {
+  struct Visitor : StmtExprVisitor {
+    GlobalVar current;
+    PMap<GlobalVar, PSet<GlobalVar>> caller_lookup;
+
+    void VisitExpr_(const CallNode* op) {
+      if (auto gvar = op->op.as<GlobalVar>()) {
+        caller_lookup[gvar.value()].insert(current);
+      }
+      StmtExprVisitor::VisitExpr_(op);
+    }
+  } visitor;
+
+  for (const auto& [gvar, base_func] : mod->functions) {
+    if (auto prim_func = base_func.as<PrimFuncNode>()) {
+      visitor.current = gvar;
+      visitor(prim_func->body);
+    }
+  }
+
+  return visitor.caller_lookup;
+}
+
+PSet<GlobalVar> CollectRecursiveFunctions(const IRModule& mod) {
+  // Collect all direct callers
+  auto call_map = CollectCallMap(mod);
+
+  // Propagate to find all indirect callers
+  while (true) {
+    bool made_change = false;
+    for (const auto& [callee, callers] : call_map) {
+      for (const auto& caller : callers) {
+        if (auto it = call_map.find(caller); it != call_map.end()) {
+          PSet<GlobalVar>& indirect_callers = it->second;
+
+          auto res = indirect_callers.insert(callee);
+          made_change = made_change || res.second;
+        }
+      }
+    }
+    if (!made_change) {
+      break;
+    }
+  }
+
+  // Filter all GlobalVars that can be called by themselves, either
+  // directly or indirectly.
+  PSet<GlobalVar> recursive_funcs;
+  for (const auto& [caller, callees] : call_map) {
+    if (callees.count(caller)) {
+      recursive_funcs.insert(caller);
+    }
+  }
+  return recursive_funcs;
+}
+
+Map<GlobalVar, PrimFunc> CollectInlinablePrimFuncs(const IRModule& mod) {
+  auto recursive_functions = CollectRecursiveFunctions(mod);
+
+  Map<GlobalVar, PrimFunc> output;
+  for (const auto& [gvar, base_func] : mod->functions) {
+    if (auto opt = base_func.as<PrimFunc>()) {
+      auto prim_func = opt.value();
+
+      // Only inline private functions.  Externally-exposed functions
+      // must be preserved so to avoid breaking callsites outside of
+      // the IRModule.
+      bool is_exposed = 
prim_func->GetAttr<String>(tvm::attr::kGlobalSymbol).defined();
+
+      // We do not currently implement any analysis for termination of
+      // a function.  If a recursive function requires runtime checks
+      // in order to terminate, we would keep inlining until the
+      // recursive visits segfault.
+      bool is_recursive = recursive_functions.count(gvar);
+
+      // We do not currently support inlining of functions that accept
+      // buffer arguments.
+      bool has_buffer_arguments = prim_func->buffer_map.size();
+
+      // We do not currently support inlining of schedulable TIR
+      // functions.  To support this use case, repeated names in
+      // `tir::Block` nodes resulting from multiple calls to the same
+      // inlined function will need to be de-duplicated.
+      bool has_block_node = prim_func->body.as<BlockRealizeNode>();
+
+      if (!is_exposed && !is_recursive && !has_buffer_arguments && 
!has_block_node) {
+        output.Set(gvar, prim_func);
+      }
+    }
+  }
+
+  return output;
+}
+
+class PrimFuncInliner : StmtExprMutator {
+ public:
+  explicit PrimFuncInliner(Map<GlobalVar, PrimFunc> inlinable_funcs)
+      : inlinable_funcs_(inlinable_funcs) {
+    for (const auto& [gvar, callee] : inlinable_funcs_) {
+      removable_funcs_.insert(gvar);
+    }
+  }
+
+  PrimFunc VisitFunc(PrimFunc func) {
+    current_target_ = func->GetAttr<Target>(tvm::attr::kTarget);
+    auto new_body = VisitStmt(func->body);
+    current_target_ = NullOpt;
+
+    if (!new_body.same_as(func->body)) {
+      func.CopyOnWrite()->body = new_body;
+    }
+
+    return func;
+  }
+
+  PSet<GlobalVar> GetRemovableFunctions() const { return removable_funcs_; }
+
+ private:
+  Stmt VisitStmt_(const EvaluateNode* eval) override {
+    if (auto call = eval->value.as<CallNode>()) {
+      if (auto gvar = call->op.as<GlobalVar>()) {
+        if (auto opt_callee = inlinable_funcs_.Get(gvar.value())) {

Review Comment:
   Yeah, the nesting is a bit deep here.  Reordered to instead call a 
`GetInlinedSubroutine` method, and let me know what you think on it.



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to