hoist_if_then_else.cc 14.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * 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.
 */

/*!
 * \file hoist_if_then_else.cc
 */
23 24
#include <tvm/tir/expr.h>
#include <tvm/tir/stmt_functor.h>
25
#include <tvm/arith/analyzer.h>
26 27
#include <tvm/runtime/registry.h>

28 29 30
#include <unordered_map>
#include <unordered_set>
#include <queue>
31 32
#include "../../arith/interval_set.h"
#include "../../runtime/thread_storage_scope.h"
33 34

namespace tvm {
35
namespace tir {
36

37 38
using HoistMap = std::unordered_map<const Object*, std::vector<Stmt>>;
using VarMap = std::unordered_map<const Object*, std::unordered_set<const Object*>>;
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

/*
 * This pass tries to hoist IfThenElse stmt out of For loop if condition is loop invariant.
 * For example, given the following block:
 * for (i = 0; i < 3; i++)
 *    for (j = 0; j < 4; j++)
 *        for (k = 0; k < 5; k++)
 *            if (likely(i*2 < 4))
 *                A[3*i+2j+k] = B[7*i+3j+k]
 *
 * We first detect all IfThenElse stmt and find the corresponding loop invariant For stmt.
 * Then we hoist IfThenElse stmt by one For stmt each step:
 *
 * Step 1:
 * for (i = 0; i < 3; i++)
 *     for (j = 0; j < 4; j++)
 *         if (likely(i*2 < 4))
 *             for (k = 0; k < 5; k++)
 *                 A[3*i+2j+k] = B[7*i+3j+k]
 *
 * Step 2:
 * for (i = 0; i < 3; i++)
 *     if (likely(i*2 < 4))
 *         for (j = 0; j < 4; j++)
 *             for (k = 0; k < 5; k++)
 *                 A[3*i+2j+k] = B[7*i+3j+k]
 *
 * In this pass, we only continue detecting possible hoisting chance when visiting For,
 * IfThenElse or AttrStmt Node. For example, for the following block:
 * for (i = 0; i < 3; i++)
 *    for (j = 0; j < 4; j++)
 *        A[i + j] = A[i + j] - 1
 *        for (k = 0; k < 5; k++)
 *            if (likely(i*2 < 4))
 *                A[3*i+2j+k] = B[7*i+3j+k]
 *
 * Only the For with k variable will be considered and the resulting stmt would be:
 * for (i = 0; i < 3; i++)
 *    for (j = 0; j < 4; j++)
 *        A[i + j] = A[i + j] - 1
 *        if (likely(i*2 < 4))
 *            for (k = 0; k < 5; k++)
 *                A[3*i+2j+k] = B[7*i+3j+k]
 *
 * This pass doesn't do hoisting for consecutive IfThenElse stmt. The following
 * block won't be optimized:
 * for (i = 0; i < 3; i++)
 *    for (j = 0; j < 4; j++)
 *        for (k = 0; k < 5; k++)
 *            if (likely(i*2 < 4))
 *                A[3*i+2j+k] = B[7*i+3j+k]
 *            if (likely(j > 2))
 *                A[i+j+k] = B[i+j+k]
 *
 */
class IfThenElseHoist {
 public:
  Stmt VisitAndMutate(const Stmt& stmt) {
    SelectCandidates(stmt);
    LocateTopFor();
    return PostOrderMutate(stmt);
  }

 private:
  void SelectCandidates(const Stmt& stmt);
  void LocateTopFor();
  Stmt PostOrderMutate(const Stmt& stmt);
  size_t GetUpdatedFor(const Stmt& for_stmt, const Stmt& if_stmt);
  Stmt HoistIf(const Stmt& if_stmt);

  // Map of all For nodes to all child IfThenElse nodes.
  HoistMap for2if_map_;
  // Map of all IfThenElse nodes to all For nodes which are loop invariant.
  HoistMap if2for_map_;
  // Map of highest loop invariant For to child IfThenElse.
  HoistMap top_for_var_map_;
  // Map of original For to list of update For nodes.
  HoistMap for_tracking_map_;
  // Map of all IfThenElse nodes to condition variable nodes.
  VarMap cond_var_map_;
  // List of For nodes added in post order DFS visiting.
  std::vector<Stmt> ordered_for_list_;
};

// Check whether a given IfThenElse stmt is the first one appearing
// in a For stmt.
bool is_first_if(const Stmt& for_stmt, const Stmt& if_stmt) {
126
  std::vector<const Object*> if_node_list;
127
  const ForNode* for_node = for_stmt.as<ForNode>();
128
  CHECK(for_node);
129
  CHECK(if_stmt.as<IfThenElseNode>());
130

131
  PostOrderVisit(for_node->body, [&](const ObjectRef& node) {
132
    if (node.as<IfThenElseNode>()) {
133 134 135 136 137 138 139 140 141 142
      if_node_list.push_back(node.get());
    }
  });
  return if_node_list.empty() ? false : if_stmt.get() == if_node_list.back();
}

// Update upper level For node when current For node is modified.
// With this function we only need to visit and mutate top level For node
// in the main VisitAndMutate function.
Stmt update_for(const Stmt& parent_for_stmt, const Stmt& new_if_stmt) {
143
  const Object* top_for_node;
144
  const ForNode* parent_for_node = parent_for_stmt.as<ForNode>();
145
  CHECK(parent_for_node);
146
  CHECK(new_if_stmt.as<IfThenElseNode>());
147

148
  PostOrderVisit(parent_for_node->body, [&](const ObjectRef& node) {
149
    if (node.as<ForNode>()) {
150 151 152 153 154 155
      top_for_node = node.get();
    }
  });

  PackedFunc replace_target_for = PackedFunc(
    [&](TVMArgs args, TVMRetValue *ret){
156
      const ObjectRef& current_for = args[0];
157 158 159 160 161 162
      if (current_for.get() == top_for_node) {
        *ret = new_if_stmt;
      }
    });

  return IRTransform(parent_for_stmt, nullptr, replace_target_for,
163
                     {PrimExpr("For")});
164 165 166 167 168 169 170
}

// Remove IfThenElse node from a For node.
// A pair of For nodes will be generated.
std::pair<Stmt, Stmt> RemoveIf(const Stmt& for_stmt, const Stmt& if_stmt) {
  Stmt then_for;
  Stmt else_for;
171
  CHECK(if_stmt.as<IfThenElseNode>());
172 173 174

  PackedFunc replace_then_case = PackedFunc(
    [&](TVMArgs args, TVMRetValue *ret){
175
      const ObjectRef& node  = args[0];
176
      if (node == if_stmt) {
177
        *ret = node.as<IfThenElseNode>()->then_case;
178 179 180 181 182
      }
    });

  PackedFunc replace_else_case = PackedFunc(
    [&](TVMArgs args, TVMRetValue *ret){
183
      const ObjectRef& node  = args[0];
184
      if (node == if_stmt) {
185
        *ret = node.as<IfThenElseNode>()->else_case;
186 187 188 189
      }
    });

  then_for = IRTransform(for_stmt, nullptr, replace_then_case,
190
                         {PrimExpr("IfThenElse")});
191
  if (if_stmt.as<IfThenElseNode>()->else_case.defined()) {
192
    else_for = IRTransform(for_stmt, nullptr, replace_else_case,
193
                           {PrimExpr("IfThenElse")});
194 195 196 197 198 199 200
  }

  return std::make_pair(then_for, else_for);
}

// Locate all For nodes and capture child IfThenElse nodes.
void IfThenElseHoist::SelectCandidates(const Stmt& stmt) {
201
  PostOrderVisit(stmt, [&](const ObjectRef& node){
202
    const ForNode* for_node = node.as<ForNode>();
203 204 205 206
    if (!for_node) return;

    std::queue<Stmt> tracker;
    tracker.push(for_node->body);
207
    Stmt for_stmt = Downcast<Stmt, ObjectRef>(node);
208 209 210 211
    for2if_map_.insert({for_stmt.get(), std::vector<Stmt>()});
    while (!tracker.empty()) {
      Stmt head = tracker.front();
      tracker.pop();
212
      if (head->IsInstance<ForNode>()) {
213 214 215
        for (const auto& if_stmt : for2if_map_.at(head.get())) {
          for2if_map_[for_stmt.get()].push_back(if_stmt);
        }
216 217
      } else if (head->IsInstance<AttrStmtNode>()) {
        const AttrStmtNode* attr_node = head.as<AttrStmtNode>();
218
        tracker.push(attr_node->body);
219
      } else if (head->IsInstance<IfThenElseNode>()) {
220
        for2if_map_[for_stmt.get()].push_back(head);
221
        const IfThenElseNode* if_node = head.as<IfThenElseNode>();
222
        tracker.push(if_node->then_case);
223
        if (if_node->else_case.defined()) {
224 225 226 227 228
          tracker.push(if_node->else_case);
        }

        // Record condition variables.
        if (!cond_var_map_.count(head.get())) {
229
          std::unordered_set<const Object*> new_var_set;
230
          cond_var_map_.insert({head.get(), new_var_set});
231
          PostOrderVisit(if_node->condition, [&](const ObjectRef& cond_node) {
232
            if (cond_node.as<VarNode>()) {
233 234 235 236 237 238 239 240
              cond_var_map_[head.get()].insert(cond_node.get());
            }
          });
        }
      } else {
        continue;
      }
    }
241
    ordered_for_list_.emplace_back(Downcast<Stmt, ObjectRef>(node));
242 243 244 245 246 247
  });
}

// For each IfThenElse node, find the highest For node which
// meets loop invariant condition.
void IfThenElseHoist::LocateTopFor() {
248 249
  std::unordered_map<const Object*, Stmt> if_position_map;
  std::unordered_set<const Object*> top_for_var_set;
250 251 252 253

  // Create IfThenElse -> For map.
  for (const Stmt& for_stmt : ordered_for_list_) {
    std::vector<Stmt> if_list = for2if_map_[for_stmt.get()];
254
    const ForNode* for_node = for_stmt.as<ForNode>();
255 256 257
    CHECK(for_node);
    top_for_var_map_.insert({for_node->loop_var.get(), if_list});
    for (const Stmt& if_stmt : if_list) {
258
      const Object* if_node = if_stmt.get();
259 260 261 262 263 264 265
      if2for_map_[if_node].push_back(for_stmt);
    }
  }

  // Locate the highest For node which is loop invariant.
  for (const auto& item : if2for_map_) {
    Stmt top_for;
266
    const Object* if_stmt = item.first;
267 268 269
    std::vector<Stmt> for_list = item.second;
    for (size_t i = 0; i < for_list.size(); ++i) {
      const Stmt& for_stmt = for_list.at(i);
270
      const ForNode* for_node = for_stmt.as<ForNode>();
271 272 273 274 275 276 277 278 279 280 281 282 283
      CHECK(for_node);
      std::vector<Stmt> new_for_list{for_stmt};
      for_tracking_map_.insert({for_stmt.get(), new_for_list});
      if (cond_var_map_[if_stmt]
        .count(for_node->loop_var.get())) {
        std::vector<Stmt> updated_for_list(for_list.begin(),
                                           for_list.begin() + i);
        if2for_map_[if_stmt] = updated_for_list;
        break;
      } else {
        top_for = for_stmt;
      }
    }
284
    if (top_for.as<ForNode>()) {
285 286 287 288 289
      if_position_map.insert({if_stmt, top_for});
    }
  }

  for (const auto& item : if_position_map) {
290
    top_for_var_set.insert(item.second.as<ForNode>()->loop_var.get());
291 292
  }

293
  std::vector<const Object*> removed_for_var_list;
294
  for (const auto& item : top_for_var_map_) {
295
    const Object* top_for_var = item.first;
296 297 298 299 300 301 302 303 304 305 306 307 308
    std::vector<Stmt> if_list = item.second;
    if (!top_for_var_set.count(top_for_var)) {
      removed_for_var_list.push_back(top_for_var);
    } else {
      std::vector<Stmt> actual_if_list;
      for (const Stmt& if_stmt : if_list) {
        if (if_position_map.count(if_stmt.get())) {
          actual_if_list.push_back(if_stmt);
        }
      }
      top_for_var_map_[top_for_var] = actual_if_list;
    }
  }
309
  for (const Object* top_for_var : removed_for_var_list) {
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
    top_for_var_map_.erase(top_for_var);
  }
}

// When we try to mutate a For node, some child For nodes can have already
// been mutated. This function is to get the updated For node and further
// hoisting can be done based on this new node.
// We keep all For nodes tracing in for_tracking_map_. When we get a
// hoisted IfThenElse, we match it with tracing For nodes to pick
// the updated one.
size_t IfThenElseHoist::GetUpdatedFor(const Stmt& for_stmt,
                                       const Stmt& if_stmt) {
  std::vector<Stmt> tracked_for_list = for_tracking_map_[for_stmt.get()];
  size_t updated_for_idx = 0;
  for (size_t i = 0; i < tracked_for_list.size(); ++i) {
    const Stmt& current_for =
      tracked_for_list.at(tracked_for_list.size() - 1 - i);
    if (is_first_if(current_for, if_stmt)) {
      updated_for_idx = tracked_for_list.size() - 1 - i;
      break;
    }
  }
  return updated_for_idx;
}

// Hoist an IfThenElse node as high as possible.
// This function iterates on all candidate For nodes. For each For node,
// it first removes IfThenElse nodes. Then it generates a new IfThenElse
// node using mutated For nodes.
Stmt IfThenElseHoist::HoistIf(const Stmt& if_stmt) {
  Stmt new_if = if_stmt;

  for (size_t i = 0; i < if2for_map_[if_stmt.get()].size(); ++i) {
    const Stmt& for_stmt = if2for_map_[if_stmt.get()].at(i);
    size_t updated_for_idx = GetUpdatedFor(for_stmt, new_if);
    const Stmt& updated_for_node =
      for_tracking_map_[for_stmt.get()].at(updated_for_idx);
    auto generated_for_pair = RemoveIf(updated_for_node, new_if);
    const Stmt& then_for = generated_for_pair.first;
    const Stmt& else_for = generated_for_pair.second;;
    for_tracking_map_[for_stmt.get()].at(updated_for_idx) = then_for;

    if (else_for.get()) {
      for_tracking_map_[for_stmt.get()].push_back(else_for);
    }

356
    const IfThenElseNode* new_if_node = new_if.as<IfThenElseNode>();
357
    CHECK(new_if_node);
358
    new_if = IfThenElseNode::make(new_if_node->condition, then_for, else_for);
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    if (i < if2for_map_[if_stmt.get()].size() - 1) {
      const Stmt& original_next_for = if2for_map_[if_stmt.get()].at(i + 1);
      const Stmt& actual_next_for =
        for_tracking_map_[original_next_for.get()].at(updated_for_idx);
      Stmt update_for_stmt = update_for(actual_next_for, new_if);

      for_tracking_map_[original_next_for.get()].
        at(updated_for_idx) = update_for_stmt;
    }
  }
  return new_if;
}

// Mutate For nodes in post order DFS manner.
Stmt IfThenElseHoist::PostOrderMutate(const Stmt& stmt) {
  PackedFunc replace_top_for = PackedFunc(
    [&](TVMArgs args, TVMRetValue *ret){
376
      const ObjectRef& current_for = args[0];
377
      const ForNode* for_node = current_for.as<ForNode>();
378 379 380 381 382 383 384 385 386
      if (!for_node) return;

      if (top_for_var_map_.count(for_node->loop_var.get())) {
        std::vector<Stmt> new_if_list;
        for (const Stmt& if_stmt :
          top_for_var_map_[for_node->loop_var.get()]) {
          new_if_list.emplace_back(HoistIf(if_stmt));
        }

387 388 389
        const IfThenElseNode* next_if_node;
        const IfThenElseNode* current_if_node =
          new_if_list.back().as<IfThenElseNode>();
390 391 392 393
        Stmt new_for = Stmt();
        for (size_t i = new_if_list.size() - 1; i > 0; --i) {
          CHECK(current_if_node);
          const Stmt current_if_stmt =
394
            IfThenElseNode::make(current_if_node->condition,
395 396
                             current_if_node->then_case,
                             current_if_node->else_case);
397
          next_if_node = new_if_list[i - 1].as<IfThenElseNode>();
398
          CHECK(next_if_node);
399
          new_for = IfThenElseNode::make(next_if_node->condition, current_if_stmt,
400
                                     next_if_node->else_case);
401
          current_if_node = new_for.as<IfThenElseNode>();
402 403 404
        }

        if (!new_for.get()) {
405
          const IfThenElseNode* first_if_node = new_if_list[0].as<IfThenElseNode>();
406
          CHECK(first_if_node);
407
          new_for = IfThenElseNode::make(first_if_node->condition,
408 409 410 411 412 413
                                     first_if_node->then_case,
                                     first_if_node->else_case);
        }
        *ret = new_for;
      }
    });
414
  return IRTransform(stmt, nullptr, replace_top_for, {PrimExpr("For")});
415 416 417 418 419 420
}

Stmt HoistIfThenElse(Stmt stmt) {
  return IfThenElseHoist().VisitAndMutate(stmt);
}

421
}  // namespace tir
422
}  // namespace tvm