inline.cc 1.68 KB
Newer Older
tqchen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*!
 *  Copyright (c) 2016 by Contributors
 * \file inline.cc
 */
#include <tvm/ir.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>

namespace tvm {
namespace ir {

// inliner to inline a function
// the result may not be SSA,
// ConvertSSA need to be applied after this pass
15
class IRInline final : public IRMutator {
tqchen committed
16 17 18 19
 public:
  IRInline(FunctionRef f, Array<Var> args, Expr body)
      : f_(f), args_(args), body_(body) {}

20 21 22 23 24 25
  Expr Mutate_(const Call* op, const Expr& e) final {
    Expr expr = IRMutator::Mutate_(op, e);
    op = expr.as<Call>();

    if (op->func == f_) {
      CHECK_EQ(op->value_index, 0);
26
      expr = body_;
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
      CHECK_EQ(args_.size(), op->args.size());

      bool has_side_effect = false;
      for (size_t i = 0; i < op->args.size(); ++i) {
        if (HasSideEffect(op->args[i])) has_side_effect = true;
      }
      if (has_side_effect) {
        for (size_t i = 0; i < args_.size(); ++i) {
          expr = Let::make(args_[i], op->args[i], expr);
        }
      } else {
        Map<Var, Expr> vmap;
        for (size_t i = 0; i < args_.size(); ++i) {
          vmap.Set(args_[i], op->args[i]);
        }
        expr = Substitute(
            Evaluate::make(expr), vmap).as<Evaluate>()->value;
44
      }
tqchen committed
45
      return expr;
46
    } else {
47
      return expr;
tqchen committed
48 49 50 51 52 53 54 55 56
    }
  }

 private:
  FunctionRef f_;
  Array<Var> args_;
  Expr body_;
};

57 58
Stmt Inline(Stmt stmt,
            FunctionRef f,
tqchen committed
59
            Array<Var> args,
60
            Expr body) {
61 62
  CHECK_EQ(f->num_outputs(), 1)
      << "can only inline output single value operation";
63 64 65
  Stmt ret = IRInline(f, args, body).Mutate(stmt);
  if (ret.same_as(stmt)) return ret;
  return ConvertSSA(ret);
tqchen committed
66 67 68
}
}  // namespace ir
}  // namespace tvm