-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathtvmscript_printer.cc
1911 lines (1768 loc) · 67.3 KB
/
tvmscript_printer.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.
*/
/*!
* \file printer/tvmscript_printer.cc
* \brief Printer class to print Tensor IR to python syntax script
*/
#include <tvm/arith/analyzer.h>
#include <tvm/ir/module.h>
#include <tvm/node/serialization.h>
#include <tvm/runtime/registry.h>
#include <tvm/target/target.h>
#include <tvm/tir/analysis.h>
#include <tvm/tir/buffer.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/expr_functor.h>
#include <tvm/tir/function.h>
#include <tvm/tir/op.h>
#include <tvm/tir/stmt.h>
#include <tvm/tir/stmt_functor.h>
#include <algorithm>
#include <utility>
#include "../tir/transforms/ir_utils.h"
#include "doc.h"
#include "meta_data.h"
#include "text_printer.h"
namespace tvm {
namespace tir {
enum class ExprPrecedence : int {
/*! \brief Identity(e.g., IntImm, Var) and function call(e.g., floordiv, min) */
kIdentity = 0,
/*!
* \brief Multiplication(*), division(/), and remainder(%)
* \note floorDiv, floorMod is marked as kIdentity since they are function calls.
*/
kMultiplicationDivision = 1,
/*! \brief Addition(+) and subtraction(-) */
kAdditionSubtraction = 2,
/*! \brief For relational operators < and <= and > and >= respectively */
kRelational = 3,
/*! \brief For equality operators = and != respectively */
kEquality = 4,
/*! \brief And(&&) */
kAnd = 5,
/*! \brief Or(||) */
kOr = 6,
/*! \brief Unknown precedence */
kUnknown = 7,
};
/*! \brief Utility used for identifying usage of a buffer_var
*
* \details Find the Buffer object that corresponds to a variable or
* allocation, based on the BufferLoad/BufferStore instances that
* occur within the allocation's body.
*/
class BufferUsageFinder : public StmtExprVisitor {
public:
static Map<Var, Array<Buffer>> FindUsage(Map<Var, Array<Buffer>> usage, Stmt body) {
BufferUsageFinder visitor(std::move(usage));
visitor.VisitStmt(body);
return std::move(visitor.usage_);
}
void VisitExpr_(const VarNode* op) final {
Var var = GetRef<Var>(op);
if (!usage_.count(var)) {
usage_.Set(var, {});
}
}
void VisitExpr_(const BufferLoadNode* op) final {
VisitBuffer(op->buffer);
StmtExprVisitor::VisitExpr_(op);
}
void VisitStmt_(const BufferStoreNode* op) final {
VisitBuffer(op->buffer);
StmtExprVisitor::VisitStmt_(op);
}
private:
explicit BufferUsageFinder(Map<Var, Array<Buffer>> usage) : usage_(usage) {}
void VisitBuffer(const Buffer& buffer) {
if (buffers_visited_.count(buffer.get())) {
return;
}
buffers_visited_.insert(buffer.get());
Array<Buffer> arr = usage_.Get(buffer->data).value_or({});
arr.push_back(buffer);
usage_.Set(buffer->data, arr);
}
// The search result.
Map<Var, Array<Buffer>> usage_;
// The buffers that have been visited so far, to avoid duplicate
// entries in the search result.
std::unordered_set<const BufferNode*> buffers_visited_;
};
/*!
* \brief The printer for TVMScript
* \details The printer obtain the precedence of the top-level operation when printing each
* subexpression to decide whether or not parentheses is needed.
*/
class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
public ExprFunctor<Doc(const PrimExpr&, ExprPrecedence*)>,
public TypeFunctor<Doc(const Type&)> {
public:
explicit TVMScriptPrinter(const String& tir_prefix, bool show_meta,
runtime::TypedPackedFunc<std::string(Stmt)> annotate = nullptr)
: tir_prefix_(tir_prefix),
show_meta_(show_meta),
annotate_(std::move(annotate)),
meta_collector_(&meta_) {}
/*!
* \brief Print the node.
* \param node The node to be printed.
* \param out_precedence The operator precedence of node if it's a PrimExpr,
* so we can simplify the bracket.
*/
TVM_DLL Doc Print(const ObjectRef& node);
protected:
/*! \brief The tir prefix */
String tir_prefix_;
/*! \brief whether show meta data */
bool show_meta_;
/*! \brief additional comment function */
runtime::TypedPackedFunc<std::string(Stmt)> annotate_;
/*! \brief meta data context */
TextMetaDataContext meta_;
/*! \brief meta collector */
MetaCollector meta_collector_;
/*! \brief map from Function to GlobalVar */
std::unordered_map<const BaseFuncNode*, GlobalVar> func2var_;
/*! \brief var collector (var defined by For/Loop/Block) */
std::unordered_set<const VarNode*> var_not_in_headers_;
/*!
* \brief buffer collector
* (buffer defined in BufferMap, BufferAllocation and MatchBufferRegion)
*/
std::unordered_set<const BufferNode*> buf_not_in_headers_;
/*! \brief Map from Var to thread env name */
std::unordered_map<Var, String, ObjectPtrHash, ObjectPtrEqual> var_env_map_;
/*! \brief Map from Var to Doc */
std::unordered_map<Var, Doc, ObjectPtrHash, ObjectPtrEqual> memo_var_;
/*! \brief Map from Buffer to Doc */
std::unordered_map<Buffer, Doc, ObjectPtrHash, ObjectPtrEqual> memo_buf_;
/*! \brief Map from Buffer to Declaration Doc */
std::unordered_map<Buffer, Doc, ObjectPtrHash, ObjectPtrEqual> memo_buf_decl_;
/*! \brief name allocation map */
std::unordered_map<std::string, int> name_alloc_map_;
/*! \brief number of children of current node's parent */
int num_child_;
/*! \brief the number of current node */
int current_num_;
/*! \brief loop stack without annotations */
std::vector<For> simple_loop_stack_;
/*! \brief the maps from loop_vars to the loops */
std::unordered_map<const VarNode*, For> loop_var_map_;
/*!
* \brief simple block vars remap from loop vars
* simple_remap requires:
* 1. block var iter type is kDataPar or kCommReduce
* 2. value is a single Var, which is a loop_var outside the block
* 3. The iter range is equal to loop range
*/
std::vector<std::pair<IterVar, PrimExpr>> block_var_remaps_;
/*!
* \brief Map from variables to the buffers they are used in.
*
* Used for identifying buffers that should be declared after the
* LetStmt or Allocate that generates their data pointer, rather
* than in the header.
*/
Map<Var, Array<Buffer>> buffer_var_usage_;
/*! \brief Analyzer to simplify some expressions. */
arith::Analyzer ana_;
Doc VisitExpr_(const CastNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const VarNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const AddNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const SubNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const MulNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const DivNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const ModNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const FloorDivNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const FloorModNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const MinNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const MaxNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const EQNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const NENode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const LTNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const LENode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const GTNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const GENode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const AndNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const OrNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const NotNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const SelectNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const IntImmNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const FloatImmNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const StringImmNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const ProducerLoadNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const BufferLoadNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const LoadNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const RampNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const BroadcastNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const LetNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const CallNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const ShuffleNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExpr_(const ReduceNode* op, ExprPrecedence* out_precedence) override;
Doc VisitExprDefault_(const Object* op, ExprPrecedence* out_precedence) override;
Doc VisitStmt_(const LetStmtNode* op) override;
Doc VisitStmt_(const AttrStmtNode* op) override;
Doc VisitStmt_(const AssertStmtNode* op) override;
Doc VisitStmt_(const StoreNode* op) override;
Doc VisitStmt_(const BufferStoreNode* op) override;
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Doc VisitStmt_(const WhileNode* op) override;
Doc VisitStmt_(const PrefetchNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Doc VisitStmt_(const BlockRealizeNode* op) override;
Doc VisitStmtDefault_(const Object* op) override;
Doc VisitType_(const PrimTypeNode* node) override;
Doc VisitType_(const PointerTypeNode* node) override;
Doc VisitType_(const TupleTypeNode* node) override;
Doc PrintBody(const Stmt& body);
Doc PrintIRModule(const IRModule& module);
Doc PrintPrimFunc(const PrimFunc& primFunc);
Doc PrintIterVar(const IterVarNode* op);
Doc PrintRange(const RangeNode* op);
Doc PrintArray(const ArrayNode* op);
Doc PrintBuffer(const BufferNode* op);
Doc PrintBufferIndices(const Array<PrimExpr>& indices);
Doc PrintNonHeaderBufferDeclarations(const Array<Buffer>& aliasing_buffers);
Doc AllocBufferDeclaration(const Buffer& buf);
Doc PrintBlockVar(const IterVar& iter_var, const PrimExpr& value);
Doc PrintBlockVarRemaps();
Doc PrintBlockVars(const BlockRealizeNode* op);
Doc PrintBlockAttr(const BlockRealizeNode* op);
Doc PrintExpandedArray(const ArrayNode* op);
Doc PrintBlockBody(const BlockNode* op);
virtual Doc PrintBlockName(const BlockNode* block_op);
Doc PrintBufferRegion(const BufferRegionNode* op);
Doc PrintMatchBufferRegion(const MatchBufferRegionNode* op);
Doc PrintCommReducer(const CommReducerNode* op);
Doc PrintAnnotations(const Map<String, ObjectRef>& annotations);
Doc PrintTarget(const TargetNode* target);
static Doc PrintString(const StringObj* op) { return Doc::StrLiteral(op->data); }
Doc GetUniqueName(std::string prefix);
Doc AllocVar(const Var& var);
Doc AllocBuf(const Buffer& buffer);
void TryDeallocVar(const Var& var);
bool ContainsOptionalInfo(const Stmt& stmt);
/*!
* \brief Check if a buffer declaration satisfies:
* 1. has only 'shape' and 'dtype' arguments specified,
* 2. the shape and strides are not dynamic.
* \param buffer The match buffer to be checked
*/
bool IsSimpleBuffer(const Buffer& buffer);
Doc PrintInlineBufferBind(const Buffer& buffer);
Doc PrintTuple(const ArrayNode* op);
/*! Helper functions for loop printing. */
/*!
* \brief Print a single for loop
* \param loop The for loop to be printed
*/
virtual Doc PrintLoop(const For& loop);
/*! \brief Print all simple loops in stack into one line using tir_prefix_.grid(). */
Doc PrintLoopStack();
/*!
* \brief Check whether a loop satisfies:
* 1. the loop is serial;
* 2. the loop has no annotation;
* 3. the loop starts from 0;
* 4. there is no optional information.
* \param for_op the for node to be checked
* \return A boolean indicating whether the input loop satisfies the above conditions
*/
bool IsSimpleLoop(const ForNode* for_op) {
return for_op->kind == ForKind::kSerial && for_op->annotations.empty() &&
is_zero(for_op->min) && !ContainsOptionalInfo(GetRef<Stmt>(for_op));
}
/*!
* \brief Check whether the `min` or `extent` of a loop depends on previous loops
* \param for_op The loop to be checked
* \return A boolean indicating whether the input loop depends on previous loops
*/
bool DependOnPrevLoops(const ForNode* for_op) {
auto f_check = [&var_map = this->loop_var_map_](const VarNode* v) { return var_map.count(v); };
return UsesVar(for_op->min, f_check) || UsesVar(for_op->extent, f_check);
}
/*!
* \brief Print additional info about expr in comment.
* \param expr The expression.
*/
Doc PrintOptionalInfo(const Stmt& stmt) {
Doc doc;
// default annotations
if (ContainsOptionalInfo(stmt)) {
std::string annotated_stmt = annotate_(stmt);
doc << "# " << annotated_stmt << Doc::NewLine();
}
return doc;
}
/*!
* \brief special method to render vectors of docs with a separator
* \param vec vector of docs
* \param sep separator
*/
static Doc PrintSep(const std::vector<Doc>& vec, const Doc& sep) {
Doc seq;
if (vec.size() != 0) {
seq = vec[0];
for (size_t i = 1; i < vec.size(); i++) {
seq << sep << vec[i];
}
}
return seq;
}
/*!
* \brief dump meta info
* \return Doc with meta info
*/
Doc DumpMeta() {
if (show_meta_) {
return Doc::Text("__tvm_meta__ = ")
<< (meta_.empty() ? Doc::Text("None") : meta_.GetMetaSection());
} else {
return Doc::Text("");
}
}
/*!
* \brief special method to print out data type
* \param dtype The data type
*/
static Doc PrintDType(DataType dtype) {
return Doc::StrLiteral(runtime::DLDataType2String(dtype));
}
/*!
* \brief special method to print out const scalar
* \param dtype The data type
* \param data The pointer to hold the data.
*/
template <typename T>
Doc PrintConstScalar(DataType dtype, const T* data) const {
Doc doc;
std::ostringstream os;
if (dtype.is_float() || dtype.is_float16() || dtype.is_bfloat16()) {
os.precision(17);
}
os << data[0];
if (dtype == DataType::Int(32)) {
doc << Doc::Text(os.str());
} else if (dtype == DataType::Bool()) {
doc << Doc::Text(data[0] ? "True" : "False");
} else {
doc << tir_prefix_ << "." << runtime::DLDataType2String(dtype) << "(" << Doc::Text(os.str())
<< ")";
}
return doc;
}
public:
static Doc PrintHeader(const std::string& tir_prefix) {
Doc header;
if (tir_prefix != "tir") {
header << "# from tvm.script import tir as " << tir_prefix << Doc::NewLine();
} else {
header << "# from tvm.script import tir" << Doc::NewLine();
}
return header;
}
};
/*!
* \brief special method to print NDArray in TIR
* \param arr the NDArray to be printed
* \param os the output stream where the NDArray will be printed to
*/
template <typename T>
void NDArrayToTIR(::tvm::runtime::NDArray arr, std::ostream& os) {
int ndim = arr->ndim;
int tot_dim = 1;
for (int i = 0; i < ndim; i++) {
tot_dim *= arr->shape[i];
}
T* data_ptr = reinterpret_cast<T*>(arr->data);
os << "[";
for (int i = 0; i < tot_dim; i++) {
os << (i != 0 ? ", " : "") << data_ptr[i];
}
os << "]";
}
Doc TVMScriptPrinter::GetUniqueName(std::string prefix) {
std::replace(prefix.begin(), prefix.end(), '.', '_');
std::string unique_prefix = prefix;
auto it = name_alloc_map_.find(prefix);
if (it != name_alloc_map_.end() && it->second >= 0) {
while (name_alloc_map_.count(unique_prefix = prefix + "_" + std::to_string(++it->second)) > 0) {
}
}
name_alloc_map_[unique_prefix] = 0;
return Doc::Text(unique_prefix);
}
Doc TVMScriptPrinter::AllocVar(const Var& var) {
const auto& it = memo_var_.find(var);
if (it != memo_var_.end()) {
return it->second;
}
std::string name = var->name_hint.operator std::string();
if (name.length() == 0 || !std::isalpha(name[0])) {
name = "v" + name;
}
Doc val = GetUniqueName(name);
memo_var_[var] = val;
return val;
}
Doc TVMScriptPrinter::AllocBufferDeclaration(const Buffer& buf) {
Doc doc = Print(buf->shape);
bool print_factor_explicitly = false;
doc << ", dtype=" << PrintDType(buf->dtype);
if (memo_var_.find(buf->data) != memo_var_.end()) {
doc << ", data=" << Print(buf->data);
} else {
// implicitly define data
memo_var_[buf->data] = Doc::Text(memo_buf_[buf].str() + ".data");
var_not_in_headers_.insert(buf->data.get());
}
if (!buf->strides.empty()) {
doc << ", strides=" << Print(buf->strides);
}
if (buf->elem_offset->IsInstance<VarNode>()) {
Var elem_offset = Downcast<Var>(buf->elem_offset);
if (memo_var_.find(elem_offset) != memo_var_.end()) {
doc << ", elem_offset=" << Print(buf->elem_offset);
} else {
// implicitly define elem_offset
memo_var_[elem_offset] = Doc::Text(memo_buf_[buf].str() + ".elem_offset");
var_not_in_headers_.insert(elem_offset.get());
print_factor_explicitly = true;
}
} else if (buf->elem_offset->IsInstance<IntImmNode>()) {
IntImm elem_offset = Downcast<IntImm>(buf->elem_offset);
if (elem_offset->value != 0) {
doc << ", elem_offset=" << Print(buf->elem_offset);
}
}
if (buf.scope() != "global") {
doc << ", scope=" << Doc::StrLiteral(buf.scope());
}
if (buf->data_alignment != runtime::kAllocAlignment) {
doc << ", align=" << buf->data_alignment;
}
if (buf->offset_factor != 1 || print_factor_explicitly) {
doc << ", offset_factor=" << buf->offset_factor;
}
if (buf->buffer_type != BufferType::kDefault) {
doc << ", type=" << Doc::StrLiteral("auto");
}
if (buf->axis_separators.size()) {
doc << ", axis_separators=" << Print(buf->axis_separators);
}
return doc;
}
Doc TVMScriptPrinter::AllocBuf(const Buffer& buffer) {
const auto& it = memo_buf_.find(buffer);
if (it != memo_buf_.end()) {
return it->second;
}
std::string name = buffer->name;
if (name.length() == 0 || !std::isalpha(name[0])) {
name = "buf_" + name;
}
Doc val = GetUniqueName(name);
memo_buf_[buffer] = val;
memo_buf_decl_[buffer] = AllocBufferDeclaration(buffer);
return val;
}
/*!
* \brief Check if any optional information exists in annotate_ for
* a given Stmt.
* \param stmt The statement.
*/
bool TVMScriptPrinter::ContainsOptionalInfo(const Stmt& stmt) {
if (annotate_ == nullptr) return false;
return !annotate_(stmt).empty();
}
/*!
* \brief Try to dealloc vars out of space and leave the index to coming vars.
* \note It is not a necessary step.
*/
void TVMScriptPrinter::TryDeallocVar(const Var& var) {
auto it = memo_var_.find(var);
ICHECK(it != memo_var_.end());
std::string print_name = it->second.str();
std::string name_hint = var->name_hint.operator std::string();
if (name_hint.length() == 0 || !std::isalpha(name_hint[0])) {
name_hint = "v" + name_hint;
}
std::replace(name_hint.begin(), name_hint.end(), '.', '_');
auto it2 = name_alloc_map_.find(name_hint);
// Skip it if we can not find the name_hint in name_alloc_map_.
if (it2 == name_alloc_map_.end()) return;
if (it2->second > 0) {
name_hint = name_hint + '_' + std::to_string(it2->second);
}
// Skip it if the name_hint is not equal to how it should be printed.
if (name_hint != print_name) return;
// Free the conresponding name_alloc_map_ index
--it2->second;
}
Doc TVMScriptPrinter::PrintMatchBufferRegion(const MatchBufferRegionNode* op) {
const Buffer& buf = op->buffer;
buf_not_in_headers_.insert(buf.get());
Doc doc = Print(op->buffer) << " = " << tir_prefix_ << ".match_buffer(" << Print(op->source)
<< ", " << memo_buf_decl_[op->buffer] << ")";
return doc;
}
// check if all arguments, except the first two, are specified for T.match_buffer
// if not, then this match buffer is printed out as T.buffer in prim_func arguments
// and check whether there are undefined variables in the shape/strides.
bool TVMScriptPrinter::IsSimpleBuffer(const Buffer& buf) {
if (memo_var_.find(buf->data) != memo_var_.end()) {
return false;
}
if (!buf->strides.empty()) {
return false;
}
for (const PrimExpr& shp_i : buf->shape) {
if (!UndefinedVars(shp_i).empty()) {
return false;
}
}
for (const PrimExpr& stride_i : buf->strides) {
if (!UndefinedVars(stride_i).empty()) {
return false;
}
}
if (!UndefinedVars(buf->elem_offset).empty()) {
return false;
} else if (buf->elem_offset->IsInstance<IntImmNode>()) {
IntImm elem_offset = Downcast<IntImm>(buf->elem_offset);
if (elem_offset->value != 0) {
return false;
}
}
if (buf.scope() != "global") {
return false;
}
if (buf->data_alignment != runtime::kAllocAlignment) {
return false;
}
if (buf->offset_factor != 1) {
return false;
}
if (buf->buffer_type != BufferType::kDefault) {
return false;
}
if (buf->axis_separators.size()) {
return false;
}
return true;
}
Doc TVMScriptPrinter::PrintInlineBufferBind(const Buffer& buffer) {
Doc doc;
doc << tir_prefix_ << ".Buffer[";
if (buffer->shape.size() == 1) {
doc << Print(buffer->shape[0]);
} else {
doc << PrintTuple(buffer->shape.as<ArrayNode>());
}
doc << ", " << PrintDType(buffer->dtype) << "]";
return doc;
}
// print array out as tuple with parentheses
Doc TVMScriptPrinter::PrintTuple(const ArrayNode* op) {
Doc doc;
doc << '(';
for (size_t i = 0; i < op->size(); ++i) {
if (i != 0) {
doc << ", ";
}
doc << Print(op->at(i));
}
if (op->size() == 1) doc << ",";
doc << ')';
return doc;
}
Doc TVMScriptPrinter::PrintCommReducer(const CommReducerNode* op) {
Doc doc;
int n_var = static_cast<int>(op->rhs.size());
doc << tir_prefix_ << ".comm_reducer(lambda ";
for (const Var& v_lhs : op->lhs) {
doc << Print(v_lhs) << ", ";
}
for (int i = 0; i < n_var; ++i) {
doc << Print(op->rhs[i]) << (i == n_var - 1 ? ": " : ", ");
}
if (n_var == 1) {
doc << Print(op->result[0]) << ", ";
} else {
doc << "(";
for (int i = 0; i < n_var; ++i) {
doc << Print(op->result[i]);
if (i != n_var - 1) {
doc << ", ";
}
}
doc << "), ";
}
doc << Print(op->identity_element) << ")";
// Remove the vars in `lhs` and `rhs`, because they are the parameters of the printed lambda.
for (int i = 0; i < n_var; ++i) {
memo_var_.erase(op->lhs[i]);
memo_var_.erase(op->rhs[i]);
}
return doc;
}
Doc TVMScriptPrinter::Print(const ObjectRef& node) {
if (!node.defined()) return Doc::Text("None");
if (node->IsInstance<StmtNode>()) {
return PrintOptionalInfo(Downcast<Stmt>(node)) << VisitStmt(Downcast<Stmt>(node));
} else if (node->IsInstance<PrimExprNode>()) {
ExprPrecedence t = ExprPrecedence::kUnknown;
return VisitExpr(Downcast<PrimExpr>(node), &t);
} else if (node->IsInstance<TypeNode>()) {
return VisitType(Downcast<Type>(node));
} else if (node->IsInstance<PrimFuncNode>()) {
return PrintPrimFunc(Downcast<PrimFunc>(node));
} else if (node->IsInstance<IRModuleNode>()) {
return PrintIRModule(Downcast<IRModule>(node));
} else if (node->IsInstance<ArrayNode>()) {
return PrintArray(node.as<ArrayNode>());
} else if (node->IsInstance<BufferNode>()) {
return PrintBuffer(node.as<BufferNode>());
} else if (node->IsInstance<StringObj>()) {
return PrintString(node.as<StringObj>());
} else if (node->IsInstance<IterVarNode>()) {
return PrintIterVar(node.as<IterVarNode>());
} else if (node->IsInstance<RangeNode>()) {
return PrintRange(node.as<RangeNode>());
} else if (node->IsInstance<BufferRegionNode>()) {
return PrintBufferRegion(node.as<BufferRegionNode>());
} else if (node->IsInstance<MatchBufferRegionNode>()) {
return PrintMatchBufferRegion(node.as<MatchBufferRegionNode>());
} else if (node->IsInstance<CommReducerNode>()) {
return PrintCommReducer(node.as<CommReducerNode>());
} else if (node->IsInstance<TargetNode>()) {
return PrintTarget(node.as<TargetNode>());
} else {
LOG(FATAL) << "Do not know how to print " << node->GetTypeKey();
return Doc();
}
}
Doc TVMScriptPrinter::VisitExprDefault_(const Object* op, ExprPrecedence* out_precedence) {
LOG(FATAL) << "Do not know how to print " << op->GetTypeKey();
return Doc();
}
Doc TVMScriptPrinter::VisitStmtDefault_(const Object* op) {
LOG(FATAL) << "Do not know how to print " << op->GetTypeKey();
return Doc();
}
Doc TVMScriptPrinter::VisitExpr_(const IntImmNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
return PrintConstScalar<int64_t>(op->dtype, &(op->value));
}
Doc TVMScriptPrinter::VisitExpr_(const FloatImmNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
return PrintConstScalar<double>(op->dtype, &(op->value));
}
Doc TVMScriptPrinter::VisitExpr_(const StringImmNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
return Doc::StrLiteral(op->value);
}
Doc TVMScriptPrinter::VisitExpr_(const CastNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".cast(" << Print(op->value) << ", " << PrintDType(op->dtype) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const VarNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
const Var& var = GetRef<Var>(op);
return meta_.InMeta(var) ? meta_.GetMetaNode(var) : AllocVar(GetRef<Var>(op));
}
#define TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(OpName, OpString, OpPrecedence) \
Doc TVMScriptPrinter::VisitExpr_(const OpName* op, ExprPrecedence* out_precedence) { \
Doc doc; \
ExprPrecedence lhs_precedence = ExprPrecedence::kUnknown; \
ExprPrecedence rhs_precedence = ExprPrecedence::kUnknown; \
/* Get children expr out_precedence */ \
Doc lhs_doc = VisitExpr(op->a, &lhs_precedence); \
Doc rhs_doc = VisitExpr(op->b, &rhs_precedence); \
ICHECK(lhs_precedence != ExprPrecedence::kUnknown); \
ICHECK(rhs_precedence != ExprPrecedence::kUnknown); \
/* Update out_precedence of current node. */ \
*out_precedence = OpPrecedence; \
if (lhs_precedence > OpPrecedence) { \
doc << "(" << lhs_doc << ")"; \
} else { \
doc << lhs_doc; \
} \
doc << OpString; \
if (rhs_precedence >= OpPrecedence) { \
doc << "(" << rhs_doc << ")"; \
} else { \
doc << rhs_doc; \
} \
return doc; \
}
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(MulNode, " * ", ExprPrecedence::kMultiplicationDivision)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(DivNode, " / ", ExprPrecedence::kMultiplicationDivision)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(FloorDivNode, " // ", ExprPrecedence::kMultiplicationDivision)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(FloorModNode, " % ", ExprPrecedence::kMultiplicationDivision)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(AddNode, " + ", ExprPrecedence::kAdditionSubtraction)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(SubNode, " - ", ExprPrecedence::kAdditionSubtraction)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(LTNode, " < ", ExprPrecedence::kRelational)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(LENode, " <= ", ExprPrecedence::kRelational)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(GTNode, " > ", ExprPrecedence::kRelational)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(GENode, " >= ", ExprPrecedence::kRelational)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(EQNode, " == ", ExprPrecedence::kEquality)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(NENode, " != ", ExprPrecedence::kEquality)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(AndNode, " and ", ExprPrecedence::kAnd)
TVM_DECLARE_TVMSCRIPT_PRINTER_BINOP(OrNode, " or ", ExprPrecedence::kOr)
Doc TVMScriptPrinter::VisitExpr_(const ModNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".truncmod(" << Print(op->a) << ", " << Print(op->b) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const MinNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".min(" << Print(op->a) << ", " << Print(op->b) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const MaxNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".max(" << Print(op->a) << ", " << Print(op->b) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const NotNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << "not(" << Print(op->a) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const SelectNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".Select(" << Print(op->condition) << ", " << Print(op->true_value) << ", "
<< Print(op->false_value) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const ProducerLoadNode* op, ExprPrecedence* out_precedence) {
LOG(FATAL) << "Cannot print a tir.ProducerLoad as it is not valid in TIR Primfuncs. You need to "
"lower this function first.";
return Doc();
}
Doc TVMScriptPrinter::VisitExpr_(const BufferLoadNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
if (op->indices.size() == 0) {
doc << Print(op->buffer) << "[()]";
} else {
doc << Print(op->buffer) << PrintBufferIndices(op->indices);
}
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const LoadNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
if (op->dtype == DataType::Float(32) && is_one(op->predicate) &&
op->buffer_var->dtype == DataType::Float(32)) {
doc << Print(op->buffer_var) << "[" << Print(op->index) << "]";
} else {
doc << tir_prefix_ << ".load(" << PrintDType(op->dtype) << ", " << Print(op->buffer_var) << ", "
<< Print(op->index);
if (!is_one(op->predicate) || op->dtype.lanes() != 1) {
doc << ", " << Print(op->predicate);
}
doc << ")";
}
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const RampNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".ramp(" << Print(op->base) << ", " << Print(op->stride) << ", "
<< op->lanes << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const BroadcastNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".broadcast(" << Print(op->value) << ", " << op->lanes << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const LetNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".let(" << Print(op->var) << ", " << Print(op->value) << ", "
<< Print(op->body) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const CallNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
if (auto* ptr_op = op->op.as<OpNode>()) {
std::string name = ptr_op->name;
if (name.find("tir.") == 0) {
name = tir_prefix_ + "." + name.substr(4);
}
doc << name << "(";
} else {
auto* op_gvar = op->op.as<GlobalVarNode>();
ICHECK(op_gvar != nullptr);
doc << Doc::Text(op_gvar->name_hint) << "(";
}
std::vector<Doc> args;
for (const auto& arg : op->args) {
args.push_back(Print(arg));
}
args.push_back(Doc::Text("dtype=") << PrintDType(op->dtype));
doc << PrintSep(args, Doc::Text(", ")) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const ShuffleNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".shuffle(" << Print(op->vectors) << ", " << Print(op->indices) << ")";
return doc;
}
Doc TVMScriptPrinter::VisitExpr_(const ReduceNode* op, ExprPrecedence* out_precedence) {
*out_precedence = ExprPrecedence::kIdentity;
Doc doc;
doc << tir_prefix_ << ".reduce(" << Print(op->combiner) << ", " << Print(op->source) << ", "
<< Print(op->axis) << ", " << op->value_index << ")";
return doc;
}
Doc TVMScriptPrinter::VisitStmt_(const LetStmtNode* op) {
if (!buffer_var_usage_.count(op->var)) {
buffer_var_usage_ = BufferUsageFinder::FindUsage(std::move(buffer_var_usage_), op->body);
}
Array<Buffer> buffer_usage = buffer_var_usage_.Get(op->var).value_or({});
Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << tir_prefix_ << ".let(" << Print(op->var) << ", " << Print(op->value) << "):";
doc << Doc::Indent(
4, Doc::NewLine() << PrintNonHeaderBufferDeclarations(buffer_usage) << PrintBody(op->body));
} else {
if (memo_var_.find(op->var) == memo_var_.end()) var_not_in_headers_.insert(op->var.get());
doc << Print(op->var) << ": " << Print(GetType(op->var)) << " = " << Print(op->value)
<< Doc::NewLine();
doc << PrintNonHeaderBufferDeclarations(buffer_usage) << PrintBody(op->body);
}
return doc;
}
Doc TVMScriptPrinter::VisitStmt_(const AttrStmtNode* op) {
Doc doc;
if (op->node.defined()) {
// merge attr with realize when possible
if (op->node->IsInstance<BufferNode>() && op->attr_key == "realize_scope" &&
op->body->IsInstance<BufferRealizeNode>()) {
const auto* realize = Downcast<BufferRealize>(op->body).get();
if (realize->buffer.same_as(op->node)) {
if (current_num_ != num_child_ - 1) {
doc << "with " << tir_prefix_ << ".realize(" << Print(realize->buffer)
<< Print(realize->bounds) << ", " << Print(op->value);
if (!is_one(realize->condition)) {
doc << ", " << Print(realize->condition);
}
doc << "):" << Doc::Indent(4, Doc::NewLine() << PrintBody(realize->body));
} else {
doc << tir_prefix_ << ".realize(" << Print(realize->buffer) << Print(realize->bounds)
<< ", " << Print(op->value);
if (!is_one(realize->condition)) {
doc << ", " << Print(realize->condition);
}
doc << ")" << Doc::NewLine() << PrintBody(realize->body);
}
return doc;
}
}
// concise thread env
if (op->node->IsInstance<IterVarNode>() &&
(op->attr_key == "thread_extent" || op->attr_key == "virtual_thread")) {
const auto* iter_var = Downcast<IterVar>(op->node).get();
var_not_in_headers_.insert(iter_var->var.get());
var_env_map_[iter_var->var] = iter_var->thread_tag;
if (current_num_ != num_child_ - 1) {
doc << "with " << tir_prefix_ << ".launch_thread(" << Print(iter_var->var) << ", "
<< Print(op->value) << "):";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << tir_prefix_ << ".launch_thread(" << Print(iter_var->var) << ", " << Print(op->value)
<< ")";
doc << Doc::NewLine() << PrintBody(op->body);
}
TryDeallocVar(iter_var->var);
return doc;
}
}
// default
if (current_num_ != num_child_ - 1) {
doc << "with " << tir_prefix_ << ".attr(" << Print(op->node) << ", "
<< Doc::StrLiteral(op->attr_key) << ", " << Print(op->value) << "):";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << tir_prefix_ << ".attr(" << Print(op->node) << ", " << Doc::StrLiteral(op->attr_key)
<< ", " << Print(op->value) << ")";
doc << Doc::NewLine() << PrintBody(op->body);