-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathlayout_transformation.cc
1700 lines (1461 loc) · 63.7 KB
/
layout_transformation.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
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
720
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
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
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
833
834
835
836
837
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.
*/
#include <tvm/arith/analyzer.h>
#include <tvm/node/node.h>
#include <optional>
#include <variant>
#include "../../../arith/ir_mutator_with_analyzer.h"
#include "../utils.h"
namespace tvm {
namespace tir {
/*! \brief Planning stage prior to rewriting in TransformLayoutRewriter
*
* There are four ways that transformation may be handled. Each
* updates the buffer shape and the indices used to acces the buffer
* in BufferStore/BufferLoad nodes, but differ in how they handle the
* `pad_value`. In order of preference, the different strategies are
* as follows:
*
* 1. NoPaddingRequired. The transformation does not introduce
* padding, so only local changes to update the indices of
* BufferLoad/BufferStore nodes are required. No blocks are added,
* removed, or replaced.
*
* 2. ProloguePlan. The transformation introduces padding, but the
* analyzed block has no write stages for the transformed buffer.
* This buffer is an input and the caller is responsible for ensuring
* that the padding contains the specified `pad_value`. The generated
* prologue contains `builtin::assume()` calls that will expose this
* known value during scheduling/simplification, but will be removed
* during lowering.
*
* 3. ReplacementPlan. The transformation introduces padding, has at
* least one write stage for the transformed buffer, and at least one
* of those write stages writes to all pre-transformation indices
* following a row-major traversal. These write stage is rewritten to
* be row-major traversals of the post-transformation indices, with a
* `tir::if_then_else` call to write either the specified `pad_value`
* into padding or the computed value into non-padding.
*
* 4. EpiloguePlan. The transformation introduces padding, has at
* least one write stage for the transformed buffer, but no write
* stage can be rewritten to use `tir::if_then_else`. The
* transformation still requires the `pad_value` to be written into
* the padding, so a new block is inserted after the last write stage
* to explicitly fill the padding.
*
*/
class TransformLayoutPlanner : private StmtExprVisitor {
public:
// Statement to be inserted prior to the analyzed block
struct ProloguePlan {
Stmt prologue;
};
// Loops within the analyzed block that should be replaced
struct ReplacementPlan {
Map<For, Stmt> replacements;
Map<Block, Block> new_block_to_old;
};
// The block to be inserted, along with the location at which it
// should be inserted. The location will be either a For or a
// Block, and will be after all writes the transformed buffer.
struct EpiloguePlan {
Stmt insert_after;
Stmt new_block;
};
struct NoPaddingRequired {};
using TransformPlan =
std::variant<ProloguePlan, ReplacementPlan, EpiloguePlan, NoPaddingRequired>;
static TransformPlan Plan(Block block, Buffer old_buffer, Buffer new_buffer, IndexMap index_map,
IndexMap inverse, PrimExpr padding_predicate,
Optional<IndexMap> pad_value, arith::Analyzer* analyzer) {
ICHECK(!pad_value.defined() || pad_value.value()->final_indices.size() == 1)
<< "Internal error: Should be caught by ScheduleError checks prior to this point";
TransformLayoutPlanner visitor(old_buffer);
visitor(block);
return visitor.Finalize(new_buffer, index_map, inverse, padding_predicate, pad_value, analyzer);
}
private:
struct WriteInfo {
// The BufferStore object
BufferStore store;
// The block realize that contains the store, if any.
Optional<BlockRealize> innermost_block_realize;
// The nested loops whose values contribute to the indices used in
// the store. Not all loop variables in the loopnest need to
// contribute, but the first and last must.
std::vector<For> dependent_loopnest;
// Whether the padding could be represented as a tir::if_then_else
// node. This requires that the surrounding loop iterators
// iterate over all pre-transformation buffer axes, that there are
// no data dependencies between loop iterations, and that
bool contains_row_major_traversal{false};
};
explicit TransformLayoutPlanner(Buffer old_buffer) : old_buffer_(old_buffer) {}
void VisitStmt_(const ForNode* op) override {
BindLoopVar context(this, GetRef<For>(op));
StmtExprVisitor::VisitStmt_(op);
}
void VisitStmt_(const LetStmtNode* op) override {
BindVariableDefinition context(this, op->var, op->value);
StmtExprVisitor::VisitStmt_(op);
}
void VisitStmt_(const BlockRealizeNode* op) override {
BindBlockRealize context(this, GetRef<BlockRealize>(op));
StmtExprVisitor::VisitStmt_(op);
}
void VisitStmt_(const BufferStoreNode* op) override {
if (!op->buffer.same_as(old_buffer_)) {
return;
}
std::optional<std::pair<size_t, size_t>> loop_dependency_range = std::nullopt;
for (const auto& index : op->indices) {
if (auto index_depth = LoopDependencyRange(index); index_depth.has_value()) {
if (loop_dependency_range) {
loop_dependency_range = {
std::min(loop_dependency_range.value().first, index_depth.value().first),
std::max(loop_dependency_range.value().second, index_depth.value().second)};
} else {
loop_dependency_range = index_depth;
}
}
}
WriteInfo write_info;
write_info.store = GetRef<BufferStore>(op);
if (loop_dependency_range) {
size_t i = loop_dependency_range.value().first;
size_t j = loop_dependency_range.value().second;
ICHECK_LT(i, active_loops_.size());
ICHECK_LT(j, active_loops_.size());
write_info.dependent_loopnest = {active_loops_.begin() + i, active_loops_.begin() + j + 1};
}
write_info.innermost_block_realize = innermost_block_realize_;
write_info.contains_row_major_traversal = [&]() -> bool {
const auto& loopnest = write_info.dependent_loopnest;
if (loopnest.empty()) {
return false;
}
if (loopnest.size() != old_buffer_->shape.size() || loopnest.size() != op->indices.size()) {
return false;
}
for (size_t i = 0; i < loopnest.size(); i++) {
const For& loop = loopnest[i];
const PrimExpr& buffer_dim = old_buffer_->shape[i];
PrimExpr index = Substitute(op->indices[i], active_var_bindings_);
bool is_loop_over_axis = index.same_as(loop->loop_var) && is_const_int(loop->min, 0) &&
ExprDeepEqual()(loop->extent, buffer_dim) &&
loop->kind == ForKind::kSerial;
if (!is_loop_over_axis) {
return false;
}
}
return true;
}();
write_info_.push_back(write_info);
// Don't need to continue recursing, as the entire goal was to
// find the BufferStore.
}
std::optional<std::pair<size_t, size_t>> LoopDependencyRange(const PrimExpr& expr) const {
std::optional<std::pair<size_t, size_t>> prev = std::nullopt;
for (const auto& var : UndefinedVars(expr)) {
auto it = loop_depth_lookup_.find(var.get());
if (it != loop_depth_lookup_.end()) {
if (prev.has_value()) {
prev = {std::min(prev.value().first, it->second.first),
std::max(prev.value().second, it->second.second)};
} else {
prev = it->second;
}
}
}
return prev;
}
class BufferStoreReplacer : public StmtExprMutator {
public:
BufferStoreReplacer(const WriteInfo& info, const Buffer& new_buffer, PrimExpr padding_predicate,
const IndexMap& inverse, const Optional<IndexMap>& pad_value,
Map<Block, Block>* new_block_to_old, arith::Analyzer* analyzer)
: info(info),
new_buffer(new_buffer),
new_indices(inverse->initial_indices),
padding_predicate(padding_predicate),
inverse(inverse),
pad_value(pad_value),
new_block_to_old(*new_block_to_old),
analyzer(analyzer) {
ICHECK_EQ(info.dependent_loopnest.size(), inverse->final_indices.size());
for (size_t i = 0; i < info.dependent_loopnest.size(); i++) {
Var var = info.dependent_loopnest[i]->loop_var;
PrimExpr expr = inverse->final_indices[i];
var_remap.Set(var, expr);
}
DefineBlockUpdates();
}
bool is_all_stores_replaced() const { return all_stores_replaced; }
private:
void DefineBlockUpdates() {
if (!info.innermost_block_realize) {
return;
}
BlockRealize block_realize = info.innermost_block_realize.value();
const auto& block = block_realize->block;
const Array<PrimExpr>& old_indices = info.store->indices;
const auto& old_iter_vars = block->iter_vars;
this->new_iter_vars = old_iter_vars;
this->new_iter_values = block_realize->iter_values;
if (old_indices.empty()) {
return;
}
// Find the block iterators that are used to access the buffer. Must be in the same
// order as they appear in the indices.
if (block->iter_vars.size() < old_indices.size()) {
return;
}
size_t block_index_start = 0;
for (; block_index_start < old_iter_vars.size() - old_indices.size(); block_index_start++) {
if (old_indices[0].same_as(old_iter_vars[block_index_start]->var)) {
break;
}
}
if (block_index_start > old_iter_vars.size() - old_indices.size()) {
return;
}
for (size_t i = 0; i < old_indices.size(); i++) {
if (!old_indices[i].same_as(old_iter_vars[block_index_start + i]->var) ||
old_iter_vars[block_index_start + i]->iter_type != kDataPar) {
return;
}
}
// If we got to this point, all indices used to access the
// buffer are virtual indices defined in the innermost block.
// Therefore, generate new virtual indices for iterating over
// the post-transform buffer.
new_indices = inverse->initial_indices.Map([](Var var) {
std::stringstream ss;
ss << "v_" << var->name_hint;
return Var(ss.str(), var.dtype());
});
Map<Var, Var>
loop_var_to_virtual_var; // For updating padding_predicate in terms of the new indices
Array<PrimExpr> new_iter_values; // For BlockRealize
Array<IterVar> new_iter_vars; // For Block
for (size_t i = 0; i < block_index_start; i++) {
new_iter_vars.push_back(old_iter_vars[i]);
new_iter_values.push_back(block_realize->iter_values[i]);
}
ICHECK_EQ(new_indices.size(), new_buffer->shape.size());
for (size_t i = 0; i < new_indices.size(); i++) {
Var var = inverse->initial_indices[i];
Var virtual_var = new_indices[i];
PrimExpr dim = new_buffer->shape[i];
new_iter_values.push_back(var);
new_iter_vars.push_back(
IterVar(Range::FromMinExtent(make_zero(dim.dtype()), dim), virtual_var, kDataPar));
loop_var_to_virtual_var.Set(var, virtual_var);
}
for (size_t i = block_index_start + old_indices.size(); i < old_iter_vars.size(); i++) {
new_iter_vars.push_back(old_iter_vars[i]);
new_iter_values.push_back(block_realize->iter_values[i]);
}
ICHECK_EQ(inverse->final_indices.size(), old_indices.size());
for (size_t i = 0; i < old_indices.size(); i++) {
Var var = Downcast<Var>(old_indices[i]);
PrimExpr expr = Substitute(inverse->final_indices[i], loop_var_to_virtual_var);
var_remap.Set(var, expr);
}
padding_predicate = Substitute(padding_predicate, loop_var_to_virtual_var);
this->new_iter_vars = new_iter_vars;
this->new_iter_values = new_iter_values;
}
Stmt VisitStmt_(const BufferStoreNode* op) final {
bool can_replace = [&]() -> bool {
if (!op->buffer.same_as(info.store->buffer)) {
return false;
}
const Array<PrimExpr>& old_indices = info.store->indices;
ICHECK_EQ(old_indices.size(), op->indices.size());
ExprDeepEqual expr_equal;
for (size_t i = 0; i < old_indices.size(); i++) {
if (!expr_equal(old_indices[i], op->indices[i])) {
return false;
}
}
return true;
}();
BufferStore store = GetRef<BufferStore>(op);
if (can_replace) {
Array<PrimExpr> new_index_exprs =
new_indices.Map([](const auto& var) -> PrimExpr { return var; });
PrimExpr pad_value_at_index = pad_value.value()->MapIndices(new_index_exprs, analyzer)[0];
store =
BufferStore(new_buffer, if_then_else(padding_predicate, pad_value_at_index, op->value),
new_index_exprs);
} else {
all_stores_replaced = false;
}
return StmtExprMutator::VisitStmt_(store.get());
}
Stmt VisitStmt_(const BlockRealizeNode* op) final {
BlockRealize realize = Downcast<BlockRealize>(StmtExprMutator::VisitStmt_(op));
if (op == info.innermost_block_realize.get()) {
Block block = realize->block;
if (!block->iter_vars.same_as(this->new_iter_vars)) {
block.CopyOnWrite()->iter_vars = this->new_iter_vars;
RecordReplacement(op->block, block);
}
if (!block.same_as(realize->block) ||
!realize->iter_values.same_as(this->new_iter_values)) {
auto write_ptr = realize.CopyOnWrite();
write_ptr->block = block;
write_ptr->iter_values = this->new_iter_values;
}
}
return std::move(realize);
}
Stmt VisitStmt_(const BlockNode* op) final {
Block orig = GetRef<Block>(op);
Block mutated = Downcast<Block>(StmtExprMutator::VisitStmt_(op));
RecordReplacement(orig, mutated);
return std::move(mutated);
}
PrimExpr VisitExpr_(const VarNode* op) final {
Var var = GetRef<Var>(op);
if (auto opt = var_remap.Get(var)) {
return opt.value();
} else {
return std::move(var);
}
}
void RecordReplacement(Block before, Block after) {
if (before.same_as(after)) {
return;
}
ICHECK(!new_block_to_old.count(after));
while (true) {
if (auto opt = new_block_to_old.Get(before)) {
before = opt.value();
} else {
break;
}
}
new_block_to_old.Set(after, before);
}
const WriteInfo& info;
const Buffer& new_buffer;
Array<Var> new_indices;
Array<IterVar> new_iter_vars;
Array<PrimExpr> new_iter_values;
PrimExpr padding_predicate;
const IndexMap& inverse;
const Optional<IndexMap>& pad_value;
Map<Block, Block>& new_block_to_old;
bool all_stores_replaced{true};
arith::Analyzer* analyzer;
Map<Var, PrimExpr> var_remap;
};
TransformPlan Finalize(Buffer new_buffer, IndexMap index_map, IndexMap inverse,
PrimExpr padding_predicate, Optional<IndexMap> pad_value,
arith::Analyzer* analyzer) const {
if (auto prologue_plan = FinalizeProloguePlan(new_buffer, index_map, inverse, padding_predicate,
pad_value, analyzer);
prologue_plan.has_value()) {
return prologue_plan.value();
} else if (auto replacement_plan = FinalizeReplacementPlan(
new_buffer, index_map, inverse, padding_predicate, pad_value, analyzer);
replacement_plan.has_value()) {
return replacement_plan.value();
} else if (auto epilogue_plan = FinalizeEpiloguePlan(new_buffer, index_map, inverse,
padding_predicate, pad_value, analyzer);
epilogue_plan.has_value()) {
return epilogue_plan.value();
} else {
return NoPaddingRequired();
}
}
std::optional<ProloguePlan> FinalizeProloguePlan(Buffer new_buffer, IndexMap index_map,
IndexMap inverse, PrimExpr padding_predicate,
Optional<IndexMap> pad_value,
arith::Analyzer* analyzer) const {
if (write_info_.size() || is_zero(padding_predicate) || !pad_value.defined()) {
return std::nullopt;
}
Array<IterVar> iter_vars;
Array<PrimExpr> iter_values;
Array<PrimExpr> indices;
Map<Var, Var> loop_indices_to_block_indices;
ICHECK_EQ(inverse->initial_indices.size(), new_buffer->shape.size());
for (size_t i = 0; i < inverse->initial_indices.size(); i++) {
const auto& loop_var = inverse->initial_indices[i];
const auto& dim = new_buffer->shape[i];
Var block_var("v_" + loop_var->name_hint, loop_var->dtype);
IterVar iter_var(Range(0, dim), block_var, kDataPar);
loop_indices_to_block_indices.Set(loop_var, block_var);
indices.push_back(iter_var->var);
iter_vars.push_back(iter_var);
iter_values.push_back(loop_var);
}
padding_predicate = Substitute(std::move(padding_predicate), loop_indices_to_block_indices);
PrimExpr pad_value_at_index = pad_value.value()->MapIndices(indices, analyzer)[0];
PrimExpr expr = (!padding_predicate) || (BufferLoad(new_buffer, indices) == pad_value_at_index);
Stmt stmt = Evaluate(Call(DataType::Bool(), builtin::assume(), {expr}));
std::stringstream block_name;
block_name << "buffer_" << new_buffer->name << "_assumptions";
auto read_region = BufferRegion::FromPoint(new_buffer, indices);
stmt = BlockRealize(iter_values, Bool(true),
Block(iter_vars, {read_region}, {}, block_name.str(), stmt));
for (size_t rev_i = 0; rev_i < inverse->initial_indices.size(); rev_i++) {
size_t i = (inverse->initial_indices.size() - 1) - rev_i;
Var loop_var = inverse->initial_indices[i];
PrimExpr extent = new_buffer->shape[i];
stmt = For(loop_var, 0, extent, ForKind::kSerial, stmt);
}
return ProloguePlan{stmt};
}
std::optional<ReplacementPlan> FinalizeReplacementPlan(Buffer new_buffer, IndexMap index_map,
IndexMap inverse,
PrimExpr padding_predicate,
Optional<IndexMap> pad_value,
arith::Analyzer* analyzer) const {
if (write_info_.empty() || is_zero(padding_predicate) || !pad_value.defined()) {
return std::nullopt;
}
Map<Block, Block> new_block_to_old;
auto generate_if_then_else_block = [&](const WriteInfo& info) -> Optional<Stmt> {
if (!info.contains_row_major_traversal || !pad_value.defined() ||
is_zero(padding_predicate)) {
return NullOpt;
}
BufferStoreReplacer replacer(info, new_buffer, padding_predicate, inverse, pad_value,
&new_block_to_old, analyzer);
Stmt stmt = replacer(info.dependent_loopnest.back()->body);
if (!replacer.is_all_stores_replaced()) {
return NullOpt;
}
ICHECK_EQ(inverse->initial_indices.size(), new_buffer->shape.size());
for (size_t rev_i = 0; rev_i < inverse->initial_indices.size(); rev_i++) {
size_t i = (inverse->initial_indices.size() - 1) - rev_i;
Var loop_var = inverse->initial_indices[i];
PrimExpr extent = new_buffer->shape[i];
stmt = For(loop_var, 0, extent, ForKind::kSerial, stmt);
}
return stmt;
};
Map<For, Stmt> loop_replacements;
for (const auto& info : write_info_) {
if (info.dependent_loopnest.size()) {
if (auto opt_stmt = generate_if_then_else_block(info)) {
loop_replacements.Set(info.dependent_loopnest[0], opt_stmt.value());
}
}
}
if (loop_replacements.size()) {
return ReplacementPlan{std::move(loop_replacements), std::move(new_block_to_old)};
} else {
return std::nullopt;
}
}
std::optional<EpiloguePlan> FinalizeEpiloguePlan(Buffer new_buffer, IndexMap index_map,
IndexMap inverse, PrimExpr padding_predicate,
Optional<IndexMap> pad_value,
arith::Analyzer* analyzer) const {
if (write_info_.empty() || is_zero(padding_predicate) || !pad_value.defined()) {
return std::nullopt;
}
Array<IterVar> iter_vars;
Array<PrimExpr> iter_values;
Array<PrimExpr> indices;
ICHECK_EQ(inverse->initial_indices.size(), new_buffer->shape.size());
for (size_t i = 0; i < inverse->initial_indices.size(); i++) {
const auto& loop_var = inverse->initial_indices[i];
const auto& dim = new_buffer->shape[i];
Var block_var("v_" + loop_var->name_hint, loop_var->dtype);
IterVar iter_var(Range(0, dim), block_var, kDataPar);
indices.push_back(iter_var->var);
iter_vars.push_back(iter_var);
iter_values.push_back(loop_var);
}
PrimExpr pad_value_at_index = pad_value.value()->MapIndices(indices, analyzer)[0];
Stmt stmt = BufferStore(new_buffer, pad_value_at_index, indices);
std::stringstream block_name;
block_name << "buffer_" << new_buffer->name << "_padding";
auto write_region = BufferRegion::FromPoint(new_buffer, indices);
stmt = BlockRealize(iter_values, padding_predicate,
Block(iter_vars, {}, {write_region}, block_name.str(), stmt));
ICHECK_EQ(inverse->initial_indices.size(), new_buffer->shape.size());
for (size_t rev_i = 0; rev_i < inverse->initial_indices.size(); rev_i++) {
size_t i = (inverse->initial_indices.size() - 1) - rev_i;
Var loop_var = inverse->initial_indices[i];
PrimExpr extent = new_buffer->shape[i];
stmt = For(loop_var, 0, extent, ForKind::kSerial, stmt);
}
const auto& info = write_info_.back();
Stmt insert_after = [&]() -> Stmt {
if (info.dependent_loopnest.size()) {
return info.dependent_loopnest.front();
} else if (info.innermost_block_realize) {
return info.innermost_block_realize.value();
} else {
LOG(FATAL) << "Write occured outside of any block/loop";
}
}();
return EpiloguePlan{insert_after, stmt};
}
struct BindLoopVar {
BindLoopVar(TransformLayoutPlanner* self, For for_node)
: self_(self), var_(for_node->loop_var) {
size_t loop_depth = self_->active_loops_.size();
self_->loop_depth_lookup_[var_.get()] = {loop_depth, loop_depth};
self_->active_loops_.push_back(std::move(for_node));
}
~BindLoopVar() {
self_->active_loops_.pop_back();
self_->loop_depth_lookup_.erase(var_.get());
}
BindLoopVar(const BindLoopVar&) = delete;
BindLoopVar& operator=(const BindLoopVar&) = delete;
BindLoopVar(BindLoopVar&&) = delete;
BindLoopVar& operator=(BindLoopVar&&) = delete;
TransformLayoutPlanner* self_{nullptr};
Var var_;
};
struct BindVariableDefinition {
BindVariableDefinition() {}
BindVariableDefinition(TransformLayoutPlanner* self, Var var, PrimExpr value)
: self_(self), var_(var) {
if (auto loop_depth = self->LoopDependencyRange(value); loop_depth.has_value()) {
self_->loop_depth_lookup_[var_.get()] = loop_depth.value();
self_->active_var_bindings_[var_.get()] = Substitute(value, self_->active_var_bindings_);
}
}
~BindVariableDefinition() {
if (self_) {
self_->loop_depth_lookup_.erase(var_.get());
self_->active_var_bindings_.erase(var_.get());
}
}
BindVariableDefinition(const BindVariableDefinition&) = delete;
BindVariableDefinition& operator=(const BindVariableDefinition&) = delete;
BindVariableDefinition(BindVariableDefinition&& other) : BindVariableDefinition() {
swap(other);
}
BindVariableDefinition& operator=(BindVariableDefinition&& other) {
swap(other);
return *this;
}
void swap(BindVariableDefinition& other) {
std::swap(self_, other.self_);
std::swap(var_, other.var_);
}
TransformLayoutPlanner* self_{nullptr};
Var var_;
};
struct BindBlockRealize {
BindBlockRealize(TransformLayoutPlanner* self, BlockRealize block_realize) : self_(self) {
ICHECK_EQ(block_realize->iter_values.size(), block_realize->block->iter_vars.size());
for (size_t i = 0; i < block_realize->iter_values.size(); i++) {
bound_vars_.emplace_back(self, block_realize->block->iter_vars[i]->var,
block_realize->iter_values[i]);
}
cache_ = std::move(block_realize);
std::swap(self_->innermost_block_realize_, cache_);
}
~BindBlockRealize() { std::swap(self_->innermost_block_realize_, cache_); }
BindBlockRealize(const BindBlockRealize&) = delete;
BindBlockRealize& operator=(const BindBlockRealize&) = delete;
BindBlockRealize(BindBlockRealize&&) = delete;
BindBlockRealize& operator=(BindBlockRealize&&) = delete;
TransformLayoutPlanner* self_{nullptr};
Optional<BlockRealize> cache_;
std::vector<BindVariableDefinition> bound_vars_;
};
/*! \brief Collected information about each BufferStore */
std::vector<WriteInfo> write_info_;
/*! \brief The loop iterators surrounding the current node
*
* The outermost loop iterator is `active_loops_.front()`, and the
* innermost loop iterator is `active_loops_.back()`.
*
* Used to fill the `WriteInfo::dependent_loopnest` field.
*/
std::vector<For> active_loops_;
/*! \brief Lookup for the outer/inner loops
*
* Used to fill the `WriteInfo::dependent_loopnest` field.
*/
std::unordered_map<const VarNode*, std::pair<size_t, size_t>> loop_depth_lookup_;
/*! \brief The variable mappings that are currently in-scope
*
* Used to determine whether the indices of a BufferStore are a
* row-major traversal, even if they are rebound in let/block
* mappings.
*/
std::unordered_map<const VarNode*, PrimExpr> active_var_bindings_;
/*! \brief The innermost BlockRealize surrounding the current node
*
* Used to fill the `WriteInfo::innermost_block_realize` field..
*/
Optional<BlockRealize> innermost_block_realize_{NullOpt};
/*! \brief The buffer to be replaced */
Buffer old_buffer_;
};
/*!
* \brief Collect blocks that are part of root block to be passed to ScheduleState::Replace for SRef
* reuse
*/
class ReuseBlocksCollector : public tir::StmtVisitor {
public:
static Map<Block, Block> Collect(Block result, Map<Block, Block> new_block_to_old) {
return ReuseBlocksCollector(new_block_to_old).Run(result);
}
private:
/*! \brief Entry point */
Map<Block, Block> Run(const Block result) {
VisitStmt(result);
return block_sref_reuse_;
}
/*! \brief Constructor */
explicit ReuseBlocksCollector(Map<Block, Block> new_block_to_old)
: new_block_to_old_(new_block_to_old) {}
/*! \brief Override the Stmt visiting behaviour */
void VisitStmt_(const tir::BlockNode* block) override {
Block block_ref = GetRef<Block>(block);
auto it = new_block_to_old_.find(block_ref);
if (it != new_block_to_old_.end()) {
block_sref_reuse_.Set((*it).second, (*it).first);
}
StmtVisitor::VisitStmt_(block);
}
/*! \brief New map to be filled with just blocks from scope block */
Map<Block, Block> block_sref_reuse_;
/*! \brief All block replacements collected so far */
Map<Block, Block> new_block_to_old_;
};
class TransformLayoutRewriter : private arith::IRMutatorWithAnalyzer {
public:
/*!
* \brief Rewrite the access to the buffer after the transformation
* \param scope_stmt The parent statement that contains all accesses to the target buffer
* \param old_buffer The target buffer before transformation
* \param new_buffer The new buffer after transformation
* \param index_map The transformation applied to the buffer
* \return The new AST rooting at the original parent scope and the map from the old block to the
* new block
*/
static std::pair<Stmt, Map<Block, Block>> Rewrite(
const Block& scope_stmt, const Buffer& old_buffer, const Buffer& new_buffer,
const IndexMap& index_map, const Optional<IndexMap>& opt_inverse,
const PrimExpr& padding_predicate, const Optional<IndexMap>& pad_value) {
arith::Analyzer analyzer;
auto plan = pad_value.defined()
? TransformLayoutPlanner::Plan(scope_stmt, old_buffer, new_buffer, index_map,
opt_inverse.value(), padding_predicate,
pad_value, &analyzer)
: TransformLayoutPlanner::NoPaddingRequired();
TransformLayoutRewriter rewriter(old_buffer, new_buffer, index_map, plan, &analyzer);
Block result = Downcast<Block>(rewriter(scope_stmt));
if (auto plan_ptr = std::get_if<TransformLayoutPlanner::ProloguePlan>(&plan)) {
auto write_ptr = result.CopyOnWrite();
write_ptr->body = SeqStmt({plan_ptr->prologue, write_ptr->body});
}
Map<Block, Block> block_sref_reuse =
ReuseBlocksCollector::Collect(result, rewriter.new_block_to_old_);
return {result, block_sref_reuse};
}
private:
TransformLayoutRewriter(const Buffer& old_buffer, const Buffer& new_buffer,
const IndexMap& index_map,
const TransformLayoutPlanner::TransformPlan& plan,
arith::Analyzer* analyzer)
: IRMutatorWithAnalyzer(analyzer),
old_buffer_(old_buffer),
new_buffer_(new_buffer),
index_map_(index_map),
plan_(plan),
buffer_data_to_buffer_{{new_buffer->data, new_buffer}} {
if (auto plan_ptr = std::get_if<TransformLayoutPlanner::ReplacementPlan>(&plan_)) {
new_block_to_old_ = plan_ptr->new_block_to_old;
}
}
void RewriteBufferAccess(Buffer* buffer, Array<PrimExpr>* indices) {
*buffer = new_buffer_;
*indices = index_map_->MapIndices(*indices, &index_simplifier_);
*indices = this->IterMapSimplifyWithContext(*indices, true);
}
using Parent = arith::IRMutatorWithAnalyzer;
using Parent::VisitExpr_;
using Parent::VisitStmt_;
Stmt VisitStmt(const Stmt& stmt) final {
Stmt output = Parent::VisitStmt(stmt);
if (auto plan_ptr = std::get_if<TransformLayoutPlanner::EpiloguePlan>(&plan_)) {
if (plan_ptr->insert_after.same_as(stmt)) {
return SeqStmt({output, plan_ptr->new_block});
}
}
return output;
}
Stmt VisitStmt_(const ForNode* op) final {
// Some replacements may include the original string, such as
// replacing `loop` with `{loop, post_proc}`. In this case, avoid
// infinite recursion.
For node = GetRef<For>(op);
if (auto plan_ptr = std::get_if<TransformLayoutPlanner::ReplacementPlan>(&plan_)) {
auto it = plan_ptr->replacements.find(node);
if (it != plan_ptr->replacements.end()) {
return VisitStmt((*it).second);
}
}
return Parent::VisitStmt_(op);
}
PrimExpr VisitExpr_(const BufferLoadNode* op) final {
BufferLoad buffer_load = Downcast<BufferLoad>(Parent::VisitExpr_(op));
if (buffer_load->buffer.same_as(old_buffer_)) {
auto* n = buffer_load.CopyOnWrite();
RewriteBufferAccess(&n->buffer, &n->indices);
}
return std::move(buffer_load);
}
Stmt VisitStmt_(const BufferStoreNode* op) final {
BufferStore buffer_store = Downcast<BufferStore>(Parent::VisitStmt_(op));
if (buffer_store->buffer.same_as(old_buffer_)) {
auto* n = buffer_store.CopyOnWrite();
RewriteBufferAccess(&n->buffer, &n->indices);
}
return std::move(buffer_store);
}
void RewriteAccessRegion(Array<BufferRegion>* old_access_regions,
const Array<BufferRegion>& infered_access_regions) {
auto fmutate = [this, &infered_access_regions](const BufferRegion& buffer_region) {
if (buffer_region->buffer.same_as(old_buffer_)) {
ICHECK(infered_access_regions.size() == 1);
return infered_access_regions[0];
}
return buffer_region;
};
(*old_access_regions).MutateByApply(fmutate);
}
Stmt VisitStmt_(const BlockNode* op) final {
Block orig = [&]() {
Block block = GetRef<Block>(op);
while (true) {
if (auto it = new_block_to_old_.find(block); it != new_block_to_old_.end()) {
block = (*it).second;
} else {
break;
}
}
return block;
}();
Block block = Downcast<Block>(Parent::VisitStmt_(op));
auto infered_access_regions = GetBlockReadWriteRegion(block, buffer_data_to_buffer_);
auto* n = block.CopyOnWrite();
RewriteAccessRegion(&n->reads, infered_access_regions[0]);
RewriteAccessRegion(&n->writes, infered_access_regions[1]);
n->alloc_buffers.MutateByApply([this](const Buffer& buffer) {
if (buffer.same_as(old_buffer_)) {
return new_buffer_;
} else {
return buffer;
}
});
RecordReplacement(orig, block);
return std::move(block);
}
void RecordReplacement(Block before, Block after) {
if (before.same_as(after)) {
return;
}
ICHECK(!new_block_to_old_.count(after));
while (true) {
if (auto opt = new_block_to_old_.Get(before)) {
before = opt.value();
} else {
break;
}
}
new_block_to_old_.Set(after, before);
}
const Buffer& old_buffer_;
const Buffer& new_buffer_;
const IndexMap& index_map_;
const TransformLayoutPlanner::TransformPlan& plan_;
Map<Var, Buffer> buffer_data_to_buffer_;
Map<Block, Block> new_block_to_old_;
arith::Analyzer index_simplifier_;
};
class BufferIsSubregionError : public ScheduleError {
public:
explicit BufferIsSubregionError(IRModule mod, Buffer buffer) : mod_(mod), buffer_(buffer) {}
String FastErrorString() const final {
return "ScheduleError: The input buffer is defined in `match_buffer` of a block, it is expected"
" to be a function parameter or allocated by a block";
}
String DetailRenderTemplate() const final {
std::ostringstream os;
os << "ScheduleError: The input buffer " << buffer_->name << " is defined in `match_buffer` of "
<< "a block, it is expected to be a function parameter or allocated by a block.";
return os.str();
}
Array<ObjectRef> LocationsOfInterest() const final { return {}; }
IRModule mod() const final { return mod_; }
private:
IRModule mod_;
Buffer buffer_;
};
class TransformationPaddingIndexMapError : public ScheduleError {
public:
TransformationPaddingIndexMapError(IRModule mod, IndexMap pad_value)
: mod_(mod), pad_value_(pad_value) {}
String FastErrorString() const final {
std::ostringstream ss;
ss << "ScheduleError: The IndexMap specifying pad_value has "
<< pad_value_->final_indices.size() << " outputs, should only have one output";
return ss.str();
}
String DetailRenderTemplate() const final {
std::ostringstream ss;
ss << "ScheduleError: Pad value is specified as " << pad_value_ << " which has "
<< pad_value_->final_indices.size() << " outputs, but should only have one output";
return ss.str();
}
IRModule mod() const final { return mod_; }
Array<ObjectRef> LocationsOfInterest() const final { return {}; }
private:
IRModule mod_;
IndexMap pad_value_;
};
class TransformationPaddingTypeError : public ScheduleError {
public:
TransformationPaddingTypeError(IRModule mod, Buffer buffer, IndexMap pad_value)
: mod_(mod), buffer_(buffer), pad_value_(pad_value) {
ICHECK_EQ(pad_value_->final_indices.size(), 1);
pad_value_dtype_ = pad_value_->final_indices[0].dtype();
}
String FastErrorString() const final {
std::ostringstream ss;
ss << "ScheduleError: Type mismatch " << buffer_->dtype << " vs " << pad_value_dtype_;
return ss.str();
}
String DetailRenderTemplate() const final {
std::ostringstream ss;
ss << "ScheduleError: Buffer " << buffer_->name << " has elements of type " << buffer_->dtype
<< ", but the transformation fills padding with " << pad_value_ << ", which is of type "
<< pad_value_dtype_;
return ss.str();
}
IRModule mod() const final { return mod_; }
Array<ObjectRef> LocationsOfInterest() const final { return {}; }