ir_pass.h 16.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * 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
20
/*!
tqchen committed
21
 * \file tvm/ir_pass.h
tqchen committed
22 23
 * \brief Collection of IR pass functions
 *
24 25
 *  When the pass functions in this file are for Stmt,
 *  we can use PassFunction(Evaluate(expr)) to apply it to Expr
tqchen committed
26 27 28 29
 */
#ifndef TVM_IR_PASS_H_
#define TVM_IR_PASS_H_

30
#include <arithmetic/Simplify.h>
tqchen committed
31
#include <unordered_map>
32
#include <unordered_set>
tqchen committed
33
#include <vector>
34
#include <string>
35 36 37 38
#include "expr.h"
#include "buffer.h"
#include "schedule.h"
#include "lowered_func.h"
tqchen committed
39 40 41 42

namespace tvm {
namespace ir {

43 44 45 46 47 48
/*!
 * \brief Simplify the expression.
 * \param expr The expression to be simplifed.
 * \param vrange The range information about the variable.
 * \return Canonicalized statement.
 */
49
TVM_DLL Expr Simplify(Expr expr, Map<Var, Range> vrange = Map<Var, Range>());
50

51 52 53 54 55 56 57
/*!
 * \brief Simplify the statement.
 * \param stmt The statement to be simplifed.
 * \param vrange The range information about the variable.
 * \return Canonicalized statement.
 */
Stmt Simplify(Stmt stmt, Map<Var, Range> vrange = Map<Var, Range>());
58 59

/*!
60 61
 * \brief Simplify by applying canonical form.
 * \param stmt The statement to be canonically simplifed.
62
 * \param vrange The range information about the variable.
63 64
 * \return Canonicalized statement.
 */
65 66
Stmt CanonicalSimplify(Stmt stmt,
                       Map<Var, Range> vrange = Map<Var, Range>());
67 68 69 70

/*!
 * \brief Simplify by applying canonical form.
 * \param expr The statement to be canonically simplifed.
71
 * \param vrange The range information about the variable.
72 73
 * \return Canonicalized expression.
 */
74
TVM_DLL Expr CanonicalSimplify(Expr expr,
75
                              Map<Var, Range> vrange = Map<Var, Range>());
76 77

/*!
78 79 80 81 82
 * \brief Deep compare lhs and rhs
 * \param lhs The left operand
 * \param rhs The right operand
 * \return The comparison result.
 */
83
TVM_DLL bool Equal(const Expr& lhs, const Expr& rhs);
84 85 86 87 88 89 90 91 92 93

/*!
 * \brief Deep compare lhs and rhs
 * \param lhs The left operand
 * \param rhs The right operand
 * \return The comparison result.
 */
bool Equal(const Stmt& lhs, const Stmt& rhs);

/*!
94 95 96 97 98 99 100 101 102 103 104 105 106
 * \brief Deep compare lhs and rhs.
 *
 *  If you only want equality comparison, use Equal
 *  which will also tie definitions. The compare mode
 *  will give order of expression in total order.
 *
 * \param lhs The left operand
 * \param rhs The right operand
 * \return The comparison result.
 */
int Compare(const Expr& lhs, const Expr& rhs);

/*!
tqchen committed
107 108 109 110 111 112
 * \brief verifies whether the IR stmt or Expr is in SSA form.
 *  That is: each VarExpr is defined and assigned once(in Let/For)
 *
 * \param ir The root of the IR DAG.
 * \return Whether IR is in SSA form.
 * \note All the passes in this file uses SSA form and outputs SSA form.
tqchen committed
113
 */
114
TVM_DLL bool VerifySSA(const Stmt& ir);
tqchen committed
115 116

/*!
117 118 119
 * \brief Whether the expression have side effect.
 * \return whether expression have side effect
 */
120
TVM_DLL bool HasSideEffect(const Expr& e);
121 122

/*!
123 124 125 126 127 128 129 130
 * \brief Whether e expression used var.
 * \param e The expression to be checked.
 * \param v The variable.
 * \return Whether e uses v.
 */
bool ExprUseVar(const Expr& e, const Var& v);

/*!
131 132 133 134 135 136 137 138
 * \brief Whether e expression used any var in variable set..
 * \param e The expression to be checked.
 * \param vset The variable set.
 * \return Whether e uses vset.
 */
bool ExprUseVar(const Expr& e, const std::unordered_set<const Variable*>& vset);

/*!
tqchen committed
139 140 141 142
 * \brief Convert a IR node to be SSA form.
 * \param stmt The source statement to be converted.
 * \return The converted form.
 */
143
TVM_DLL Stmt ConvertSSA(Stmt stmt);
tqchen committed
144 145

/*!
146 147 148 149 150
 * \brief Substitute the var specified in key->var to be value.
 * \param stmt The source statement to be substituted
 * \param value_map The map of new values.
 * \return The converted form.
 */
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
Stmt Substitute(Stmt stmt,
                const std::unordered_map<const Variable*, Expr>& value_map);

/*!
 * \brief Substitute the var specified in key->var to be value.
 * \param expr The source expression to be substituted
 * \param value_map The map of new values.
 * \return The converted expression.
 */
Expr Substitute(Expr expr,
                const std::unordered_map<const Variable*, Expr>& value_map);

/*!
 * \brief Substitute the var specified in key->var to be value.
 * \param stmt The source statement to be substituted
 * \param value_map The map of new values.
 * \return The converted form.
 */
169
Stmt Substitute(Stmt stmt, const Map<Var, Expr>& value_map);
170 171 172 173 174 175 176

/*!
 * \brief Substitute the var specified in key->var to be value.
 * \param expr The source expression to be substituted
 * \param value_map The map of new values.
 * \return The converted expression.
 */
ziheng committed
177
Expr Substitute(Expr expr, const Map<Var, Expr>& value_map);
178 179

/*!
tqchen committed
180 181
 * \brief inline all calls of f in stmt.
 *
182
 * \param stmt The statement to apply inline optimization.
tqchen committed
183 184
 * \param f The function reference to be inlined
 * \param args The arguments variable of the function.
185
 * \param body The definition body of the function.
tqchen committed
186 187 188 189
 * \return The result stmt
 *
 * \note All the passes in this file uses SSA form and outputs SSA form.
 */
190 191
Stmt Inline(Stmt stmt,
            FunctionRef f,
tqchen committed
192
            Array<Var> args,
193 194 195 196 197 198 199 200 201
            Expr body);

/*!
 * \brief Flatten the multi-dimensional read/write
 *  to single dimensional Load/Store
 *
 * \param stmt The stmt to be trasnformed.
 * \param extern_buffer Map specifies external
 *    buffer assignment of input and outputs.
202
 * \param cache_line_size The size of CPU cache line.
203
 * \param create_bound_attribute Whether to create bound attributes.
204
 * \return Transformed stmt.
205 206
 */
Stmt StorageFlatten(Stmt stmt,
207
                    Map<Tensor, Buffer> extern_buffer,
208 209
                    int cache_line_size,
                    bool create_bound_attribute = false);
tqchen committed
210

211
/*!
Tianqi Chen committed
212 213 214 215 216 217 218 219 220
 * \brief Remove No Op from the Stmt.
 * \param stmt The stmt to be trasnformed
 * \return Transformed stmt.
 */
Stmt RemoveNoOp(Stmt stmt);

/*!
 * \brief Split statement into pipeine stages.
 * \param stmt The stmt to be splitted
221 222 223 224 225 226 227 228
 * \param split_load Whether split load into its own stage.
 * \return Transformed stmt.
 */
Stmt SplitPipeline(Stmt stmt, bool split_load);

/*!
 * \brief Narrow channel access to smaller range.
 * \param stmt The stmt to do access rewriting.
Tianqi Chen committed
229 230
 * \return Transformed stmt.
 */
231
Stmt NarrowChannelAccess(Stmt stmt);
Tianqi Chen committed
232 233

/*!
234 235 236
 * \brief unroll the constant loop marked by unroll.
 * This pass also automatically attach pragma unroll tag to loops which meets the standard.
 *
237
 * \param stmt The statment to be unrolled.
238
 * \param auto_max_step The maximum step before stop attach automatic unroll
239
 * \param auto_max_depth The maximum depth before stop attach automatic unroll
240
 * \param auto_max_extent The maximum extent of the loop we can unroll,
Siju committed
241
 *                     this is an legacy option that do not take the loop total steps into account.
242
 * \param explicit_unroll Whether explicitly unroll the loop, or leave unroll annotation to codegen.
243
 * \return Transformed stmt.
244
 */
245 246
Stmt UnrollLoop(Stmt stmt,
                int auto_max_step,
247
                int auto_max_depth,
248 249
                int auto_max_extent,
                bool explicit_unroll);
250 251

/*!
252 253
 * \brief vectorize the constant loops
 * \param stmt The statment to be vectorized.
254
 * \return Transformed stmt.
255 256 257 258
 */
Stmt VectorizeLoop(Stmt stmt);

/*!
259 260 261 262 263 264 265
* \brief instruments bound checkers.
* \param stmt The statment to be instrumented.
* \return Instrumented Stmt.
*/
Stmt InstrumentBoundCheckers(Stmt stmt);

/*!
266 267 268 269 270 271 272
 * \brief Inject virtual thread loops into stmt.
 * \param stmt The statment to be transformed.
 * \return Transformed stmt.
 */
Stmt InjectVirtualThread(Stmt stmt);

/*!
273 274 275 276 277 278 279
 * \brief Inject prefetch instructions into stmt.
 * \param stmt The statment to be transformed.
 * \return Transformed stmt.
 */
Stmt InjectPrefetch(Stmt stmt);

/*!
280 281
 * \brief Inject double buffer into stmt.
 * \param stmt The statment to be transformed.
282
 * \param split_loop Loop splitting factor.
283 284
 * \return Transformed stmt.
 */
285
Stmt InjectDoubleBuffer(Stmt stmt, int split_loop);
286 287

/*!
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
 * \brief Inject copy intrinsics with optional pad.
 *
 * \param stmt The statment to be transformed.
 * \param pragma_key The pragma key for hint of copy.
 * \param fintrin The function with signature
 *
 *   Stmt fintrin(Buffer src,
 *                Buffer dst,
 *                Array<Expr> pad_before,
 *                Array<Expr> pad_after,
 *                Expr pad_value)
 * \return Transformed stmt.
 */
Stmt InjectCopyIntrin(Stmt stmt,
                      const std::string& pragma_key,
                      const runtime::PackedFunc& fintrin);

/*!
306 307 308 309
 * \brief Rewrite storage allocation pattern.
 *  Moves the allocation to outer most possible scope.
 *  Trying to share space between allocations to make
 *  a static allocation plan when possible.
310 311 312 313
 *
 * \param stmt The stmt to be trasnformed
 * \return Transformed stmt.
 */
314
Stmt StorageRewrite(Stmt stmt);
315 316

/*!
317 318
 * \brief partition loops in the stmt
 * \param stmt The stmt to do loop partition
319
 * \param split_const_loop flag to enable partition for const loop
320 321
 * \return Transformed stmt.
 */
322
Stmt LoopPartition(Stmt stmt, bool split_const_loop);
323 324

/*!
325 326 327 328 329 330 331 332
 * \brief Detect and insert sync points to co-processor.
 *
 * \param stmt The stmt to be trasnformed
 * \return Transformed stmt.
 */
Stmt CoProcSync(Stmt stmt);

/*!
333 334 335 336 337 338 339 340 341
 * \brief Lift common attrs with attr_key to outer scope.
 *
 * \param stmt The stmt to be trasnformed
 * \param attr_key The attribute key to be checked.
 * \return Transformed stmt.
 */
Stmt LiftAttrScope(Stmt stmt, std::string attr_key);

/*!
342 343 344 345 346 347 348
 * \brief Detect and rewrite unsafe select that contains memory access.
 * \param stmt The statment to be rewritten.
 * \return Transformed stmt.
 */
Stmt RewriteUnsafeSelect(Stmt stmt);

/*!
349 350 351 352 353 354 355 356 357
 * \brief Lower attached storage access information.
 * Do this pass after all storage access analysis finish.
 *
 * \param stmt The stmt to be trasnformed
 * \return Transformed stmt.
 */
Stmt LowerStorageAccessInfo(Stmt stmt);

/*!
358
 * \brief Decorate the stmt with a device scope, this is helpful for
359 360 361 362 363 364 365 366
 * hardware accelerator without thread blocks.
 *
 * \param stmt The stmt to be trasnformed
 * \return Transformed stmt.
 */
Stmt DecorateDeviceScope(Stmt stmt);

/*!
367 368 369 370 371 372 373 374 375
 * \brief Make an user callable API LoweredFunc.
 *
 *  The main task of this function is to create code to :
 *   - Map the values in the api_args to of Var that is required by body.
 *   - Insert assertions to check type/value of the passed arguments.
 *
 * \param body The body of the function.
 * \param name The name of the function.
 * \param api_args Arguments to the function, can be either Var, or Buffer
376 377
 * \param num_unpacked_args Number of arguments that
 *         are processed in plain form instead of packed form.
378 379 380
 * \param is_restricted Whether the caller can guarantee that each buffer argument do not overlap.
 *  It is recommended to set to true for optimized code if such invariant holds.
 *
381 382 383 384 385
 * \return a LoweredFunc with the specified signiture.
 *
 * \note
 *  The function signiture have two cases
 *
386 387
 *  let num_packed_args = len(api_args) - num_unpacked_args;
 *
388 389 390 391 392 393 394 395 396 397 398 399 400 401
 *  if num_packed_args is zero:
 *     f(api_arg_0, api_arg_1, .., api_arg_n) where n == len(api_args)
 *
 *  if num_packed_args is not zero:
 *       f(TVMArg* packed_args, int* packed_arg_type_ids, int num_packed_args,
 *         api_arg_k, api_arg_k+1, ... api_arg_n)
 *
 *       where n == len(api_args), k == num_packed_args
 *
 *  There is no thread_axis in generated function.
 */
LoweredFunc MakeAPI(Stmt body,
                    std::string name,
                    Array<NodeRef> api_args,
402 403
                    int num_unpacked_args,
                    bool is_restricted);
404 405

/*!
406 407 408 409 410 411 412 413
 * \brief Bind the device type of host function to be device_type.
 * \param func The function to be binded.
 * \param device_type The device type to be binded.
 * \return The binded function.
 */
LoweredFunc BindDeviceType(LoweredFunc func,
                           int device_type);
/*!
414 415 416 417
 * \brief Find undefined vars in the statment.
 * \param stmt The function to be checked.
 * \param defs The vars that is defined.
 * \return Array of undefined vars.
418
 */
419
Array<Var> UndefinedVars(const Stmt& stmt, const Array<Var>& defs);
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

/*!
 * \brief Split the function into a host function and device functions.
 * \param func The function to be splitted.
 *
 * \return Array of functions, the first one is host function,
 *     the others are device functions.
 */
Array<LoweredFunc> SplitHostDevice(LoweredFunc func);

/*!
 * \brief Insert sync between parallel read/write of shared buffers.
 *
 * \param stmt The stmt to be trasnformed.
 * \param storage_scope The storage scope considered.
 */
436
LoweredFunc ThreadSync(LoweredFunc stmt, std::string storage_scope);
437

438 439 440 441 442 443 444
/*!
 * \brief Lower cross thread alleduce in the stmt.
 * \param f The device function to be lowered.
 * \param warp_size the size of warp where no sync is needed.
 * \return Transformed function.
 */
LoweredFunc LowerThreadAllreduce(LoweredFunc f, int warp_size);
445 446

/*!
447 448 449 450 451 452 453 454 455
 * \brief Lower warp memory in stmt.
 * \param f The device function to be lowered.
 * \param warp_size the size of warp where no sync is needed.
 *        this function will only take in effect if warp_size is bigger than one.
 * \return Transformed function.
 */
LoweredFunc LowerWarpMemory(LoweredFunc f, int warp_size);

/*!
456 457 458 459 460 461 462 463 464 465 466 467 468 469
 * \brief Remap the thread axis
 *
 *  This can be used to get equivalent program which uses
 *  threadIdx.y in place of threadIdx.x by passing
 *  {"threadIdx.x": thread_axis("threadIdx.y")}
 *
 *
 * \param f The device function to be lowered.
 * \param axis_map The map from StringImm -> ItrVar
 * \return Transformed function.
 */
LoweredFunc RemapThreadAxis(LoweredFunc f, Map<Expr, IterVar> axis_map);

/*!
470 471 472 473
 * \brief Lower packed function call.
 * \param f The function to be lowered.
 * \return Transformed function.
 */
474
LoweredFunc LowerTVMBuiltin(LoweredFunc f);
475 476

/*!
477 478 479 480 481 482 483
 * \brief Combine context function calls.
 * \param f The host function to be lowered.
 * \return Transformed function.
 */
LoweredFunc CombineContextCall(LoweredFunc f);

/*!
484 485 486 487 488 489 490 491 492 493 494 495
 * \brief Rewrite the pointer content type of arguments,
 *  as well as Alloc internal to the function to use
 *  the most frequently accessed type for load/store
 *  to avoid pointer casting in backend when possible.
 *
 * \note implemeneted in storage_rewrite.cc
 * \param f The function to be trasnformed
 * \return Transformed function.
 */
LoweredFunc PointerValueTypeRewrite(LoweredFunc f);

/*!
496 497 498 499 500 501
 * \brief Lower intrinsic function calls.
 * \param f The device function to be lowered.
 * \param target The target device.
 * \return Transformed function.
 */
LoweredFunc LowerIntrin(LoweredFunc f, const std::string& target);
502 503 504 505 506 507 508 509 510 511 512 513 514 515

/*!
 * \brief Verify if memory accesses are legal for a specific target device type.
 *
 *  In the case that tgt is cuda, if not all workload is bound with
 *  threads, CPU code is generated that tries to access GPU memory,
 *  which is illegal. This pass performs verification for this case.
 *
 * \param func The function to be verified.
 * \param device_type The target device type.
 * \return Success of memory verification.
 */
bool VerifyMemory(LoweredFunc func, int device_type);

516 517 518 519 520 521 522 523 524 525 526

/*!
 * \brief Verify the correctness of a GPU code
 *        It will check the whether the amount of memory usage or the number of threads
 *        in a block exceeds the limit
 * \param stmt The statement to be checked
 * \param constraints The dict to specify constraints to check.
 *        Possible keys are
 *
 *        "max_local_memory_per_block": Total amount of local memory per block (in bytes).
 *        "max_shared_memory_per_block": Total amount of shared memory per block (in bytes).
527
 *        "max_threads_per_block": Maximum number of threads per block.
528 529 530 531 532 533 534 535 536 537 538 539
 *        "max_thread_x": Maximum length of threadIdx.x.
 *        "max_thread_y": Maximum length of threadIdx.y.
 *        "max_thread_z": Maximum length of threadIdx.z.
 *
 *        If one key is missing in this argument, the pass won't check for that item.
 * \return valid Whether it is a valid GPU code
 *
 */
bool VerifyGPUCode(Stmt stmt,
                   Map<std::string, Expr> constraints);


tqchen committed
540 541 542 543
}  // namespace ir
}  // namespace tvm

#endif  // TVM_IR_PASS_H_