const_int_bound.cc 17.6 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * 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
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16 17 18 19
 * 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.
 */

20
/*!
21
 * \file tvm/arith/const_int_bound.cc
22
 */
23
#include <tvm/runtime/registry.h>
24
#include <tvm/arith/analyzer.h>
25
#include <tvm/tir/expr_functor.h>
26
#include <algorithm>
27
#include "int_operator.h"
28
#include "pattern_match.h"
29 30 31 32

namespace tvm {
namespace arith {

33
using namespace tir;
34 35 36

TVM_REGISTER_NODE_TYPE(ConstIntBoundNode);

37
ConstIntBound::ConstIntBound(
38
    int64_t min_value, int64_t max_value) {
39
  auto node = make_object<ConstIntBoundNode>();
40 41
  node->min_value = min_value;
  node->max_value = max_value;
42
  data_ = std::move(node);
43 44
}

45 46 47 48 49 50 51
ConstIntBound MakeConstIntBound(int64_t min_value, int64_t max_value) {
  return ConstIntBound(min_value, max_value);
}

TVM_REGISTER_GLOBAL("arith.ConstIntBound")
.set_body_typed(MakeConstIntBound);

52 53 54 55 56 57 58 59 60 61
inline void PrintBoundValue(std::ostream& os, int64_t val) {
  if (val == ConstIntBound::kPosInf) {
    os << "pos_inf";
  } else if (val == ConstIntBound::kNegInf) {
    os << "neg_inf";
  } else {
    os << val;
  }
}

62 63
TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<ConstIntBoundNode>([](const ObjectRef& node, ReprPrinter* p) {
64
    auto* op = static_cast<const ConstIntBoundNode*>(node.get());
65 66 67 68 69
    p->stream << "ConstIntBound[";
    PrintBoundValue(p->stream, op->min_value);
    p->stream << ',';
    PrintBoundValue(p->stream, op->max_value);
    p->stream << ']';
70 71 72 73 74 75 76 77 78 79
  });

// internal entry for const int bound
struct ConstIntBoundAnalyzer::Entry {
  int64_t min_value;
  int64_t max_value;

  bool is_const(int64_t value) const {
    return min_value == max_value && min_value == value;
  }
80 81 82 83

  bool operator==(const Entry& other) const {
    return min_value == other.min_value && max_value == other.max_value;
  }
84 85 86
};

class ConstIntBoundAnalyzer::Impl :
87
      public ExprFunctor<ConstIntBoundAnalyzer::Entry(const PrimExpr&)> {
88
 public:
89 90 91
  /*! \brief additional bound info about expr \in bound */
  struct BoundInfo {
    /*! \brief The expr */
92
    PrimExpr expr;
93 94 95 96
    /*! \brief The additional bound */
    Entry bound;

    BoundInfo() {}
97
    BoundInfo(PrimExpr expr, Entry bound)
98 99 100 101
        : expr(expr), bound(bound) {
    }
  };

102 103 104 105 106 107 108 109 110 111 112 113 114
  void Bind(const Var& var, const Range& range) {
    Entry a = VisitExpr(range->min);
    Entry b = VisitExpr(range->extent);
    Entry ret;
    ret.min_value = a.min_value;
    ret.max_value = InfAwareAdd(a.max_value, InfAwareAdd(b.max_value, -1));
    Update(var, ret, false);
  }

  void Update(const Var& var,
              const Entry& info,
              bool override) {
    if (!override) {
115 116 117
      auto it = var_map_.find(var);
      if (it != var_map_.end()) {
        CHECK(it->second == info)
118 119 120 121
            << "Trying to update var \'" << var << "\'"
            << " with a different const bound: "
            << "original=" << ConstIntBound(it->second.min_value, it->second.max_value)
            << ", new=" << ConstIntBound(info.min_value, info.max_value);
122
      }
123 124 125 126 127 128 129 130 131 132 133
    }
    var_map_[var] = info;
  }

  void Update(const Var& var,
              const ConstIntBound& info,
              bool override) {
    Update(var, MakeBound(info->min_value, info->max_value), override);
  }

  // Override visitor behaviors
134
  Entry VisitExprDefault_(const Object* op) final {
135
    return Everything(
136
        static_cast<const PrimExprNode*>(op)->dtype);
137 138
  }

139
  Entry VisitExpr(const PrimExpr& expr) final {
140
    Entry res = ExprFunctor::VisitExpr(expr);
141
    tir::ExprDeepEqual equal;
142 143 144
    // a linear search over additional info
    // assume we won't have a lot of conditions
    for (const BoundInfo& info : additional_info_) {
145
      if (equal(expr, info.expr)) {
146 147 148
        res = Intersect(res, info.bound);
      }
    }
149 150 151 152 153 154 155 156 157 158 159
    if (bound_) {
      const PrimExprNode* op = expr.as<PrimExprNode>();
      auto val = bound_->find(op);
      if (val != bound_->end()) {
        CHECK(val->second->min_value == res.min_value &&
              val->second->max_value == res.max_value)
          << "Detected bound for " << expr
          << "conflicts with memorization";
      }
      (*bound_)[op] = ConstIntBound(res.min_value, res.max_value);
    }
160 161 162
    return res;
  }

163 164 165 166 167 168 169 170 171 172
  Entry VisitExpr_(const RampNode* op) final {
    // op = {base + i * stride | 0 <= i < lanes}
    // Entry(op) = Union(Entry(base + i * stride) | 0 <= i < lanes)
    // Note that `base + i * stride` is linear w.r.t. `i`
    // Entry(op) = Union(Entry(base + i * stride) | i = 0, i = lanes-1)
    Entry a = VisitExpr(op->base);
    Entry b = VisitExpr(op->base + (op->lanes - 1) * op->stride);
    return Union(a, b);
  }

173
  Entry VisitExpr_(const CastNode* op) final {
174
    Entry a = VisitExpr(op->value);
175
    Entry b = Everything(op->dtype);
176 177 178
    return Intersect(a, b);
  }

179
  Entry VisitExpr_(const IntImmNode* op) final {
180 181 182
    return MakeBound(op->value, op->value);
  }

183
  Entry VisitExpr_(const AddNode* op) final {
184 185 186 187 188 189 190 191
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    Entry ret;
    ret.min_value = InfAwareAdd(a.min_value, b.min_value);
    ret.max_value = InfAwareAdd(a.max_value, b.max_value);
    return ret;
  }

192
  Entry VisitExpr_(const SubNode* op) final {
193 194 195 196 197 198 199 200
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    Entry ret;
    ret.min_value = InfAwareAdd(a.min_value, -b.max_value);
    ret.max_value = InfAwareAdd(a.max_value, -b.min_value);
    return ret;
  }

201
  Entry VisitExpr_(const MulNode* op) final {
202 203 204 205 206
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    return BinaryOpBoundry(a, b, InfAwareMul);
  }

207
  Entry VisitExpr_(const DivNode* op) final {
208 209 210 211 212 213 214 215 216
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    CHECK(!b.is_const(0)) << "divide by zero";
    // assume no division by 0
    if (b.min_value == 0) b.min_value = 1;
    if (b.max_value == 0) b.max_value = -1;
    return BinaryOpBoundry(a, b, InfAwareDiv);
  }

217
  Entry VisitExpr_(const ModNode* op) final {
218 219 220 221 222 223 224 225 226 227 228 229
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    if (b.min_value > 0) {
      int64_t b_max_cap = InfAwareAdd(b.max_value, -1);
      if (a.min_value >= 0) {
        // 0 <= [a_min, a_max] < b_min
        if (a.max_value < b.min_value) return a;
        // other case, we can get close to 0
        return MakeBound(0,
                         std::min(a.max_value, b_max_cap));
      } else {
        return MakeBound(std::max(a.min_value, -b_max_cap),
230
                         std::min(std::max(a.max_value, (int64_t)0), b_max_cap));
231 232 233 234 235
      }
    } else {
      CHECK(!b.is_const(0)) << "mod by zero";
      // mod by negative value is rare,
      // and we just use the simpliest rule.
236
      return Everything(op->dtype);
237 238 239
    }
  }

240
  Entry VisitExpr_(const FloorDivNode* op) final {
241 242 243 244 245 246 247 248 249
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    CHECK(!b.is_const(0)) << "floordiv by zero";
    // assume no division by 0
    if (b.min_value == 0) b.min_value = 1;
    if (b.max_value == 0) b.max_value = -1;
    return BinaryOpBoundry(a, b, InfAwareFloorDiv);
  }

250
  Entry VisitExpr_(const FloorModNode* op) final {
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    if (b.min_value > 0) {
      int64_t b_max_cap = InfAwareAdd(b.max_value, -1);
      if (a.min_value >= 0) {
        // 0 <= [a_min, a_max] < b_min
        if (a.max_value < b.min_value) return a;
        // other case, we can get close to 0
        return MakeBound(0, std::min(a.max_value, b_max_cap));
      } else {
        return MakeBound(0, b_max_cap);
      }
    } else {
      CHECK(!b.is_const(0)) << "floormod by zero";
      // mod by negative value is rare,
      // and we just use the simpliest rule.
267
      return Everything(op->dtype);
268 269 270
    }
  }

271
  Entry VisitExpr_(const MinNode* op) final {
272 273 274 275 276 277 278 279
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    Entry ret;
    ret.min_value = std::min(a.min_value, b.min_value);
    ret.max_value = std::min(a.max_value, b.max_value);
    return ret;
  }

280
  Entry VisitExpr_(const MaxNode* op) final {
281 282 283 284 285 286 287 288
    Entry a = VisitExpr(op->a);
    Entry b = VisitExpr(op->b);
    Entry ret;
    ret.min_value = std::max(a.min_value, b.min_value);
    ret.max_value = std::max(a.max_value, b.max_value);
    return ret;
  }

289
  Entry VisitExpr_(const SelectNode* op) final {
290 291 292 293 294
    Entry a = VisitExpr(op->true_value);
    Entry b = VisitExpr(op->false_value);
    return Union(a, b);
  }

295
  Entry VisitExpr_(const CallNode* op) final {
296 297
    // only special handle >> and & which can be
    // used for index calculation.
298
    if (op->is_intrinsic(CallNode::shift_right)) {
299
      return VisitRightShift(op);
300
    } else if (op->is_intrinsic(CallNode::bitwise_and)) {
301 302
      return VisitBitwiseAnd(op);
    } else {
303
      return Everything(op->dtype);
304 305 306
    }
  }

307
  Entry VisitExpr_(const VarNode* op) final {
308 309 310 311 312
    Var v = GetRef<Var>(op);
    auto it = var_map_.find(v);
    if (it != var_map_.end()) {
      return it->second;
    } else {
313
      return Everything(op->dtype);
314 315 316
    }
  }

317 318 319 320 321 322 323 324 325 326
  Entry VisitExpr_(const SizeVarNode* op) final {
    SizeVar v = GetRef<SizeVar>(op);
    auto it = var_map_.find(v);
    if (it != var_map_.end()) {
      return it->second;
    } else {
      return MakeBound(0, kPosInf);
    }
  }

327
  Entry VisitRightShift(const CallNode* op) {
328 329 330 331 332
    Entry a = VisitExpr(op->args[0]);
    Entry b = VisitExpr(op->args[1]);
    return BinaryOpBoundry(a, b, InfAwareRightShift);
  }

333
  Entry VisitBitwiseAnd(const CallNode* op) {
334 335 336 337 338 339 340 341 342 343 344 345
    Entry a = VisitExpr(op->args[0]);
    Entry b = VisitExpr(op->args[1]);
    // handle positive index case.
    if (a.min_value >= 0 && b.min_value >= 0) {
      return MakeBound(0, std::min(a.max_value, b.max_value));
    } else {
      if (b.min_value >= 0) {
        return MakeBound(0, b.max_value);
      }
      if (a.min_value >= 0) {
        return MakeBound(0, a.max_value);
      }
346
      return Everything(op->dtype);
347 348 349
    }
  }

350
  std::function<void()> EnterConstraint(const PrimExpr& constraint) {
351 352 353 354 355 356 357 358 359 360 361 362
    std::vector<BoundInfo> info = DetectBoundInfo(constraint);
    if (info.size() == 0) return nullptr;
    size_t old_size = additional_info_.size();
    additional_info_.insert(additional_info_.end(), info.begin(), info.end());
    size_t new_size = old_size + info.size();
    auto frecover = [old_size, new_size, this]() {
      CHECK_EQ(additional_info_.size(), new_size);
      additional_info_.resize(old_size);
    };
    return frecover;
  }

363
 private:
364
  friend class ConstIntBoundAnalyzer;
365
  // internal variable map
366
  std::unordered_map<Var, Entry, ObjectHash, ObjectEqual> var_map_;
367 368
  // additional bound info
  std::vector<BoundInfo> additional_info_;
369 370
  // look up table for memorization
  std::unordered_map<const PrimExprNode*, ConstIntBound>* bound_{nullptr};
371 372
  // constants: the limit value means umlimited
  // NOTE: kNegInf/kPosInf are used to represent infinity.
373 374
  static const constexpr int64_t kNegInf = ConstIntBound::kNegInf;
  static const constexpr int64_t kPosInf = ConstIntBound::kPosInf;
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
  static_assert(-kNegInf == kPosInf, "invariant of inf");
  // internal helper functions
  /*!
   * \brief Get boundary of binary op who are monotonic wrt to one argument.
   * \param param a The entry of the left operand.
   * \param param a The entry of the right operand.
   * \param op The operator.
   * \tparam F the operator function type.
   * \return The result.
   */
  template<typename F>
  static Entry BinaryOpBoundry(Entry a, Entry b, const F& op) {
    Entry ret;
    // The boundary point must be shihft of the original boundary.
    int64_t v1 = op(a.min_value, b.min_value);
    int64_t v2 = op(a.max_value, b.max_value);
    int64_t v3 = op(a.min_value, b.max_value);
    int64_t v4 = op(a.max_value, b.min_value);
    ret.min_value = std::min(std::min(std::min(v1, v2), v3), v4);
    ret.max_value = std::max(std::max(std::max(v1, v2), v3), v4);
    return ret;
  }
  /*!
   * \brief Compute x + y, aware of inf.
   * \param x The left operand.
   * \param y The right operand.
   * \return the result.
   */
  static int64_t InfAwareAdd(int64_t x, int64_t y) {
    if (x == kPosInf) {
      CHECK(y != kNegInf);
      return kPosInf;
    }
    if (x == kNegInf) {
      CHECK(y != kPosInf);
      return kNegInf;
    }
    if (y == kPosInf || y == kNegInf) return y;
413
    if (WillOverflow<AddNode>(x, y, kNegInf, kPosInf)) {
414 415 416 417 418 419 420 421 422 423 424 425
      if (x > 0) return kPosInf;
      return kNegInf;
    }
    return x + y;
  }
  /*!
   * \brief Compute x * y, aware of inf.
   * \param x The left operand.
   * \param y The right operand.
   * \return the result.
   */
  static int64_t InfAwareMul(int64_t x, int64_t y) {
426
    if (!WillOverflow<MulNode>(x, y, kNegInf, kPosInf)) return x * y;
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    if ((x > 0 && y > 0) || (x < 0 && y < 0)) return kPosInf;
    return kNegInf;
  }
  /*!
   * \brief Compute x / y, aware of inf.
   * \param x The left operand.
   * \param y The right operand.
   * \return the result.
   */
  static int64_t InfAwareDiv(int64_t x, int64_t y) {
    CHECK_NE(y, 0);
    if (x == kPosInf || x == kNegInf) {
      if (y > 0) return x;
      return -x;
    }
    return x / y;
  }
  /*!
445 446 447 448 449 450 451 452 453 454 455 456 457 458
   * \brief Compute floodiv(x, y), aware of inf.
   * \param x The left operand.
   * \param y The right operand.
   * \return the result.
   */
  static int64_t InfAwareFloorDiv(int64_t x, int64_t y) {
    CHECK_NE(y, 0);
    if (x == kPosInf || x == kNegInf) {
      if (y > 0) return x;
      return -x;
    }
    return floordiv(x, y);
  }
  /*!
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
   * \brief Compute x / y, aware of inf.
   * \param x The left operand.
   * \param y The right operand.
   * \return the result.
   */
  static int64_t InfAwareRightShift(int64_t x, int64_t y) {
    if (x == kPosInf || x == kNegInf) return x;
    return x >> y;
  }
  /*!
   * \brief Make a new bound entry.
   */
  static Entry MakeBound(int64_t min_value, int64_t max_value) {
    Entry e;
    e.min_value = min_value;
    e.max_value = max_value;
    return e;
  }
  /*!
   * \brief Create union of two sets.
   * \param a The left operand.
   * \param b the right operand.
   */
  static Entry Union(Entry a, Entry b) {
    Entry ret;
    ret.min_value = std::min(a.min_value, b.min_value);
    ret.max_value = std::max(a.max_value, b.max_value);
    return ret;
  }
  /*!
   * \brief Create intersect of two sets.
   * \param a The left operand.
   * \param b the right operand.
   */
  static Entry Intersect(Entry a, Entry b) {
    Entry ret;
    ret.min_value = std::max(a.min_value, b.min_value);
    ret.max_value = std::min(a.max_value, b.max_value);
    return ret;
  }
  /*!
   * \brief return everything dtype can represent.
   * \param dtype The data type.
   * \return Bound that represent everything dtype can represent.
   */
504
  static Entry Everything(DataType dtype) {
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    if (!dtype.is_int() && !dtype.is_uint()) {
      return MakeBound(kNegInf, kPosInf);
    }
    Entry ret;
    int64_t vbits = dtype.bits() - static_cast<int>(dtype.is_int());
    if (dtype.is_uint()) {
      ret.min_value = 0;
    } else {
      if (vbits >= 63) {
        ret.min_value = kNegInf;
      } else {
        ret.min_value = -(static_cast<int64_t>(1) << vbits);
      }
    }
    if (vbits >= 63) {
      ret.max_value = kPosInf;
    } else {
      ret.max_value = (static_cast<int64_t>(1) << vbits) - 1;
    }
    return ret;
  }
526 527 528 529 530 531

  /*!
   * \brief Detect additional constant bound from cond, if any
   * \param cond The constraint condition.
   * \return List of detected bounds.
   */
532 533
  static std::vector<BoundInfo> DetectBoundInfo(const PrimExpr& cond) {
    PVar<PrimExpr> x, y;
534
    PVar<IntImm> c;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    // NOTE: canonical form always use <= or <
    if ((c <= x).Match(cond)) {
      return {BoundInfo(x.Eval(), MakeBound(c.Eval()->value, kPosInf))};
    }
    if ((c < x).Match(cond)) {
      return {BoundInfo(x.Eval(), MakeBound(c.Eval()->value + 1, kPosInf))};
    }
    if ((x <= c).Match(cond)) {
      return {BoundInfo(x.Eval(), MakeBound(kNegInf, c.Eval()->value))};
    }
    if ((x < c).Match(cond)) {
      return {BoundInfo(x.Eval(), MakeBound(kNegInf, c.Eval()->value - 1))};
    }
    if ((x && y).Match(cond)) {
      auto ret1 = DetectBoundInfo(x.Eval());
      auto ret2 = DetectBoundInfo(y.Eval());
      ret1.insert(ret1.end(), ret2.begin(), ret2.end());
      return ret1;
    }
    return {};
  }
556 557
};

558
ConstIntBound ConstIntBoundAnalyzer::operator()(const PrimExpr& expr) {
559
  Entry ret = impl_->VisitExpr(expr);
560
  return ConstIntBound(ret.min_value, ret.max_value);
561 562
}

563 564 565 566 567 568 569 570
ConstIntBound ConstIntBoundAnalyzer::operator()(const PrimExpr& expr,
  std::unordered_map<const PrimExprNode*, ConstIntBound>* bound) {
  impl_->bound_ = bound;
  Entry ret = impl_->VisitExpr(expr);
  impl_->bound_ = nullptr;
  return ConstIntBound(ret.min_value, ret.max_value);
}

571 572 573 574 575 576 577 578 579 580
void ConstIntBoundAnalyzer::Update(const Var& var,
                                   const ConstIntBound& info,
                                   bool override) {
  impl_->Update(var, info, override);
}

void ConstIntBoundAnalyzer::Bind(const Var& var, const Range& range) {
  impl_->Bind(var, range);
}

581
std::function<void()> ConstIntBoundAnalyzer::EnterConstraint(const PrimExpr& constraint) {
582
  return impl_->EnterConstraint(constraint);
583 584 585 586 587 588 589 590 591 592 593 594
}

ConstIntBoundAnalyzer::ConstIntBoundAnalyzer(Analyzer* parent)
    : impl_(new Impl()) {
}

ConstIntBoundAnalyzer::~ConstIntBoundAnalyzer() {
  delete impl_;
}

}  // namespace arith
}  // namespace tvm