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


##########
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>()) {

Review Comment:
   Not sure it's entirely necessary, but you can reduce nesting with a 
construction like
   ```c++
   if (!base_func.as<PrimFunc>()) { continue; }
   auto prim_func = Downcast<PrimFunc>(base_func);
   // ...
   ```
   I'm a fan of reducing nesting when possible, but that's up to you.



##########
src/tir/ir/specialize.cc:
##########
@@ -140,16 +141,54 @@ class PrimFuncSpecializer : public StmtExprMutator {
     }
   }
 
+  Stmt VisitStmt_(const DeclBufferNode* op) final {
+    // Visit the buffer before delegating to StmtExprMutator, so the
+    // buffer's replacement will be defined before the point of use.
+    Var old_buffer_var = op->buffer->data;
+    Buffer new_buf = MutateAllocBuffer(op->buffer);
+
+    auto node = Downcast<DeclBuffer>(StmtExprMutator::VisitStmt_(op));
+
+    if (!new_buf.same_as(node->buffer)) {
+      node.CopyOnWrite()->buffer = new_buf;
+    }
+
+    // If the buffer variable is begin remapped to an expression, we

Review Comment:
   ```suggestion
       // If the buffer variable is being remapped to an expression, we
   ```



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

Review Comment:
   I assume "indirect callers" is aiming to get cases like mutual recursion?



##########
src/tir/ir/specialize.cc:
##########
@@ -115,18 +116,18 @@ class PrimFuncSpecializer : public StmtExprMutator {
  private:
   Stmt VisitStmt_(const BlockNode* op) final {
     // Step.0. Define buffer mappings which is allocated inside the block
-    Array<Buffer> alloc_buffers = op->alloc_buffers.Map(
-        std::bind(&PrimFuncSpecializer::MutateAllocBuffer, this, 
std::placeholders::_1));
+    Array<Buffer> alloc_buffers =
+        op->alloc_buffers.Map([this](const auto& buf) { return 
MutateAllocBuffer(buf); });

Review Comment:
   Much cleaner this way :)



##########
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:
   This is perhaps a place where reducing nesting might improve readability.



##########
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 {

Review Comment:
   You should probably mention the details from the PR description as for why 
`EvaluateNode` is the only case handled



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