-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathspirv_codegen.cpp
More file actions
3447 lines (3175 loc) · 177 KB
/
Copy pathspirv_codegen.cpp
File metadata and controls
3447 lines (3175 loc) · 177 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/codegen/spirv/spirv_codegen.h"
#include <string>
#include <string_view>
#include <vector>
#include <variant>
#include <filesystem>
#include "spirv/unified1/GLSL.std.450.h"
#include "quadrants/codegen/codegen_utils.h"
#include "quadrants/program/program.h"
#include "quadrants/program/kernel.h"
#include "quadrants/program/adstack_size_expr_eval.h"
#include "quadrants/ir/statements.h"
#include "quadrants/ir/ir.h"
#include "quadrants/util/line_appender.h"
#include "quadrants/codegen/spirv/kernel_utils.h"
#include "quadrants/codegen/spirv/spirv_ir_builder.h"
#include "quadrants/codegen/spirv/detail/spirv_codegen.h"
#include "quadrants/codegen/spirv/spirv_shared_array_retyping.h"
#include "quadrants/ir/analysis.h"
#include "quadrants/ir/transforms.h"
#include "quadrants/ir/snode.h"
#include "quadrants/math/arithmetic.h"
#include "quadrants/codegen/ir_dump.h"
#include <spirv-tools/libspirv.hpp>
#include <spirv-tools/optimizer.hpp>
namespace quadrants::lang {
namespace spirv {
constexpr char kRootBufferName[] = "root_buffer";
constexpr char kGlobalTmpsBufferName[] = "global_tmps_buffer";
constexpr char kArgsBufferName[] = "args_buffer";
constexpr char kRetBufferName[] = "ret_buffer";
constexpr char kListgenBufferName[] = "listgen_buffer";
constexpr char kExtArrBufferName[] = "ext_arr_buffer";
constexpr char kAdStackOverflowBufferName[] = "adstack_overflow_buffer";
constexpr char kAdStackRowCounterBufferName[] = "adstack_row_counter_buffer";
constexpr char kAdStackBoundRowCapacityBufferName[] = "adstack_bound_row_capacity_buffer";
constexpr char kAdStackTaskRegistryIdBufferName[] = "adstack_task_registry_id_buffer";
constexpr char kAdStackHeapFloatBufferName[] = "adstack_heap_float_buffer";
constexpr char kAdStackHeapIntBufferName[] = "adstack_heap_int_buffer";
constexpr char kAdStackMetadataBufferName[] = "adstack_metadata_buffer";
constexpr int kMaxNumThreadsGridStrideLoop = 65536 * 2;
using BufferType = TaskAttributes::BufferType;
using namespace detail;
std::string buffer_instance_name(BufferInfo b) {
// https://www.khronos.org/opengl/wiki/Interface_Block_(GLSL)#Syntax
switch (b.type) {
case BufferType::Root:
return std::string(kRootBufferName) + "_" + std::to_string(b.root_id);
case BufferType::GlobalTmps:
return kGlobalTmpsBufferName;
case BufferType::Args:
return kArgsBufferName;
case BufferType::Rets:
return kRetBufferName;
case BufferType::ListGen:
return kListgenBufferName;
case BufferType::ExtArr:
return std::string(kExtArrBufferName) + "_" + std::to_string(b.root_id) + (b.is_grad ? "_grad" : "");
case BufferType::AdStackOverflow:
return kAdStackOverflowBufferName;
case BufferType::AdStackRowCounter:
return kAdStackRowCounterBufferName;
case BufferType::AdStackBoundRowCapacity:
return kAdStackBoundRowCapacityBufferName;
case BufferType::AdStackTaskRegistryId:
return kAdStackTaskRegistryIdBufferName;
case BufferType::AdStackHeapFloat:
return kAdStackHeapFloatBufferName;
case BufferType::AdStackHeapInt:
return kAdStackHeapIntBufferName;
case BufferType::AdStackMetadata:
return kAdStackMetadataBufferName;
default:
QD_NOT_IMPLEMENTED;
break;
}
return {};
}
TaskCodegen::TaskCodegen(const Params ¶ms)
: arch_(params.arch),
caps_(params.caps),
compile_config_(params.compile_config),
task_id_in_kernel_(params.task_id_in_kernel),
task_ir_(params.task_ir),
compiled_structs_(params.compiled_structs),
ctx_attribs_(params.ctx_attribs),
task_name_(params.task_ir->loop_name.empty()
? fmt::format("{}_t{:02d}", params.qd_kernel_name, params.task_id_in_kernel)
: fmt::format("{}_t{:02d}_{}",
params.qd_kernel_name,
params.task_id_in_kernel,
params.task_ir->loop_name)) {
allow_undefined_visitor = true;
invoke_default_visitor = true;
fill_snode_to_root();
ir_ = std::make_shared<spirv::IRBuilder>(arch_, caps_);
// Workaround for Metal/MoltenVK shader compiler bug: the compiler
// incorrectly hoists storage buffer loads out of loops (LICM), causing
// stale reads when a buffer is written and re-read within the same loop.
// Marking buffer accesses as Volatile prevents this optimization.
use_volatile_buffer_access_ = (arch_ == Arch::metal);
}
void TaskCodegen::fill_snode_to_root() {
for (int root = 0; root < compiled_structs_.size(); ++root) {
for (auto &[node_id, node] : compiled_structs_[root].snode_descriptors) {
snode_to_root_[node_id] = root;
}
}
}
// Replace the wild '%' in the format string with "%%".
std::string TaskCodegen::sanitize_format_string(std::string const &str) {
std::string sanitized_str;
for (char c : str) {
if (c == '%') {
sanitized_str += "%%";
} else {
sanitized_str += c;
}
}
return sanitized_str;
}
struct Result {
std::vector<uint32_t> spirv_code;
TaskAttributes task_attribs;
std::unordered_map<std::vector<int>, irpass::ExternalPtrAccess, hashing::Hasher<std::vector<int>>> arr_access;
};
TaskCodegen::Result TaskCodegen::run() {
ir_->init_header();
kernel_function_ = ir_->new_function(); // void main();
ir_->debug_name(spv::OpName, kernel_function_, "main");
scan_shared_atomic_allocs(task_ir_->body.get(), shared_float_allocas_with_atomic_rmw_);
// Run the shared static-adstack analysis over the task body. Returns the LCA of every f32 push/load-top site, the set
// of autodiff-bootstrap const-init pushes the codegen must skip the slot store for, the per-thread strides, and an
// optional `StaticBoundExpr` capturing the gating predicate when the LCA-to-root chain has a single recognized gate.
// The SNode descriptor resolver below turns the SPIR-V backend's `compiled_structs_` / `snode_to_root_` state into
// the generic `SNodeFieldDescriptor` the analysis consumes; ndarray-backed gates are recognized without the resolver.
auto snode_descriptor_resolver = [this](const SNode *leaf,
const SNode *dense) -> std::optional<SNodeFieldDescriptor> {
if (leaf == nullptr || dense == nullptr || dense->parent == nullptr) {
return std::nullopt;
}
auto root_it = snode_to_root_.find(dense->parent->id);
if (root_it == snode_to_root_.end()) {
return std::nullopt;
}
const int root_id = root_it->second;
const auto &snode_descs = compiled_structs_[root_id].snode_descriptors;
auto leaf_desc_it = snode_descs.find(leaf->id);
auto dense_desc_it = snode_descs.find(dense->id);
if (leaf_desc_it == snode_descs.end() || dense_desc_it == snode_descs.end()) {
return std::nullopt;
}
SNodeFieldDescriptor desc;
desc.root_id = root_id;
// Combined byte offset: dense's offset within its single root cell plus the leaf's offset within the dense's
// per-cell layout. Both come from the snode descriptor's compile-time prefix-sum so the captured value is stable
// across launches.
desc.byte_base_offset = static_cast<uint32_t>(dense_desc_it->second.mem_offset_in_parent_cell +
leaf_desc_it->second.mem_offset_in_parent_cell);
desc.byte_cell_stride = static_cast<uint32_t>(dense_desc_it->second.cell_stride);
desc.iter_count = static_cast<uint32_t>(dense_desc_it->second.total_num_cells_from_root);
return desc;
};
auto adstack_analysis = analyze_adstack_static_bounds(task_ir_, snode_descriptor_resolver,
compile_config_->ad_stack_sparse_threshold_bytes);
ad_stack_heap_per_thread_stride_float_ = adstack_analysis.per_thread_stride_float;
ad_stack_heap_per_thread_stride_int_ = adstack_analysis.per_thread_stride_int;
num_ad_stacks_ = adstack_analysis.num_ad_stacks;
ad_stack_lca_block_float_ = adstack_analysis.lca_block_float;
ad_stack_bootstrap_pushes_ = std::move(adstack_analysis.bootstrap_pushes);
if (adstack_analysis.bound_expr.has_value()) {
task_attribs_.ad_stack.bound_expr = *adstack_analysis.bound_expr;
}
// Carry the (possibly nested) graph_do_while loop level through to the SPIR-V task attributes so the GFX host-side
// do-while driver can reconstruct the loop nesting from the flat task list (mirrors the LLVM OffloadedTask tag).
task_attribs_.graph_do_while_level_id = task_ir_->graph_do_while_level_id;
if (task_ir_->task_type == OffloadedTaskType::serial) {
generate_serial_kernel(task_ir_);
} else if (task_ir_->task_type == OffloadedTaskType::range_for) {
// struct_for is automatically lowered to ranged_for for dense snodes
generate_range_for_kernel(task_ir_);
} else if (task_ir_->task_type == OffloadedTaskType::struct_for) {
generate_struct_for_kernel(task_ir_);
} else {
QD_ERROR("Unsupported offload type={} on SPIR-V codegen", task_ir_->task_name());
}
// Headers need global information, so it has to be delayed after visiting
// the task IR.
emit_headers();
task_attribs_.ad_stack.per_thread_stride_float_compile_time = ad_stack_heap_per_thread_stride_float_;
task_attribs_.ad_stack.per_thread_stride_int_compile_time = ad_stack_heap_per_thread_stride_int_;
// recognize `MaxOverRange` nodes the runtime can reduce in parallel via the dedicated max-reducer dispatch instead of
// letting the per-thread sizer enumerate. Indexing matches `task_attribs_.ad_stack.allocas` (each entry's `size_expr`
// is the per-stack tree captured above).
{
std::vector<SerializedSizeExpr> per_stack_size_exprs;
per_stack_size_exprs.reserve(task_attribs_.ad_stack.allocas.size());
for (const auto &a : task_attribs_.ad_stack.allocas) {
per_stack_size_exprs.push_back(a.size_expr);
}
task_attribs_.ad_stack.max_reducer_specs = recognize_adstack_max_reducer_specs(per_stack_size_exprs);
}
// Snodes the task body mutates (any `GlobalStore` or `AtomicOp` whose dest resolves to a
// `GlobalPtrStmt`). Persisted on `task_attribs_.snode_writes` so the SPIR-V launcher can bump
// `Program::snode_write_gen_` for each id on every `launch_kernel` call - that is the precise signal
// the per-task adstack metadata cache uses to invalidate when a prior kernel may have changed a
// value an enclosing `size_expr::FieldLoad` reads. Stored as raw int ids (not `SNode *`) so the
// field round-trips through the offline cache without resolving the pointer at serialise time.
auto snode_rw = irpass::analysis::gather_snode_read_writes(task_ir_);
task_attribs_.snode_writes.reserve(snode_rw.second.size());
for (auto *s : snode_rw.second) {
if (s != nullptr) {
task_attribs_.snode_writes.push_back(s->id);
}
}
std::sort(task_attribs_.snode_writes.begin(), task_attribs_.snode_writes.end());
task_attribs_.snode_writes.erase(std::unique(task_attribs_.snode_writes.begin(), task_attribs_.snode_writes.end()),
task_attribs_.snode_writes.end());
Result res;
res.spirv_code = ir_->finalize();
res.task_attribs = std::move(task_attribs_);
res.arr_access = irpass::detect_external_ptr_access_in_task(task_ir_);
res.grad_arr_access = irpass::detect_external_ptr_grad_access_in_task(task_ir_);
return res;
}
void TaskCodegen::visit(OffloadedStmt *) {
QD_ERROR("This codegen is supposed to deal with one offloaded task");
}
void TaskCodegen::visit(Block *stmt) {
// Sparse adstack heap: when codegen enters the float Lowest Common Ancestor (LCA) block of every f32-typed
// AdStackPushStmt / AdStackLoadTopStmt / AdStackLoadTopAdjStmt in this task, atomically claim a heap row id for this
// thread and store it into the Function-scope `ad_stack_row_id_var_float_`. The claim runs exactly once per thread
// per task: every thread that reaches a float push / load-top must first pass through this block (by definition of
// LCA), and a thread that does not pass through this block also never reaches a float push or load-top, so the
// unclaimed row_id_var (UINT32_MAX) is observable only at sites that are guaranteed not to execute. The store happens
// BEFORE any of this block's statements are codegen'd so all descendant push / load-top sites observe the claimed
// value. Both the `row_id_var` allocation and its UINT32_MAX-initialisation live on the same block-entry hook so that
// when the float LCA is the task body root (typical for kernels without a predicate gating all f32 pushes), the init
// store dominates the atomic claim. `alloca_variable` hoists the OpVariable to the SPIR-V function entry block
// regardless of where it is called from, but the OpStore lands here in the LCA block and reaches all descendant sites
// by SPIR-V dominance. The int heap path is intentionally NOT routed through this row claim: int adstacks back
// loop-index recovery and if-branch flags that the autodiff pass emits unconditionally at the offload body root, and
// `get_ad_stack_heap_thread_base_int()` keeps the eager `gl_GlobalInvocationID * stride_int` per-thread layout
// instead of consulting any row_id_var.
if (stmt == ad_stack_lca_block_float_ && ad_stack_lca_block_float_ != nullptr) {
QD_ASSERT(ad_stack_row_id_var_float_.id == 0);
ad_stack_row_id_var_float_ = ir_->alloca_variable(ir_->u32_type());
ir_->store_variable(ad_stack_row_id_var_float_, ir_->uint_immediate_number(ir_->u32_type(), UINT32_MAX));
}
// Tasks without a captured `bound_expr` do not have a host-published row capacity and the float heap is sized at
// `dispatched_threads * stride_float` worst case. Emitting the LCA-block atomic-rmw claim in that case lets
// `claimed_row` exceed `dispatched_threads` whenever the kernel's iteration count exceeds the SPIR-V advisory cap
// (`advisory_total_num_threads = 65536` for struct_for, `<= 131072` for range_for) and the kernel grid-strides via
// `loop_var += total_invocs`, because every iteration that reaches the LCA increments the counter and the inert
// UINT32_MAX-capacity clamp does not bring the row back in-bounds. Fall back to the eager `gl_GlobalInvocationID *
// stride_float` mapping by storing the invocation id into `row_id_var_float` directly; downstream
// `get_ad_stack_heap_thread_base_float()` reads it and produces the same per-thread addressing the int heap uses.
if (stmt == ad_stack_lca_block_float_ && ad_stack_lca_block_float_ != nullptr &&
!task_attribs_.ad_stack.bound_expr.has_value()) {
spirv::Value invoc_id = ir_->get_global_invocation_id(0);
ir_->store_variable(ad_stack_row_id_var_float_, invoc_id);
} else if (stmt == ad_stack_lca_block_float_ && ad_stack_lca_block_float_ != nullptr) {
if (ad_stack_row_counter_buffer_.id == 0) {
ad_stack_row_counter_buffer_ = get_buffer_value({BufferType::AdStackRowCounter}, PrimitiveType::u32);
}
// Per-task slot: the host allocates the counter buffer as `uint[num_tasks_in_kernel]`, clears it once at the start
// of each kernel-launch (not between tasks), so each task's atomic claims accumulate in its own slot and survive
// until the post-launch host readback at `synchronize()`. Without per-task slots a single shared slot would have
// the next task's bind-time clear destroy this task's count before the host can observe it, and the heap-sizing
// path would only ever see the LAST task's claim count - useless for tasks that come earlier in a multi-task kernel
// and have wildly different work patterns.
spirv::Value counter_ptr = ir_->struct_array_access(
ir_->u32_type(), ad_stack_row_counter_buffer_, ir_->uint_immediate_number(ir_->i32_type(), task_id_in_kernel_));
spirv::Value claimed_row =
ir_->make_value(spv::OpAtomicIAdd, ir_->u32_type(), counter_ptr,
/*scope=*/ir_->const_i32_one_,
/*semantics=*/ir_->const_i32_zero_, ir_->uint_immediate_number(ir_->u32_type(), 1));
ir_->store_variable(ad_stack_row_id_var_float_, claimed_row);
// Defense-in-depth bounds check. The host writes the per-task row capacity into
// `BufferType::AdStackBoundRowCapacity[task_id]` before this dispatch starts: for tasks with a captured
// `bound_expr`, the value is the exact reducer count; for every other task the value is
// UINT32_MAX so this check is inert. When `claimed_row >= capacity` we OpAtomicUMax UINT32_MAX into the existing
// AdStackOverflow buffer; the synchronize() readback recognises that sentinel and raises a clear actionable error
// rather than letting the kernel silently OOB-write the heap. UINT32_MAX cannot collide with the existing per-stack
// `stack_id+1` overflow signal because `stack_id+1 <= num_ad_stacks << UINT32_MAX` in every realistic kernel.
// Expected behaviour on legitimate workloads: this branch is taken zero times. If it fires, the reducer's count
// diverged from the main pass's actual LCA-block-reaching thread count, which means an internal-consistency bug
// (non-determinism between reducer and main), not a user-recoverable condition. The clamp via OpSelect keeps the
// stored row id in-bounds at `capacity-1` when the over-claim happens, so downstream push / load-top sites in this
// overshooting thread do not write past the heap end.
if (ad_stack_bound_row_capacity_buffer_.id == 0) {
ad_stack_bound_row_capacity_buffer_ = get_buffer_value({BufferType::AdStackBoundRowCapacity}, PrimitiveType::u32);
}
spirv::Value capacity_ptr =
ir_->struct_array_access(ir_->u32_type(), ad_stack_bound_row_capacity_buffer_,
ir_->uint_immediate_number(ir_->i32_type(), task_id_in_kernel_));
spirv::Value capacity = ir_->load_variable(capacity_ptr, ir_->u32_type());
// Guard the `capacity - 1` clamp upper bound against `capacity == 0`: a naive `sub(capacity, 1)` wraps in u32 to
// UINT32_MAX, the `UMin(claimed_row, UINT32_MAX)` returns `claimed_row` unchanged for any realistic value, and the
// clamp goes inert. Clamp the upper bound to row 0 in that case (the launcher floors the heap allocation at one row
// precisely so the single-slot fallback is always backed by real storage). Mirrors the LLVM-side `select(capacity
// == 0, 0, capacity - 1)`.
spirv::Value zero_u32 = ir_->uint_immediate_number(ir_->u32_type(), 0);
spirv::Value one_u32 = ir_->uint_immediate_number(ir_->u32_type(), 1);
spirv::Value capacity_is_zero = ir_->eq(capacity, zero_u32);
spirv::Value capacity_minus_one_raw = ir_->sub(capacity, one_u32);
spirv::Value clamp_upper = ir_->select(capacity_is_zero, zero_u32, capacity_minus_one_raw);
spirv::Value clamped_row = ir_->call_glsl450(ir_->u32_type(), GLSLstd450UMin, claimed_row, clamp_upper);
ir_->store_variable(ad_stack_row_id_var_float_, clamped_row);
spirv::Value overflow_signal =
ir_->select(ir_->ge(claimed_row, capacity), ir_->uint_immediate_number(ir_->u32_type(), UINT32_MAX),
ir_->uint_immediate_number(ir_->u32_type(), 0));
spirv::Value overflow_buf = get_buffer_value(BufferType::AdStackOverflow, PrimitiveType::u32);
spirv::Value overflow_ptr =
ir_->struct_array_access(ir_->u32_type(), overflow_buf, ir_->uint_immediate_number(ir_->i32_type(), 0));
ir_->make_value(spv::OpAtomicUMax, ir_->u32_type(), overflow_ptr, /*scope=*/ir_->const_i32_one_,
/*semantics=*/ir_->const_i32_zero_, overflow_signal);
}
for (auto &s : stmt->statements) {
if (offload_loop_motion_.find(s.get()) == offload_loop_motion_.end()) {
s->accept(this);
}
}
}
void TaskCodegen::visit(PrintStmt *stmt) {
if (!caps_->get(DeviceCapability::spirv_has_non_semantic_info)) {
return;
}
std::string formats;
std::vector<Value> vals;
for (auto i = 0; i < stmt->contents.size(); ++i) {
auto const &content = stmt->contents[i];
auto const &format = stmt->formats[i];
if (std::holds_alternative<Stmt *>(content)) {
auto arg_stmt = std::get<Stmt *>(content);
QD_ASSERT(!arg_stmt->ret_type->is<TensorType>());
auto value = ir_->query_value(arg_stmt->raw_name());
vals.push_back(value);
auto &&merged_format = merge_printf_specifier(format, data_type_format(arg_stmt->ret_type));
// Vulkan doesn't support length, flags, or width specifier, except for
// unsigned long.
// https://vulkan.lunarg.com/doc/view/1.3.204.1/windows/debug_printf.html
auto &&[format_flags, format_width, format_precision, format_length, format_conversion] =
parse_printf_specifier(merged_format);
if (!format_flags.empty()) {
QD_WARN(
"The printf flags '{}' are not supported in Vulkan, "
"and will be discarded.",
format_flags);
format_flags.clear();
}
if (!format_width.empty()) {
QD_WARN(
"The printf width modifier '{}' is not supported in Vulkan, "
"and will be discarded.",
format_width);
format_width.clear();
}
if (!format_length.empty() && !(format_length == "l" && (format_conversion == "u" || format_conversion == "x"))) {
QD_WARN(
"The printf length modifier '{}' is not supported in Vulkan, "
"and will be discarded.",
format_length);
format_length.clear();
}
formats += "%" + format_precision.append(format_length).append(format_conversion);
} else {
auto arg_str = std::get<std::string>(content);
formats += sanitize_format_string(arg_str);
}
}
ir_->call_debugprintf(formats, vals);
}
void TaskCodegen::visit(ConstStmt *const_stmt) {
auto get_const = [&](const TypedConstant &const_val) {
auto dt = const_val.dt.ptr_removed();
spirv::SType stype = ir_->get_primitive_type(dt);
if (dt->is_primitive(PrimitiveTypeID::f32)) {
return ir_->float_immediate_number(stype, static_cast<double>(const_val.val_f32), false);
} else if (dt->is_primitive(PrimitiveTypeID::f16)) {
// Ref: See quadrants::lang::TypedConstant::TypedConstant()
// FP16 is stored as FP32 on host side,
// as some CPUs does not have native FP16 (and no libc support)
return ir_->float_immediate_number(stype, static_cast<double>(const_val.val_f32), false);
} else if (dt->is_primitive(PrimitiveTypeID::i32)) {
return ir_->int_immediate_number(stype, static_cast<int64_t>(const_val.val_i32), false);
} else if (dt->is_primitive(PrimitiveTypeID::i64)) {
return ir_->int_immediate_number(stype, static_cast<int64_t>(const_val.val_i64), false);
} else if (dt->is_primitive(PrimitiveTypeID::f64)) {
return ir_->float_immediate_number(stype, static_cast<double>(const_val.val_f64), false);
} else if (dt->is_primitive(PrimitiveTypeID::i8)) {
return ir_->int_immediate_number(stype, static_cast<int64_t>(const_val.val_i8), false);
} else if (dt->is_primitive(PrimitiveTypeID::i16)) {
return ir_->int_immediate_number(stype, static_cast<int64_t>(const_val.val_i16), false);
} else if (dt->is_primitive(PrimitiveTypeID::u1)) {
return ir_->uint_immediate_number(stype, static_cast<uint64_t>(const_val.val_u1), false);
} else if (dt->is_primitive(PrimitiveTypeID::u8)) {
return ir_->uint_immediate_number(stype, static_cast<uint64_t>(const_val.val_u8), false);
} else if (dt->is_primitive(PrimitiveTypeID::u16)) {
return ir_->uint_immediate_number(stype, static_cast<uint64_t>(const_val.val_u16), false);
} else if (dt->is_primitive(PrimitiveTypeID::u32)) {
return ir_->uint_immediate_number(stype, static_cast<uint64_t>(const_val.val_u32), false);
} else if (dt->is_primitive(PrimitiveTypeID::u64)) {
return ir_->uint_immediate_number(stype, static_cast<uint64_t>(const_val.val_u64), false);
} else {
QD_P(data_type_name(dt));
QD_NOT_IMPLEMENTED
return spirv::Value();
}
};
spirv::Value val = get_const(const_stmt->val);
ir_->register_value(const_stmt->raw_name(), val);
}
void TaskCodegen::visit(AllocaStmt *alloca) {
spirv::Value ptr_val;
// alloca->ret_type is a pointer to the stored type; ptr_removed() gives the
// stored type itself (e.g. TensorType<32 x f32> for a 32-element array).
auto alloca_type = alloca->ret_type.ptr_removed();
// Shared array is always modeled as a tensor type, i.e. an array of scalars.
if (auto tensor_type = alloca_type->cast<TensorType>()) {
// Do NOT initialize elem_num/elem_type here - the helper flattens nested
// tensor types (e.g. vec3 -> 3xf32) before computing them. Pre-initializing
// with get_primitive_type(tensor_type->get_element_type()) would crash on
// nested tensor types like Tensor(3) f32.
int elem_num;
spirv::SType elem_type;
maybe_retype_alloca(*ir_, *caps_, alloca, tensor_type, shared_float_allocas_with_atomic_rmw_,
uint_backed_shared_float_ptr_stmts_, elem_num, elem_type);
// Use `get_function_array_type` rather than `get_array_type`: the resulting array type backs an
// `OpVariable` in either `Workgroup` (shared) or `Function` storage class, neither of which is a
// storage-buffer / PSB / Uniform interface, so the `ArrayStride` decoration `get_array_type` adds
// would be illegal per `VUID-StandaloneSpirv-None-10684` and Blackwell-class NVIDIA Vulkan drivers
// refuse the resulting compute pipeline. Older drivers tolerated the over-decoration.
spirv::SType arr_type = ir_->get_function_array_type(elem_type, elem_num);
if (alloca->is_shared) { // for shared memory / workgroup memory
ptr_val = ir_->alloca_workgroup_array(arr_type);
shared_array_binds_.push_back(ptr_val);
} else { // for function memory
ptr_val = ir_->alloca_variable(arr_type);
}
} else {
// Alloca for a single variable
spirv::SType src_type = ir_->get_primitive_type(alloca_type);
ptr_val = ir_->alloca_variable(src_type);
ir_->store_variable(ptr_val, ir_->get_zero(src_type));
}
ir_->register_value(alloca->raw_name(), ptr_val);
}
void TaskCodegen::visit(MatrixPtrStmt *stmt) {
spirv::Value ptr_val;
spirv::Value origin_val = ir_->query_value(stmt->origin->raw_name());
spirv::Value offset_val = ir_->query_value(stmt->offset->raw_name());
auto dt = stmt->element_type().ptr_removed();
if (stmt->offset_used_as_index()) {
// Origin is a local/shared array allocation or a derived pointer from one
// - use OpAccessChain or OpPtrAccessChain respectively.
if (stmt->origin->is<AllocaStmt>() || origin_val.stype.flag == TypeKind::kPtr) {
maybe_retype_derived_ptr(*ir_, stmt->origin, stmt, dt, uint_backed_shared_float_ptr_stmts_);
spirv::SType ptr_type = ir_->get_pointer_type(ir_->get_primitive_type(dt), origin_val.stype.storage_class);
auto op = stmt->origin->is<AllocaStmt>() ? spv::OpAccessChain : spv::OpPtrAccessChain;
ptr_val = ir_->make_value(op, ptr_type, origin_val, offset_val);
if (auto *a = stmt->origin->cast<AllocaStmt>(); a && a->is_shared) {
ptr_to_buffers_[stmt] = ptr_to_buffers_[stmt->origin];
}
} else if (stmt->origin->is<GlobalTemporaryStmt>()) {
spirv::Value dt_bytes = ir_->int_immediate_number(ir_->i32_type(), ir_->get_primitive_type_size(dt), false);
spirv::Value offset_bytes = ir_->mul(dt_bytes, offset_val);
ptr_val = ir_->add(origin_val, offset_bytes);
ptr_to_buffers_[stmt] = ptr_to_buffers_[stmt->origin];
} else {
QD_NOT_IMPLEMENTED;
}
} else { // offset used as bytes
ptr_val = ir_->add(origin_val, ir_->cast(origin_val.stype, offset_val));
ptr_to_buffers_[stmt] = ptr_to_buffers_[stmt->origin];
}
ir_->register_value(stmt->raw_name(), ptr_val);
}
void TaskCodegen::visit(LocalLoadStmt *stmt) {
auto ptr = stmt->src;
spirv::Value ptr_val = ir_->query_value(ptr->raw_name());
spirv::Value val;
if (uint_backed_shared_float_ptr_stmts_.count(ptr)) {
val = load_uint_backed_shared_float(*ir_, ptr_val, stmt->element_type());
} else {
val = ir_->load_variable(ptr_val, ir_->get_primitive_type(stmt->element_type()));
}
ir_->register_value(stmt->raw_name(), val);
}
void TaskCodegen::visit(LocalStoreStmt *stmt) {
spirv::Value ptr_val = ir_->query_value(stmt->dest->raw_name());
spirv::Value val = ir_->query_value(stmt->val->raw_name());
if (uint_backed_shared_float_ptr_stmts_.count(stmt->dest)) {
val = float_to_shared_uint(*ir_, val, stmt->val->element_type());
}
ir_->store_variable(ptr_val, val);
}
void TaskCodegen::visit(GetRootStmt *stmt) {
const int root_id = snode_to_root_.at(stmt->root()->id);
root_stmts_[root_id] = stmt;
// get_buffer_value({BufferType::Root, root_id}, PrimitiveType::u32);
spirv::Value root_val = make_pointer(0);
ir_->register_value(stmt->raw_name(), root_val);
}
void TaskCodegen::visit(GetChStmt *stmt) {
// TODO: GetChStmt -> GetComponentStmt ?
const int root = snode_to_root_.at(stmt->input_snode->id);
const auto &snode_descs = compiled_structs_[root].snode_descriptors;
auto *out_snode = stmt->output_snode;
QD_ASSERT(snode_descs.at(stmt->input_snode->id).get_child(stmt->chid) == out_snode);
const auto &desc = snode_descs.at(out_snode->id);
spirv::Value input_ptr_val = ir_->query_value(stmt->input_ptr->raw_name());
spirv::Value offset = make_pointer(desc.mem_offset_in_parent_cell);
spirv::Value val = ir_->add(input_ptr_val, offset);
ir_->register_value(stmt->raw_name(), val);
if (out_snode->is_place()) {
QD_ASSERT(ptr_to_buffers_.count(stmt) == 0);
ptr_to_buffers_[stmt] = BufferInfo(BufferType::Root, root);
}
}
enum class ActivationOp { activate, deactivate, query };
spirv::Value TaskCodegen::bitmasked_activation(ActivationOp op,
spirv::Value parent_ptr,
int root_id,
const SNode *sn,
spirv::Value input_index) {
spirv::SType ptr_dt = parent_ptr.stype;
const auto &snode_descs = compiled_structs_[root_id].snode_descriptors;
const auto &desc = snode_descs.at(sn->id);
auto bitmask_word_index =
ir_->make_value(spv::OpShiftRightLogical, ptr_dt, input_index, ir_->uint_immediate_number(ptr_dt, 5));
auto bitmask_bit_index =
ir_->make_value(spv::OpBitwiseAnd, ptr_dt, input_index, ir_->uint_immediate_number(ptr_dt, 31));
auto bitmask_mask = ir_->make_value(spv::OpShiftLeftLogical, ptr_dt, ir_->const_i32_one_, bitmask_bit_index);
auto buffer = get_buffer_value(BufferInfo(BufferType::Root, root_id), PrimitiveType::u32);
auto bitmask_word_ptr = ir_->make_value(spv::OpShiftLeftLogical, ptr_dt, bitmask_word_index,
ir_->uint_immediate_number(ir_->u32_type(), 2));
bitmask_word_ptr = ir_->add(bitmask_word_ptr, make_pointer(desc.cell_stride * desc.snode->num_cells_per_container));
bitmask_word_ptr = ir_->add(parent_ptr, bitmask_word_ptr);
bitmask_word_ptr = ir_->make_value(spv::OpShiftRightLogical, ir_->u32_type(), bitmask_word_ptr,
ir_->uint_immediate_number(ir_->u32_type(), 2));
bitmask_word_ptr = ir_->struct_array_access(ir_->u32_type(), buffer, bitmask_word_ptr);
if (op == ActivationOp::activate) {
return ir_->make_value(spv::OpAtomicOr, ir_->u32_type(), bitmask_word_ptr,
/*scope=*/ir_->const_i32_one_,
/*semantics=*/ir_->const_i32_zero_, bitmask_mask);
} else if (op == ActivationOp::deactivate) {
bitmask_mask = ir_->make_value(spv::OpNot, ir_->u32_type(), bitmask_mask);
return ir_->make_value(spv::OpAtomicAnd, ir_->u32_type(), bitmask_word_ptr,
/*scope=*/ir_->const_i32_one_,
/*semantics=*/ir_->const_i32_zero_, bitmask_mask);
} else {
auto bitmask_val = ir_->load_variable(bitmask_word_ptr, ir_->u32_type());
auto bit = ir_->make_value(spv::OpShiftRightLogical, ir_->u32_type(), bitmask_val, bitmask_bit_index);
bit = ir_->make_value(spv::OpBitwiseAnd, ir_->u32_type(), bit, ir_->uint_immediate_number(ir_->u32_type(), 1));
return ir_->make_value(spv::OpUGreaterThan, ir_->bool_type(), bit, ir_->uint_immediate_number(ir_->u32_type(), 0));
}
}
void TaskCodegen::visit(SNodeOpStmt *stmt) {
const int root_id = snode_to_root_.at(stmt->snode->id);
std::string parent = stmt->ptr->raw_name();
spirv::Value parent_val = ir_->query_value(parent);
if (stmt->snode->type == SNodeType::bitmasked) {
spirv::Value input_index_val = ir_->cast(parent_val.stype, ir_->query_value(stmt->val->raw_name()));
if (stmt->op_type == SNodeOpType::is_active) {
auto is_active = bitmasked_activation(ActivationOp::query, parent_val, root_id, stmt->snode, input_index_val);
is_active = ir_->cast(ir_->get_primitive_type(stmt->ret_type), is_active);
is_active = ir_->make_value(spv::OpSNegate, is_active.stype, is_active);
ir_->register_value(stmt->raw_name(), is_active);
} else if (stmt->op_type == SNodeOpType::deactivate) {
bitmasked_activation(ActivationOp::deactivate, parent_val, root_id, stmt->snode, input_index_val);
} else if (stmt->op_type == SNodeOpType::activate) {
bitmasked_activation(ActivationOp::activate, parent_val, root_id, stmt->snode, input_index_val);
} else {
QD_NOT_IMPLEMENTED;
}
} else {
QD_NOT_IMPLEMENTED;
}
}
void TaskCodegen::visit(SNodeLookupStmt *stmt) {
// TODO: SNodeLookupStmt -> GetSNodeCellStmt ?
bool is_root{false}; // Eliminate first root snode access
const int root_id = snode_to_root_.at(stmt->snode->id);
std::string parent;
if (stmt->input_snode) {
parent = stmt->input_snode->raw_name();
} else {
QD_ASSERT(root_stmts_.at(root_id) != nullptr);
parent = root_stmts_.at(root_id)->raw_name();
}
const auto *sn = stmt->snode;
spirv::Value parent_val = ir_->query_value(parent);
if (stmt->activate) {
if (sn->type == SNodeType::dense) {
// Do nothing
} else if (sn->type == SNodeType::bitmasked) {
spirv::Value input_index_val = ir_->query_value(stmt->input_index->raw_name());
bitmasked_activation(ActivationOp::activate, parent_val, root_id, sn, input_index_val);
} else {
QD_NOT_IMPLEMENTED;
}
}
spirv::Value val;
if (is_root) {
val = parent_val; // Assert Root[0] access at first time
} else {
const auto &snode_descs = compiled_structs_[root_id].snode_descriptors;
const auto &desc = snode_descs.at(sn->id);
spirv::Value input_index_val = ir_->cast(parent_val.stype, ir_->query_value(stmt->input_index->raw_name()));
spirv::Value stride = make_pointer(desc.cell_stride);
spirv::Value offset = ir_->mul(input_index_val, stride);
val = ir_->add(parent_val, offset);
}
ir_->register_value(stmt->raw_name(), val);
}
void TaskCodegen::visit(RandStmt *stmt) {
spirv::Value val;
spirv::Value global_tmp = get_buffer_value(BufferType::GlobalTmps, PrimitiveType::u32);
if (stmt->element_type()->is_primitive(PrimitiveTypeID::i32)) {
val = ir_->rand_i32(global_tmp);
} else if (stmt->element_type()->is_primitive(PrimitiveTypeID::u32)) {
val = ir_->rand_u32(global_tmp);
} else if (stmt->element_type()->is_primitive(PrimitiveTypeID::f32)) {
val = ir_->rand_f32(global_tmp);
} else if (stmt->element_type()->is_primitive(PrimitiveTypeID::f16)) {
auto highp_val = ir_->rand_f32(global_tmp);
val = ir_->cast(ir_->f16_type(), highp_val);
} else {
QD_ERROR("rand only support 32-bit type");
}
ir_->register_value(stmt->raw_name(), val);
}
void TaskCodegen::visit(LinearizeStmt *stmt) {
spirv::Value val = ir_->const_i32_zero_;
for (size_t i = 0; i < stmt->inputs.size(); ++i) {
spirv::Value strides_val = ir_->int_immediate_number(ir_->i32_type(), stmt->strides[i]);
spirv::Value input_val = ir_->query_value(stmt->inputs[i]->raw_name());
val = ir_->add(ir_->mul(val, strides_val), input_val);
}
ir_->register_value(stmt->raw_name(), val);
}
void TaskCodegen::visit(LoopIndexStmt *stmt) {
const auto stmt_name = stmt->raw_name();
if (stmt->loop->is<OffloadedStmt>()) {
const auto type = stmt->loop->as<OffloadedStmt>()->task_type;
if (type == OffloadedTaskType::range_for) {
QD_ASSERT(stmt->index == 0);
spirv::Value loop_var = ir_->query_value("ii");
// spirv::Value val = ir_->add(loop_var, ir_->const_i32_zero_);
ir_->register_value(stmt_name, loop_var);
} else {
QD_NOT_IMPLEMENTED;
}
} else if (stmt->loop->is<RangeForStmt>()) {
QD_ASSERT(stmt->index == 0);
spirv::Value loop_var = ir_->query_value(stmt->loop->raw_name());
spirv::Value val = ir_->add(loop_var, ir_->const_i32_zero_);
ir_->register_value(stmt_name, val);
} else {
QD_NOT_IMPLEMENTED;
}
}
void TaskCodegen::visit(GlobalStoreStmt *stmt) {
spirv::Value val = ir_->query_value(stmt->val->raw_name());
store_buffer(stmt->dest, val);
}
void TaskCodegen::visit(GlobalLoadStmt *stmt) {
auto dt = stmt->element_type();
auto val = load_buffer(stmt->src, dt, stmt->is_volatile);
ir_->register_value(stmt->raw_name(), val);
}
void TaskCodegen::visit(ArgLoadStmt *stmt) {
const auto arg_id = stmt->arg_id;
const std::vector<int> indices_l(stmt->arg_id.begin(), stmt->arg_id.begin());
const std::vector<int> indices_r(stmt->arg_id.begin(), stmt->arg_id.end());
const auto arg_type = ctx_attribs_->args_type()->get_element_type(arg_id);
if (arg_type->is<PointerType>() ||
(arg_type->is<lang::StructType>() && arg_type->as<lang::StructType>()->elements().size() >= 2 &&
arg_type->as<lang::StructType>()->get_element_type(std::array<int, 1>{1})->is<PointerType>())) {
// Do not shift! We are indexing the buffers at byte granularity.
// spirv::Value val =
// ir_->int_immediate_number(ir_->i32_type(), offset_in_mem);
// ir_->register_value(stmt->raw_name(), val);
} else {
spirv::Value buffer_val, buffer_value;
bool is_bool = arg_type->is_primitive(PrimitiveTypeID::u1);
// `val_type` must be assigned after `get_buffer_value` because
// `args_struct_types_` needs to be initialized by `get_buffer_value`.
SType val_type;
buffer_value = get_buffer_value(BufferType::Args, PrimitiveType::i32);
val_type = is_bool ? ir_->i32_type() : args_struct_types_[arg_id];
buffer_val =
ir_->make_access_chain(ir_->get_pointer_type(val_type, spv::StorageClassUniform), buffer_value, arg_id);
buffer_val.flag = ValueKind::kVariablePtr;
if (!stmt->create_load) {
ir_->register_value(stmt->raw_name(), buffer_val);
return;
}
spirv::Value val = ir_->load_variable(buffer_val, val_type);
if (is_bool) {
val = ir_->make_value(spv::OpINotEqual, ir_->bool_type(), val, ir_->int_immediate_number(ir_->i32_type(), 0));
}
ir_->register_value(stmt->raw_name(), val);
}
}
void TaskCodegen::visit(GetElementStmt *stmt) {
spirv::Value val = ir_->query_value(stmt->src->raw_name());
const auto val_type = ir_->get_primitive_type(stmt->element_type());
const auto val_type_ptr = ir_->get_pointer_type(val_type, spv::StorageClassUniform);
val = ir_->make_access_chain(val_type_ptr, val, stmt->index);
val = ir_->load_variable(val, val_type);
ir_->register_value(stmt->raw_name(), val);
}
void TaskCodegen::visit(ReturnStmt *stmt) {
QD_ASSERT(ctx_attribs_->has_rets());
// The `PrimitiveType::i32` in this function call is a placeholder.
auto buffer_value = get_buffer_value(BufferType::Rets, PrimitiveType::i32);
// Function to store variable using indices provided by
// `calc_indices_and_store`.
auto store_variable = [&](int index, const std::vector<int> &indices) {
auto dt = stmt->element_types()[index];
auto val_type = ir_->get_primitive_type(dt);
// Extend u1 values to i32 to be passed to the host.
if (dt->is_primitive(PrimitiveTypeID::u1))
val_type = ir_->i32_type();
spirv::Value buffer_val;
// Accessing based on `indices` using OpAccessChain.
buffer_val = ir_->make_access_chain(ir_->get_storage_pointer_type(val_type), buffer_value, indices);
buffer_val.flag = ValueKind::kVariablePtr;
spirv::Value val = ir_->query_value(stmt->values[index]->raw_name());
// Extend u1 values to i32 to be passed to the host.
if (dt->is_primitive(PrimitiveTypeID::u1))
val = ir_->select(val, ir_->const_i32_one_, ir_->const_i32_zero_);
ir_->store_variable(buffer_val, val);
};
// Function to traverse struct tree in depth-first order recursively to
// calculate AccessChain indices.
std::function<void(const quadrants::lang::Type *, int &, std::vector<int> &)> calc_indices_and_store =
[&](const quadrants::lang::Type *type, int &index, std::vector<int> &indices) {
if (auto struct_type = type->cast<quadrants::lang::StructType>()) {
for (int i = 0; i < struct_type->elements().size(); ++i) {
indices.push_back(i);
calc_indices_and_store(struct_type->elements()[i].type, index, indices);
indices.pop_back();
}
} else if (auto tensor_type = type->cast<quadrants::lang::TensorType>()) {
int num = tensor_type->get_num_elements();
for (int i = 0; i < num; ++i) {
indices.push_back(i);
store_variable(index++, indices);
indices.pop_back();
}
} else {
store_variable(index++, indices);
}
};
// Launch depth-first traversal using `calc_indices_and_store` on return
// struct.
std::vector<int> indices;
int index = 0;
for (int i = 0; i < ctx_attribs_->rets_type()->elements().size(); ++i) {
indices.push_back(i);
calc_indices_and_store(ctx_attribs_->rets_type()->elements()[i].type, index, indices);
indices.pop_back();
}
}
void TaskCodegen::visit(GlobalTemporaryStmt *stmt) {
spirv::Value val = ir_->int_immediate_number(ir_->i32_type(), stmt->offset,
false); // Named Constant
ir_->register_value(stmt->raw_name(), val);
ptr_to_buffers_[stmt] = BufferType::GlobalTmps;
}
void TaskCodegen::visit(ExternalTensorShapeAlongAxisStmt *stmt) {
const auto name = stmt->raw_name();
const auto arg_id = stmt->arg_id;
const auto axis = stmt->axis;
spirv::Value var_ptr;
QD_ASSERT(ctx_attribs_->args_type()->get_element_type(arg_id)->is<lang::StructType>());
std::vector<int> indices = arg_id;
indices.push_back(TypeFactory::SHAPE_POS_IN_NDARRAY);
indices.push_back(axis);
var_ptr = ir_->make_access_chain(ir_->get_pointer_type(ir_->i32_type(), spv::StorageClassUniform),
get_buffer_value(BufferType::Args, PrimitiveType::i32), indices);
spirv::Value var = ir_->load_variable(var_ptr, ir_->i32_type());
ir_->register_value(name, var);
}
void TaskCodegen::visit(ExternalPtrStmt *stmt) {
// Used mostly for transferring data between host (e.g. numpy array) and
// device.
// Flatten the multi-dimensional index into a linear (byte) offset. When the device advertises 64-bit integers we
// accumulate in i64 so that ndarrays whose element count exceeds INT32_MAX do not wrap and silently address the
// wrong element (matches the int64 fix already applied on the LLVM backends). Devices without shaderInt64 keep the
// historical i32 arithmetic; the Python/C++ launch path emits an overflow warning for those.
const bool index_use_i64 = caps_->get(DeviceCapability::spirv_has_int64);
const spirv::SType index_type = index_use_i64 ? ir_->i64_type() : ir_->i32_type();
spirv::Value linear_offset = ir_->int_immediate_number(index_type, 0);
const auto *argload = stmt->base_ptr->as<ArgLoadStmt>();
const auto arg_id = argload->arg_id;
{
const int num_indices = stmt->indices.size();
std::vector<std::string> size_var_names;
const auto &element_shape = stmt->element_shape;
const size_t element_shape_index_offset = num_indices - element_shape.size();
for (int i = 0; i < num_indices - element_shape.size(); i++) {
std::string var_name = fmt::format("{}_size{}_", stmt->raw_name(), i);
std::vector<int> indices = arg_id;
indices.push_back(TypeFactory::SHAPE_POS_IN_NDARRAY);
indices.push_back(i);
spirv::Value var_ptr = ir_->make_access_chain(ir_->get_pointer_type(ir_->i32_type(), spv::StorageClassUniform),
get_buffer_value(BufferType::Args, PrimitiveType::i32), indices);
spirv::Value var = ir_->load_variable(var_ptr, ir_->i32_type());
ir_->register_value(var_name, var);
size_var_names.push_back(std::move(var_name));
}
int size_var_names_idx = 0;
for (int i = 0; i < num_indices; i++) {
spirv::Value size_var;
// Use immediate numbers to flatten index for element shapes.
if (i >= element_shape_index_offset && i < element_shape_index_offset + element_shape.size()) {
size_var = ir_->uint_immediate_number(index_type, element_shape[i - element_shape_index_offset]);
} else {
// Shapes are stored as i32 in the args buffer; widen to the accumulation type when using i64.
size_var = ir_->cast(index_type, ir_->query_value(size_var_names[size_var_names_idx++]));
}
spirv::Value indices = ir_->cast(index_type, ir_->query_value(stmt->indices[i]->raw_name()));
linear_offset = ir_->mul(linear_offset, size_var);
linear_offset = ir_->add(linear_offset, indices);
}
size_t type_size = ir_->get_primitive_type_size(stmt->ret_type.ptr_removed());
linear_offset = ir_->make_value(spv::OpShiftLeftLogical, index_type, linear_offset,
ir_->int_immediate_number(index_type, log2int(type_size)));
if (caps_->get(DeviceCapability::spirv_has_no_integer_wrap_decoration)) {
ir_->decorate(spv::OpDecorate, linear_offset, spv::DecorationNoSignedWrap);
}
}
if (caps_->get(DeviceCapability::spirv_has_physical_storage_buffer)) {
std::vector<int> indices = arg_id;
// Pick the data or gradient pointer slot of the ndarray argument struct. Without this, reverse-mode AD kernels
// accumulate into x.data instead of x.grad and host-side gradients stay at zero.
indices.push_back(stmt->is_grad ? TypeFactory::GRAD_PTR_POS_IN_NDARRAY : TypeFactory::DATA_PTR_POS_IN_NDARRAY);
spirv::Value addr_ptr = ir_->make_access_chain(ir_->get_pointer_type(ir_->u64_type(), spv::StorageClassUniform),
get_buffer_value(BufferType::Args, PrimitiveType::i32), indices);
spirv::Value base_addr = ir_->load_variable(addr_ptr, ir_->u64_type());
// cast() sign-extends an i32 offset to u64, or bitcasts an already-64-bit i64 offset to u64.
spirv::Value addr = ir_->add(base_addr, ir_->cast(ir_->u64_type(), linear_offset));
ir_->register_value(stmt->raw_name(), addr);
// Save decomposed base pointer and element index so at_buffer() can
// emit OpConvertUToPtr on the base address once and use OpPtrAccessChain
// for element access. This avoids a Metal shader compiler bug where
// per-element reinterpret_cast from ulong arithmetic is miscompiled
// when the stored value is loop-invariant.
size_t type_size = ir_->get_primitive_type_size(stmt->ret_type.ptr_removed());
// Keep the element index in the same width as the offset accumulation so OpPtrAccessChain indexes the correct
// element for >INT32_MAX-element ndarrays on int64-capable devices.
spirv::Value elem_index = ir_->make_value(spv::OpShiftRightLogical, index_type, linear_offset,
ir_->int_immediate_number(index_type, log2int(type_size)));
physical_ptr_components_[stmt] = {base_addr, elem_index};
} else {
ir_->register_value(stmt->raw_name(), linear_offset);
}
if (ctx_attribs_->arg_at(arg_id).is_array) {
QD_ASSERT(arg_id.size() == 1);
ptr_to_buffers_[stmt] = {BufferType::ExtArr, arg_id[0], stmt->is_grad};
} else {
ptr_to_buffers_[stmt] = BufferType::Args;
}
}
void TaskCodegen::visit(DecorationStmt *stmt) {
}
void TaskCodegen::visit(UnaryOpStmt *stmt) {
const auto operand_name = stmt->operand->raw_name();
const auto src_dt = stmt->operand->element_type();
const auto dst_dt = stmt->element_type();
spirv::SType src_type = ir_->get_primitive_type(src_dt);
spirv::SType dst_type;
if (dst_dt.is_pointer()) {
auto stype = dst_dt.ptr_removed()->as<lang::StructType>();
std::vector<std::tuple<SType, std::string, size_t>> components;
for (int i = 0; i < stype->elements().size(); i++) {
components.push_back({ir_->get_primitive_type(stype->get_element_type(std::array{i})),
fmt::format("element{}", i), stype->get_element_offset(std::array{i})});
}
dst_type = ir_->create_struct_type(components);
} else {
dst_type = ir_->get_primitive_type(dst_dt);
}
spirv::Value operand_val = ir_->query_value(operand_name);
spirv::Value val = spirv::Value();
if (stmt->op_type == UnaryOpType::logic_not) {
spirv::Value zero = ir_->get_zero(src_type); // Math zero type to left hand side
if (is_integral(src_dt)) {
if (is_signed(src_dt)) {
zero = ir_->int_immediate_number(src_type, 0);
} else {
zero = ir_->uint_immediate_number(src_type, 0);
}
} else if (is_real(src_dt)) {
zero = ir_->float_immediate_number(src_type, 0);
} else {
QD_NOT_IMPLEMENTED
}
val = ir_->cast(dst_type, ir_->eq(operand_val, zero));
} else if (stmt->op_type == UnaryOpType::neg) {
operand_val = ir_->cast(dst_type, operand_val);
if (is_integral(dst_dt)) {
if (is_signed(dst_dt)) {
val = ir_->make_value(spv::OpSNegate, dst_type, operand_val);
} else {
QD_NOT_IMPLEMENTED
}
} else if (is_real(dst_dt)) {
val = ir_->make_value(spv::OpFNegate, dst_type, operand_val);
} else {
QD_NOT_IMPLEMENTED
}
} else if (stmt->op_type == UnaryOpType::rsqrt) {
const uint32_t InverseSqrt_id = 32;
if (is_real(src_dt)) {
val = ir_->call_glsl450(src_type, InverseSqrt_id, operand_val);
val = ir_->cast(dst_type, val);