ir_functor_test.cc 1.92 KB
Newer Older
tqchen committed
1 2 3
#include <dmlc/logging.h>
#include <gtest/gtest.h>
#include <tvm/tvm.h>
4
#include <tvm/ir_functor.h>
5
#include <tvm/ir_functor_ext.h>
tqchen committed
6 7 8

TEST(IRF, Basic) {
  using namespace tvm;
9
  using namespace tvm::ir;
tqchen committed
10 11 12
  Var x("x");
  auto z = x + 1;

13
  IRFunctor<int(const NodeRef& n, int b)> f;
tqchen committed
14 15 16 17 18 19 20 21 22 23 24
  LOG(INFO) << "x";
  f.set_dispatch<Variable>([](const Variable* n, int b) {
      return b;
    });
  f.set_dispatch<Add>([](const Add* n, int b) {
      return b + 2;
    });
  CHECK_EQ(f(x, 2),  2);
  CHECK_EQ(f(z, 2),  4);
}

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
TEST(IRF, ExprTransform) {
  using namespace tvm;
  using namespace tvm::ir;
  Var x("x");
  auto z = x + 1;

  class MyExprFunctor
      : public ir::ExprFunctor<int(const Expr&, int)> {
   public:
    int VisitExpr_(const Variable* op, int b) final {
      return b;
    }
    int VisitExpr_(const IntImm* op, int b) final {
      return op->value;
    }
    int VisitExpr_(const Add* op, int b) final {
      return VisitExpr(op->a, b) + VisitExpr(op->b, b);
    }
  };
  MyExprFunctor f;
  CHECK_EQ(f(x, 2),  2);
  CHECK_EQ(f(z, 2),  3);
  try {
    f(z - 1, 2);
    LOG(FATAL) << "should fail";
  } catch(dmlc::Error) {
  }
}

TEST(IRF, ExprVisit) {
  using namespace tvm;
  using namespace tvm::ir;
  Var x("x");
  auto z = x + 1;

  class MyVisitor
      : public ir::ExprFunctor<void(const Expr&)>,
        public ir::StmtFunctor<void(const Stmt&)> {
   public:
    int count = 0;
    // implementation
    void VisitExpr_(const Variable* op) final {
      ++count;
    }
    void VisitExpr_(const IntImm* op) final {
    }
    void VisitExpr_(const Add* op) final {
      VisitExpr(op->a);
      VisitExpr(op->b);
    }
    void VisitStmt_(const Evaluate* op) final {
      VisitExpr(op->value);
    }
  };
  MyVisitor v;
Tianqi Chen committed
80
  v.VisitStmt(Evaluate::make(z));
81 82 83
  CHECK_EQ(v.count, 1);
}

tqchen committed
84 85 86 87 88
int main(int argc, char ** argv) {
  testing::InitGoogleTest(&argc, argv);
  testing::FLAGS_gtest_death_test_style = "threadsafe";
  return RUN_ALL_TESTS();
}