ir.h 45.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * 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.
 */
tqchen committed
19
/*!
tqchen committed
20
 * \file tvm/ir.h
tqchen committed
21 22
 * \brief Additional high level nodes in the IR
 */
23 24
// Acknowledgement: Most low-level IR nodes originate from Halide.

tqchen committed
25 26
#ifndef TVM_IR_H_
#define TVM_IR_H_
tqchen committed
27 28 29

#include <type_traits>
#include <string>
30 31
#include <vector>
#include <utility>
32 33 34
#include "base.h"
#include "expr.h"
#include "runtime/util.h"
tqchen committed
35 36 37 38

namespace tvm {
namespace ir {

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
using IntImm = tvm::IntImm;
using Variable = tvm::Variable;

/*! \brief constant unsigned integer. */
class UIntImm : public ExprNode {
 public:
  /*! \brief The constant value content. */
  uint64_t value;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("value", &value);
  }

  TVM_DLL static Expr make(Type t, uint64_t value);

  static constexpr const char* _type_key = "UIntImm";
  TVM_DECLARE_NODE_TYPE_INFO(UIntImm, ExprNode);
};

/*! \brief Floating point constants. */
class FloatImm : public ExprNode {
 public:
  /*! \brief The constant value content. */
  double value;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("value", &value);
  }

  TVM_DLL static Expr make(Type t, double value);

  static constexpr const char* _type_key = "FloatImm";
  TVM_DECLARE_NODE_TYPE_INFO(FloatImm, ExprNode);
};

/*! \brief String constants, only used in asserts. */
class StringImm : public ExprNode {
 public:
  /*! \brief The constant value content. */
  std::string value;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("value", &value);
  }

  TVM_DLL Expr static make(std::string value);

  static constexpr const char* _type_key = "StringImm";
  TVM_DECLARE_NODE_TYPE_INFO(StringImm, ExprNode);
};

/*!
 * \brief Cast value from one data type to another.
 * \note The lanes of value should keep fixed.
 */
class Cast : public ExprNode {
 public:
  /*! \brief Original data type. */
  Expr value;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("value", &value);
  }

  TVM_DLL static Expr make(Type t, Expr v);

  static constexpr const char* _type_key = "Cast";
  TVM_DECLARE_NODE_TYPE_INFO(Cast, ExprNode);
};

/*!
 * \brief Base template to implement binary ops.
 * \tparam T The type of the child class.
 */
template<typename T>
class BinaryOpNode : public ExprNode {
 public:
  /*! \brief The left operand. */
  Expr a;
  /*! \brief The right operand. */
  Expr b;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &(this->type));
    v->Visit("a", &a);
    v->Visit("b", &b);
  }

  static Expr make(Expr a, Expr b) {
    CHECK(a.defined()) << "ValueError: a is undefined\n";
    CHECK(b.defined()) << "ValueError: b is undefined\n";
    CHECK(a.type() == b.type()) << "TypeError: mismatched types\n";
    NodePtr<T> node = make_node<T>();
    node->type = a.type();
    node->a = std::move(a);
    node->b = std::move(b);
    return Expr(node);
  }

  TVM_DECLARE_NODE_TYPE_INFO(T, ExprNode);
};

/*! \brief a + b */
class Add : public BinaryOpNode<Add> {
 public:
  static constexpr const char* _type_key = "Add";
};

/*! \brief a - b */
class Sub : public BinaryOpNode<Sub> {
 public:
  static constexpr const char* _type_key = "Sub";
};

/*! \brief a * b */
class Mul : public BinaryOpNode<Mul> {
 public:
  static constexpr const char* _type_key = "Mul";
};

/*!
 * \brief a / b in the C semnatics.
 * \note For integer division, C standard uses trunc div.
 */
class Div : public BinaryOpNode<Div> {
 public:
  static constexpr const char* _type_key = "Div";
};

/*!
 * \brief a % b in the C semnatics.
 * \note For integer division, C standard uses trunc div.
 */
class Mod : public BinaryOpNode<Mod> {
 public:
  static constexpr const char* _type_key = "Mod";
};

181 182 183 184 185 186 187 188 189 190 191 192
/*! \brief Floor division, floor(a/b) */
class FloorDiv : public BinaryOpNode<FloorDiv> {
 public:
  static constexpr const char* _type_key = "FloorDiv";
};

/*! \brief The remainder of the floordiv */
class FloorMod : public BinaryOpNode<FloorMod> {
 public:
  static constexpr const char* _type_key = "FloorMod";
};

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
/*! \brief min(a, b) */
class Min : public BinaryOpNode<Min> {
 public:
  static constexpr const char* _type_key = "Min";
};

/*! \brief max(a, b) */
class Max : public BinaryOpNode<Max> {
 public:
  static constexpr const char* _type_key = "Max";
};

/*!
 * \brief Base template to implement comparison ops.
 * \tparam T The type of the child class.
 */
template<typename T>
class CmpOpNode : public ExprNode {
 public:
  /*! \brief The left operand. */
  Expr a;
  /*! \brief The right operand. */
  Expr b;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &(this->type));
    v->Visit("a", &a);
    v->Visit("b", &b);
  }

  static Expr make(Expr a, Expr b) {
    CHECK(a.defined()) << "ValueError: a is undefined\n";
    CHECK(b.defined()) << "ValueError: b is undefined\n";
    CHECK(a.type() == b.type()) << "TypeError: mismatched types\n";
    NodePtr<T> node = make_node<T>();
    node->type = Bool(a.type().lanes());
    node->a = std::move(a);
    node->b = std::move(b);
    return Expr(node);
  }

  TVM_DECLARE_NODE_TYPE_INFO(T, ExprNode);
};

/*! \brief a == b */
class EQ : public CmpOpNode<EQ> {
 public:
  static constexpr const char* _type_key = "EQ";
};

/*! \brief a != b */
class NE : public CmpOpNode<NE> {
 public:
  static constexpr const char* _type_key = "NE";
};

/*! \brief a < b */
class LT : public CmpOpNode<LT> {
 public:
  static constexpr const char* _type_key = "LT";
};

/*! \brief a <= b */
struct LE : public CmpOpNode<LE> {
 public:
  static constexpr const char* _type_key = "LE";
};

/*! \brief a > b */
class GT : public CmpOpNode<GT> {
 public:
  static constexpr const char* _type_key = "GT";
};

/*! \brief a >= b */
class GE : public CmpOpNode<GE> {
 public:
  static constexpr const char* _type_key = "GE";
};

/*! \brief a && b */
class And : public ExprNode {
 public:
  /*! \brief The left operand. */
  Expr a;
  /*! \brief The right operand. */
  Expr b;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &(this->type));
    v->Visit("a", &a);
    v->Visit("b", &b);
  }

  TVM_DLL static Expr make(Expr a, Expr b);

  static constexpr const char* _type_key = "And";
  TVM_DECLARE_NODE_TYPE_INFO(And, ExprNode);
};

/*! \brief a || b */
class Or : public ExprNode {
 public:
  /*! \brief The left operand. */
  Expr a;
  /*! \brief The right operand. */
  Expr b;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("a", &a);
    v->Visit("b", &b);
  }

  TVM_DLL static Expr make(Expr a, Expr b);

  static constexpr const char* _type_key = "Or";
  TVM_DECLARE_NODE_TYPE_INFO(Or, ExprNode);
};

/*! \brief !a */
class Not : public ExprNode {
 public:
  /*! \brief The input operand. */
  Expr a;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("a", &a);
  }

  TVM_DLL static Expr make(Expr a);

  static constexpr const char* _type_key = "Not";
  TVM_DECLARE_NODE_TYPE_INFO(Not, ExprNode);
};

/*!
 * \brief return true_value if condition is true, otherwise return false_value.
 * \note Both true_value and false_value could be evaluated
 *       regardless of the condition value.
 *       Do not use it to guard against out of bound access,
 *       please use if_then_else instead.
 */
class Select : public ExprNode {
 public:
  /*! \brief The condition */
  Expr condition;
  /*! \brief value to be returned when condition is true. */
  Expr true_value;
  /*! \brief value to be returned when condition is false. */
  Expr false_value;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("condition", &condition);
    v->Visit("true_value", &true_value);
    v->Visit("false_value", &false_value);
  }

  TVM_DLL static Expr make(Expr condition, Expr true_value, Expr false_value);

  static constexpr const char* _type_key = "Select";
  TVM_DECLARE_NODE_TYPE_INFO(Select, ExprNode);
};

/*!
 * \brief Load the value from buffer_var.
 *
 *  Equivalent to ((DType*)buffer_var)[index]
 *  where DType is the type specified by type().element_of().
 *
 *  For example, if type = float32x3, then the load will corresponds to
 *
 * \code
 *
 *  auto buffer = static_cast<float*>(buffer_var);
 *  auto loaded_val = float32x3(buffer[index.v0], buffer[index.v1], buffer[index.v2]);
 *
 * \endcode
 */
class Load : public ExprNode {
 public:
  /*! \brief The buffer variable. */
  Var buffer_var;
  /*! \brief The index locations to be loaded. */
  Expr index;
  /*! \brief The predicate to mask which lanes would be loaded. */
  Expr predicate;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("buffer_var", &buffer_var);
    v->Visit("index", &index);
    v->Visit("predicate", &predicate);
  }

  TVM_DLL static Expr make(Type type, Var buffer_var, Expr index, Expr predicate);

  static constexpr const char* _type_key = "Load";
  TVM_DECLARE_NODE_TYPE_INFO(Load, ExprNode);
};

/*!
 * \brief Construct a vector with lanes elements
 *        where its i-th element equals base + i * stride.
 *  This is useful to construct a index for a continuous vector load.
 *
 *  Examples:
 *  - ramp(0, 1, 3) = [0, 1, 2]
 *  - ramp(1, 2, 4) = [1, 3, 5, 7]
 */
class Ramp : public ExprNode {
 public:
  /*! \brief The base value. */
  Expr base;
  /*! \brief The stride of each step. */
  Expr stride;
  /*! \brief Total number of lanes. */
  int lanes;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("base", &base);
    v->Visit("stride", &stride);
    v->Visit("lanes", &lanes);
  }

  TVM_DLL static Expr make(Expr base, Expr stride, int lanes);

  static constexpr const char* _type_key = "Ramp";
  TVM_DECLARE_NODE_TYPE_INFO(Ramp, ExprNode);
};

/*! \brief Create a vector where all the elements are value. */
class Broadcast : public ExprNode {
 public:
  /*! \brief The base value. */
  Expr value;
  /*! \brief The numerb of lanes. */
  int lanes;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("value", &value);
    v->Visit("lanes", &lanes);
  }

  TVM_DLL static Expr make(Expr value, int lanes);

  static constexpr const char* _type_key = "Broadcast";
  TVM_DECLARE_NODE_TYPE_INFO(Broadcast, ExprNode);
};

/*!
 * \brief Let binding. Bind var to value then evaluate body.
 */
class Let : public ExprNode {
 public:
  /*! \brief The variable. */
  Var var;
  /*! \brief The value to be binded. */
  Expr value;
  /*! \brief The result expression. */
  Expr body;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("var", &var);
    v->Visit("value", &value);
    v->Visit("body", &body);
  }

  TVM_DLL static Expr make(Var var, Expr value, Expr body);

  static constexpr const char* _type_key = "Let";
  TVM_DECLARE_NODE_TYPE_INFO(Let, ExprNode);
};

// Call node, represent a function call or a multi-dimensional array load.
//
// TODO(tvm-team):
// Refactor call with more explicit property registrations.
// rather than calling a string symbol.
// We should move most information into function itself and remove name.

/*! \brief Base node of internal functions. */
class FunctionBaseNode : public Node {
 public:
  /*! \return the name of the function */
  virtual const std::string& func_name() const = 0;
  /*! \return the number of outputs of this function */
  virtual int num_outputs() const = 0;
};

/*! \brief reference to a function */
class FunctionRef : public NodeRef {
 public:
  TVM_DEFINE_NODE_REF_METHODS(FunctionRef, NodeRef, FunctionBaseNode);
};

/*!
 * \brief Call node.
 */
class Call : public ExprNode {
 public:
  /*! \brief Possible types of calls. */
  enum CallType : int {
    /*! \brief Extern "C" function. */
    Extern = 0,
    /*! \brief Extern CXX function. */
    ExternCPlusPlus = 1,
    /*! \brief Extern "C" without side-effect. */
    PureExtern = 2,
    /*! \brief Halide-style call, evaluates func(args). */
    Halide = 3,
    /*! \brief Intrinsic functions. */
    Intrinsic = 4,
    /*! \brief Intrinsic functions that are pure. */
    PureIntrinsic = 5
  };
  /*! \brief The name of the function/intrinsic. */
  std::string name;
  /*! \brief The arguments. */
  Array<Expr> args;
  /*! \brief Type of calls. */
  CallType call_type;
  /*! \brief The function to be called. */
  FunctionRef func;
  /*! \brief The output value index if func's value is a tuple. */
  int value_index{0};

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
    v->Visit("name", &name);
    v->Visit("args", &args);
    v->Visit("call_type", &call_type);
    v->Visit("func", &func);
    v->Visit("value_index", &value_index);
  }

  TVM_DLL static Expr make(Type type,
                           std::string name,
                           Array<Expr> args,
                           CallType call_type,
                           FunctionRef func = FunctionRef(),
                           int value_index = 0);

  /*! \return Whether call node is pure. */
  bool is_pure() const {
    return (call_type == PureExtern ||
            call_type == PureIntrinsic ||
            call_type == Halide);
  }

  /*!
   * \return Whether call node corresponds to a defined intrinsic.
   * \param intrin_name The name of the intrinsic.
   */
  bool is_intrinsic(const char* intrin_name) const {
    return
        ((call_type == Intrinsic ||
          call_type == PureIntrinsic) &&
         name == intrin_name);
  }

559 560 561
  /*! \return Whether call node can be vectorized. */
  bool is_vectorizable() const;

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  static constexpr const char* _type_key = "Call";
  TVM_DECLARE_NODE_TYPE_INFO(Call, ExprNode);

  // Build-in intrinsics
  static constexpr const char* reinterpret = "reinterpret";
  static constexpr const char* bitwise_and = "bitwise_and";
  static constexpr const char* bitwise_not = "bitwise_not";
  static constexpr const char* bitwise_xor = "bitwise_xor";
  static constexpr const char* bitwise_or = "bitwise_or";
  static constexpr const char* shift_left = "shift_left";
  static constexpr const char* shift_right = "shift_right";
  static constexpr const char* popcount = "popcount";
  static constexpr const char* likely = "likely";
  static constexpr const char* glsl_texture_store = "glsl_texture_store";
  static constexpr const char* prefetch = "prefetch";
577
  static constexpr const char* isnan = "isnan";
578 579 580

  /*! \brief Vectorizable intrinsic list. */
  static const char* vectorizable_intrinsics[];
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
};

/*!
 * \brief Shuffle instruction.
 *  vec = concat(vectors)
 *  result = (vec[indices[0]], vec[indices[1]] ...)
 */
class Shuffle : public ExprNode {
 public:
  /*! \brief the input vectors. */
  Array<Expr> vectors;
  /*! \brief The indices of each element. */
  Array<Expr> indices;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("vectors", &vectors);
    v->Visit("indices", &indices);
  }

  TVM_DLL static Expr make(Array<Expr> vectors, Array<Expr> indices);
  TVM_DLL static Expr make_concat(Array<Expr> vectors);
  TVM_DLL static Expr make_extract_element(Expr vector, int index);
tqchen committed
603

604 605 606
  static constexpr const char* _type_key = "Shuffle";
  TVM_DECLARE_NODE_TYPE_INFO(Shuffle, ExprNode);
};
ziheng committed
607

608 609 610 611 612
// Reduce operator
class CommReducerNode;

class CommReducer : public NodeRef {
 public:
ziheng committed
613
  CommReducer() {}
614
  explicit CommReducer(NodePtr<Node> n) : NodeRef(n) {}
ziheng committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
  /*!
   * \brief access the internal node container
   * \return the pointer to the internal node container
   */
  inline const CommReducerNode* get() const;
  /*!
   * \brief access the internal node container
   * \return the pointer to the internal node container
   */
  inline const CommReducerNode* operator->() const;
  /*! \brief type indicate the container type */
  using ContainerType = CommReducerNode;
};

/*!
 * \brief A commutative reducer node to represent a commutative
 *  binary operator with identity element
 */
633 634
class CommReducerNode : public Node {
 public:
635 636 637 638
  /*! \brief The left argument of reducer */
  Array<Var> lhs;
  /*! \brief The right argument of reducer */
  Array<Var> rhs;
ziheng committed
639
  /*! \brief The result of reducer */
640
  Array<Expr> result;
tqchen committed
641
  /*!
ziheng committed
642 643 644
   * \brief The identity element of reducer, which leaves other
   *  elements unchanged when combined with it, with respect to
   *  the binary operation of this reducer uses.
tqchen committed
645
   */
646
  Array<Expr> identity_element;
ziheng committed
647
  /*! \brief Function call operator to combine a and b */
648
  Array<Expr> operator()(Array<Expr> a, Array<Expr> b) const;
ziheng committed
649
  /*! \brief construct CommReducer from args, result and identity_element */
650 651 652 653
  TVM_DLL static CommReducer make(Array<Var> lhs,
                                  Array<Var> rhs,
                                  Array<Expr> result,
                                  Array<Expr> identity_element);
ziheng committed
654 655

  void VisitAttrs(AttrVisitor* v) final {
656 657
    v->Visit("lhs", &lhs);
    v->Visit("rhs", &rhs);
ziheng committed
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    v->Visit("result", &result);
    v->Visit("identity_element", &identity_element);
  }

  static constexpr const char* _type_key = "CommReducer";
  TVM_DECLARE_NODE_TYPE_INFO(CommReducerNode, Node);
};

inline const CommReducerNode* CommReducer::get() const {
  return static_cast<CommReducerNode*>(node_.get());
}
inline const CommReducerNode* CommReducer::operator->() const {
  return static_cast<CommReducerNode*>(node_.get());
}

/*! \brief Reduction operator operator */
674 675
class Reduce : public ExprNode {
 public:
ziheng committed
676 677
  /*! \brief The commutative combiner */
  CommReducer combiner;
tqchen committed
678
  /*! \brief The source operand */
679
  Array<Expr> source;
680 681
  /*! \brief The reduction axis */
  Array<IterVar> axis;
682 683 684 685 686
  /*!
   * \brief Predicate on the reduction
   *  Only add the body to reduction if condition is true.
   */
  Expr condition;
687 688
  /*! \brief the index of this reduce node */
  int value_index;
tqchen committed
689

tqchen committed
690
  /*! \brief construct expr from op and rdom */
691 692 693 694 695
  TVM_DLL static Expr make(CommReducer combiner,
                           Array<Expr> src,
                           Array<IterVar> rdom,
                           Expr condition,
                           int value_index);
tqchen committed
696 697 698

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("dtype", &type);
699
    v->Visit("combiner", &combiner);
tqchen committed
700
    v->Visit("source", &source);
701
    v->Visit("axis", &axis);
702
    v->Visit("condition", &condition);
703
    v->Visit("value_index", &value_index);
tqchen committed
704
  }
705

tqchen committed
706
  static constexpr const char* _type_key = "Reduce";
707
  TVM_DECLARE_NODE_TYPE_INFO(Reduce, ExprNode);
tqchen committed
708
};
tqchen committed
709

710
/*! \brief Any shape. */
711 712 713
class Any : public ExprNode {
 public:
  void VisitAttrs(AttrVisitor* v) final {}
714 715 716 717
  /*! \brief Convert to var. */
  Var ToVar() const {
    return Variable::make(Int(32), "any_dim");
  }
718

719 720 721
  TVM_DLL static Expr make();

  static constexpr const char* _type_key = "Any";
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  TVM_DECLARE_NODE_TYPE_INFO(Any, ExprNode);
};

// Statements
/*!
 * \brief Let binding, bind var to value, then run body.
 */
class LetStmt : public StmtNode {
 public:
  /*! \brief The variable. */
  Var var;
  /*! \brief The value to be binded. */
  Expr value;
  /*! \brief The body block. */
  Stmt body;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("var", &var);
    v->Visit("value", &value);
    v->Visit("body", &body);
  }

  TVM_DLL static Stmt make(Var var, Expr value, Stmt body);

  static constexpr const char* _type_key = "LetStmt";
  TVM_DECLARE_NODE_TYPE_INFO(LetStmt, StmtNode);
};

/*!
 * \brief Define certain auxiliary attribute for the body to be a symbolic value.
 *  This provide auxiliary information for IR passes that transforms body.
 *
 *  In terms of effect, this is equivalent to Block(Evaluate(value), body).
 *
 *  Examples of possible usage:
 *    - Bound of function, variables.
 *    - Hint which block corresponds to a parallel region.
 */
class AttrStmt : public StmtNode {
 public:
  /*! \brief this is attribute about certain node */
  NodeRef node;
  /*! \brief the type key of the attribute */
  std::string attr_key;
  /*! \brief The attribute value, value is well defined at current scope. */
  Expr value;
  /*! \brief The body statement to be executed */
  Stmt body;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("node", &node);
    v->Visit("attr_key", &attr_key);
    v->Visit("value", &value);
    v->Visit("body", &body);
  }

  TVM_DLL static Stmt make(NodeRef node,
                           std::string type_key,
                           Expr value,
                           Stmt body);

  static constexpr const char* _type_key = "AttrStmt";
  TVM_DECLARE_NODE_TYPE_INFO(AttrStmt, StmtNode);
};

/*!
 * \brief Assert condition, if an error occurs, return the error message.
 */
class AssertStmt : public StmtNode {
 public:
  /*! \brief Condition to be checked. */
  Expr condition;
  /*! \brief Error message when assertion failed. */
  Expr message;
  /*!
   * \brief Body which this assertion holds true.
   *  Will be executed after the assertion.
   */
  Stmt body;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("condition", &condition);
    v->Visit("message", &message);
    v->Visit("body", &body);
  }

  TVM_DLL static Stmt make(Expr condition, Expr message, Stmt body);

  static constexpr const char* _type_key = "AssertStmt";
  TVM_DECLARE_NODE_TYPE_INFO(AssertStmt, StmtNode);
};

// TODO(tvm-team): consider consolidate with AttrStmt.
/*! \brief annotation node of producer/consumer relation. */
class ProducerConsumer : public StmtNode {
 public:
  /*! \brief The corresponding tensor. */
  FunctionRef func;
  /*! \brief Whether the relation is producer. */
  bool is_producer;
  /*! \brief Body to be executed. */
  Stmt body;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("func", &func);
    v->Visit("is_producer", &is_producer);
    v->Visit("body", &body);
  }

  TVM_DLL static Stmt make(FunctionRef func, bool is_producer, Stmt body);

  static constexpr const char* _type_key = "ProducerConsumer";
  TVM_DECLARE_NODE_TYPE_INFO(ProducerConsumer, StmtNode);
};

/*!
 * \brief Store value to the buffer.
 *
 *  Equivalent to ((DType*)buffer_var)[index] = value.
 *  where DType is the type specified by type().element_of().
 *
 *  For example, if type = float32x3, then the load will corresponds to
 *
 * \code
 *
 *  auto buffer = static_cast<float*>(buffer_var);
 *  buffer[index.v0] = value.v0;
 *  buffer[index.v1] = value.v1;
 *  buffer[index.v2] = value.v2;
 *
 * \endcode
 * \sa Load
 */
class Store : public StmtNode {
 public:
  /*! \brief The buffer variable. */
  Var buffer_var;
  /*! \brief The value to be stored. */
  Expr value;
  /*! \brief The index locations to be stored. */
  Expr index;
  /*! \brief The predicate to mask which lanes would be stored. */
  Expr predicate;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("buffer_var", &buffer_var);
    v->Visit("value", &value);
    v->Visit("index", &index);
    v->Visit("predicate", &predicate);
  }

  TVM_DLL static Stmt make(Var buffer_var,
                           Expr value,
                           Expr index,
                           Expr predicate);

  static constexpr const char* _type_key = "Store";
  TVM_DECLARE_NODE_TYPE_INFO(Store, StmtNode);
};

/*!
 * \brief Store value into mult-dimensional array defined by func.
 */
class Provide : public StmtNode {
 public:
  /*! \brief The function to be updated. */
  FunctionRef func;
  /*! \brief The output value index if func's value is a tuple. */
  int value_index{0};
  /*! \brief The value to be stored. */
  Expr value;
  /*! \brief The index arguments of the function. */
  Array<Expr> args;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("func", &func);
    v->Visit("value_index", &value_index);
    v->Visit("value", &value);
    v->Visit("args", &args);
  }

  TVM_DLL static Stmt make(FunctionRef func,
                           int value_index,
                           Expr value,
                           Array<Expr> args);

  static constexpr const char* _type_key = "Provide";
  TVM_DECLARE_NODE_TYPE_INFO(Provide, StmtNode);
};

/*!
 * \brief Allocate a buffer that can be used in body.
 */
class Allocate : public StmtNode {
 public:
  /*! \brief The buffer variable. */
  Var buffer_var;
  /*! \brief The type of the buffer. */
  DataType type;
  /*! \brief The extents of the buffer. */
  Array<Expr> extents;
  /*! \brief Only allocate buffer when condition is satisfied. */
  Expr condition;
  /*! \brief The body to be executed. */
  Stmt body;
  // The following two fields are deprecated
  // kept for backward compatibility and will be refactored later.
  Expr new_expr;
  std::string free_function;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("buffer_var", &buffer_var);
    v->Visit("dtype", &type);
    v->Visit("extents", &extents);
    v->Visit("condition", &condition);
    v->Visit("body", &body);
  }

  TVM_DLL static Stmt make(Var buffer_var,
                           DataType type,
                           Array<Expr> extents,
                           Expr condition,
                           Stmt body,
                           Expr new_expr = Expr(),
                           std::string free_function = std::string());

  /*!
   * \brief If the buffer size is constant, return the size.
   *        Otherwise return 0.
   * \return The result.
   */
  int32_t constant_allocation_size() const {
    return constant_allocation_size(extents);
  }
  /*!
   * \brief If the buffer size is constant, return the size.
   *        Otherwise return 0.
   * \param extents The extents of the buffer.
   * \return The result.
   */
  TVM_DLL static int32_t constant_allocation_size(
      const Array<Expr>& extents);

  static constexpr const char* _type_key = "Allocate";
  TVM_DECLARE_NODE_TYPE_INFO(Allocate, StmtNode);
};

/*! \brief Free the resources in the buffer before the scope ends. */
class Free : public StmtNode {
 public:
  /*! \brief The buffer variable. */
  Var buffer_var;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("buffer_var", &buffer_var);
  }

  TVM_DLL static Stmt make(Var buffer_var);

  static constexpr const char* _type_key = "Free";
  TVM_DECLARE_NODE_TYPE_INFO(Free, StmtNode);
};

/*!
 * \brief Annotate the bounds where func need to be written and read in body.
 *  We will need to allocate space for the corresponding regions.
 */
class Realize : public StmtNode {
 public:
  /*! \brief The function to be realized. */
  FunctionRef func;
  /*! \brief The output value index if func's value is a tuple. */
  int value_index;
  /*! \brief The data type of the array. */
  DataType type;
  /*! \brief Bounds to be realized. */
  Region bounds;
  /*! \brief Only realize if condition holds. */
  Expr condition;
  /*! \brief The body of realization. */
  Stmt body;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("func", &func);
    v->Visit("value_index", &value_index);
    v->Visit("dtype", &type);
    v->Visit("bounds", &bounds);
    v->Visit("condition", &condition);
    v->Visit("body", &body);
  }

  TVM_DLL static Stmt make(FunctionRef func,
                           int value_index,
                           DataType type,
                           Region bounds,
                           Expr condition,
                           Stmt body);

  static constexpr const char* _type_key = "Realize";
  TVM_DECLARE_NODE_TYPE_INFO(Realize, StmtNode);
};

/*!
 * \brief A sequence of statements.
 */
class Block : public StmtNode {
 public:
  /*! \brief The first statement. */
  Stmt first;
  /*! \brief The restof statments. */
  Stmt rest;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("first", &first);
    v->Visit("rest", &rest);
  }

  TVM_DLL static Stmt make(Stmt first, Stmt rest);
  TVM_DLL static Stmt make(const std::vector<Stmt> &stmts);

  static constexpr const char* _type_key = "Block";
  TVM_DECLARE_NODE_TYPE_INFO(Block, StmtNode);
};

/*!
 * \brief IfThenElse statment.
 */
class IfThenElse : public StmtNode {
 public:
  /*! \brief The condition. */
  Expr condition;
  /*! \brief The branch to be executed when condition is true. */
  Stmt then_case;
  /*! \brief The branch to be executed when condition is false, can be null. */
  Stmt else_case;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("condition", &condition);
    v->Visit("then_case", &then_case);
    v->Visit("else_case", &else_case);
  }

  TVM_DLL static Stmt make(Expr condition, Stmt then_case, Stmt else_case = Stmt());

  static constexpr const char* _type_key = "IfThenElse";
  TVM_DECLARE_NODE_TYPE_INFO(IfThenElse, StmtNode);
};

/*!
 * \brief Evaluates an expression.
 *  This is mostly used for putting a Call node into Stmt.
 *
 *  If value do not have side-effect, this node can be safely removed.
 */
class Evaluate : public StmtNode {
 public:
  /*! \brief The expression to be evaluated. */
  Expr value;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("value", &value);
  }

  TVM_DLL static Stmt make(Expr v);

  static constexpr const char* _type_key = "Evaluate";
  TVM_DECLARE_NODE_TYPE_INFO(Evaluate, StmtNode);
};

/*! \brief Additional annotation of for loop. */
enum class ForType : int {
  /*! \brief serial execution. */
  Serial = 0,
  /*! \brief parallel execution on CPU. */
  Parallel = 1,
  /*! \brief Vector SIMD loop annotaion. */
  Vectorized = 2,
  /*! \brief Unroll annotation. */
  Unrolled = 3
};

// Kevice api of for loop
// kept for backward compatibility
// consider refactor and remove later.
enum class DeviceAPI: int {
  None = 0
};

/*!
 * \brief A for loop, with poissible type annotations.
 *
 * \code
 *
 *  for (loop_var = min; loop_var < min + extent; ++loop_var) {
 *    // body
 *  }
 * \endcode
 */
class For : public StmtNode {
 public:
  /*! \brief The loop variable. */
  Var loop_var;
  /*! \brief The minimum value of iteration. */
  Expr min;
  /*! \brief The extent of the iteration. */
  Expr extent;
  /*! \brief The type of the for loop. */
  ForType for_type;
  /*!
   * \brief Deprecated, reserved for backward compatibility.
   *  Consider refactor and remove later.
   */
  DeviceAPI device_api;
  /*! \brief The body of the for loop. */
  Stmt body;

  TVM_DLL static Stmt make(Var loop_var,
                           Expr min,
                           Expr extent,
                           ForType for_type,
                           DeviceAPI device_api,
                           Stmt body);

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("loop_var", &loop_var);
    v->Visit("min", &min);
    v->Visit("extent", &extent);
    v->Visit("for_type", &for_type);
    v->Visit("device_api", &device_api);
    v->Visit("body", &body);
  }

  static constexpr const char* _type_key = "For";
  TVM_DECLARE_NODE_TYPE_INFO(For, StmtNode);
};

/*!
 * \brief A prefetch hint of func.
 */
class Prefetch : public StmtNode {
 public:
  /*! \brief The function to be prefetched. */
  FunctionRef func;
  /*! \brief The output value index if func's value is a tuple. */
  int value_index;
  /*! \brief The data type of the array. */
  DataType type;
  /*! \brief Bounds to be prefetched. */
  Region bounds;

  void VisitAttrs(AttrVisitor* v) final {
    v->Visit("func", &func);
    v->Visit("value_index", &value_index);
    v->Visit("type", &type);
    v->Visit("bounds", &bounds);
  }

  TVM_DLL static Stmt make(FunctionRef func,
                           int value_index,
                           DataType type,
                           Region bounds);

  static constexpr const char* _type_key = "Prefetch";
  TVM_DECLARE_NODE_TYPE_INFO(Prefetch, StmtNode);
1186 1187
};

1188
/*!
1189
 * \brief Auxiliary data structure used in IR Pass to indicate a tensor.
1190
 */
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
struct TensorKey {
  FunctionRef f;
  int value_index;

  inline bool operator==(const TensorKey& other) const {
    return f == other.f && value_index == other.value_index;
  }
  inline std::string GetName() const {
    if (f->num_outputs() == 1) return f->func_name();
    std::ostringstream os;
    os << f->func_name() << ".v" << value_index;
    return os.str();
  }
};

1206
/*! \brief namespace of possible attribute sin AttrStmt.attr_key */
1207 1208
namespace attr {
// The above attr does not pass to ir stage.
ziheng committed
1209
/*! \brief Mark launching extent of thread, used by device API. */
1210
constexpr const char* thread_extent = "thread_extent";
ziheng committed
1211
/*! \brief Mark launching of a virtual thread. */
1212
constexpr const char* virtual_thread = "virtual_thread";
1213 1214
/*! \brief Mark region is processed by a co-proccesor */
constexpr const char* coproc_scope = "coproc_scope";
1215 1216 1217 1218 1219
/*!
 * \brief Mark region creates coprocessor micro ops,
 *  can be reused if corresponding variable is independent.
 */
constexpr const char* coproc_uop_scope = "coproc_uop_scope";
ziheng committed
1220
/*! \brief Mark the scope as volatile access for certain handle. */
1221
constexpr const char* volatile_scope = "volatile_scope";
1222
/*!
1223 1224 1225 1226 1227 1228
 * \brief Mark the scope as generated by extern primitive.
 *  such scope can contain arbitrary ir program and we need to be careful
 *  when make certain assumptions about the structure of the program.
 */
constexpr const char* extern_scope = "extern_scope";
/*!
1229 1230 1231 1232
 * \brief Mark the scope as when computation start to happen
 *  This can hint some code generator to create a new function for compute.
 */
constexpr const char* compute_scope = "compute_scope";
ziheng committed
1233
/*! \brief Mark storage scope of buffers */
1234
constexpr const char* storage_scope = "storage_scope";
1235 1236
/*! \brief Mark storage alignement requirement of buffers */
constexpr const char* storage_alignment = "storage_alignment";
Tianqi Chen committed
1237
/*! \brief Mark storage scope of realization */
1238
constexpr const char* realize_scope = "realize_scope";
1239 1240 1241 1242
/*! \brief The allocation context for global malloc in host. */
constexpr const char* device_context_id = "device_context_id";
/*! \brief The device type. */
constexpr const char* device_context_type = "device_context_type";
1243 1244
/*! \brief Mark of loop scope */
constexpr const char* loop_scope = "loop_scope";
ziheng committed
1245 1246
/*! \brief Mark of reduce scope */
constexpr const char* reduce_scope = "reduce_scope";
1247 1248
/*! \brief Mark region is guarded by the pragma extension */
constexpr const char* pragma_scope_prefix = "pragma_";
1249 1250
/*! \brief Import llvm source or file into the final code gen module */
constexpr const char* pragma_import_llvm = "pragma_import_llvm";
1251 1252 1253 1254 1255
/*!
 * \brief Mark of prefetch scope, value=offset,
 *  run prefetch of Tensor on the current loop scope
 */
constexpr const char* prefetch_scope = "prefetch_scope";
1256 1257 1258 1259 1260 1261 1262 1263
/*!
 * \brief Marks production of double buffer data
 */
constexpr const char* double_buffer_scope = "double_buffer_scope";
/*!
 * \brief Marks region used by double buffer write
 */
constexpr const char* double_buffer_write = "double_buffer_write";
1264 1265 1266 1267
/*! \brief Mark of scan update scope */
constexpr const char* scan_update_scope = "scan_update_scope";
/*! \brief Mark of scan init scope */
constexpr const char* scan_init_scope = "scan_init_scope";
1268
/*!
1269 1270 1271 1272 1273 1274
 * \brief Mark alignment of buffer dimension
 *  stmt.node is Tensor
 *  stmt.value is tvm_tuple(dim, align, offset)
 *  This gives hint to require stride of dim to be k * align + offset.
 */
constexpr const char* buffer_dim_align = "buffer_dim_align";
1275 1276
/*! \brief Mark stores/loads with theirs bounds.  */
constexpr const char* buffer_bound = "buffer_bound";
1277
/*!
1278 1279 1280 1281 1282 1283 1284 1285 1286
 * \brief Bind the buffer specification to the region of the op
 *  When this scope occurs, the stmt.node is a Array<NodeRef> = [buffer, tensor]
 *  stmt.value is a tvm_tuple(min0, extent0, min1, extent1, ...).
 *  The scope represents that we need to bind the storage region of tensor to buffer.
 *  This will affect replacement of some variables inside the scope that
 *  corresponds to field of buffer to be the actual expressions of tensor during
 *  storage flattening phase.
 */
constexpr const char* buffer_bind_scope = "buffer_bind_scope";
Tianqi Chen committed
1287 1288 1289
// Pipeline related attributes
/*! \brief channel read scope */
constexpr const char* channel_read_scope = "channel_read_scope";
1290 1291
/*! \brief Advance step of channel after end of scope */
constexpr const char* channel_read_advance = "channel_read_advance";
Tianqi Chen committed
1292 1293
/*! \brief channel write scope */
constexpr const char* channel_write_scope = "channel_write_scope";
1294 1295 1296
/*! \brief Advance step of channel after end of scope */
constexpr const char* channel_write_advance = "channel_write_advance";
/*! \brief pipeline stage scope, implies always execution */
Tianqi Chen committed
1297
constexpr const char* pipeline_stage_scope = "pipeline_stage_scope";
1298 1299
/*! \brief pipeline execution scope, implies the scope can be pipelined. */
constexpr const char* pipeline_exec_scope = "pipeline_exec_scope";
1300 1301 1302 1303 1304 1305 1306
/*!
 * \brief Mark that this stage is an OpenGL shader. Since OpenGL shader only
 * allows writing out to one element of the output texture, the Provide node
 * gets translated to a special Call::glsl_texture_store statement instead of a
 * Store statement.
 */
constexpr const char* opengl_stage_scope = "opengl_stage_scope";
1307 1308

/*!
1309 1310 1311 1312 1313
 * \brief Mark that it is in the device scope.
 */
constexpr const char* device_scope = "device_scope";

/*!
1314 1315 1316 1317 1318 1319 1320 1321
 * \brief Check if attr_key is a pragma key extension
 * \param attr_key The attr key to be compared
 * \return true if it is a pragma key
 */
inline bool IsPragmaKey(const std::string& attr_key) {
  return attr_key.compare(0, 7, "pragma_") == 0;
}

1322 1323
}  // namespace attr

1324 1325 1326 1327 1328
/*! \brief namespace of TVM Intrinsic functions */
namespace intrinsic {
/*!
 * \brief See pesudo code
 *
1329 1330 1331 1332 1333 1334
 *  Handle tvm_address_of(Load *op) {
 *     return &op->buffer_var[index];
 *  }
 */
constexpr const char* tvm_address_of = "tvm_address_of";
/*!
1335 1336 1337 1338 1339 1340 1341 1342
 * \brief Same as select, used for unsafe memory access.
 *
 *  Type tvm_if_then_else(cond, a, b) {
 *    return cond ? a : b;
 *  }
 */
constexpr const char* tvm_if_then_else = "tvm_if_then_else";
/*!
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
 * \brief Get head access address with memory access pattern info.
 *
 *  This operator also marks range of the memory access
 *  The offset and extent are in unit of the DType(including vectorization factor).
 *  rw_mask is a bit_mask setting whether the access is a read(1) or write(2).
 *  The access is assume to happen in the current expression.
 *
 *  PtrType tvm_access_ptr(Expr dtype, DType* data,
 *                         int offset, int extent,
 *                         int rw_mask) {
 *    // DType == dtype.type();
 *    return &data[offset];
 *  }
 */
constexpr const char* tvm_access_ptr = "tvm_access_ptr";
/*!
1359 1360 1361 1362 1363
 * \brief Create a function local static handle that iniitalizes to nullptr.
 *  can be used to cache function local static resources.
 */
constexpr const char* tvm_static_handle = "tvm_static_handle";
/*!
1364 1365 1366 1367 1368
 * \brief Return a unique context id, used for hint of workspace separation.
 *  Different context id ganrantees not having overlapping workspace.
 */
constexpr const char* tvm_context_id = "tvm_context_id";
/*!
1369 1370 1371 1372 1373 1374 1375 1376
 * \brief tvm_tuple is not an actual function and cannot codegen.
 *  It is used to represent tuple structure in value field of AttrStmt,
 *  for the sake of giving hint to optimization.
 *
 *  Handle tvm_tuple(value0, value1, ..., value_n);
 */
constexpr const char* tvm_tuple = "tvm_tuple";
/*!
1377 1378
 * \brief See pesudo code
 *
1379 1380
 *  Type tvm_struct_get(StructType* arr, int index, int field_id) {
 *     return arr[index]->field;
1381
 *  }
1382
 * \sa TVMStructFieldKind
1383
 */
1384
constexpr const char* tvm_struct_get = "tvm_struct_get";
1385 1386 1387
/*!
 * \brief See pesudo code
 *
1388 1389
 *  Handle tvm_struct_set(StructType* arr, int index, int field_id, value) {
 *     arr[index]->field = value;
1390
 *  }
1391
 * \sa TVMStructFieldKind
1392
 */
1393
constexpr const char* tvm_struct_set = "tvm_struct_set";
1394 1395 1396 1397 1398 1399 1400 1401
/*!
 * \brief See pesudo code
 *
 *  bool tvm_handle_is_null(void* handle) {
 *     return handle == nullptr
 *  }
 */
constexpr const char* tvm_handle_is_null = "tvm_handle_is_null";
1402 1403 1404
/*!
 * \brief See pesudo code
 *
1405 1406 1407 1408 1409 1410 1411 1412
 *  void tvm_throw_last_error() {
 *    throw TVMGetLastError();
 *  }
 */
constexpr const char* tvm_throw_last_error = "tvm_throw_last_error";
/*!
 * \brief See pesudo code
 *
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
 *  dtype in {shape, array, arg_value, arg_tcode}
 *
 *  Handle tvm_stack_alloca(string dtype, int num) {
 *     return new on stack dtype[num];
 *  }
 */
constexpr const char* tvm_stack_alloca = "tvm_stack_alloca";
/*!
 * \brief Allocate a shape tuple on stack, return the handle.
 *
 *  Handle tvm_stack_make_shape(list args) {
 *     ret = alloca stack int64_t[len(args)];
 *     for i in range(len(args)):
 *        ret[i] = args[i]
 *     return &ret[0];
 *  }
 */
constexpr const char* tvm_stack_make_shape = "tvm_stack_make_shape";
/*!
 * \brief Allocate a NDArray(DLTensor) on stack, return the handle.
 *
 *  Type tvm_stack_make_array(Expr data,
 *                            Expr shape,
 *                            Expr strides,
 *                            Expr ndim,
 *                            Expr dtype,
1439
 *                            Expr elem_offset) {
1440 1441 1442 1443 1444 1445
 *     ret = alloca stack DLTensor();
 *     ret->data = data;
 *     ret->shape = shape;
 *     ret->strides = strides != 0 ? strides : nullptr;
 *     ret->ndim = ndim;
 *     ret->dtype = dtype.type();
1446
 *     ret->byte_offset = elem_offset * sizeof(dtype);
1447 1448 1449 1450 1451 1452 1453
 *     return ret;
 *  }
 */
constexpr const char* tvm_stack_make_array = "tvm_stack_make_array";
/*!
 * \brief See pesudo code
 *
1454 1455 1456 1457
 *  int tvm_call_packed(name, TVMValue* args) {
 *     ModuleNode* env = GetCurrentEnv();
 *     const PackedFunc* f = env->GetFuncFromEnv(name);
 *     (*f)(args, type_code_of(args), len(args));
1458
 *     return 0;
1459 1460
 *  }
 */
1461
constexpr const char* tvm_call_packed = "tvm_call_packed";
1462
/*!
1463
 * \brief See pesudo code
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
 *
 *  int tvm_call_trace_packed(name, TVMValue* args) {
 *     ModuleNode* env = GetCurrentEnv();
 *     const PackedFunc* f = env->GetFuncFromEnv(name);
 *     (*f)(args, type_code_of(args), len(args));
 *     return 0;
 *  }
 */
constexpr const char *tvm_call_trace_packed = "tvm_call_trace_packed";
/*!
 * \brief See pesudo code
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
 *  Mark the content as thread local context, can get optimized
 *  by only call the call once at thread start.
 *
 *  Do not allow nesting(getting a thread context from another).
 *
 *  Handle tvm_thread_context(Expr call) {
 *     return call;
 *  }
 */
constexpr const char* tvm_thread_context = "tvm_thread_context";
/*!
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
 * \brief Lowered version of call packed, the space of value and
 *  type codes are explicitly allocated.
 *
 *  int tvm_call_packed_lowered(name,
 *                              TVMValue* value_stack,
 *                              int* tcode_stack,
 *                              int begin,
 *                              int end) {
 *     ModuleNode* env = GetCurrentEnv();
 *     const PackedFunc* f = env->GetFuncFromEnv(name);
 *     f->CallPacked(TVMArgs(value_stack[begin:end],
 *                           tcode_stack[begin:end]),
 *                   TVMRetValue(value_stack + end, tcode_stack + end));
 *  }
 */
constexpr const char* tvm_call_packed_lowered = "tvm_call_packed_lowered";
/*!
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
 * \brief Lowered version of trace intrinsic, the space of value and
 *  type codes are explicitly allocated. The return value is the
 *  (end - 1) value on the stack.
 *
 *  int tvm_call_trace_packed_lowered(name,
 *                                    TVMValue* value_stack,
 *                                    int* tcode_stack,
 *                                    int begin,
 *                                    int end) {
 *     ModuleNode* env = GetCurrentEnv();
 *     const PackedFunc* f = env->GetFuncFromEnv(name);
 *     f->CallPacked(TVMArgs(value_stack[begin:end],
 *                           tcode_stack[begin:end]),
 *                   TVMRetValue(value_stack + end, tcode_stack + end));
 *  }
 */
constexpr const char *tvm_call_trace_packed_lowered =
    "tvm_call_trace_packed_lowered";
/*!
1522
 * \brief See pseudo code
1523 1524 1525 1526 1527 1528 1529
 *
 *  int tvm_storage_sync(std::string storage_scope) {
 *     __sync(storage_scope);
 *     return 0;
 *  }
 */
constexpr const char* tvm_storage_sync = "tvm_storage_sync";
1530
/*!
1531 1532 1533 1534 1535 1536 1537 1538
 * \brief See pseudo code
 *
 *  Type tvm_warp_shuffle(Type value, warp_id) {
 *     return (value passed in by warp indicated by warp_id);
 *  }
 */
constexpr const char* tvm_warp_shuffle = "tvm_warp_shuffle";
/*!
1539 1540 1541 1542 1543
 * \brief Initialize the global barrier.
 *  Call this at beginning of kernel that need global barrier.
 */
constexpr const char* tvm_global_barrier_kinit = "tvm_global_barrier_kinit";
/*!
1544 1545
 * \brief See pesudo code
 *
1546 1547
 *  void tvm_thread_allreduce(UIntImm size, Expr source0, ..., Expr cond,
 *                            Var reduce_temp0, .., Var thread_idx1, ...) {
1548
 *     // constraint by the other thread_idx remain the same.
1549 1550 1551
 *     // reduce_temp is used to save intermediate result.
 *     reduce_temp0, ... = reduce(combiner, source0, ..., cond
 *       over [thread_idx1, thread_idx2] passed by any caller)
1552 1553 1554
 *  }
 */
constexpr const char* tvm_thread_allreduce = "tvm_thread_allreduce";
1555 1556 1557

}   // namespace intrinsic

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
/*!
 * \brief Create a type annotation expression
 * \param dtype The data type
 * \return Expr a expression with dtype.
 */
inline Expr TypeAnnotation(Type dtype) {
  return ir::Call::make(dtype,
                        "type_annotation", {},
                        ir::Call::PureIntrinsic);
}
1568 1569 1570 1571

// overload printing of for type.
TVM_DLL std::ostream& operator<<(std::ostream& os, ForType for_type);

tqchen committed
1572 1573 1574
}  // namespace ir
}  // namespace tvm

1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
namespace std {
template <>
struct hash<::tvm::ir::TensorKey> {
  std::size_t operator()(const ::tvm::ir::TensorKey& k) const {
    size_t lhs = k.f.hash();
    size_t rhs = static_cast<size_t>(k.value_index);
    lhs ^= rhs + 0x9e3779b9 + (lhs << 6) + (lhs >> 2);
    return lhs;
  }
};
}  // namespace std

tqchen committed
1587
#endif  // TVM_IR_H_