-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathCodeGen_Vulkan_Dev.cpp
More file actions
3092 lines (2643 loc) · 136 KB
/
CodeGen_Vulkan_Dev.cpp
File metadata and controls
3092 lines (2643 loc) · 136 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 <algorithm>
#include <filesystem> // for dump to file
#include <fstream> // for dump to file
#include <sstream>
#include <unordered_set>
#include "CSE.h"
#include "CanonicalizeGPUVars.h"
#include "CodeGen_GPU_Dev.h"
#include "CodeGen_Internal.h"
#include "CodeGen_Vulkan_Dev.h"
#include "Debug.h"
#include "Deinterleave.h"
#include "FindIntrinsics.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "Scope.h"
#include "Simplify.h"
#include "SpirvIR.h"
#include "StrictifyFloat.h"
#include "Target.h"
#ifdef WITH_SPIRV
namespace Halide {
namespace Internal {
namespace { // anonymous
// --
class CodeGen_Vulkan_Dev : public CodeGen_GPU_Dev {
public:
CodeGen_Vulkan_Dev(Target target);
/** Compile a GPU kernel into the module. This may be called many times
* with different kernels, which will all be accumulated into a single
* source module shared by a given Halide pipeline. */
void add_kernel(Stmt stmt,
const std::string &name,
const std::vector<DeviceArgument> &args) override;
/** (Re)initialize the GPU kernel module. This is separate from compile,
* since a GPU device module will often have many kernels compiled into it
* for a single pipeline. */
void init_module() override;
std::vector<char> compile_to_src() override;
std::string get_current_kernel_name() override;
void dump() override;
std::string print_gpu_name(const std::string &name) override;
std::string api_unique_name() override {
return "vulkan";
}
protected:
class SPIRV_Emitter : public IRVisitor {
public:
SPIRV_Emitter(Target t);
using IRVisitor::visit;
void visit(const IntImm *) override;
void visit(const UIntImm *) override;
void visit(const FloatImm *) override;
void visit(const StringImm *) override;
void visit(const Cast *) override;
void visit(const Reinterpret *) override;
void visit(const Variable *) override;
void visit(const Add *) override;
void visit(const Sub *) override;
void visit(const Mul *) override;
void visit(const Div *) override;
void visit(const Mod *) override;
void visit(const Min *) override;
void visit(const Max *) override;
void visit(const EQ *) override;
void visit(const NE *) override;
void visit(const LT *) override;
void visit(const LE *) override;
void visit(const GT *) override;
void visit(const GE *) override;
void visit(const And *) override;
void visit(const Or *) override;
void visit(const Not *) override;
void visit(const Select *) override;
void visit(const Load *) override;
void visit(const Ramp *) override;
void visit(const Broadcast *) override;
void visit(const Call *) override;
void visit(const Let *) override;
void visit(const LetStmt *) override;
void visit(const AssertStmt *) override;
void visit(const For *) override;
void visit(const Store *) override;
void visit(const Provide *) override;
void visit(const Allocate *) override;
void visit(const Free *) override;
void visit(const Realize *) override;
void visit(const ProducerConsumer *op) override;
void visit(const IfThenElse *) override;
void visit(const Evaluate *) override;
void visit(const Shuffle *) override;
void visit(const VectorReduce *) override;
void visit(const Prefetch *) override;
void visit(const Fork *) override;
void visit(const Acquire *) override;
void visit(const Atomic *) override;
void reset();
// Top-level function for adding kernels
void add_kernel(const Stmt &s, const std::string &name, const std::vector<DeviceArgument> &args);
void init_spirv_module();
void encode_spirv_module(std::vector<char> &binary);
void dump_spirv_module() const;
// Encode the descriptor sets into a sidecar which will be added
// as a header to the module prior to the actual SPIR-V binary
void encode_header(SpvBinary &spirv_header);
// Scalarize expressions
void scalarize(const Expr &e);
SpvId map_type_to_pair(const Type &t);
// Workgroup size
void reset_workgroup_size();
void find_workgroup_size(const Stmt &s);
void declare_workgroup_size(SpvId kernel_func_id);
void declare_entry_point(const Stmt &s, SpvId kernel_func_id);
void declare_device_args(const Stmt &s, uint32_t entry_point_index, const std::string &kernel_name, const std::vector<DeviceArgument> &args);
// Common operator visitors
void visit_unary_op(SpvOp op_code, Type t, const Expr &a);
void visit_binary_op(SpvOp op_code, Type t, const Expr &a, const Expr &b);
void visit_glsl_op(SpvId glsl_op_code, Type t, const std::vector<Expr> &args);
void load_from_scalar_index(const Load *op, SpvId index_id, SpvId variable_id, Type value_type, Type storage_type, SpvStorageClass storage_class);
void load_from_vector_index(const Load *op, SpvId variable_id, Type value_type, Type storage_type, SpvStorageClass storage_class);
void store_at_scalar_index(const Store *op, SpvId index_id, SpvId variable_id, Type value_type, Type storage_type, SpvStorageClass storage_class, SpvId value_id);
void store_at_vector_index(const Store *op, SpvId variable_id, Type value_type, Type storage_type, SpvStorageClass storage_class, SpvId value_id);
SpvFactory::Components split_vector(Type type, SpvId value_id);
SpvId join_vector(Type type, const SpvFactory::Components &value_components);
SpvId fill_vector(Type type, SpvId value_id);
SpvId cast_type(Type target_type, Type value_type, SpvId value_id);
SpvId convert_to_bool(Type target_type, Type value_type, SpvId value_id);
// Returns Phi node inputs.
template<typename StmtOrExpr>
SpvFactory::BlockVariables emit_if_then_else(const Expr &condition, const StmtOrExpr &then_case, const StmtOrExpr &else_case);
template<typename T>
SpvId declare_constant_int(Type value_type, int64_t value);
template<typename T>
SpvId declare_constant_uint(Type value_type, uint64_t value);
template<typename T>
SpvId declare_constant_float(Type value_type, float value);
// Map from Halide built-in names to extended GLSL intrinsics for SPIR-V
using BuiltinMap = std::unordered_map<std::string, SpvId>;
const BuiltinMap glsl_builtin = {
{"acos_f16", GLSLstd450Acos},
{"acos_f32", GLSLstd450Acos},
{"acosh_f16", GLSLstd450Acosh},
{"acosh_f32", GLSLstd450Acosh},
{"asin_f16", GLSLstd450Asin},
{"asin_f32", GLSLstd450Asin},
{"asinh_f16", GLSLstd450Asinh},
{"asinh_f32", GLSLstd450Asinh},
{"atan2_f16", GLSLstd450Atan2},
{"atan2_f32", GLSLstd450Atan2},
{"atan_f16", GLSLstd450Atan},
{"atan_f32", GLSLstd450Atan},
{"atanh_f16", GLSLstd450Atanh},
{"atanh_f32", GLSLstd450Atanh},
{"ceil_f16", GLSLstd450Ceil},
{"ceil_f32", GLSLstd450Ceil},
{"cos_f16", GLSLstd450Cos},
{"cos_f32", GLSLstd450Cos},
{"cosh_f16", GLSLstd450Cosh},
{"cosh_f32", GLSLstd450Cosh},
{"exp_f16", GLSLstd450Exp},
{"exp_f32", GLSLstd450Exp},
{"fast_inverse_sqrt_f16", GLSLstd450InverseSqrt},
{"fast_inverse_sqrt_f32", GLSLstd450InverseSqrt},
{"fast_log_f16", GLSLstd450Log},
{"fast_log_f32", GLSLstd450Log},
{"fast_exp_f16", GLSLstd450Exp},
{"fast_exp_f32", GLSLstd450Exp},
{"fast_pow_f16", GLSLstd450Pow},
{"fast_pow_f32", GLSLstd450Pow},
{"floor_f16", GLSLstd450Floor},
{"floor_f32", GLSLstd450Floor},
{"fma", GLSLstd450Fma},
{"log_f16", GLSLstd450Log},
{"log_f32", GLSLstd450Log},
{"sin_f16", GLSLstd450Sin},
{"sin_f32", GLSLstd450Sin},
{"sinh_f16", GLSLstd450Sinh},
{"sinh_f32", GLSLstd450Sinh},
{"sqrt_f16", GLSLstd450Sqrt},
{"sqrt_f32", GLSLstd450Sqrt},
{"tan_f16", GLSLstd450Tan},
{"tan_f32", GLSLstd450Tan},
{"tanh_f16", GLSLstd450Tanh},
{"tanh_f32", GLSLstd450Tanh},
{"trunc_f16", GLSLstd450Trunc},
{"trunc_f32", GLSLstd450Trunc},
{"mix", GLSLstd450FMix},
};
// The SPIRV-IR builder
SpvBuilder builder;
// The scope contains both the symbol id and its storage class
using SymbolIdStorageClassPair = std::pair<SpvId, SpvStorageClass>;
using SymbolScope = Scope<SymbolIdStorageClassPair>;
using ScopedSymbolBinding = ScopedBinding<SymbolIdStorageClassPair>;
SymbolScope symbol_table;
// Map from a variable ID to its corresponding storage type definition
struct StorageAccess {
SpvStorageClass storage_class = SpvStorageClassMax;
uint32_t storage_array_size = 0; // zero if not an array
SpvId storage_type_id = SpvInvalidId;
Type storage_type;
};
using StorageAccessMap = std::unordered_map<SpvId, StorageAccess>;
StorageAccessMap storage_access_map;
// Defines the binding information for a specialization constant
// that is exported by the module and can be overriden at runtime
struct SpecializationBinding {
SpvId constant_id = 0;
uint32_t type_size = 0;
std::string constant_name;
};
using SpecializationConstants = std::vector<SpecializationBinding>;
// Defines a shared memory allocation
struct SharedMemoryAllocation {
SpvId constant_id = 0; // specialization constant to dynamically adjust array size (zero if not used)
uint32_t array_size = 0;
uint32_t type_size = 0;
std::string variable_name;
};
using SharedMemoryUsage = std::vector<SharedMemoryAllocation>;
// Defines the specialization constants used for dynamically overiding the dispatch size
struct WorkgroupSizeBinding {
SpvId local_size_constant_id[3] = {0, 0, 0}; // zero if unused
};
// Keep track of the descriptor sets so we can add a sidecar to the
// module indicating which descriptor set to use for each entry point
struct DescriptorSet {
std::string entry_point_name;
uint32_t uniform_buffer_count = 0;
uint32_t storage_buffer_count = 0;
SpecializationConstants specialization_constants;
SharedMemoryUsage shared_memory_usage;
WorkgroupSizeBinding workgroup_size_binding;
};
using DescriptorSetTable = std::vector<DescriptorSet>;
DescriptorSetTable descriptor_set_table;
// The workgroup size ... this indicates the extents of the 1-3 dimensional index space
// used as part of the kernel dispatch. It can also be used to adjust the layout for work
// items (aka GPU threads), based on logical groupings. If a zero sized workgroup is
// encountered during CodeGen, it is assumed that the extents are dynamic and specified
// at runtime
uint32_t workgroup_size[3];
// Current index of kernel for module
uint32_t kernel_index = 0;
// Target for codegen
Target target;
};
// Current target for codegen
Target current_target;
// Current kernel name for CodeGen
std::string current_kernel_name;
// In order to avoid using up all descriptor sets for complicated pipelines,
// we will encode each Kernel entry-point into it's own SPIR-V module and
// bind them as separate shaders to avoid running out of resources on
// constrained devices.
struct KernelModule {
std::string kernel_name;
std::vector<char> spirv_module; // header + binary
};
using KernelModuleTable = std::vector<KernelModule>;
KernelModuleTable kernel_module_table;
// merge the contents of the kernel module table into a single binary
// containing a header followed by the SPIR-V modules for each kernel
void encode_module(std::vector<char> &module);
// dump the contents of the combined module, outputting separate
// SPIR-V binary files for each kernel
void dump_module(const std::vector<char> &module);
};
// Check if all loads and stores to the member 'buffer' are dense, aligned, and
// have the same number of lanes. If this is indeed the case then the 'lanes'
// member stores the number of lanes in those loads and stores.
//
class CheckAlignedDenseVectorLoadStore : public IRVisitor {
public:
// True if all loads and stores from the buffer are dense, aligned, and all
// have the same number of lanes, false otherwise.
bool are_all_dense = true;
// The number of lanes in the loads and stores. If the number of lanes is
// variable, then are_all_dense is set to false regardless, and this value
// is undefined. Initially set to -1 before any dense operation is
// discovered.
int lanes = -1;
CheckAlignedDenseVectorLoadStore(std::string name)
: buffer_name(std::move(name)) {
}
private:
// The name of the buffer to check.
std::string buffer_name;
using IRVisitor::visit;
void visit(const Load *op) override {
IRVisitor::visit(op);
if (op->name != buffer_name) {
return;
}
if (op->type.is_scalar()) {
are_all_dense = false;
return;
}
Expr ramp_base = strided_ramp_base(op->index);
if (!ramp_base.defined()) {
are_all_dense = false;
return;
}
if ((op->alignment.modulus % op->type.lanes() != 0) ||
(op->alignment.remainder % op->type.lanes() != 0)) {
are_all_dense = false;
return;
}
if (lanes != -1 && op->type.lanes() != lanes) {
are_all_dense = false;
return;
}
lanes = op->type.lanes();
}
void visit(const Store *op) override {
IRVisitor::visit(op);
if (op->name != buffer_name) {
return;
}
if (op->value.type().is_scalar()) {
are_all_dense = false;
return;
}
Expr ramp_base = strided_ramp_base(op->index);
if (!ramp_base.defined()) {
are_all_dense = false;
return;
}
if ((op->alignment.modulus % op->value.type().lanes() != 0) ||
(op->alignment.remainder % op->value.type().lanes() != 0)) {
are_all_dense = false;
return;
}
if (lanes != -1 && op->value.type().lanes() != lanes) {
are_all_dense = false;
return;
}
lanes = op->value.type().lanes();
}
};
struct FindWorkGroupSize : public IRVisitor {
using IRVisitor::visit;
void visit(const For *loop) override {
user_assert(loop->for_type != ForType::GPULane)
<< "The Vulkan backend does not support the gpu_lanes() scheduling directive.";
if (is_gpu(loop->for_type)) {
// This should always be true at this point in codegen
internal_assert(is_const_zero(loop->min));
// Save & validate the workgroup size
int index = thread_loop_workgroup_index(loop->name);
if (index >= 0) {
Expr extent = simplify(loop->extent());
const IntImm *literal = extent.as<IntImm>();
if (literal != nullptr) {
uint32_t new_wg_size = literal->value;
user_assert(workgroup_size[index] == 0 || workgroup_size[index] == new_wg_size)
<< "Vulkan requires all kernels have the same workgroup size, "
<< "but two different sizes were encountered: "
<< workgroup_size[index] << " and "
<< new_wg_size << " in dimension " << index << "\n";
workgroup_size[index] = new_wg_size;
}
}
debug(4) << "Thread group size for index " << index << " is " << workgroup_size[index] << "\n";
}
loop->body.accept(this);
}
int thread_loop_workgroup_index(const std::string &name) {
for (size_t i = 0; i < 3; i++) {
if (ends_with(name, gpu_thread_name(i))) {
return i;
}
}
return -1;
}
uint32_t workgroup_size[3] = {0, 0, 0};
};
CodeGen_Vulkan_Dev::SPIRV_Emitter::SPIRV_Emitter(Target t)
: IRVisitor(), target(t) {
// Empty
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::scalarize(const Expr &e) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::scalarize(): " << (Expr)e << "\n";
internal_assert(e.type().is_vector()) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::scalarize must be called with an expression of vector type.\n";
SpvId type_id = builder.declare_type(e.type());
SpvId value_id = builder.declare_null_constant(e.type());
SpvId result_id = value_id;
for (int i = 0; i < e.type().lanes(); i++) {
extract_lane(e, i).accept(this);
SpvId extracted_id = builder.current_id();
SpvId composite_id = builder.reserve_id(SpvResultId);
SpvFactory::Indices indices = {(uint32_t)i};
builder.append(SpvFactory::composite_insert(type_id, composite_id, extracted_id, value_id, indices));
result_id = composite_id;
}
builder.update_id(result_id);
}
SpvId CodeGen_Vulkan_Dev::SPIRV_Emitter::map_type_to_pair(const Type &t) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::map_type_to_pair(): " << t << "\n";
SpvId base_type_id = builder.declare_type(t);
SpvBuilder::StructMemberTypes member_type_ids = {base_type_id, base_type_id};
const std::string struct_name = std::string("_struct_") + type_to_c_type(t, false, false) + std::string("_pair");
SpvId struct_type_id = builder.declare_struct(struct_name, member_type_ids);
return struct_type_id;
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Variable *var) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Variable): " << var->type << " " << var->name << "\n";
SpvId variable_id = symbol_table.get(var->name).first;
user_assert(variable_id != SpvInvalidId) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Variable): Invalid symbol name!\n";
builder.update_id(variable_id);
}
template<typename T>
SpvId CodeGen_Vulkan_Dev::SPIRV_Emitter::declare_constant_int(Type value_type, int64_t value) {
const T typed_value = (T)(value);
SpvId constant_id = builder.declare_constant(value_type, &typed_value);
builder.update_id(constant_id);
return constant_id;
}
template<typename T>
SpvId CodeGen_Vulkan_Dev::SPIRV_Emitter::declare_constant_uint(Type value_type, uint64_t value) {
const T typed_value = (T)(value);
SpvId constant_id = builder.declare_constant(value_type, &typed_value);
builder.update_id(constant_id);
return constant_id;
}
template<typename T>
SpvId CodeGen_Vulkan_Dev::SPIRV_Emitter::declare_constant_float(Type value_type, float value) {
const T typed_value = (T)(value);
SpvId constant_id = builder.declare_constant(value_type, &typed_value);
builder.update_id(constant_id);
return constant_id;
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const IntImm *imm) {
if (imm->type.bits() == 8) {
declare_constant_int<int8_t>(imm->type, imm->value);
} else if (imm->type.bits() == 16) {
declare_constant_int<int16_t>(imm->type, imm->value);
} else if (imm->type.bits() == 32) {
declare_constant_int<int32_t>(imm->type, imm->value);
} else if (imm->type.bits() == 64) {
declare_constant_int<int64_t>(imm->type, imm->value);
} else {
internal_error << "Vulkan backend currently only supports 8-bit, 16-bit, 32-bit or 64-bit signed integers!\n";
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const UIntImm *imm) {
if (imm->type.bits() == 8) {
declare_constant_uint<uint8_t>(imm->type, imm->value);
} else if (imm->type.bits() == 16) {
declare_constant_uint<uint16_t>(imm->type, imm->value);
} else if (imm->type.bits() == 32) {
declare_constant_uint<uint32_t>(imm->type, imm->value);
} else if (imm->type.bits() == 64) {
declare_constant_uint<uint64_t>(imm->type, imm->value);
} else {
internal_error << "Vulkan backend currently only supports 8-bit, 16-bit, 32-bit or 64-bit unsigned integers!\n";
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const StringImm *imm) {
SpvId constant_id = builder.declare_string_constant(imm->value);
builder.update_id(constant_id);
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const FloatImm *imm) {
if (imm->type.bits() == 16) {
if (imm->type.is_bfloat()) {
declare_constant_float<bfloat16_t>(imm->type, imm->value);
} else {
declare_constant_float<float16_t>(imm->type, imm->value);
}
} else if (imm->type.bits() == 32) {
declare_constant_float<float>(imm->type, imm->value);
} else if (imm->type.bits() == 64) {
declare_constant_float<double>(imm->type, imm->value);
} else {
internal_error << "Vulkan backend currently only supports 16-bit, 32-bit or 64-bit floats\n";
}
}
template<typename T>
void fill_bytes_with_value(uint8_t *bytes, int count, int value) {
T *v = reinterpret_cast<T *>(bytes);
for (int i = 0; i < count; ++i) {
v[i] = (T)value;
}
}
SpvId CodeGen_Vulkan_Dev::SPIRV_Emitter::convert_to_bool(Type target_type, Type value_type, SpvId value_id) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::convert_to_bool(): casting from value type '"
<< value_type << "' to target type '" << target_type << "' for value id '" << value_id << "' !\n";
if (!value_type.is_bool()) {
value_id = cast_type(Bool(), value_type, value_id);
}
const int true_value = 1;
const int false_value = 0;
std::vector<uint8_t> true_data(target_type.bytes(), (uint8_t)0);
std::vector<uint8_t> false_data(target_type.bytes(), (uint8_t)0);
if (target_type.is_int_or_uint() && target_type.bits() == 8) {
fill_bytes_with_value<int8_t>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<int8_t>(&false_data[0], target_type.lanes(), false_value);
} else if (target_type.is_int_or_uint() && target_type.bits() == 16) {
fill_bytes_with_value<int16_t>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<int16_t>(&false_data[0], target_type.lanes(), false_value);
} else if (target_type.is_int_or_uint() && target_type.bits() == 32) {
fill_bytes_with_value<int32_t>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<int32_t>(&false_data[0], target_type.lanes(), false_value);
} else if (target_type.is_int_or_uint() && target_type.bits() == 64) {
fill_bytes_with_value<int64_t>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<int64_t>(&false_data[0], target_type.lanes(), false_value);
} else if (target_type.is_float() && target_type.bits() == 16) {
if (target_type.is_bfloat()) {
fill_bytes_with_value<bfloat16_t>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<bfloat16_t>(&false_data[0], target_type.lanes(), false_value);
} else {
fill_bytes_with_value<float16_t>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<float16_t>(&false_data[0], target_type.lanes(), false_value);
}
} else if (target_type.is_float() && target_type.bits() == 32) {
fill_bytes_with_value<float>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<float>(&false_data[0], target_type.lanes(), false_value);
} else if (target_type.is_float() && target_type.bits() == 64) {
fill_bytes_with_value<double>(&true_data[0], target_type.lanes(), true_value);
fill_bytes_with_value<double>(&false_data[0], target_type.lanes(), false_value);
} else {
user_error << "Unhandled type cast from value type '" << value_type << "' to target type '" << target_type << "'!";
}
SpvId result_id = builder.reserve_id(SpvResultId);
SpvId target_type_id = builder.declare_type(target_type);
SpvId true_value_id = builder.declare_constant(target_type, &true_data[0]);
SpvId false_value_id = builder.declare_constant(target_type, &false_data[0]);
builder.append(SpvFactory::select(target_type_id, result_id, value_id, true_value_id, false_value_id));
return result_id;
}
SpvId CodeGen_Vulkan_Dev::SPIRV_Emitter::cast_type(Type target_type, Type value_type, SpvId value_id) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::cast_type(): casting from value type '"
<< value_type << "' to target type '" << target_type << "'!\n";
if (value_type == target_type) {
return value_id;
}
SpvOp op_code = SpvOpNop;
if (value_type.is_float()) {
if (target_type.is_float()) {
op_code = SpvOpFConvert;
} else if (target_type.is_bool()) {
op_code = SpvOpSelect;
} else if (target_type.is_uint()) {
op_code = SpvOpConvertFToU;
} else if (target_type.is_int()) {
op_code = SpvOpConvertFToS;
}
} else if (value_type.is_bool()) {
op_code = SpvOpSelect;
} else if (value_type.is_uint()) {
if (target_type.is_float()) {
op_code = SpvOpConvertUToF;
} else if (target_type.is_bool()) {
op_code = SpvOpSelect;
} else if (target_type.is_int_or_uint()) {
op_code = SpvOpUConvert;
}
} else if (value_type.is_int()) {
if (target_type.is_float()) {
op_code = SpvOpConvertSToF;
} else if (target_type.is_bool()) {
op_code = SpvOpSelect;
} else if (target_type.is_int_or_uint()) {
op_code = SpvOpSConvert;
}
}
// If none of the explicit conversions matched, do a direct bitcast if the total
// size of both types is the same
if (op_code == SpvOpNop) {
if (target_type.bytes() == value_type.bytes()) {
op_code = SpvOpBitcast;
}
}
// Error If we still didn't find a suitable cast ...
if (op_code == SpvOpNop) {
user_error << "Unhandled type cast from value type '" << value_type << "' to target type '" << target_type << "'!";
return SpvInvalidId;
}
SpvId result_id = SpvInvalidId;
SpvId target_type_id = builder.declare_type(target_type);
if (op_code == SpvOpBitcast) {
result_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::bitcast(target_type_id, result_id, value_id));
} else if (op_code == SpvOpSelect) {
result_id = convert_to_bool(target_type, value_type, value_id);
} else if (op_code == SpvOpUConvert && target_type.is_int()) {
// SPIR-V requires both value and target types to be unsigned and of
// different component bit widths in order to be compatible with UConvert
// ... so do the conversion to an equivalent unsigned type then bitcast this
// result into the target type
Type unsigned_type = target_type.with_code(halide_type_uint);
if (unsigned_type.bytes() != value_type.bytes()) {
SpvId unsigned_type_id = builder.declare_type(unsigned_type);
SpvId unsigned_value_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::convert(op_code, unsigned_type_id, unsigned_value_id, value_id));
value_id = unsigned_value_id;
}
result_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::bitcast(target_type_id, result_id, value_id));
} else if (op_code == SpvOpSConvert && target_type.is_uint()) {
// Same as above but for SConvert
Type signed_type = target_type.with_code(halide_type_int);
if (signed_type.bytes() != value_type.bytes()) {
SpvId signed_type_id = builder.declare_type(signed_type);
SpvId signed_value_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::convert(op_code, signed_type_id, signed_value_id, value_id));
value_id = signed_value_id;
}
result_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::bitcast(target_type_id, result_id, value_id));
} else {
result_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::convert(op_code, target_type_id, result_id, value_id));
}
return result_id;
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Cast *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Cast): " << op->value.type() << " to " << op->type << "\n";
Type value_type = op->value.type();
Type target_type = op->type;
op->value.accept(this);
SpvId value_id = builder.current_id();
if ((value_type.is_vector() && target_type.is_vector())) {
if (value_type.lanes() == target_type.lanes()) {
SpvId result_id = cast_type(target_type, value_type, value_id);
builder.update_id(result_id);
} else {
user_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Cast): unhandled case " << op->value.type() << " to " << op->type << " (incompatible lanes)\n";
}
} else if (value_type.is_scalar() && target_type.is_scalar()) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Cast): scalar type (cast)\n";
SpvId result_id = cast_type(target_type, value_type, value_id);
builder.update_id(result_id);
} else if (value_type.bytes() == target_type.bytes()) {
SpvId result_id = cast_type(target_type, value_type, value_id);
builder.update_id(result_id);
} else {
user_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Cast): unhandled case " << op->value.type() << " to " << op->type << "\n";
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Reinterpret *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Reinterpret): " << op->value.type() << " to " << op->type << "\n";
SpvId type_id = builder.declare_type(op->type);
op->value.accept(this);
SpvId src_id = builder.current_id();
SpvId result_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::bitcast(type_id, result_id, src_id));
builder.update_id(result_id);
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Add *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Add): " << op->type << " ((" << op->a << ") + (" << op->b << "))\n";
visit_binary_op(op->type.is_float() ? SpvOpFAdd : SpvOpIAdd, op->type, op->a, op->b);
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Sub *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Sub): " << op->type << " ((" << op->a << ") - (" << op->b << "))\n";
visit_binary_op(op->type.is_float() ? SpvOpFSub : SpvOpISub, op->type, op->a, op->b);
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Mul *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Mul): " << op->type << " ((" << op->a << ") * (" << op->b << "))\n";
visit_binary_op(op->type.is_float() ? SpvOpFMul : SpvOpIMul, op->type, op->a, op->b);
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Div *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Div): " << op->type << " ((" << op->a << ") / (" << op->b << "))\n";
user_assert(!is_const_zero(op->b)) << "Division by constant zero in expression: " << Expr(op) << "\n";
if (op->type.is_int()) {
Expr e = lower_euclidean_div(op->a, op->b);
e.accept(this);
} else if (op->type.is_uint()) {
visit_binary_op(SpvOpUDiv, op->type, op->a, op->b);
} else if (op->type.is_float()) {
visit_binary_op(SpvOpFDiv, op->type, op->a, op->b);
} else {
internal_error << "Failed to find a suitable Div operator for type: " << op->type << "\n";
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Mod *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Mod): " << op->type << " ((" << op->a << ") % (" << op->b << "))\n";
if (auto bits = is_const_power_of_two_integer(op->b)) {
op->a.accept(this);
SpvId src_a_id = builder.current_id();
int bitwise_value = ((1 << *bits) - 1);
Expr expr = make_const(op->type, bitwise_value);
expr.accept(this);
SpvId src_b_id = builder.current_id();
SpvId type_id = builder.declare_type(op->type);
SpvId result_id = builder.reserve_id(SpvResultId);
builder.append(SpvFactory::binary_op(SpvOpBitwiseAnd, type_id, result_id, src_a_id, src_b_id));
builder.update_id(result_id);
} else if (op->type.is_int() || op->type.is_uint()) {
// Just exploit the Euclidean identity
Expr zero = make_zero(op->type);
Expr equiv = select(op->a == zero, zero,
op->a - (op->a / op->b) * op->b);
equiv = common_subexpression_elimination(equiv);
equiv.accept(this);
} else if (op->type.is_float()) {
// SPIR-V FMod is strangely not what we want .. FRem does what we need
visit_binary_op(SpvOpFRem, op->type, op->a, op->b);
} else {
internal_error << "Failed to find a suitable Mod operator for type: " << op->type << "\n";
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Max *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Max): " << op->type << " Max((" << op->a << "), (" << op->b << "))\n";
SpvId op_code = SpvOpNop;
if (op->type.is_float()) {
op_code = GLSLstd450FMax;
} else if (op->type.is_int()) {
op_code = GLSLstd450SMax;
} else if (op->type.is_uint()) {
op_code = GLSLstd450UMax;
} else {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Max *op): unhandled type: " << op->type << "\n";
}
std::vector<Expr> args;
args.reserve(2);
if (op->type.is_vector()) {
if (op->a.type().is_scalar()) {
Expr a_vector = Broadcast::make(op->a, op->type.lanes());
args.push_back(a_vector);
} else {
args.push_back(op->a);
}
if (op->b.type().is_scalar()) {
Expr b_vector = Broadcast::make(op->b, op->type.lanes());
args.push_back(b_vector);
} else {
args.push_back(op->b);
}
} else {
args.push_back(op->a);
args.push_back(op->b);
}
visit_glsl_op(op_code, op->type, args);
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Min *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(Min): " << op->type << " Min((" << op->a << "), (" << op->b << "))\n";
SpvId op_code = SpvOpNop;
if (op->type.is_float()) {
op_code = GLSLstd450FMin;
} else if (op->type.is_int()) {
op_code = GLSLstd450SMin;
} else if (op->type.is_uint()) {
op_code = GLSLstd450UMin;
} else {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const Min *op): unhandled type: " << op->type << "\n";
}
std::vector<Expr> args;
args.reserve(2);
if (op->type.is_vector()) {
if (op->a.type().is_scalar()) {
Expr a_vector = Broadcast::make(op->a, op->type.lanes());
args.push_back(a_vector);
} else {
args.push_back(op->a);
}
if (op->b.type().is_scalar()) {
Expr b_vector = Broadcast::make(op->b, op->type.lanes());
args.push_back(b_vector);
} else {
args.push_back(op->b);
}
} else {
args.push_back(op->a);
args.push_back(op->b);
}
visit_glsl_op(op_code, op->type, args);
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const EQ *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(EQ): " << op->type << " (" << op->a << ") == (" << op->b << ")\n";
if (op->a.type() != op->b.type()) {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const EQ *op): Mismatched operand types: " << op->a.type() << " != " << op->b.type() << "\n";
}
SpvOp op_code = SpvOpNop;
if (op->a.type().is_float()) {
op_code = SpvOpFOrdEqual;
} else {
op_code = SpvOpIEqual;
}
Type bool_type = UInt(1, op->type.lanes());
visit_binary_op(op_code, bool_type, op->a, op->b);
if (!op->type.is_bool()) {
SpvId current_id = builder.current_id();
SpvId result_id = cast_type(op->type, bool_type, current_id);
builder.update_id(result_id);
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const NE *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(NE): " << op->type << " (" << op->a << ") != (" << op->b << ")\n";
if (op->a.type() != op->b.type()) {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const NE *op): Mismatched operand types: " << op->a.type() << " != " << op->b.type() << "\n";
}
SpvOp op_code = SpvOpNop;
if (op->a.type().is_float()) {
op_code = SpvOpFOrdNotEqual;
} else {
op_code = SpvOpINotEqual;
}
Type bool_type = UInt(1, op->type.lanes());
visit_binary_op(op_code, bool_type, op->a, op->b);
if (!op->type.is_bool()) {
Type bool_type = UInt(1, op->type.lanes());
SpvId current_id = builder.current_id();
SpvId result_id = cast_type(op->type, bool_type, current_id);
builder.update_id(result_id);
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const LT *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(LT): " << op->type << " (" << op->a << ") < (" << op->b << ")\n";
if (op->a.type() != op->b.type()) {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const LT *op): Mismatched operand types: " << op->a.type() << " != " << op->b.type() << "\n";
}
SpvOp op_code = SpvOpNop;
if (op->a.type().is_float()) {
op_code = SpvOpFOrdLessThan;
} else if (op->a.type().is_int()) {
op_code = SpvOpSLessThan;
} else if (op->a.type().is_uint()) {
op_code = SpvOpULessThan;
} else {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const LT *op): unhandled type: " << op->a.type() << "\n";
}
Type bool_type = UInt(1, op->type.lanes());
visit_binary_op(op_code, bool_type, op->a, op->b);
if (!op->type.is_bool()) {
Type bool_type = UInt(1, op->type.lanes());
SpvId current_id = builder.current_id();
SpvId result_id = cast_type(op->type, bool_type, current_id);
builder.update_id(result_id);
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const LE *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(LE): " << op->type << " (" << op->a << ") <= (" << op->b << ")\n";
if (op->a.type() != op->b.type()) {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const LE *op): Mismatched operand types: " << op->a.type() << " != " << op->b.type() << "\n";
}
SpvOp op_code = SpvOpNop;
if (op->a.type().is_float()) {
op_code = SpvOpFOrdLessThanEqual;
} else if (op->a.type().is_int()) {
op_code = SpvOpSLessThanEqual;
} else if (op->a.type().is_uint()) {
op_code = SpvOpULessThanEqual;
} else {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const LE *op): unhandled type: " << op->a.type() << "\n";
}
Type bool_type = UInt(1, op->type.lanes());
visit_binary_op(op_code, bool_type, op->a, op->b);
if (!op->type.is_bool()) {
Type bool_type = UInt(1, op->type.lanes());
SpvId current_id = builder.current_id();
SpvId result_id = cast_type(op->type, bool_type, current_id);
builder.update_id(result_id);
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const GT *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(GT): " << op->type << " (" << op->a << ") > (" << op->b << ")\n";
if (op->a.type() != op->b.type()) {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const GT *op): Mismatched operand types: " << op->a.type() << " != " << op->b.type() << "\n";
}
SpvOp op_code = SpvOpNop;
if (op->a.type().is_float()) {
op_code = SpvOpFOrdGreaterThan;
} else if (op->a.type().is_int()) {
op_code = SpvOpSGreaterThan;
} else if (op->a.type().is_uint()) {
op_code = SpvOpUGreaterThan;
} else {
internal_error << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const GT *op): unhandled type: " << op->a.type() << "\n";
}
Type bool_type = UInt(1, op->type.lanes());
visit_binary_op(op_code, bool_type, op->a, op->b);
if (!op->type.is_bool()) {
Type bool_type = UInt(1, op->type.lanes());
SpvId current_id = builder.current_id();
SpvId result_id = cast_type(op->type, bool_type, current_id);
builder.update_id(result_id);
}
}
void CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(const GE *op) {
debug(2) << "CodeGen_Vulkan_Dev::SPIRV_Emitter::visit(GE): " << op->type << " (" << op->a << ") >= (" << op->b << ")\n";