inject_pipeline.cc 53.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * 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 inject_software_pipeline.cc
22
23
 * \brief Transform annotated loops into pipelined one that parallelize
 * producers and consumers
24
 */
25
#include <tvm/ffi/reflection/registry.h>
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <tvm/target/target.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/transform.h>

#include <unordered_set>

#include "support/utils.h"
#include "tir/schedule/utils.h"
#include "tir/transforms/ir_utils.h"

namespace tvm {
namespace tl {
using namespace tir;

40
41
namespace software_pipeline {

42
43
44
/*!
 * \brief Create a block and infer the access region with the given body.
 *
45
46
47
 * The result is a opaque block that doesn't contain any block iter vars. In
 * case the body is a block realize without predicate, it is unnecessary to
 * create a new block, the block of the block realize will be returned.
48
49
50
51
52
 *
 * \param body The body of the block.
 * \param buffer_data_to_buffer The map from buffer data to buffer.
 * \return The result block.
 */
53
54
55
Block MakeBlock(const Stmt &body,
                const Map<Var, Buffer> &buffer_data_to_buffer) {
  if (const BlockRealizeNode *block_realize = body.as<BlockRealizeNode>()) {
56
57
58
59
60
    if (is_one(block_realize->predicate)) {
      // no need to create a new block
      return block_realize->block;
    }
  }
61
62
63
64
65
  Block block(/*iter_vars=*/{}, /*reads=*/{}, /*writes=*/{}, /*name_hint=*/"",
              /*body*/ body);
  Array<Array<BufferRegion>> access =
      GetBlockReadWriteRegion(block, buffer_data_to_buffer);
  BlockNode *n = block.CopyOnWrite();
66
67
68
69
70
71
72
73
74
75
76
77
  n->reads = access[0];
  n->writes = access[1];
  return block;
}

/*! Structure that represents the provided annotation per block or loop. */
struct PipelineAnnotation {
  int stage;
  int order;
  bool async;
};

78
79
using PipelineInfo = std::unordered_map<Block, PipelineAnnotation,
                                        ObjectPtrHash, ObjectPtrEqual>;
80
81

struct BufferAccessInfo {
82
83
  int def = -1; // the defining stage of the buffer
  int use = -1; // the last using stage of the buffer
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
class PipelineOpaqueAccessRewriter {
public:
  /*!
   * \brief Constructor
   * \param buffer_data_to_buffer The map from buffer data to buffer.
   * \param buffer_remap The map from original buffer to the buffer with updated
   * shape for multi-versioning in the software pipeline. \param pipeline_loop
   * The original loop to be software pipelined. \param fragment_info
   * Information about tensor core fragment
   */
  PipelineOpaqueAccessRewriter(
      const Map<Var, Buffer> &buffer_data_to_buffer,
      const Map<Buffer, Buffer> &buffer_remap, const For &pipeline_loop,
      const std::unordered_map<const VarNode *, FragmentInfo> &fragment_info)
      : buffer_data_to_buffer_(buffer_data_to_buffer),
        buffer_remap_(buffer_remap), pipeline_loop_(pipeline_loop),
        fragment_info_(fragment_info) {}

  PrimExpr Rewrite(const Call &call) {
    // Intrinsic calls should be handled explicitly here as they are opaque
    // accesses to buffer.
    static const auto &load_matrix_sync = builtin::tvm_load_matrix_sync();
    static const auto &store_matrix_sync = builtin::tvm_store_matrix_sync();
    static const auto &mma_sync = builtin::tvm_mma_sync();
    static const auto &access_ptr = builtin::tvm_access_ptr();
    static const auto &ptx_ldmatrix = builtin::ptx_ldmatrix();
    static const auto &ptx_mma = builtin::ptx_mma();
    if (call->op.same_as(load_matrix_sync) ||
        call->op.same_as(store_matrix_sync)) {
      const Buffer &buffer =
          buffer_data_to_buffer_.at(Downcast<Var>(call->args[0]));
      auto it = buffer_remap_.find(buffer);
      if (it != buffer_remap_.end()) {
        Array<PrimExpr> new_args = call->args;
        const Buffer &new_buffer = (*it).second;
        new_args.Set(
            4, RewriteWmmaFragmentIndex(buffer, new_buffer, call->args[4]));
        return Call(call->dtype, call->op, new_args, call->span);
      }
    } else if (call->op.same_as(mma_sync)) {
      Array<PrimExpr> new_args = call->args;
      for (int i = 0; i < 4; i++) {
        const Var &buffer_var = Downcast<Var>(call->args[i * 2]);
        const PrimExpr &index = call->args[i * 2 + 1];
        const Buffer &buffer = buffer_data_to_buffer_.at(buffer_var);
        auto it = buffer_remap_.find(buffer);
        if (it != buffer_remap_.end()) {
          PrimExpr new_index =
              RewriteWmmaFragmentIndex(buffer, (*it).second, index);
          new_args.Set(i * 2 + 1, new_index);
        }
      }
      return Call(call->dtype, call->op, new_args, call->span);
    } else if (call->op.same_as(access_ptr)) {
      return RewriteBufferAccess(call, {1});
    } else if (call->op.same_as(ptx_mma)) {
      return RewriteBufferAccess(call, {6, 8, 10});
    } else if (call->op.same_as(ptx_ldmatrix)) {
      return RewriteBufferAccess(call, {3});
145
    }
146
147
148
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    return call;
  }

private:
  int GetWmmaFragmentSize(const Buffer &buffer) {
    auto it = fragment_info_.find(buffer->data.get());
    ICHECK(it != fragment_info_.end());
    const FragmentInfo &info = (*it).second;
    return info.GetSize();
  }

  PrimExpr RewriteWmmaFragmentIndex(const Buffer &old_buffer,
                                    const Buffer &new_buffer,
                                    const PrimExpr &old_index) {
    PrimExpr new_buffer_offset = old_index;

    int fragment_size = GetWmmaFragmentSize(old_buffer);
    PrimExpr offset = floordiv(
        foldl([](PrimExpr a, PrimExpr b, Span span) { return mul(a, b, span); },
              make_const(DataType::Int(32), 1), old_buffer->shape),
        fragment_size);
    new_buffer_offset +=
        floormod(pipeline_loop_->loop_var - pipeline_loop_->min,
                 new_buffer->shape[0]) *
        offset;
    return new_buffer_offset;
  }

  PrimExpr RewriteBufferAccess(const Call &call,
                               const std::vector<int> arg_indices) {
    auto product = [](const Array<PrimExpr> &input) {
      return foldl(
          [](PrimExpr a, PrimExpr b, Span span) { return mul(a, b, span); },
          make_const(DataType::Int(32), 1), input);
    };
    Array<PrimExpr> new_args = call->args;
    for (int i : arg_indices) {
      const Buffer &buffer =
          buffer_data_to_buffer_.at(Downcast<Var>(call->args[i]));
      auto it = buffer_remap_.find(buffer);
      if (it != buffer_remap_.end()) {
        const Buffer &new_buffer = (*it).second;
        const PrimExpr &old_index = call->args[i + 1];
        PrimExpr offset;
        if (new_buffer->strides.empty()) {
          offset = product(buffer->shape);
        } else {
          offset = new_buffer->strides[0];
        }
        if (buffer.scope() == "m16n8k8.matrixA" ||
            buffer.scope() == "m16n8k8.matrixB") {
          // mma scope size will shrink by warp size
          // @see transform_mma_buffer_layout
          ICHECK_EQ(Downcast<IntImm>(floormod(offset, 32))->value, 0)
              << "mma scope size should be multiple of warp size";
          offset = floordiv(offset, 32);
        }
        PrimExpr new_index =
            old_index +
            floormod(pipeline_loop_->loop_var, new_buffer->shape[0]) * offset;
        new_args.Set(i + 1, new_index);
      }
    }
    return Call(call->dtype, call->op, new_args, call->span);
210
  }
211
212
213
214
215
216

  const Map<Var, Buffer> &buffer_data_to_buffer_;
  const Map<Buffer, Buffer> &buffer_remap_;
  const For &pipeline_loop_;
  const std::unordered_map<const VarNode *, FragmentInfo> &fragment_info_;
};
217

218
/*!
219
220
221
 * \brief Rewriter for the body of the software pipeline. This pass inserts
 * `floormod` to indices of the remapped buffer to select the version
 * corresponding to the pipeline stage.
222
223
 */
class PipelineBodyRewriter : public StmtExprMutator {
224
public:
225
226
227
  /*!
   * \brief Constructor of PipelineBodyRewriter.
   * \param buffer_data_to_buffer The map from buffer data to buffer.
228
229
230
231
232
233
   * \param buffer_remap The map from original buffer to the buffer with updated
   * shape for multi-versioning in the software pipeline. \param pipeline_loop
   * The original loop to be software pipelined. \param access_all_versions
   * Whether all versions the buffers in the software pipeline are accessed.
   * This will be used to update block access region. In the prologue and
   * epilogue of a two-stage software pipeline, only one version of these
234
235
   * buffers are accessed. \param fragment_info Information about tensor core
   * fragment
236
   */
237
238
239
240
241
  PipelineBodyRewriter(
      const Map<Var, Buffer> &buffer_data_to_buffer,
      const Map<Buffer, Buffer> &buffer_remap, For pipeline_loop,
      bool access_all_versions,
      const std::unordered_map<const VarNode *, FragmentInfo> &fragment_info)
242
      : buffer_data_to_buffer_(buffer_data_to_buffer),
243
        buffer_remap_(buffer_remap), pipeline_loop_(pipeline_loop),
244
245
246
        access_all_versions_(access_all_versions),
        opaque_access_rewriter_(buffer_data_to_buffer_, buffer_remap_,
                                pipeline_loop_, fragment_info) {}
247

248
249
250
private:
  BufferRegion
  RewritePipelineBufferRegion(const BufferRegion &buffer_region) const {
251
252
253
    auto it = buffer_remap_.find(buffer_region->buffer);
    if (it != buffer_remap_.end()) {
      Region new_region = buffer_region->region;
254
255
256
      const Buffer &new_buffer = (*it).second;
      // For pipeline buffers, relax the access region of the first dimension to
      // full extent if access_all_versions == true
257
258
259
      Range accessed_version =
          access_all_versions_
              ? Range::FromMinExtent(0, new_buffer->shape[0])
260
261
262
263
              : Range::FromMinExtent(
                    floormod((pipeline_loop_->loop_var - pipeline_loop_->min),
                             new_buffer->shape[0]),
                    Integer(1));
264
265
266
267
268
269
      new_region.insert(new_region.begin(), accessed_version);
      return BufferRegion(new_buffer, new_region);
    }
    return buffer_region;
  }

270
271
  Stmt VisitStmt_(const BlockNode *op) final {
    for (const Buffer &alloc_buffer : op->alloc_buffers) {
272
273
274
      buffer_data_to_buffer_.Set(alloc_buffer->data, alloc_buffer);
    }
    Block block = Downcast<Block>(StmtExprMutator::VisitStmt_(op));
275
276
    BlockNode *n = block.CopyOnWrite();
    n->reads.MutateByApply([this](const BufferRegion &buffer_region) {
277
278
      return RewritePipelineBufferRegion(buffer_region);
    });
279
    n->writes.MutateByApply([this](const BufferRegion &buffer_region) {
280
281
      return RewritePipelineBufferRegion(buffer_region);
    });
282
    for (const Buffer &alloc_buffer : op->alloc_buffers) {
283
284
      buffer_data_to_buffer_.erase(alloc_buffer->data);
    }
285
    return block;
286
287
  }

288
  Stmt VisitStmt_(const BufferStoreNode *op) final {
289
290
291
    BufferStore store = Downcast<BufferStore>(StmtExprMutator::VisitStmt_(op));
    auto it = buffer_remap_.find(store->buffer);
    if (it == buffer_remap_.end()) {
292
      return store;
293
    }
294
295
    const Buffer &new_buffer = (*it).second;
    auto *n = store.CopyOnWrite();
296
    n->buffer = new_buffer;
297
298
    PrimExpr version = floormod(
        (pipeline_loop_->loop_var - pipeline_loop_->min), new_buffer->shape[0]);
299
    n->indices.insert(n->indices.begin(), version);
300
    return store;
301
302
  }

303
  PrimExpr VisitExpr_(const BufferLoadNode *op) final {
304
305
306
    BufferLoad load = Downcast<BufferLoad>(StmtExprMutator::VisitExpr_(op));
    auto it = buffer_remap_.find(load->buffer);
    if (it == buffer_remap_.end()) {
307
      return load;
308
    }
309
310
    const Buffer &new_buffer = (*it).second;
    auto *n = load.CopyOnWrite();
311
    n->buffer = new_buffer;
312
313
    PrimExpr version = floormod(
        (pipeline_loop_->loop_var - pipeline_loop_->min), new_buffer->shape[0]);
314
    n->indices.insert(n->indices.begin(), version);
315
    return load;
316
317
  }

318
  PrimExpr VisitExpr_(const CallNode *op) final {
319
    Call call = Downcast<Call>(StmtExprMutator::VisitExpr_(op));
320
    return opaque_access_rewriter_.Rewrite(call);
321
322
323
324
325
326
  }

  Map<Var, Buffer> buffer_data_to_buffer_;
  Map<Buffer, Buffer> buffer_remap_;
  For pipeline_loop_;
  bool access_all_versions_;
327
  PipelineOpaqueAccessRewriter opaque_access_rewriter_;
328
329
330
};

/*!
331
332
 * \brief Rewriter for the software pipeline that rewrite a loop into a
 * pipelined one.
333
334
 */
class PipelineRewriter : public StmtExprMutator {
335
public:
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
  static Stmt Rewrite(
      Map<Var, Buffer> buffer_data_to_buffer,
      const std::unordered_set<Buffer, ObjectPtrHash, ObjectPtrEqual>
          &double_buffers,
      const Array<Buffer> pipeline_allocs, const For &pipeline_loop,
      const PipelineInfo &pipeline_info,
      const std::unordered_map<const VarNode *, FragmentInfo> &fragment_info,
      const Map<String, ffi::Any> preserved_annotations) {
    PipelineRewriter rewriter(buffer_data_to_buffer, double_buffers,
                              pipeline_allocs, pipeline_loop, pipeline_info,
                              fragment_info, preserved_annotations);
    return rewriter.BuildPipeline();
  }

private:
  PipelineRewriter(
      Map<Var, Buffer> buffer_data_to_buffer,
      const std::unordered_set<Buffer, ObjectPtrHash, ObjectPtrEqual>
          &double_buffers,
      const Array<Buffer> &pipeline_allocs, const For &pipeline_loop,
      const PipelineInfo &pipeline_info,
      const std::unordered_map<const VarNode *, FragmentInfo> &fragment_info,
      const Map<String, ffi::Any> preserved_annotations)

360
      : buffer_data_to_buffer_(std::move(buffer_data_to_buffer)),
361
362
363
364
        double_buffers_(double_buffers), pipeline_allocs_(pipeline_allocs),
        pipeline_loop_(pipeline_loop), pipeline_info_(pipeline_info),
        fragment_info_(fragment_info),
        preserved_annotations_(preserved_annotations) {}
365
366

  Stmt BuildPipeline() {
367
368
369
370
371
    // Step 1: Analyze accesses to the buffers in the pipeline and compute the
    // number of versions need to maintain for each buffer.
    std::unordered_map<Buffer, BufferAccessInfo, ObjectPtrHash, ObjectPtrEqual>
        infos = GetBufferAccessInfo();
    for (const Buffer &buffer : pipeline_allocs_) {
372
373
374
375
376
377
378
      int num_versions = ComputeBufferVersions(buffer, infos.at(buffer));
      if (num_versions > 1) {
        buffer_remap_.Set(buffer, RewriteAllocBuffer(buffer, num_versions));
      }
    }

    ordered_stmts_.resize(pipeline_info_.size());
379
380
381
382
    for (const auto &pair : pipeline_info_) {
      const Block &block = pair.first;
      int order = pair.second.order;
      ordered_stmts_.Set(order, block);
383
384
    }

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
    // Step 2: Emit the pipeline prologue, body and epilogue.
    Stmt prologue =
        EmitImpl(pipeline_loop_->min, pipeline_loop_->min + max_stage_, true);
    Stmt body = EmitImpl(pipeline_loop_->min + max_stage_,
                         pipeline_loop_->min + pipeline_loop_->extent, false);
    // introduce extra lowerbound when the loop length is smaller than num
    // stages to ensure the epilogue interval do not overlap the prologue
    // interval.
    PrimExpr epigogue_start = pipeline_loop_->min + pipeline_loop_->extent;
    Optional<PrimExpr> extra_epilogue_lower_bound = std::nullopt;
    if (max_stage_ > 1 &&
        !analyzer_.CanProveGreaterEqual(pipeline_loop_->extent, max_stage_)) {
      if (is_const_int(epigogue_start)) {
        epigogue_start = max(epigogue_start, pipeline_loop_->min + max_stage_);
      } else {
        // for dynamic case, introduce extra lowerbound as loop predicate
        // to ensure the epilogue part unrollable.
        extra_epilogue_lower_bound = pipeline_loop_->min + max_stage_;
403
404
      }
    }
405
406
407
408
    Stmt epilogue =
        EmitImpl(epigogue_start,
                 pipeline_loop_->min + pipeline_loop_->extent + max_stage_,
                 true, extra_epilogue_lower_bound);
409
410
411

    SeqStmt stmt = SeqStmt({prologue, body, epilogue});

412
413
    // Step 3: Make a new block that contains new buffer allocations after
    // pipeline rewriting.
414
    Array<Buffer> alloc_buffers;
415
    for (const auto &alloc : pipeline_allocs_) {
416
417
418
419
420
421
422
423
      alloc_buffers.push_back(buffer_remap_.Get(alloc).value_or(alloc));
      buffer_data_to_buffer_.erase(alloc->data);
    }
    Block block = MakeBlock(stmt, buffer_data_to_buffer_);
    block.CopyOnWrite()->alloc_buffers = std::move(alloc_buffers);
    return BlockRealize({}, Bool(true), block);
  }

424
private:
425
426
427
  /*!
   * \brief Analyze accesses to the buffers in the software pipeline.
   *
428
429
430
   * This method check the 'define' and 'use' stage of the buffers in the
   * software pipeline, which can be used to compute the number of versions
   * needed to maintain after rewriting.
431
432
433
   */
  std::unordered_map<Buffer, BufferAccessInfo, ObjectPtrHash, ObjectPtrEqual>
  GetBufferAccessInfo() {
434
435
436
437
    std::unordered_map<Buffer, BufferAccessInfo, ObjectPtrHash, ObjectPtrEqual>
        infos;
    for (const auto &pair : pipeline_info_) {
      const Block &block = pair.first;
438
439
440
      int stage = pair.second.stage;
      max_stage_ = std::max(max_stage_, stage);

441
      for (const BufferRegion &write : block->writes) {
442
443
444
        if (!infos.count(write->buffer)) {
          infos.emplace(write->buffer, BufferAccessInfo{});
        }
445
        auto &info = infos.at(write->buffer);
446
447
448
449
450
451
452
        if (info.def == -1) {
          info.def = stage;
        } else {
          info.def = std::min(info.def, stage);
        }
      }

453
      for (const BufferRegion &read : block->reads) {
454
455
456
        if (!infos.count(read->buffer)) {
          infos.emplace(read->buffer, BufferAccessInfo{});
        }
457
        auto &info = infos.at(read->buffer);
458
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
        info.use = std::max(info.use, stage);
      }
    }
    return infos;
  }

  /*!
   * \brief Check whether two regions have intersections.
   * \param region1 The first region.
   * \param region2 The second region.
   * \return Whether region1 and region2 have intersections.
   */
  bool MayConflict(Region region1, Region region2) {
    ICHECK(region1.size() == region2.size());
    for (size_t i = 0; i < region1.size(); i++) {
      Range dim1 = region1[i];
      Range dim2 = region2[i];
      auto int_set1 = arith::IntSet::FromRange(dim1);
      auto int_set2 = arith::IntSet::FromRange(dim2);
      if (arith::Intersect({int_set1, int_set2}).IsNothing()) {
        return false;
      }
    }
    return true;
  }

  /*!
485
486
   * \brief Compute the number of versions need to maintain for buffer accessed
   * in the software pipeline.
487
   *
488
489
490
491
492
493
   * This method applies liveness analysis to the target buffer to compute the
   * number of versions need to maintain during the software pipeline.
   * Annotation `attr::double_buffer_scope` is handled here which provides a way
   * to override the result of the analysis. Additional double buffering in the
   * software pipeline can be useful to eliminate synchronizations in GPU
   * devices.
494
495
496
497
498
   *
   * \param buffer The target buffer
   * \param buffer_info The access information of the target buffer.
   * \return The number of versions required for the target buffer.
   */
499
500
  int ComputeBufferVersions(const Buffer &buffer,
                            const BufferAccessInfo &buffer_info) {
501
    if (buffer_info.def == -1) {
502
503
      // Keep the original number of versions as buffers defined outside the
      // software pipeline should not be mutated.
504
505
506
507
      return 1;
    }

    // `use - def + 1` is a upper bound of the needed versions
508
509
    // We optimize a few case where the number of versions can be smaller than
    // the upper bound
510
    int num_versions = buffer_info.use - buffer_info.def + 1;
511
    if (num_versions == 2) {
512
513
514
515
      // A special case when `use - def + 1 == 2`. Double buffering is only
      // needed in this case when these exists a reader block_i and a writer
      // block_j such that order(block_i) < order(block_j) and stage(block_i) <
      // stage(block_j) and the access regions of block_i and block_j overlap.
516
      bool need_multi_version = false;
517
518
519
      for (const auto &pair1 : pipeline_info_) {
        const Block &writer_block = pair1.first;
        const auto &writer_info = pair1.second;
520

521
522
523
        auto it1 = std::find_if(writer_block->writes.begin(),
                                writer_block->writes.end(),
                                [&](const BufferRegion &buffer_region) {
524
525
526
527
528
529
                                  return buffer_region->buffer.same_as(buffer);
                                });
        if (it1 == writer_block->writes.end()) {
          continue;
        }

530
531
532
533
534
535
536
537
        for (const auto &pair2 : pipeline_info_) {
          const Block &reader_block = pair2.first;
          const auto &reader_info = pair2.second;
          auto it2 = std::find_if(
              reader_block->reads.begin(), reader_block->reads.end(),
              [&](const BufferRegion &buffer_region) {
                return buffer_region->buffer.same_as(buffer);
              });
538
539
540
          if (it2 == reader_block->reads.end()) {
            continue;
          }
541
542
          if (writer_info.order < reader_info.order &&
              writer_info.stage < reader_info.stage &&
543
544
545
546
547
548
549
              MayConflict((*it1)->region, (*it2)->region)) {
            need_multi_version = true;
            break;
          }
        }
      }
      if (!need_multi_version) {
550
        num_versions = 1;
551
552
      }
    }
553
554
555
    if (num_versions == 1 && double_buffers_.count(buffer)) {
      num_versions = 2;
    }
556
557
558
559
    return num_versions;
  }

  /*!
560
561
   * \brief Rewrite buffer allocation to keep multiple versions of original
   * buffer for pipelined accesses. \param buffer The buffer to be resized.
562
563
564
   * \param num_versions The number of versions to keep.
   * \return The resized buffer.
   */
565
  Buffer RewriteAllocBuffer(const Buffer &buffer, int num_versions) {
566
567
568
569
570
571
572
573
574
575
    ObjectPtr<BufferNode> new_buffer = make_object<BufferNode>(*(buffer.get()));
    new_buffer->shape.insert(new_buffer->shape.begin(), PrimExpr(num_versions));
    if (new_buffer->strides.size()) {
      ICHECK(new_buffer->strides.size() + 1 == new_buffer->shape.size());
      PrimExpr stride_0 = new_buffer->strides[0] * new_buffer->shape[1];
      new_buffer->strides.insert(new_buffer->strides.begin(), stride_0);
    }
    return Buffer(new_buffer);
  }

576
577
  // Per-stage states that need to be tracked across pipeline prologue, body,
  // and epilogue.
578
579
  struct AsyncStateGlobal {
    // Buffers that this stage asynchronously writes.
580
581
582
583
584
585
586
    std::unordered_set<const BufferNode *> dst_buffers;
    // An imaginary index that the latest async operation associated with this
    // stage has written into. Only valid if all associated predicates are true,
    // so that we can count the number of async invocations exactly. When it is
    // valid, it is the "sum of extents of loops that have been executed" - 1,
    // e.g. for epilogue it is prologue extent + body extent - 1. This is only
    // needed to compute wait count for epilogue without async producers.
587
588
    Optional<PrimExpr> producer_head{PrimExpr(-1)};

589
590
591
    bool writes(Buffer buf) const { return dst_buffers.count(buf.get()) > 0; }
  };

592
593
  // Per-stage states that are local to each of pipeline prologue, body, and
  // epilogue.
594
  struct AsyncStateLocal {
595
    struct {
596
597
      // The index into a list of blocks, where async_wait_queue should be
      // attached at the beginning.
598
      int insert_before;
599
600
      // in_flight_count would be a more precise name, but the implementation
      // uses wait_count for brevity.
601
602
603
      PrimExpr wait_count{nullptr};

      bool valid() const { return wait_count.defined(); }
604
605
606
607
608
609
610
611
612
613
614
615
616
617
    } pending_wait;

    // Destination buffers of async operations that have been encountered so far
    // in the loop
    //
    // for (size_t i = 0; i < new_blocks.size(); ++i) {
    //    ...
    // }
    //
    // This is for tracking which async operations have been issued at the
    // "current" iteration, up until a point where we encounter a consumer of
    // async result buffers. This is used to decide if the producer_head of each
    // buffer points to a copy written in the current or previous iteration.
    std::unordered_set<const BufferNode *> seen;
618

619
620
    // A symbolic expression representing the index the latest async operation
    // associated with this stage has written into, at the "current" iteration.
621
    Optional<PrimExpr> producer_head;
622
623
624
625
626
627
628
629
630
631
632
    // The predicate of BlockRealize containing the async operation of this
    // stage.
    Optional<PrimExpr> predicate;
    // Indices into a list of blocks, where async_commit_queue scope should be
    // attached. If multiple async producers are interleaved with their consumer
    // in between, we need separate async_commit_queue for each producer. Thus,
    // we need multiple sets of indices.
    std::vector<std::vector<size_t>> commit_groups;

    // This is set to true when we reach a stage that consumes this async stage.
    bool consumed{false};
633
634
635
636
637
638
639
640
641
642
643
  };

  /*! Structure holding intermediate information for pipeline loop rewriting. */
  struct RewrittenBlockInfo {
    int stage;
    PrimExpr predicate;
    Block block;
    PrimExpr access_index;
    bool is_async;
  };

644
645
646
647
648
649
  // Determine where to insert async_wait and the corresponding wait count.
  void PopulateWaitCounts(
      const std::vector<RewrittenBlockInfo> &new_blocks,
      arith::Analyzer *ana_normalized,
      const std::unordered_map<const BufferNode *, int> &buffer_to_commit_group,
      std::map<int, AsyncStateLocal> *async_states_local) {
650
    for (size_t i = 0; i < new_blocks.size(); ++i) {
651
652
653
654
655
656
657
658
      if (new_blocks[i].is_async) {
        // Record the fact that we have encountered these write buffers.
        for (auto write_region : new_blocks[i].block->writes) {
          (*async_states_local)[new_blocks[i].stage].seen.insert(
              write_region->buffer.get());
        }
      }

659
660
      int producer_stage_idx = -1;
      for (auto read_region : new_blocks[i].block->reads) {
661
662
663
        for (auto kv : async_states) {
          if (kv.first <= new_blocks[i].stage &&
              kv.second.writes(read_region->buffer)) {
664
665
            // Found an earlier stage where read_region->buffer was
            // asynchronously written
666
            ICHECK(producer_stage_idx == -1 || producer_stage_idx == kv.first)
667
                << "A dependency on multiple async stages is not supported";
668
            producer_stage_idx = kv.first;
669
670
671
          }
        }
      }
672

673
674
      if (producer_stage_idx == -1)
        continue;
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719

      // The following logic has become complicated to handle case like this:
      //
      // for i in range(13):
      //     # Stage 0
      //     async_commit_queue(0):
      //        async_scope:
      //           A_shared[(i + 3) % 4] = A[...]
      //
      //
      //     # Stage 1
      //     async_wait_queue(0, 5):
      //        compute(A_shared[i], B_shared[i])
      //
      //     # Stage 0
      //     async_commit_queue(0)
      //        async_scope:
      //           B_shared[(i + 3) % 4] = B[...]
      //
      //
      // Here, multiple async producers in the same stage are interleaved with
      // their consumer in between. Since each buffer is associated with
      // different commit groups, the wait_count before the consumer should be
      // bigger than the simpler case:
      //
      // for i in range(13):
      //     # Stage 0
      //     async_commit_queue(0):
      //        async_scope:
      //           A_shared[(i + 3) % 4] = A[...]
      //           B_shared[(i + 3) % 4] = B[...]
      //
      //     # Stage 1
      //     async_wait_queue(0, 3):
      //        compute(A_shared[i], B_shared[i])
      //
      // The correct wait_count can be determined by considering each commit
      // group separately, and summing "per-commit" wait_counts.
      //
      // From A_shared's perspective, it allows for (i + 3) - i async commit
      // groups to be in flight while from B_shared's perspective, the producer
      // head at compute points to the copy done by the previous iteration, so
      // its wait_count is calculated as ((i - 1) + 3) - i. The sum of the two
      // wait_counts gives 5.

720
      auto &dep_local_state = (*async_states_local)[producer_stage_idx];
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
      const auto num_commit_group = dep_local_state.commit_groups.size();
      std::vector<Optional<PrimExpr>> producer_head_per_commit;

      if (num_commit_group == 0) {
        // Epilogue, no async producer. Since "local" producer_head is not
        // available, use "global" producer_head.
        ICHECK(!dep_local_state.producer_head);
        producer_head_per_commit.push_back(
            async_states[producer_stage_idx].producer_head);
      } else {
        ICHECK(dep_local_state.producer_head);
        std::vector<bool> need_wait_count(num_commit_group, true);

        for (auto read_region : new_blocks[i].block->reads) {
          if (!async_states[producer_stage_idx].writes(read_region->buffer))
            continue;
          auto commit_group_id =
              buffer_to_commit_group.at(read_region->buffer.get());
          if (!need_wait_count[commit_group_id])
            continue;

          if (!dep_local_state.seen.count(read_region->buffer.get())) {
            // Multiple async producers interleaved: The most recent async write
            // is from the previous iteration. This is the B_shared case above.
            producer_head_per_commit.push_back(
                dep_local_state.producer_head.value() - 1);
          } else {
            // Normal case
            producer_head_per_commit.push_back(
                dep_local_state.producer_head.value());
          }

          need_wait_count[commit_group_id] = false;
754
755
756
        }
      }

757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
      auto wait_count = [=, &ana_normalized]() {
        auto sum = PrimExpr(0);
        for (auto producer_head : producer_head_per_commit) {
          if (producer_head &&
              ana_normalized->CanProve(producer_head.value() >= 0)) {
            // Here, new_blocks[i].access_index corresponds to "consumer_head".
            // The difference of producer_head and consumer_head is precisely
            // the number of async commit groups that can still be in flight
            // after this wait.
            sum += analyzer_.Simplify(producer_head.value() -
                                      new_blocks[i].access_index);
          } else {
            // The precise count cannot be determined, give up.
            return PrimExpr(0);
          }
        }
        return sum;
      }();

      auto &pending_wait = dep_local_state.pending_wait;

      if (!pending_wait.valid()) {
        pending_wait = {static_cast<int>(i), wait_count};
      } else if (analyzer_.CanProve(wait_count < pending_wait.wait_count)) {
        // Coalesce multiple wait_queue if the later one allows fewer in-flight
        // ops.
        pending_wait = {pending_wait.insert_before, wait_count};
784
785
786
787
      }
    }
  }

788
789
  // Given pipelined blocks and async-related information, generate final loop
  // statements with async scopes (if any).
790
  Array<Stmt> CompletePipelineLoopStatements(
791
      const std::vector<RewrittenBlockInfo> &blocks,
792
793
      const std::map<int, AsyncStateLocal> &async_states_local,
      arith::Analyzer *ana_normalized) const {
794
    std::vector<RewrittenBlockInfo> new_blocks = blocks;
795
    std::vector<int> commit_group_indices(new_blocks.size(), -1);
796
    for (const auto &[stage_id, state] : async_states_local) {
797
798
799
800
801
802
803
      if (!state.commit_groups.empty()) {
        for (size_t i = 0; i < state.commit_groups.size(); ++i) {
          for (size_t j = 0; j < state.commit_groups[i].size(); ++j) {
            ICHECK(state.commit_groups[i][0] + j < new_blocks.size());
            commit_group_indices[state.commit_groups[i][0] + j] = stage_id;
          }
        }
804
805
      }

806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
      if (state.pending_wait.valid()) {
        auto attach_wait_scope = [&new_blocks](int i, int stage_id,
                                               PrimExpr wait_count) {
          auto &block = new_blocks[i].block;
          BlockNode *n = block.CopyOnWrite();
          auto zero = make_zero(DataType::Int(32));
          n->body =
              AttrStmt(zero, tir::attr::async_wait_queue_scope, stage_id,
                       AttrStmt(zero, tir::attr::async_wait_inflight_count,
                                wait_count, n->body));
        };

        if (state.predicate &&
            !ana_normalized->CanProve(state.predicate.value())) {
          // If the async operation that this wait_queue is waiting on is
          // predicated, and we cannot prove that the predicate is always true,
          // the precise wait count is only valid at iterations where the
          // predicate is true;
          auto wait_count =
              Call(DataType::Int(32), builtin::if_then_else(),
                   {state.predicate.value(), state.pending_wait.wait_count, 0});
          attach_wait_scope(state.pending_wait.insert_before, stage_id,
                            wait_count);
        } else {
          attach_wait_scope(state.pending_wait.insert_before, stage_id,
                            state.pending_wait.wait_count);
        }
833
834
835
836
837
      }
    }

    Array<Stmt> stmts;

838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
    for (size_t i = 0; i < new_blocks.size();) {
      if (commit_group_indices[i] == -1) {
        // A synchrnous block, not part of any commit group
        stmts.push_back(
            BlockRealize({}, new_blocks[i].predicate, new_blocks[i].block));
        ++i;
      } else {
        Array<Stmt> group_bodies;
        auto stage_id = commit_group_indices[i];
        auto predicate = new_blocks[i].predicate;
        for (; i < commit_group_indices.size() &&
               commit_group_indices[i] == stage_id;
             ++i) {
          ICHECK(tvm::StructuralEqual()(predicate, new_blocks[i].predicate))
              << "Predicates in the same stage are expected to be identical";
          group_bodies.push_back(new_blocks[i].block->body);
        }

        if (group_bodies.size() > 1) {
          auto merged_bodies = SeqStmt(group_bodies);
          group_bodies.clear();
          group_bodies.push_back(merged_bodies);
        }

        for (auto body : group_bodies) {
          auto commit_queue_scope =
              AttrStmt(make_zero(DataType::Int(32)),
                       tir::attr::async_commit_queue_scope, stage_id, body);
          auto new_block =
              MakeBlock(commit_queue_scope, buffer_data_to_buffer_);
          stmts.push_back(BlockRealize({}, predicate, new_block));
        }
870
871
872
873
874
875
876
877
878
879
880
      }
    }

    return stmts;
  }

  /*!
   * \brief Emit the pipeline loop in the given range.
   * \param start The start of the range
   * \param end The end of the range
   * \param unroll_loop Whether the loop should be unrolled.
881
   * \param extra_loop_lower_bound Extra loop lower bound.
882
883
   * \return The result loop.
   */
884
  Stmt EmitImpl(PrimExpr start, PrimExpr end, bool unroll_loop,
885
                Optional<PrimExpr> extra_loop_lower_bound = std::nullopt) {
886
887
    PrimExpr new_loop_var;
    PrimExpr extent = end - start;
888

889
890
891
    auto make_nop = []() {
      return BlockRealize({}, Bool(true), MakeBlock(Evaluate(0), {}));
    };
892

893
894
895
    if (analyzer_.CanProve(extent <= 0)) {
      return make_nop();
    }
896
897
    bool is_unit_loop = analyzer_.CanProveEqual(extent, 1);
    if (is_unit_loop) {
898
      new_loop_var = start; // use constants as the loop var for unit loops
899
900
901
902
903
    } else {
      new_loop_var = pipeline_loop_->loop_var.copy_with_suffix("");
      analyzer_.Bind(Downcast<Var>(new_loop_var), Range(start, end));
    }

904
905
906
907
908
909
910
911
    // In contrast to analyzer_ which is bound to [start, end), this one is
    // bound to the "normalized" range, [pipeline_loop_->min, extent).
    arith::Analyzer ana_normalized;
    if (!is_unit_loop) {
      ana_normalized.Bind(Downcast<Var>(new_loop_var),
                          Range(pipeline_loop_->min, extent));
    }

912
913
914
915
    std::vector<RewrittenBlockInfo> new_blocks;

    // Async related
    std::map<int, AsyncStateLocal> async_states_local;
916
    std::unordered_map<const BufferNode *, int> buffer_to_commit_group;
917

918
    for (const Block &block : ordered_stmts_) {
919
920
      int stage = pipeline_info_.at(block).stage;
      PrimExpr skewed_loop_var = new_loop_var - stage;
921
922
923
924
925
926
927
      PrimExpr inbound =
          analyzer_.Simplify(pipeline_loop_->min <= skewed_loop_var) &&
          (skewed_loop_var < pipeline_loop_->min + pipeline_loop_->extent);
      if (extra_loop_lower_bound.defined()) {
        inbound = analyzer_.Simplify(
            inbound && new_loop_var >= extra_loop_lower_bound.value());
      }
928
929
930
      if (analyzer_.CanProve(!inbound)) {
        continue;
      }
931
932
933
      Block new_block = Downcast<Block>(PipelineBodyRewriter(
          buffer_data_to_buffer_, buffer_remap_, pipeline_loop_,
          max_stage_ != 1, fragment_info_)(block));
934
935
936
937

      PrimExpr delta = start - pipeline_loop_->min;
      // This variable corresponds to
      // - "producer_head" if this stage is an async producer
938
939
      // - "consumer_head" if this stage reads from asynchronously written
      // buffers.
940
      PrimExpr normalized_access_index =
941
          is_unit_loop ? skewed_loop_var : skewed_loop_var + delta;
942

943
944
      // Adjust the block predicate and the body according to the final loop
      // bound
945
946
947
948
949
      //  [pipeline_loop_->min, extent).
      if (!is_unit_loop) {
        Var loop_iter = Downcast<Var>(new_loop_var);
        inbound = Substitute(inbound, {{loop_iter, loop_iter + delta}});
      }
950

951
952
      new_block = Downcast<Block>(Substitute(
          new_block, {{pipeline_loop_->loop_var, normalized_access_index}}));
953

954
      if (pipeline_info_[block].async) {
955
        auto &local_state = async_states_local[stage];
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980

        int commit_group_id = -1;
        if (local_state.commit_groups.empty() || local_state.consumed) {
          // consumed == true means there is already a consumer stage waiting
          // for an eariler async operation of this stage. In such cases, we
          // make multiple commit_queue for this stage.
          commit_group_id = local_state.commit_groups.size();
          local_state.commit_groups.push_back({new_blocks.size()});
        } else {
          // This is the case when one commit_queue groups multiple async
          // blocks. with commit_queue(stage):
          //   async_scope:
          //     A_shared[...] = ...
          //   async_scope:
          //     B_shared[...] = ...

          commit_group_id = local_state.commit_groups.size() - 1;
          local_state.commit_groups.back().push_back(new_blocks.size());
        }

        for (auto write_region : new_block->writes) {
          async_states[stage].dst_buffers.insert(write_region->buffer.get());
          buffer_to_commit_group[write_region->buffer.get()] = commit_group_id;
        }

981
        local_state.producer_head = normalized_access_index;
982
983
984
985
986
987
988
989
990

        if (!local_state.predicate ||
            ana_normalized.CanProve(local_state.predicate.value())) {
          local_state.predicate = inbound;
        } else if (local_state.predicate) {
          local_state.predicate =
              ana_normalized.Simplify(local_state.predicate.value() & inbound);
        }

991
992
993
        BlockNode *n = new_block.CopyOnWrite();
        n->body = AttrStmt(make_zero(DataType::Int(32)), tir::attr::async_scope,
                           1, n->body);
994
995
      }

996
      new_blocks.push_back({stage, inbound, new_block, normalized_access_index,
997
                            pipeline_info_[block].async});
998

999
1000
1001
1002
1003
1004
1005
1006
1007
1008
      for (auto read_region : new_block->reads) {
        for (auto kv : async_states) {
          int producer_stage_id = kv.first;
          if (producer_stage_id <= stage &&
              kv.second.writes(read_region->buffer)) {
            async_states_local[producer_stage_id].consumed = true;
          }
        }
      }
    }
1009

1010
1011
1012
1013
    PopulateWaitCounts(new_blocks, &ana_normalized, buffer_to_commit_group,
                       &async_states_local);
    auto stmts = CompletePipelineLoopStatements(new_blocks, async_states_local,
                                                &ana_normalized);
1014

1015
1016
    Stmt new_loop{nullptr};

1017
    if (stmts.empty()) {
1018
1019
      return make_nop();
    }
1020
1021
    if (stmts.size() == 1) {
      new_loop = stmts[0];
1022
    } else {
1023
      new_loop = SeqStmt(stmts);
1024
1025
1026
1027
    }

    if (!is_unit_loop) {
      new_loop = For(Downcast<Var>(new_loop_var), pipeline_loop_->min, extent,
1028
                     unroll_loop ? ForKind::kUnrolled : pipeline_loop_->kind,
1029
                     std::move(new_loop), std::nullopt, preserved_annotations_);
1030
    }
1031

1032
    // Update producer heads in the global async states.
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
    for (const auto &kv : async_states_local) {
      const int stage_id = kv.first;
      const AsyncStateLocal &state = kv.second;

      if (state.predicate && ana_normalized.CanProve(state.predicate.value()) &&
          async_states[stage_id].producer_head) {
        // Advance the "global" producer head if it is still valid and we know
        // exactly how much we can increment
        async_states[stage_id].producer_head =
            async_states[stage_id].producer_head.value() + extent;
      } else {
        // Otherwise, invalidate the global producer head
        async_states[stage_id].producer_head = std::nullopt;
      }
1047
1048
    }

1049
1050
    return BlockRealize({}, Bool(true),
                        MakeBlock(std::move(new_loop), buffer_data_to_buffer_));
1051
1052
1053
1054
  }

  arith::Analyzer analyzer_;
  Map<Var, Buffer> buffer_data_to_buffer_;
1055
1056
  const std::unordered_set<Buffer, ObjectPtrHash, ObjectPtrEqual>
      &double_buffers_;
1057
1058
1059
  Array<Buffer> pipeline_allocs_;
  For pipeline_loop_;
  PipelineInfo pipeline_info_;
1060
  const std::unordered_map<const VarNode *, FragmentInfo> &fragment_info_;
1061
1062
1063
1064
  int max_stage_ = -1;
  Map<Buffer, Buffer> buffer_remap_;
  Array<Block> ordered_stmts_;
  std::map<int, AsyncStateGlobal> async_states;
1065
  Map<String, ffi::Any> preserved_annotations_;
1066
1067
1068
1069
1070
};

/*!
 * \brief Build the dependency graph among a array of blocks.
 * \param[in] blocks The array of blocks.
1071
1072
1073
 * \param[out] dep_src2dst Optional, a map to store dependency edges from the
 * source to the destination. \param[out] dep_dst2src Optional, a map to store
 * dependency edges from the destination to the source.
1074
 */
1075
1076
1077
1078
1079
void BuildDependencyGraph(const Array<Block> &blocks,
                          std::unordered_map<Block, Array<Block>, ObjectPtrHash,
                                             ObjectPtrEqual> *dep_src2dst,
                          std::unordered_map<Block, Array<Block>, ObjectPtrHash,
                                             ObjectPtrEqual> *dep_dst2src) {
1080
  std::unordered_map<Var, Array<Block>> buffer_writers;
1081
1082
1083

  for (const Block &block : blocks) {
    for (const BufferRegion &read : block->reads) {
1084
1085
      auto it = buffer_writers.find(read->buffer->data);
      if (it != buffer_writers.end()) {
1086
        for (const Block &writer : it->second) {
1087
1088
1089
1090
1091
1092
1093
1094
1095
          if (dep_src2dst != nullptr) {
            (*dep_src2dst)[writer].push_back(block);
          }
          if (dep_dst2src != nullptr) {
            (*dep_dst2src)[block].push_back(writer);
          }
        }
      }
    }
1096
    for (const BufferRegion &write : block->writes) {
1097
1098
1099
1100
1101
1102
      buffer_writers[write->buffer->data].push_back(block);
    }
  }
}

class PipelineInjector : private StmtExprMutator {
1103
1104
public:
  static Stmt Inject(const PrimFunc &func) {
1105
1106
    auto global_symbol = func->GetAttr<String>(tvm::attr::kGlobalSymbol);
    PipelineInjector injector(global_symbol);
1107
1108
    for (const auto &kv : func->buffer_map) {
      const Buffer &buffer = kv.second;
1109
1110
      injector.buffer_data_to_buffer_.Set(buffer->data, buffer);
    }
1111
    injector.fragment_info_ = GetTensorCoreFragmentInfo(func->body);
1112
1113
1114
    return injector(func->body);
  }

1115
1116
1117
private:
  explicit PipelineInjector(Optional<String> global_symbol)
      : global_symbol_(global_symbol) {}
1118
1119
1120
1121

  /*!
   * \brief Check the pipeline satisfies the following conditions:
   * 1. No conflicting order: The order of each statement should be unique.
1122
1123
1124
1125
   * 2. Reordering of statements doesn't break buffer access dependencies.
   * Specifically, for dependency (e.g. read-after-write) from statement A to
   * statement B, it requires: case 1: stage(A) < stage(B) case 2: stage(A) ==
   * stage(B) and order(A) < order(B)
1126
   */
1127
1128
  void ValidatePipelineBody(const PipelineInfo &pipeline_info,
                            const Array<Block> &original_order) {
1129
1130
    std::unordered_set<int> used_orders;
    std::unordered_map<int, int> stage_max_order;
1131
1132
1133
1134
    std::unordered_map<int, const Block *> order_to_block;
    std::unordered_map<const Block *, int> block_to_stage;
    for (const Block &block : original_order) {
      const auto &stmt_info = pipeline_info.at(block);
1135
1136
      int order = stmt_info.order;
      CHECK(!used_orders.count(order))
1137
1138
          << "ValueError: Two statements in the software pipeline cannot have "
             "the same order";
1139
1140
1141
      used_orders.insert(order);
    }

1142
1143
    std::unordered_map<Block, Array<Block>, ObjectPtrHash, ObjectPtrEqual>
        dep_src2dst;
1144
1145
    BuildDependencyGraph(original_order, &dep_src2dst, nullptr);

1146
1147
1148
1149
1150
1151
    for (const auto &pair : dep_src2dst) {
      const Block &src = pair.first;
      const auto &src_info = pipeline_info.at(src);
      const Array<Block> &dsts = pair.second;
      for (const Block &dst : dsts) {
        const auto &dst_info = pipeline_info.at(dst);
1152
1153
        CHECK_LE(src_info.stage, dst_info.stage)
            << "ValueError: statement " << dst << " in stage " << dst_info.stage
1154
1155
            << " cannot depends on statement " << src << " in a later stage "
            << src_info.stage;
1156
        if (src_info.stage == dst_info.stage) {
1157
1158
1159
1160
          CHECK_LT(src_info.order, dst_info.order)
              << "ValueError: two statements with buffer "
                 "access dependency in the same stage of the "
                 "software pipeline cannot be reordered";
1161
1162
1163
1164
1165
        }
      }
    }
  }

1166
  Stmt VisitStmt_(const ForNode *op) final {
1167
1168
1169
1170
1171
    // Step 1: Recursively rewrite the children first.
    For for_node = Downcast<For>(StmtExprMutator::VisitStmt_(op));
    if (!HasPipelineAnnotation(op)) {
      return std::move(for_node);
    }
1172
1173
1174
    // Step 2: Find the body and buffer allocations of the pipeline. The body
    // can be direct child of the for-loop. If the for-loop has BlockRealize as
    // its child, the pipeline body will be the child of the block.
1175
1176
    Stmt pipeline_body{nullptr};
    Array<Buffer> pipeline_allocs;
1177
1178
1179
    if (const auto *realize = for_node->body.as<BlockRealizeNode>()) {
      const auto &block = realize->block;
      for (const auto &buffer : block->alloc_buffers) {
1180
1181
1182
        ICHECK(buffer->IsInstance<BufferNode>());
        buffer_data_to_buffer_.Set(buffer->data, buffer);
      }
1183
      pipeline_body = block->body;
1184
1185
1186
1187
1188
      pipeline_allocs = block->alloc_buffers;
    } else {
      pipeline_body = for_node->body;
    }

1189
1190
1191
1192
    const SeqStmtNode *pipeline_body_seq = pipeline_body.as<SeqStmtNode>();
    CHECK(pipeline_body_seq) << "ValueError: The body of the software pipeline "
                                "should be SeqStmt, got "
                             << pipeline_body->GetTypeKey();
1193

1194
1195
    // Step 3: Blockize the components of the pipeline. Each child of the
    // pipelined loop will be converted into a block.
1196
    PipelineInfo pipeline_info;
1197
    Array<Block> original_order; // pipeline body blocks in the original order
1198

1199
    auto f_add_child = [&](const Stmt &child) {
1200
1201
1202
      original_order.push_back(MakeBlock(child, buffer_data_to_buffer_));
    };
    for (size_t i = 0; i < pipeline_body_seq->seq.size(); i++) {
1203
1204
      const auto *nested_block_realize =
          pipeline_body_seq->seq[i].as<BlockRealizeNode>();
1205
1206
      if (nested_block_realize && is_one(nested_block_realize->predicate) &&
          nested_block_realize->block->body->IsInstance<SeqStmtNode>()) {
1207
1208
1209
1210
        const Block &nested_pipeline_block = nested_block_realize->block;
        ICHECK(nested_pipeline_block->match_buffers
                   .empty()); // match_buffer should have been lowered
        for (const auto &buffer : nested_pipeline_block->alloc_buffers) {
1211
1212
1213
          pipeline_allocs.push_back(buffer);
          buffer_data_to_buffer_.Set(buffer->data, buffer);
        }
1214
        const auto *nested_seq = nested_pipeline_block->body.as<SeqStmtNode>();
1215
1216
1217
1218
1219
1220
1221
1222
        for (size_t j = 0; j < nested_seq->seq.size(); j++) {
          f_add_child(nested_seq->seq[j]);
        }
      } else {
        f_add_child(pipeline_body_seq->seq[i]);
      }
    }

1223
1224
1225
1226
    auto pipeline_stages = Downcast<Array<Integer>>(
        op->annotations.at(tir::attr::software_pipeline_stage));
    auto pipeline_orders = Downcast<Array<Integer>>(
        op->annotations.at(tir::attr::software_pipeline_order));
1227
1228
    CHECK_EQ(pipeline_stages.size(), original_order.size())
        << "PrimFunc " << global_symbol_ << " has original order "
1229
1230
1231
1232
        << original_order.Map(
               [](const auto &block) { return block->name_hint; })
        << ", but pipeline annotation is " << pipeline_stages
        << " with different size";
1233
1234
    CHECK_EQ(pipeline_orders.size(), original_order.size())
        << "PrimFunc " << global_symbol_ << " has original order "
1235
1236
1237
1238
        << original_order.Map(
               [](const auto &block) { return block->name_hint; })
        << ", but pipeline annotation is " << pipeline_orders
        << " with different size";
1239
1240

    std::unordered_set<int> pipeline_async_stages;
1241
1242
    if (auto annot =
            op->annotations.Get(tir::attr::software_pipeline_async_stages)) {
1243
      for (auto s : Downcast<Array<Integer>>(annot.value())) {
1244
1245
1246
1247
        pipeline_async_stages.insert(s->value);
      }
    }

1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
    Map<String, ffi::Any> preserved_annotations;
    for (const auto &kv : op->annotations) {
      const String &key = kv.first;
      if (kv.first != tir::attr::software_pipeline_stage &&
          kv.first != tir::attr::software_pipeline_order &&
          kv.first != tir::attr::software_pipeline_async_stages) {
        preserved_annotations.Set(key, kv.second);
      }
    }

1258
1259
    for (size_t i = 0; i < pipeline_stages.size(); i++) {
      int stage = static_cast<int>(pipeline_stages[i]->value);
1260
1261
1262
1263
1264
      bool is_async =
          pipeline_async_stages.find(stage) != pipeline_async_stages.end();
      PipelineAnnotation stage_order{
          stage,
          /*order=*/static_cast<int>(pipeline_orders[i]->value), is_async};
1265
1266
1267
1268
1269
1270
      pipeline_info.emplace(original_order[i], stage_order);
    }

    ValidatePipelineBody(pipeline_info, original_order);

    // Step 4: Rewrite the pipeline body.
1271
1272
1273
    Stmt pipeline = PipelineRewriter::Rewrite(
        buffer_data_to_buffer_, double_buffers, pipeline_allocs,
        GetRef<For>(op), pipeline_info, fragment_info_, preserved_annotations);
1274

1275
1276
1277
    if (const auto *realize = op->body.as<BlockRealizeNode>()) {
      const auto &block = realize->block;
      for (const auto &buffer : block->alloc_buffers) {
1278
1279
1280
1281
1282
1283
        buffer_data_to_buffer_.erase(buffer->data);
      }
    }
    return pipeline;
  }

1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
  /*!
   * \brief Add buffer allocations to a block and update the write region of the
   * block. \param n The block pointer to which the buffer allocations are
   * added. \param alloc_buffers The buffer allocations to be added.
   */
  void AddAllocBuffers(BlockNode *n, const Array<Buffer> alloc_buffers) {
    for (const Buffer &alloc_buffer : alloc_buffers) {
      n->alloc_buffers.push_back(alloc_buffer);
      Region region;
      region.reserve(alloc_buffer->shape.size());
      for (const PrimExpr &dim : alloc_buffer->shape) {
        region.push_back(Range::FromMinExtent(0, dim));
      }
      n->writes.push_back(BufferRegion(alloc_buffer, region));
    }
  }

1301
1302
  Stmt VisitStmt_(const BlockNode *op) final {
    for (const auto &buffer : op->alloc_buffers) {
1303
1304
1305
      buffer_data_to_buffer_.Set(buffer->data, buffer);
    }

1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
    auto it = op->annotations.find(tir::attr::double_buffer_scope);
    if (it != op->annotations.end()) {
      int buffer_index = Downcast<Integer>((*it).second).IntValue();
      CHECK(buffer_index >= 0 &&
            static_cast<size_t>(buffer_index) < op->writes.size())
          << "ValueError: Index of the buffer exceeds the size of the write "
             "regions of the block. ("
          << buffer_index << " vs. " << op->writes.size() << ")";
      double_buffers.insert(op->writes[buffer_index]->buffer);
    }
1316
1317
    Block block = Downcast<Block>(StmtExprMutator::VisitStmt_(op));

1318
    for (const auto &buffer : op->alloc_buffers) {
1319
1320
      buffer_data_to_buffer_.erase(buffer->data);
    }
1321
    return block;
1322
1323
  }

1324
  bool HasPipelineAnnotation(const ForNode *op) const {
1325
1326
1327
1328
1329
1330
1331
1332
    auto it1 = op->annotations.find(tir::attr::software_pipeline_stage);
    auto it2 = op->annotations.find(tir::attr::software_pipeline_order);
    bool has_stage = it1 != op->annotations.end();
    bool has_order = it2 != op->annotations.end();
    if (has_stage && has_order) {
      return true;
    }
    if (has_stage) {
1333
      LOG(FATAL)
1334
          << "ValueError: Order of the software pipeline is not defined.";
1335
1336
    }
    if (has_order) {
1337
      LOG(FATAL)
1338
          << "ValueError: Stage of the software pipeline is not defined.";
1339
1340
1341
1342
1343
    }
    return false;
  }

  Map<Var, Buffer> buffer_data_to_buffer_;
1344
1345
  std::unordered_map<const VarNode *, FragmentInfo> fragment_info_;
  std::unordered_set<Buffer, ObjectPtrHash, ObjectPtrEqual> double_buffers;
1346
1347
1348
  Optional<String> global_symbol_;
};

1349
1350
} // namespace software_pipeline

1351
/*!
1352
1353
 * \brief Transform annotated loops into pipelined one that parallelize
 * producers and consumers. \return The IR transform pass.
1354
1355
1356
1357
 */
tir::transform::Pass InjectSoftwarePipeline() {
  using namespace tir::transform;
  auto pass_func = [=](PrimFunc f, IRModule m, PassContext ctx) {
1358
    auto *fptr = f.CopyOnWrite();
1359
    fptr->body = software_pipeline::PipelineInjector::Inject(f);
1360
1361
1362
1363
1364
1365
    fptr->body = ConvertSSA(std::move(fptr->body));
    return f;
  };
  return CreatePrimFuncPass(pass_func, 0, "tl.InjectSoftwarePipeline", {});
}

1366
1367
1368
1369
1370
TVM_FFI_STATIC_INIT_BLOCK({
  namespace refl = tvm::ffi::reflection;
  refl::GlobalDef().def("tl.transform.InjectSoftwarePipeline",
                        InjectSoftwarePipeline);
});
1371

1372
1373
} // namespace tl
} // namespace tvm