|
| 1 | +/*! |
| 2 | + * Copyright (c) 2016 by Contributors |
| 3 | + * SSA related checks and pass. |
| 4 | + * \file ssa.cc |
| 5 | + */ |
| 6 | +#include <tvm/ir.h> |
| 7 | +#include <tvm/ir_pass.h> |
| 8 | +#include <tvm/ir_mutator.h> |
| 9 | +#include <unordered_set> |
| 10 | +#include <unordered_map> |
| 11 | +#include <vector> |
| 12 | +#include "../schedule/compute_expr.h" |
| 13 | + |
| 14 | +namespace tvm { |
| 15 | +namespace ir { |
| 16 | + |
| 17 | +class LoopUnroller : public IRMutator { |
| 18 | + public: |
| 19 | + explicit LoopUnroller(int max_auto_step) |
| 20 | + : max_auto_step_(max_auto_step) { |
| 21 | + } |
| 22 | + |
| 23 | + Stmt Mutate_(const For* op, const Stmt& s) { |
| 24 | + Stmt stmt = s; |
| 25 | + // constant folding. |
| 26 | + Expr extent = ir::Simplify(op->extent); |
| 27 | + const IntImm* v1 = extent.as<IntImm>(); |
| 28 | + const UIntImm* v2 = extent.as<UIntImm>(); |
| 29 | + int value = -1; |
| 30 | + if (v1 != nullptr) { |
| 31 | + value = static_cast<int>(v1->value); |
| 32 | + } |
| 33 | + if (v2 != nullptr) { |
| 34 | + value = static_cast<int>(v2->value); |
| 35 | + } |
| 36 | + bool allow_unroll = value >= 0 && value <= max_auto_step_; |
| 37 | + if (op->for_type == ForType::Unrolled) { |
| 38 | + CHECK_GE(value, 0) |
| 39 | + << "Cannot unroll non-constant loop"; |
| 40 | + allow_unroll = true; |
| 41 | + } |
| 42 | + |
| 43 | + if (allow_unroll) { |
| 44 | + if (value == 0) return Evaluate::make(0); |
| 45 | + Stmt body = op->body; |
| 46 | + Map<Var, Expr> vmap; |
| 47 | + Stmt unrolled; |
| 48 | + for (int i = 0; i < value; ++i) { |
| 49 | + Var lv(op->loop_var.node_); |
| 50 | + vmap.Set(lv, |
| 51 | + schedule::ComputeExpr<Add>( |
| 52 | + op->min, make_const(op->loop_var.type(), i))); |
| 53 | + Stmt step = Substitute(body, vmap); |
| 54 | + if (unrolled.defined()) { |
| 55 | + unrolled = Block::make(unrolled, step); |
| 56 | + } else { |
| 57 | + unrolled = step; |
| 58 | + } |
| 59 | + } |
| 60 | + return this->Mutate(unrolled); |
| 61 | + } else { |
| 62 | + return IRMutator::Mutate_(op, stmt); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + private: |
| 67 | + int max_auto_step_; |
| 68 | +}; |
| 69 | + |
| 70 | + |
| 71 | +Stmt UnrollLoop(Stmt stmt, int max_auto_step) { |
| 72 | + Stmt ret = LoopUnroller(max_auto_step).Mutate(stmt); |
| 73 | + return ConvertSSA(ret); |
| 74 | +} |
| 75 | + |
| 76 | +} // namespace ir |
| 77 | +} // namespace tvm |
0 commit comments