lower_intrin.cc 9.85 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
 *  Lower intrinsic calls and ops to device specific ir when possible.
22 23 24 25 26 27
 * \file lower_intrin.cc
 */
#include <tvm/ir.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>
#include <tvm/api_registry.h>
28
#include <tvm/expr_operator.h>
29
#include <unordered_set>
30
#include "ir_util.h"
31 32
#include "../arithmetic/pattern_match.h"
#include "../arithmetic/ir_mutator_with_analyzer.h"
33 34 35 36

namespace tvm {
namespace ir {

37
class IntrinInjecter : public arith::IRMutatorWithAnalyzer {
38
 public:
39 40 41 42
  using IRMutatorWithAnalyzer::Mutate_;

  IntrinInjecter(arith::Analyzer* analyzer, std::string target)
      : IRMutatorWithAnalyzer(analyzer) {
43 44 45 46
    std::istringstream is(target);
    std::string starget;
    is >> starget;
    patterns_.push_back("tvm.intrin.rule." + starget + ".");
47
    patterns_.push_back("tvm.intrin.rule.default.");
48
    fma_ = runtime::Registry::Get(patterns_[0] + "fma");
49 50 51
    if (target == "stackvm") {
      support_bitwise_op_ = false;
    }
52 53 54 55 56
  }

  Expr Mutate_(const Call* op, const Expr& e) final {
    if (op->call_type == Call::Intrinsic ||
        op->call_type == Call::PureIntrinsic) {
57 58
      Expr r = ApplyPattern(op->name, e);
      if (r.defined()) return r;
59 60 61 62
    }
    return IRMutator::Mutate_(op, e);
  }

63 64
  Expr Mutate_(const Add* op, const Expr& e) final {
    if (const Mul* mb = op->b.as<Mul>()) {
65
      return MakeFMA(mb->a, mb->b, op->a, op, e);
66
    } else if (const Mul* ma = op->a.as<Mul>()) {
67 68 69 70 71
      return MakeFMA(ma->a, ma->b, op->b, op, e);
    }
    return IRMutator::Mutate_(op, e);
  }

72 73 74 75 76 77 78 79 80 81
  // We use floordiv for integer analysis,
  // but will need to lower them to native truncdiv instructions
  Expr Mutate_(const FloorDiv* op, const Expr& e) final {
    Expr ret = IRMutatorWithAnalyzer::Mutate_(op, e);
    op = ret.as<FloorDiv>();
    if (op == nullptr) return ret;
    int shift;
    const DataType& dtype = op->type;
    CHECK(dtype.is_int() || !dtype.is_uint());

82 83
    if (support_bitwise_op_ &&
        is_const_power_of_two_integer(op->b, &shift)) {
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
      // lower to right shift if possible.
      return op->a >> make_const(dtype, shift);
    }

    if (analyzer_->CanProveGreaterEqual(op->b, 0)) {
      // Common path, positive divisor
      if (analyzer_->CanProveGreaterEqual(op->a, 0) ||
          analyzer_->CanProveGreaterEqual(e, 0)) {
        return truncdiv(op->a, op->b);
      } else {
        DLOG(INFO) << "LowerFloorDiv: Cannot decide the sign of divident";
        Expr rdiv = truncdiv(op->a, op->b);
        Expr rmod = truncmod(op->a, op->b);
        // condition on b >= 0.
        // truncmod(a, b) < 0 will implies ceildiv,
        // So we need to correct these cases.
100
        if ((dtype == Int(32) || dtype == Int(64)) && support_bitwise_op_) {
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
          // equivalent to rdiv + (rmod >= 0 ? 0: -1);
          return rdiv + (rmod >> make_const(dtype, dtype.bits() - 1));
        } else {
          return ir::Select::make(rmod >= 0 , rdiv, rdiv - make_const(dtype, 1));
        }
      }
    } else {
      // uncommon case
      DLOG(INFO) << "LowerFloorDiv: Cannot decide the sign of divisor";
      // b >= 0 => (rmod >=0 ? rdiv : rdiv - 1)
      // b < 0  => (rmod <= 0 ? rdiv : rdiv - 1)
      Expr rdiv = truncdiv(op->a, op->b);
      Expr rmod = truncmod(op->a, op->b);
      return ir::Select::make(
          (op->b >= 0 && rmod >= 0) || (op->b < 0 && rmod <= 0),
          rdiv, rdiv - make_const(dtype, 1));
    }
  }

  Expr Mutate_(const FloorMod* op, const Expr& e) final {
    Expr ret = IRMutatorWithAnalyzer::Mutate_(op, e);
    op = ret.as<FloorMod>();
    if (op == nullptr) return ret;
    // Lower floordiv to native truncdiv.
    int shift;
    const DataType& dtype = op->type;
    CHECK(dtype.is_int() || !dtype.is_uint());

129 130
    if (support_bitwise_op_ &&
        is_const_power_of_two_integer(op->b, &shift)) {
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
      // lower to masking if possible.
      int64_t mask = (
          static_cast<int64_t>(1) << static_cast<int64_t>(shift)) - 1;
      return op->a & make_const(dtype, mask);
    }

    if (analyzer_->CanProveGreaterEqual(op->b, 0)) {
      // Common pass, positive divisor
      if (analyzer_->CanProveGreaterEqual(op->a, 0) ||
          analyzer_->CanProveGreaterEqual(e, 0)) {
        return truncmod(op->a, op->b);
      } else {
        DLOG(INFO) << "LowerFloorMod: Cannot decide the sign of divident";
        // NOTE:condition on b >= 0.
        // mod(a, b) < 0 will imply we are doing ceildiv,
        // So we need to correct these cases.
        Expr rmod = truncmod(op->a, op->b);
148
        if ((dtype == Int(32) || dtype == Int(64)) && support_bitwise_op_) {
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
          // (rmod >> shift) & b
          // -> (rmod >= 0 ? 0: -1) & b
          // -> rmod >= 0 ? 0 : b
          return rmod + (op->b & (rmod >> make_const(dtype, dtype.bits() - 1)));
        } else {
          return ir::Select::make(rmod >= 0, rmod, rmod + op->b);
        }
      }
    } else {
      // uncommon case
      DLOG(INFO) << "LowerFloorMod: Cannot decide the sign of divsor and divident";
      Expr rmod = truncmod(op->a, op->b);
      // b > 0 && rmod >= 0 -> rmod
      // b > 0 && rmod < 0  -> rmod + b
      // b < 0 && rmod < 0 -> rmod
      // b < 0 && rmod > 0 -> rmod + b
      return ir::Select::make(
          (op->b >= 0 && rmod >= 0) || (op->b < 0 && rmod <= 0),
          rmod, rmod + op->b);
    }
  }

  Expr Mutate_(const Max* op, const Expr& e) final {
    using namespace arith;
    PVar<Expr> x, y;
    PVar<Integer> c;
    if (max(floordiv(x, y), c).Match(e) &&
        c.Eval()->value >= 0 &&
        analyzer_->CanProveGreaterEqual(y.Eval(), 0)) {
      return max(Mutate(truncdiv(x, y).Eval()), c.Eval());
    }
    return IRMutatorWithAnalyzer::Mutate_(op, e);
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  }

  Expr Mutate_(const EQ* op, const Expr& e) final {
    using namespace arith;
    PVar<Expr> x, y;
    if ((floormod(x, y) == 0).Match(e)) {
      return Mutate((truncmod(x, y) == 0).Eval());
    }
    return IRMutatorWithAnalyzer::Mutate_(op, e);
  }

  Expr Mutate_(const NE* op, const Expr& e) final {
    using namespace arith;
    PVar<Expr> x, y;
    if ((floormod(x, y) != 0).Match(e)) {
196
      return Mutate((truncmod(x, y) != 0).Eval());
197 198
    }
    return IRMutatorWithAnalyzer::Mutate_(op, e);
199 200
  }

201 202 203 204 205 206 207 208
 private:
  Expr SwapBroadcastCast(const Expr& e) {
    // Try to change broadcast(cast(x)) to cast(broadcast(x))
    // For some targets, LLVM will generate more efficient FMA
    // instruction with the latter. For example, vmla vs. vmlal
    // on ARM.
    if (const Broadcast* bcast = e.as<Broadcast>()) {
      if (const Cast* cast = bcast->value.as<Cast>()) {
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
        auto should_swap = [&]() {
          // Maintain behaviour (int8 -> int16, fp16 -> fp32).
          if (cast->type.bits() == cast->value.type().bits() * 2) {
            return true;
          }
          // Check both operands are integer-like.
          if (!cast->type.is_uint() && !cast->type.is_int()) {
            return false;
          }
          if (!cast->value.type().is_uint() && !cast->value.type().is_int()) {
            return false;
          }
          // If both are integer-like, swap if we have a widening cast.
          return cast->type.bits() > cast->value.type().bits();
        };

        if (should_swap()) {
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
          Expr new_bcast = Broadcast::make(cast->value, bcast->lanes);
          return Cast::make(bcast->type, new_bcast);
        }
      }
    }
    return e;
  }

  Expr MakeFMA(const Expr& a, const Expr& b, const Expr& c,
               const Add* op, const Expr& e) {
    // emit fma instruction: a * b + c
    Expr lhs = SwapBroadcastCast(a);
    Expr rhs = SwapBroadcastCast(b);

    if (fma_ != nullptr && op->type.is_float()) {
241
      Expr r = (*fma_)(Call::make(
242
          op->type, "fma", {lhs, rhs, c}, Call::PureIntrinsic));
243
      if (r.defined()) return this->Mutate(r);
244 245 246 247 248
    } else {
      if (!lhs.same_as(a) || !rhs.same_as(b)) {
        Expr mul = this->Mutate(Mul::make(lhs, rhs));
        return Add::make(mul, this->Mutate(c));
      }
249 250 251 252
    }
    return IRMutator::Mutate_(op, e);
  }

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  Expr ApplyPattern(const std::string& name, const Expr& e) {
    for (size_t i = 0; i < patterns_.size(); ++i) {
      std::string& p = patterns_[i];
      size_t psize = p.length();
      p.resize(psize + name.length());
      name.copy(&p[0] + psize, name.length());
      const runtime::PackedFunc* f = runtime::Registry::Get(p);
      p.resize(psize);
      // if pattern exists.
      if (f != nullptr) {
        Expr r = (*f)(e);
        CHECK(r.defined()) << "intrinsic rule must always return valid Expr";
        if (!r.same_as(e)) {
          return this->Mutate(r);
        }
      }
    }
    return Expr();
  }
272

273
  // patterns
274
  std::vector<std::string> patterns_;
275
  const PackedFunc* fma_{nullptr};
276
  bool support_bitwise_op_{true};
277 278
};

279 280 281 282 283
Stmt LowerIntrinStmt(Stmt stmt, const std::string& target) {
  arith::Analyzer analyzer;
  return IntrinInjecter(&analyzer, target).Mutate(stmt);
}

284 285
LoweredFunc
LowerIntrin(LoweredFunc f, const std::string& target) {
286
  auto n = make_node<LoweredFuncNode>(*f.operator->());
287
  n->body = LowerIntrinStmt(n->body, target);
288 289 290
  return LoweredFunc(n);
}

291 292 293 294
// Register the api only for test purposes
TVM_REGISTER_API("ir_pass._LowerIntrinStmt")
.set_body_typed(LowerIntrinStmt);

295 296
}  // namespace ir
}  // namespace tvm