-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathfrontend_ir.cpp
More file actions
1677 lines (1471 loc) · 64.2 KB
/
Copy pathfrontend_ir.cpp
File metadata and controls
1677 lines (1471 loc) · 64.2 KB
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
#include "quadrants/ir/frontend_ir.h"
#include "quadrants/ir/expression_printer.h"
#include "quadrants/ir/statements.h"
#include "quadrants/program/program.h"
#include "quadrants/common/exceptions.h"
#include <numeric>
namespace quadrants::lang {
#define QD_ASSERT_TYPE_CHECKED(x) \
do { \
if (x->ret_type == PrimitiveType::unknown) { \
ErrorEmitter(QuadrantsTypeError(), x.expr.get(), \
fmt::format("[{}] was not type-checked", ExpressionHumanFriendlyPrinter::expr_to_string(x))); \
} \
} while (false)
static bool is_primitive_or_tensor_type(DataType &type) {
return type->is<PrimitiveType>() || type->is<TensorType>();
}
FrontendSNodeOpStmt::FrontendSNodeOpStmt(SNodeOpType op_type,
SNode *snode,
const ExprGroup &indices,
const Expr &val,
const DebugInfo &dbg_info)
: Stmt(dbg_info), op_type(op_type), snode(snode), indices(indices), val(val) {
if (val.expr != nullptr) {
QD_ASSERT(op_type == SNodeOpType::append);
} else {
QD_ASSERT(op_type != SNodeOpType::append);
}
}
FrontendReturnStmt::FrontendReturnStmt(const ExprGroup &group, const DebugInfo &dbg_info)
: Stmt(dbg_info), values(group) {
}
FrontendAssignStmt::FrontendAssignStmt(const Expr &lhs, const Expr &rhs, const DebugInfo &dbg_info)
: Stmt(dbg_info), lhs(lhs), rhs(rhs) {
QD_ASSERT(lhs->is_lvalue());
if (lhs.is<IdExpression>() && lhs->ret_type == PrimitiveType::unknown) {
lhs.expr->ret_type = TypeFactory::get_instance().get_pointer_type(rhs.get_rvalue_type());
}
}
FrontendIfStmt::FrontendIfStmt(const FrontendIfStmt &o)
: Stmt(o.dbg_info),
condition(o.condition),
true_statements(o.true_statements->clone()),
false_statements(o.false_statements->clone()) {
}
FrontendForStmt::FrontendForStmt(const ExprGroup &loop_vars,
SNode *snode,
Arch arch,
const ForLoopConfig &config,
const DebugInfo &dbg_info)
: Stmt(dbg_info), snode(snode) {
init_config(arch, config);
init_loop_vars(loop_vars);
}
FrontendForStmt::FrontendForStmt(const ExprGroup &loop_vars,
const Expr &external_tensor,
Arch arch,
const ForLoopConfig &config,
const DebugInfo &dbg_info)
: Stmt(dbg_info), external_tensor(external_tensor) {
init_config(arch, config);
init_loop_vars(loop_vars);
}
FrontendForStmt::FrontendForStmt(const ExprGroup &loop_vars,
const mesh::MeshPtr &mesh,
const mesh::MeshElementType &element_type,
Arch arch,
const ForLoopConfig &config,
const DebugInfo &dbg_info)
: Stmt(dbg_info), mesh(mesh.ptr.get()), element_type(element_type) {
init_config(arch, config);
init_loop_vars(loop_vars);
}
FrontendForStmt::FrontendForStmt(const Expr &loop_var,
const Expr &begin,
const Expr &end,
Arch arch,
const ForLoopConfig &config,
const DebugInfo &dbg_info)
: Stmt(dbg_info), begin(begin), end(end) {
init_config(arch, config);
add_loop_var(loop_var);
}
FrontendForStmt::FrontendForStmt(const FrontendForStmt &o)
: Stmt(o.dbg_info),
snode(o.snode),
external_tensor(o.external_tensor),
mesh(o.mesh),
element_type(o.element_type),
begin(o.begin),
end(o.end),
body(o.body->clone()),
loop_var_ids(o.loop_var_ids),
is_bit_vectorized(o.is_bit_vectorized),
num_cpu_threads(o.num_cpu_threads),
strictly_serialized(o.strictly_serialized),
mem_access_opt(o.mem_access_opt),
block_dim(o.block_dim),
stream_parallel_group_id(o.stream_parallel_group_id),
loop_name(o.loop_name) {
}
void FrontendForStmt::init_config(Arch arch, const ForLoopConfig &config) {
is_bit_vectorized = config.is_bit_vectorized;
strictly_serialized = config.strictly_serialized;
mem_access_opt = config.mem_access_opt;
block_dim = config.block_dim;
stream_parallel_group_id = config.stream_parallel_group_id;
loop_name = config.loop_name;
if (arch == Arch::cuda || arch == Arch::amdgpu) {
num_cpu_threads = 1;
QD_ASSERT(block_dim <= quadrants_max_gpu_block_dim);
} else { // cpu
if (config.num_cpu_threads == 0) {
num_cpu_threads = std::thread::hardware_concurrency();
} else {
num_cpu_threads = config.num_cpu_threads;
}
}
}
void FrontendForStmt::init_loop_vars(const ExprGroup &loop_vars) {
loop_var_ids.reserve(loop_vars.size());
for (int i = 0; i < (int)loop_vars.size(); i++) {
add_loop_var(loop_vars[i]);
}
}
void FrontendForStmt::add_loop_var(const Expr &loop_var) {
loop_var_ids.push_back(loop_var.cast<IdExpression>()->id);
loop_var.expr->ret_type = TypeFactory::get_instance().get_pointer_type(PrimitiveType::i32);
}
FrontendFuncDefStmt::FrontendFuncDefStmt(const FrontendFuncDefStmt &o) : funcid(o.funcid), body(o.body->clone()) {
}
FrontendWhileStmt::FrontendWhileStmt(const FrontendWhileStmt &o)
: Stmt(o.dbg_info), cond(o.cond), body(o.body->clone()) {
}
void ArgLoadExpression::type_check(const CompileConfig *) {
ret_type = dt;
if (is_ptr) {
ret_type = TypeFactory::get_instance().get_pointer_type(ret_type, false);
}
if (!create_load) {
ret_type = TypeFactory::get_instance().get_pointer_type(ret_type, false);
}
}
void ArgLoadExpression::flatten(FlattenContext *ctx) {
auto arg_load = std::make_unique<ArgLoadStmt>(arg_id, dt, is_ptr, create_load, dbg_info);
arg_load->ret_type = ret_type;
ctx->push_back(std::move(arg_load));
stmt = ctx->back_stmt();
}
void RandExpression::type_check(const CompileConfig *) {
if (!(dt->is<PrimitiveType>() && dt != PrimitiveType::unknown)) {
ErrorEmitter(QuadrantsTypeError(), this, fmt::format("Invalid dt [{}] for RandExpression", dt->to_string()));
}
ret_type = dt;
}
void RandExpression::flatten(FlattenContext *ctx) {
auto ran = std::make_unique<RandStmt>(dt, dbg_info);
ctx->push_back(std::move(ran));
stmt = ctx->back_stmt();
}
void UnaryOpExpression::type_check(const CompileConfig *config) {
QD_ASSERT_TYPE_CHECKED(operand);
QD_ASSERT(config != nullptr);
/*
Dtype inference for both TensorType and PrimitiveType are essentially
the same. Therefore we extract the primitive type to perform the type
inference, and then reconstruct the TensorType once neccessary.
*/
auto operand_type = operand.get_rvalue_type();
auto operand_primitive_type = operand_type.get_element_type();
auto ret_primitive_type = ret_type;
if (!operand_primitive_type->is<PrimitiveType>()) {
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("unsupported operand type(s) for '{}': '{}'", unary_op_type_name(type),
operand_primitive_type->to_string()));
}
if ((type == UnaryOpType::round || type == UnaryOpType::floor || type == UnaryOpType::ceil ||
is_trigonometric(type)) &&
!is_real(operand_primitive_type))
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("'{}' takes real inputs only, however '{}' is provided", unary_op_type_name(type),
operand_primitive_type->to_string()));
if ((type == UnaryOpType::sqrt || type == UnaryOpType::exp || type == UnaryOpType::log) &&
!is_real(operand_primitive_type)) {
ret_primitive_type = config->default_fp;
} else {
ret_primitive_type = is_cast() ? cast_type : operand_primitive_type;
}
if ((type == UnaryOpType::bit_not || type == UnaryOpType::logic_not) && is_real(operand_primitive_type)) {
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("'{}' takes integral inputs only, however '{}' is provided", unary_op_type_name(type),
operand_primitive_type->to_string()));
}
if (type == UnaryOpType::logic_not) {
ret_primitive_type = PrimitiveType::u1;
}
if (type == UnaryOpType::frexp) {
std::vector<AbstractDictionaryMember> elements;
QD_ASSERT(operand_primitive_type->is_primitive(PrimitiveTypeID::f32) ||
operand_primitive_type->is_primitive(PrimitiveTypeID::f64));
elements.push_back({operand_primitive_type, "mantissa", 0});
elements.push_back({quadrants::lang::TypeFactory::get_instance().get_primitive_int_type(32, /*is_signed=*/true),
"exponent", (size_t)data_type_size(operand_primitive_type)});
ret_type = quadrants::lang::TypeFactory::get_instance().get_struct_type(elements);
ret_type.set_is_pointer(true);
return;
}
if (type == UnaryOpType::popcnt && is_real(operand_primitive_type)) {
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("'{}' takes integral inputs only, however '{}' is provided", unary_op_type_name(type),
operand_primitive_type->to_string()));
}
if (operand_type->is<TensorType>()) {
ret_type =
quadrants::lang::TypeFactory::get_instance().get_tensor_type(operand_type.get_shape(), ret_primitive_type);
} else {
QD_ASSERT(operand_type->is<PrimitiveType>());
ret_type = ret_primitive_type;
}
}
bool UnaryOpExpression::is_cast() const {
return unary_op_is_cast(type);
}
void UnaryOpExpression::flatten(FlattenContext *ctx) {
auto operand_stmt = flatten_rvalue(operand, ctx);
auto unary = std::make_unique<UnaryOpStmt>(type, operand_stmt, operand_stmt->dbg_info);
if (is_cast()) {
unary->cast_type = cast_type;
}
stmt = unary.get();
stmt->ret_type = ret_type;
ctx->push_back(std::move(unary));
}
Expr to_broadcast_tensor(const Expr &elt, const DataType &dt) {
auto elt_type = elt.get_rvalue_type();
if (!elt_type->is<TensorType>() && !dt->is<TensorType>())
return elt;
if (elt_type->is<TensorType>() && dt->is<TensorType>()) {
// Only tensor shape will be checked here, since the dtype will
// be promoted later at irpass::type_check()
if (elt_type.get_shape() != dt.get_shape()) {
ErrorEmitter(QuadrantsTypeError(), elt.expr.get(), "Cannot broadcast tensor to tensor");
} else {
return elt;
}
}
auto tensor_type = dt->as<TensorType>();
auto tensor_elt_type = tensor_type->get_element_type();
if (!tensor_elt_type->is<PrimitiveType>()) {
ErrorEmitter(QuadrantsTypeError(), elt.expr.get(),
fmt::format("Only primitive types are supported in Tensors, got {}", tensor_elt_type->to_string()));
}
std::vector<Expr> broadcast_values(tensor_type->get_num_elements(), elt);
auto matrix_expr = Expr::make<MatrixExpression>(broadcast_values, tensor_type->get_shape(), elt_type, elt->dbg_info);
matrix_expr->type_check(nullptr);
return matrix_expr;
}
std::tuple<Expr, Expr> unify_binop_operands(const Expr &e1, const Expr &e2) {
auto e1_type = e1.get_rvalue_type();
auto e2_type = e2.get_rvalue_type();
if (e1_type->is<PrimitiveType>() && e2_type->is<TensorType>()) {
return std::tuple(to_broadcast_tensor(e1, e2_type), e2);
} else if (e1_type->is<TensorType>() && e2_type->is<PrimitiveType>()) {
return std::tuple(e1, to_broadcast_tensor(e2, e1_type));
} else {
return std::tuple(e1, e2);
}
}
void BinaryOpExpression::type_check(const CompileConfig *config) {
QD_ASSERT_TYPE_CHECKED(lhs);
QD_ASSERT_TYPE_CHECKED(rhs);
auto lhs_type = lhs.get_rvalue_type();
auto rhs_type = rhs.get_rvalue_type();
auto error = [&]() {
throw QuadrantsTypeError(fmt::format("unsupported operand type(s) for '{}': '{}' and '{}'",
binary_op_type_symbol(type), lhs_type->to_string(), rhs_type->to_string()));
};
if (!is_primitive_or_tensor_type(lhs_type) || !is_primitive_or_tensor_type(rhs_type)) {
error();
}
if ((lhs_type->is<PrimitiveType>() && rhs_type->is<TensorType>()) ||
(lhs_type->is<TensorType>() && rhs_type->is<PrimitiveType>())) {
// convert Tensor/Scalar | Scalar/Tensor operations to broadcasting
auto [unified_l, unified_r] = unify_binop_operands(lhs, rhs);
lhs = unified_l;
rhs = unified_r;
if (lhs_type == PrimitiveType::unknown)
lhs.type_check(config);
if (rhs_type == PrimitiveType::unknown)
rhs.type_check(config);
lhs_type = lhs.get_rvalue_type();
rhs_type = rhs.get_rvalue_type();
QD_ASSERT(lhs_type->is<TensorType>());
QD_ASSERT(rhs_type->is<TensorType>());
}
bool is_tensor_op = false;
if (lhs_type->is<TensorType>()) {
is_tensor_op = true;
auto rhs_tensor_type = rhs_type->cast<TensorType>();
if (rhs_tensor_type->get_shape() != lhs_type->cast<TensorType>()->get_shape())
// current assume element-wise binary op
error();
}
auto make_dt = [&is_tensor_op, lhs_type](DataType dt) {
if (is_tensor_op) {
return TypeFactory::create_tensor_type(lhs_type->cast<TensorType>()->get_shape(), dt);
} else {
return dt;
}
};
if (binary_is_bitwise(type) &&
(!is_integral(lhs_type.get_element_type()) || !is_integral(rhs_type.get_element_type())))
error();
if (binary_is_logical(type) &&
!(is_integral(lhs_type.get_element_type()) && is_integral(rhs_type.get_element_type())))
error();
if (is_comparison(type)) {
ret_type = make_dt(PrimitiveType::u1);
return;
}
if (is_shift_op(type) || (type == BinaryOpType::pow && is_integral(rhs_type))) {
ret_type = lhs_type;
return;
}
// Some backends such as vulkan doesn't support fp64
// Try not promoting to fp64 unless necessary
if (type == BinaryOpType::atan2) {
if (lhs_type == PrimitiveType::f64 || rhs_type == PrimitiveType::f64) {
ret_type = make_dt(PrimitiveType::f64);
} else {
ret_type = make_dt(PrimitiveType::f32);
}
return;
}
if (type == BinaryOpType::truediv) {
auto default_fp = config->default_fp;
if (!is_real(lhs_type.get_element_type())) {
lhs_type = make_dt(default_fp);
}
if (!is_real(rhs_type.get_element_type())) {
rhs_type = make_dt(default_fp);
}
}
ret_type = promoted_type(lhs_type, rhs_type);
}
void BinaryOpExpression::flatten(FlattenContext *ctx) {
// if (stmt)
// return;
auto lhs_stmt = flatten_rvalue(lhs, ctx);
auto lhs_type = lhs.get_rvalue_type();
auto rhs_type = rhs.get_rvalue_type();
if (binary_is_logical(type) && !is_tensor(lhs_type) && !is_tensor(rhs_type)) {
auto result = ctx->push_back<AllocaStmt>(ret_type, dbg_info);
ctx->push_back<LocalStoreStmt>(result, lhs_stmt, lhs_stmt->dbg_info);
auto cond = ctx->push_back<LocalLoadStmt>(result, dbg_info);
auto if_stmt = ctx->push_back<IfStmt>(cond, dbg_info);
FlattenContext rctx;
rctx.current_block = ctx->current_block;
auto rhs_stmt = flatten_rvalue(rhs, &rctx);
rctx.push_back<LocalStoreStmt>(result, rhs_stmt, rhs_stmt->dbg_info);
auto true_block = std::make_unique<Block>();
if (type == BinaryOpType::logical_and) {
true_block->set_statements(std::move(rctx.stmts));
}
if_stmt->set_true_statements(std::move(true_block));
auto false_block = std::make_unique<Block>();
if (type == BinaryOpType::logical_or) {
false_block->set_statements(std::move(rctx.stmts));
}
if_stmt->set_false_statements(std::move(false_block));
auto ret = ctx->push_back<LocalLoadStmt>(result, dbg_info);
stmt = ret;
stmt->ret_type = ret_type;
return;
}
auto rhs_stmt = flatten_rvalue(rhs, ctx);
ctx->push_back(std::make_unique<BinaryOpStmt>(type, lhs_stmt, rhs_stmt, /*is_bit_vectorized=*/false, dbg_info));
stmt = ctx->back_stmt();
stmt->ret_type = ret_type;
}
void make_ifte(Expression::FlattenContext *ctx,
DataType ret_type,
Expr cond,
Expr true_val,
Expr false_val,
const DebugInfo &dbg_info) {
auto result = ctx->push_back<AllocaStmt>(ret_type, dbg_info);
auto cond_stmt = flatten_rvalue(cond, ctx);
auto if_stmt = ctx->push_back<IfStmt>(cond_stmt, cond->dbg_info);
Expression::FlattenContext lctx;
lctx.current_block = ctx->current_block;
auto true_val_stmt = flatten_rvalue(true_val, &lctx);
lctx.push_back<LocalStoreStmt>(result, true_val_stmt, true_val->dbg_info);
Expression::FlattenContext rctx;
rctx.current_block = ctx->current_block;
auto false_val_stmt = flatten_rvalue(false_val, &rctx);
rctx.push_back<LocalStoreStmt>(result, false_val_stmt, false_val->dbg_info);
auto true_block = std::make_unique<Block>();
true_block->set_statements(std::move(lctx.stmts));
if_stmt->set_true_statements(std::move(true_block));
auto false_block = std::make_unique<Block>();
false_block->set_statements(std::move(rctx.stmts));
if_stmt->set_false_statements(std::move(false_block));
ctx->push_back<LocalLoadStmt>(result, dbg_info);
return;
}
static std::tuple<Expr, Expr, Expr> unify_ternaryop_operands(const Expr &e1, const Expr &e2, const Expr &e3) {
auto target_dtype = PrimitiveType::unknown;
// Since we don't support broadcasting between two TensorTypes,
// we can simply use the first TensorType's dtype as the target dtype.
auto e1_type = e1.get_rvalue_type();
auto e2_type = e2.get_rvalue_type();
auto e3_type = e3.get_rvalue_type();
if (e1_type->is<TensorType>()) {
target_dtype = e1_type;
} else if (e2_type->is<TensorType>()) {
target_dtype = e2_type;
} else if (e3_type->is<TensorType>()) {
target_dtype = e3_type;
}
if (target_dtype == PrimitiveType::unknown) {
return std::tuple(e1, e2, e3);
}
return std::tuple(e1, to_broadcast_tensor(e2, target_dtype), to_broadcast_tensor(e3, target_dtype));
}
void TernaryOpExpression::type_check(const CompileConfig *config) {
QD_ASSERT_TYPE_CHECKED(op1);
QD_ASSERT_TYPE_CHECKED(op2);
QD_ASSERT_TYPE_CHECKED(op3);
bool is_valid = true;
bool is_tensor = false;
auto [unified_cond, unified_l, unified_r] = unify_ternaryop_operands(op1, op2, op3);
op1 = unified_cond;
op2 = unified_l;
op3 = unified_r;
auto op1_type = op1.get_rvalue_type();
auto op2_type = op2.get_rvalue_type();
auto op3_type = op3.get_rvalue_type();
auto error = [&]() {
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("unsupported operand type(s) for '{}': '{}', '{}' and '{}'", ternary_type_name(type),
op1_type->to_string(), op2_type->to_string(), op3_type->to_string()));
};
std::vector<int> shape;
if (op2_type->is<TensorType>() && op3_type->is<TensorType>()) {
// valid
is_tensor = true;
if (op1_type->is<TensorType>() &&
op1_type->cast<TensorType>()->get_shape() != op2_type->cast<TensorType>()->get_shape()) {
is_valid = false;
}
if (op2_type->cast<TensorType>()->get_shape() != op3_type->cast<TensorType>()->get_shape()) {
is_valid = false;
}
if (op1_type->is<TensorType>()) {
op1_type = op1_type->cast<TensorType>()->get_element_type();
}
shape = op2_type->cast<TensorType>()->get_shape();
op2_type = op2_type->cast<TensorType>()->get_element_type();
op3_type = op3_type->cast<TensorType>()->get_element_type();
} else if (op1_type->is<PrimitiveType>() && op2_type->is<PrimitiveType>() && op3_type->is<PrimitiveType>()) {
// valid
} else {
is_valid = false;
}
if (!is_integral(op1_type)) {
is_valid = false;
}
if (!op2_type->is<PrimitiveType>() || !op3_type->is<PrimitiveType>()) {
is_valid = false;
}
if (!is_valid)
error();
if (is_tensor) {
auto primitive_dtype = promoted_type(op2_type, op3_type);
ret_type = TypeFactory::create_tensor_type(shape, primitive_dtype);
} else {
ret_type = promoted_type(op2_type, op3_type);
}
}
void TernaryOpExpression::flatten(FlattenContext *ctx) {
// if (stmt)
// return;
if (type == TernaryOpType::select) {
auto op1_stmt = flatten_rvalue(op1, ctx);
auto op2_stmt = flatten_rvalue(op2, ctx);
auto op3_stmt = flatten_rvalue(op3, ctx);
ctx->push_back(std::make_unique<TernaryOpStmt>(type, op1_stmt, op2_stmt, op3_stmt, dbg_info));
} else if (type == TernaryOpType::ifte) {
make_ifte(ctx, ret_type, op1, op2, op3, dbg_info);
}
stmt = ctx->back_stmt();
stmt->ret_type = ret_type;
}
void InternalFuncCallExpression::type_check(const CompileConfig *) {
std::vector<DataType> arg_types;
for (auto &arg : args) {
QD_ASSERT_TYPE_CHECKED(arg);
arg_types.push_back(arg.get_rvalue_type());
}
ret_type = op->type_check(arg_types);
}
void InternalFuncCallExpression::flatten(FlattenContext *ctx) {
stmt = op->flatten(ctx, args, ret_type);
stmt->dbg_info = dbg_info;
}
void ExternalTensorExpression::flatten(FlattenContext *ctx) {
auto type = TypeFactory::get_instance().get_ndarray_struct_type(dt, ndim, needs_grad);
type = TypeFactory::get_instance().get_pointer_type((Type *)type);
auto ptr = Stmt::make<ArgLoadStmt>(arg_id, type, /*is_ptr=*/true,
/*create_load=*/false, /*dbg_info=*/dbg_info);
ctx->push_back(std::move(ptr));
stmt = ctx->back_stmt();
}
std::vector<Stmt *> make_index_stmts(Expression::FlattenContext *ctx,
const ExprGroup &indices,
const std::vector<int> &offsets) {
std::vector<Stmt *> index_stmts;
for (int i = 0; i < (int)indices.size(); i++) {
Stmt *ind = flatten_rvalue(indices.exprs[i], ctx);
if (!offsets.empty()) {
auto offset = ctx->push_back<ConstStmt>(TypedConstant(offsets[i]));
ind = ctx->push_back<BinaryOpStmt>(BinaryOpType::sub, ind, offset);
}
index_stmts.push_back(ind);
}
return index_stmts;
}
Stmt *make_field_access(Expression::FlattenContext *ctx, const FieldExpression &field, ExprGroup indices) {
return ctx->push_back(
std::make_unique<GlobalPtrStmt>(field.snode, make_index_stmts(ctx, indices, field.snode->index_offsets)));
}
Stmt *make_matrix_field_access(Expression::FlattenContext *ctx,
const MatrixFieldExpression &matrix_field,
ExprGroup indices,
DataType ret_type) {
std::vector<SNode *> snodes;
for (auto &field : matrix_field.fields) {
snodes.push_back(field.cast<FieldExpression>()->snode);
}
ret_type.set_is_pointer(true);
return ctx->push_back(std::make_unique<MatrixOfGlobalPtrStmt>(
snodes, make_index_stmts(ctx, indices, snodes[0]->index_offsets), matrix_field.dynamic_indexable,
matrix_field.dynamic_index_stride, ret_type));
}
Stmt *make_ndarray_access(Expression::FlattenContext *ctx, Expr var, ExprGroup indices) {
std::vector<Stmt *> index_stmts;
for (int i = 0; i < (int)indices.size(); i++) {
Stmt *ind = flatten_rvalue(indices.exprs[i], ctx);
index_stmts.push_back(ind);
}
auto var_stmt = flatten_lvalue(var, ctx);
auto expr = var.cast<ExternalTensorExpression>();
// FIXME: No need to make it negative since we only support AOS
auto element_dim = -expr->dt.get_shape().size();
auto external_ptr_stmt = std::make_unique<ExternalPtrStmt>(var_stmt, index_stmts, indices.size(),
expr->dt.get_shape(), expr->is_grad, expr->boundary);
if (expr->ndim - element_dim == indices.size()) {
// Indexing into an scalar element
external_ptr_stmt->ret_type = expr->dt.ptr_removed().get_element_type();
} else {
// Indexing outer dimensions
external_ptr_stmt->ret_type = expr->dt.ptr_removed();
}
return ctx->push_back(std::move(external_ptr_stmt));
}
Stmt *make_tensor_access_single_element(Expression::FlattenContext *ctx,
Stmt *var_stmt,
const ExprGroup &indices,
const std::vector<int> &shape,
const DebugInfo &dbg_info) {
bool needs_dynamic_index = false;
for (int i = 0; i < (int)indices.size(); ++i) {
if (!indices[i].is<ConstExpression>()) {
needs_dynamic_index = true;
}
}
Stmt *offset_stmt = nullptr;
if (needs_dynamic_index) {
offset_stmt = ctx->push_back<ConstStmt>(TypedConstant(0));
for (int i = 0; i < (int)indices.size(); ++i) {
auto index_stmt = flatten_rvalue(indices[i], ctx);
Stmt *shape_stmt = ctx->push_back<ConstStmt>(TypedConstant(shape[i]));
Stmt *mul_stmt = ctx->push_back<BinaryOpStmt>(BinaryOpType::mul, offset_stmt, shape_stmt);
offset_stmt = ctx->push_back<BinaryOpStmt>(BinaryOpType::add, mul_stmt, index_stmt);
}
} else {
int offset = 0;
for (int i = 0; i < (int)indices.size(); ++i) {
offset = offset * shape[i] + indices[i].cast<ConstExpression>()->val.val_int();
}
offset_stmt = ctx->push_back<ConstStmt>(TypedConstant(offset));
}
return ctx->push_back<MatrixPtrStmt>(var_stmt, offset_stmt, dbg_info);
}
Stmt *make_tensor_access(Expression::FlattenContext *ctx,
Expr var,
const std::vector<ExprGroup> &indices_group,
DataType ret_type,
std::vector<int> shape,
const DebugInfo &dbg_info) {
auto var_stmt = flatten_lvalue(var, ctx);
if (!var->is_lvalue()) {
auto alloca_stmt = ctx->push_back<AllocaStmt>(var.get_rvalue_type());
ctx->push_back<LocalStoreStmt>(alloca_stmt, var_stmt);
var_stmt = alloca_stmt;
}
bool is_shared_array = (var_stmt->is<AllocaStmt>() && var_stmt->as<AllocaStmt>()->is_shared);
if (ret_type.ptr_removed()->is<TensorType>() && !is_shared_array) {
std::vector<Stmt *> stmts;
for (auto &indices : indices_group) {
stmts.push_back(make_tensor_access_single_element(ctx, var_stmt, indices, shape, dbg_info));
}
return ctx->push_back<MatrixOfMatrixPtrStmt>(stmts, ret_type);
}
return make_tensor_access_single_element(ctx, var_stmt, indices_group[0], shape, dbg_info);
}
void MatrixExpression::type_check(const CompileConfig *config) {
auto tensor_type = dt->as<TensorType>();
QD_ASSERT(tensor_type->get_num_elements() == elements.size());
for (auto &arg : elements) {
QD_ASSERT_TYPE_CHECKED(arg);
if (arg.get_rvalue_type()->get_type() != tensor_type->get_element_type()) {
arg = cast(arg, tensor_type->get_element_type());
arg->type_check(config);
}
}
ret_type = dt;
}
void MatrixExpression::flatten(FlattenContext *ctx) {
QD_ASSERT(dt->is<TensorType>());
std::vector<Stmt *> values;
for (auto &elt : elements) {
values.push_back(flatten_rvalue(elt, ctx));
}
stmt = ctx->push_back<MatrixInitStmt>(values);
stmt->ret_type = dt;
}
IndexExpression::IndexExpression(const Expr &var, const ExprGroup &indices, const DebugInfo &dbg_info)
: Expression(dbg_info), var(var), indices_group({indices}) {
}
IndexExpression::IndexExpression(const Expr &var,
const std::vector<ExprGroup> &indices_group,
const std::vector<int> &ret_shape,
const DebugInfo &dbg_info)
: Expression(dbg_info), var(var), indices_group(indices_group), ret_shape(ret_shape) {
// IndexExpression with ret_shape is used for matrix slicing, where each entry
// of ExprGroup is interpreted as a group of indices to return within each
// axis. For example, mat[0, 3:5] has indices_group={0, [3, 4]}, where [3, 4]
// means "m"-axis will return a TensorType with size of 2. In this case, we
// should not expand indices_group due to its special semantics.
}
bool IndexExpression::is_field() const {
return var.is<FieldExpression>();
}
bool IndexExpression::is_matrix_field() const {
return var.is<MatrixFieldExpression>();
}
bool IndexExpression::is_ndarray() const {
return var.is<ExternalTensorExpression>();
}
bool IndexExpression::is_tensor() const {
return var->ret_type.ptr_removed()->is<TensorType>();
}
bool IndexExpression::is_local() const {
return !is_global();
}
bool IndexExpression::is_global() const {
if (var.is<IndexExpression>()) {
// Special case: Pointer chasing. For example, if we are indexing into
// tensor elements of fields / ndarrays, this index expr should be treated
// as global.
return var.cast<IndexExpression>()->is_global();
}
// Only Ndarray and Field comes outside from a kernel
return is_field() || is_matrix_field() || is_ndarray();
}
static void field_validation(FieldExpression *field_expr, int index_dim) {
QD_ASSERT(field_expr != nullptr);
QD_ASSERT(field_expr->snode != nullptr);
int field_dim = field_expr->snode->num_active_indices;
if (field_dim != index_dim) {
ErrorEmitter(QuadrantsIndexError(), field_expr,
fmt::format("Field with dim {} accessed with indices of dim {}", field_dim, index_dim));
}
}
void IndexExpression::type_check(const CompileConfig *) {
// TODO: Change to type-based solution
// Currently, dimension compatibility check happens in Python
QD_ASSERT(indices_group.size() == std::accumulate(begin(ret_shape), end(ret_shape), 1, std::multiplies<>()));
int index_dim = indices_group.empty() ? 0 : indices_group[0].size();
bool has_slice = !ret_shape.empty();
auto var_type = var.get_rvalue_type();
if (has_slice) {
if (!is_tensor()) {
ErrorEmitter(QuadrantsTypeError(), this, "Slice or swizzle can only apply on matrices");
}
auto element_type = var_type->as<TensorType>()->get_element_type();
ret_type = TypeFactory::create_tensor_type(ret_shape, element_type);
} else if (is_field()) { // field
auto field_expr = var.cast<FieldExpression>();
field_validation(field_expr.get(), index_dim);
ret_type = field_expr->dt->get_compute_type();
} else if (is_matrix_field()) {
auto matrix_field_expr = var.cast<MatrixFieldExpression>();
QD_ASSERT(!matrix_field_expr->fields.empty());
auto field_expr = matrix_field_expr->fields[0].cast<FieldExpression>();
field_validation(field_expr.get(), index_dim);
ret_type = TypeFactory::create_tensor_type(
matrix_field_expr->element_shape, matrix_field_expr->fields[0].cast<FieldExpression>()->dt->get_compute_type());
} else if (is_ndarray()) { // ndarray
auto external_tensor_expr = var.cast<ExternalTensorExpression>();
int ndim = external_tensor_expr->ndim;
int element_dim = external_tensor_expr->dt.get_shape().size();
int total_dim = ndim + element_dim;
if (total_dim != index_dim + element_dim) {
ErrorEmitter(
QuadrantsIndexError(), this,
fmt::format("Array with dim {} accessed with indices of dim {}", total_dim - element_dim, index_dim));
}
if (index_dim == total_dim) {
// Access all the way to a single element
ret_type = var.cast<ExternalTensorExpression>()->dt.get_element_type();
} else {
// Access to a Tensor
ret_type = var.cast<ExternalTensorExpression>()->dt;
}
} else if (is_tensor()) { // local tensor
auto tensor_type = var_type->as<TensorType>();
auto shape = tensor_type->get_shape();
if (indices_group[0].size() != shape.size()) {
ErrorEmitter(QuadrantsIndexError(), this,
fmt::format("Expected {} indices, got {}.", shape.size(), indices_group[0].size()));
}
ret_type = tensor_type->get_element_type();
} else {
ErrorEmitter(QuadrantsIndexError(), this,
"Invalid IndexExpression: the source is not among field, ndarray or "
"local tensor");
}
ret_type = TypeFactory::get_instance().get_pointer_type(ret_type);
for (auto &indices : indices_group) {
for (int i = 0; i < indices.exprs.size(); i++) {
auto &expr = indices.exprs[i];
QD_ASSERT_TYPE_CHECKED(expr);
auto expr_type = expr.get_rvalue_type();
if (!is_integral(expr_type))
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("indices must be integers, however '{}' is "
"provided as index {}",
expr_type->to_string(), i));
}
}
}
void IndexExpression::flatten(FlattenContext *ctx) {
if (is_field()) {
stmt = make_field_access(ctx, *var.cast<FieldExpression>(), indices_group[0]);
} else if (is_matrix_field()) {
stmt = make_matrix_field_access(ctx, *var.cast<MatrixFieldExpression>(), indices_group[0], ret_type);
} else if (is_ndarray()) {
stmt = make_ndarray_access(ctx, var, indices_group[0]);
} else if (is_tensor()) {
stmt = make_tensor_access(ctx, var, indices_group, ret_type,
var->ret_type.ptr_removed()->as<TensorType>()->get_shape(), dbg_info);
} else {
ErrorEmitter(QuadrantsIndexError(), this,
"Invalid IndexExpression: the source is not among field, ndarray or "
"local tensor");
}
stmt->dbg_info = dbg_info;
}
void RangeAssumptionExpression::type_check(const CompileConfig *) {
QD_ASSERT_TYPE_CHECKED(input);
QD_ASSERT_TYPE_CHECKED(base);
auto input_type = input.get_rvalue_type();
auto base_type = base.get_rvalue_type();
if (!input_type->is<PrimitiveType>() || !base_type->is<PrimitiveType>() || input_type != base_type)
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("unsupported operand type(s) for "
"'range_assumption': '{}' and '{}'",
input_type->to_string(), base_type->to_string()));
ret_type = input_type;
}
void RangeAssumptionExpression::flatten(FlattenContext *ctx) {
auto input_stmt = flatten_rvalue(input, ctx);
auto base_stmt = flatten_rvalue(base, ctx);
ctx->push_back(Stmt::make<RangeAssumptionStmt>(input_stmt, base_stmt, low, high, dbg_info));
stmt = ctx->back_stmt();
}
void LoopUniqueExpression::type_check(const CompileConfig *) {
QD_ASSERT_TYPE_CHECKED(input);
auto input_type = input.get_rvalue_type();
if (!input_type->is<PrimitiveType>())
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("unsupported operand type(s) for 'loop_unique': '{}'", input_type->to_string()));
ret_type = input_type;
}
void LoopUniqueExpression::flatten(FlattenContext *ctx) {
auto input_stmt = flatten_rvalue(input, ctx);
ctx->push_back(Stmt::make<LoopUniqueStmt>(input_stmt, covers, dbg_info));
stmt = ctx->back_stmt();
}
void IdExpression::flatten(FlattenContext *ctx) {
stmt = ctx->current_block->lookup_var(id);
if (!ret_type->is_primitive(PrimitiveTypeID::unknown)) {
stmt->ret_type = ret_type;
}
}
void AtomicOpExpression::type_check(const CompileConfig *config) {
QD_ASSERT_TYPE_CHECKED(dest);
QD_ASSERT_TYPE_CHECKED(val);
auto error = [&]() {
ErrorEmitter(QuadrantsTypeError(), this,
fmt::format("unsupported operand type(s) for 'atomic_{}': '{}' and '{}'", atomic_op_type_name(op_type),
dest->ret_type->to_string(), val->ret_type->to_string()));
};
// Broadcast val to dest if neccessary
auto val_dtype = val.get_rvalue_type();
auto dest_dtype = dest->ret_type.ptr_removed();
if (dest_dtype->is<PrimitiveType>() && val_dtype->is<TensorType>()) {
error();
}
if (val_dtype->is<PrimitiveType>() && dest_dtype->is<TensorType>()) {
auto broadcasted_expr = to_broadcast_tensor(val, dest_dtype);
val = std::move(broadcasted_expr);
val.type_check(config);
}
// Validate dtype
if (val_dtype->is<TensorType>()) {
val_dtype = val_dtype.get_element_type();
}
if (!val_dtype->is<PrimitiveType>()) {
error();
}
if (is_quant(dest_dtype)) {
ret_type = dest_dtype->get_compute_type();
} else if (dest_dtype->is<PrimitiveType>() || dest_dtype->is<TensorType>()) {
ret_type = dest_dtype;
} else {
error();
}
auto const &ret_element_type = ret_type.get_element_type();
if (ret_element_type != val_dtype) {
auto promoted = promoted_type(ret_element_type, val_dtype);
if (ret_element_type != promoted) {
ErrorEmitter(QuadrantsCastWarning(), this,
fmt::format("Atomic {} may lose precision: {} <- {}", atomic_op_type_name(op_type),
ret_element_type->to_string(), val_dtype->to_string()));
}
}
}
void AtomicOpExpression::flatten(FlattenContext *ctx) {
QD_ASSERT(dest.expr->is_lvalue());
// replace atomic sub with negative atomic add
if (op_type == AtomicOpType::sub) {
if (val->ret_type != ret_type) {
val.set(Expr::make<UnaryOpExpression>(UnaryOpType::cast_value, val, ret_type, val->dbg_info));
}
val.set(Expr::make<UnaryOpExpression>(UnaryOpType::neg, val, val->dbg_info));
op_type = AtomicOpType::add;
}
// expand rhs
auto val_stmt = flatten_rvalue(val, ctx);
auto dest_stmt = flatten_lvalue(dest, ctx);
stmt = ctx->push_back<AtomicOpStmt>(op_type, dest_stmt, val_stmt, dbg_info);
stmt->ret_type = stmt->as<AtomicOpStmt>()->dest->ret_type;
}
SNodeOpExpression::SNodeOpExpression(SNode *snode, SNodeOpType op_type, const ExprGroup &indices)
: snode(snode), op_type(op_type), indices(indices) {
}
SNodeOpExpression::SNodeOpExpression(SNode *snode,
SNodeOpType op_type,
const ExprGroup &indices,
const std::vector<Expr> &values)