-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspirv_to_llvm.cpp
More file actions
5814 lines (5705 loc) · 248 KB
/
spirv_to_llvm.cpp
File metadata and controls
5814 lines (5705 loc) · 248 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 "3rdparty/SPIRV/GLSL.std.450.h"
#include "3rdparty/SPIRV/spirv.hpp"
//#include <fstream>
//#include <iostream>
#include <map>
#include <set>
#define UTILS_IMPL
#include "utils.hpp"
#include "vk.hpp"
#include "llvm/ExecutionEngine/Orc/LLJIT.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Vectorize.h"
#include <llvm/ExecutionEngine/JITEventListener.h>
#include <llvm/ExecutionEngine/ObjectCache.h>
#include <llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h>
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Mangler.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/NoFolder.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <spirv-tools/libspirv.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "llvm_stdlib_1.h"
#include "llvm_stdlib_4.h"
#include "llvm_stdlib_64.h"
#define LOOKUP_FN(name) \
llvm::Function *name = module->getFunction(#name); \
ASSERT_ALWAYS(name != NULL);
#define LOOKUP_TY(name) \
llvm::Type *name = module->getTypeByName(#name); \
ASSERT_ALWAYS(name != NULL);
void llvm_fatal(void *user_data, const std::string &reason, bool gen_crash_diag) {
fprintf(stderr, "[LLVM_FATAL] %s\n", reason.c_str());
abort();
}
static void WARNING(char const *fmt, ...) {
static char buf[0x100];
va_list argptr;
va_start(argptr, fmt);
vsnprintf(buf, sizeof(buf), fmt, argptr);
va_end(argptr);
fprintf(stderr, "[WARNING] %s\n", buf);
}
void *read_file(const char *filename, size_t *size, Allocator *allocator = NULL) {
if (allocator == NULL) allocator = Allocator::get_default();
FILE *f = fopen(filename, "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
*size = (size_t)fsize;
char *data = (char *)allocator->alloc((size_t)fsize);
fread(data, 1, (size_t)fsize, f);
fclose(f);
return data;
}
// Lives on the heap, so pointers are persistent
struct Jitted_Shader {
class MyObjectCache : public llvm::ObjectCache {
public:
void notifyObjectCompiled(const llvm::Module *M, llvm::MemoryBufferRef ObjBuffer) override {
auto buf = llvm::MemoryBuffer::getMemBufferCopy(ObjBuffer.getBuffer(),
ObjBuffer.getBufferIdentifier());
if (dump) {
TMP_STORAGE_SCOPE;
char tmp_buf[0x100];
// Dump object file
{
string_ref dir = stref_s("shader_dumps/obj/");
make_dir_recursive(dir);
snprintf(tmp_buf, sizeof(tmp_buf), "%lx.o", code_hash);
string_ref final_path = stref_concat(dir, stref_s(tmp_buf));
dump_file(stref_to_tmp_cstr(final_path), buf->getBufferStart(),
(size_t)(buf->getBufferSize()));
}
}
}
std::unique_ptr<llvm::MemoryBuffer> getObject(const llvm::Module *M) override {
return nullptr;
}
bool dump = false;
u64 code_hash;
};
void init(u64 code_hash, bool debug_info = true, bool dump = false) {
obj_cache.dump = dump;
obj_cache.code_hash = code_hash;
llvm::ExitOnError ExitOnErr;
static_cast<llvm::orc::RTDyldObjectLinkingLayer &>(jit->getObjLinkingLayer())
.registerJITEventListener(*llvm::JITEventListener::createGDBRegistrationListener());
jit->getIRTransformLayer().setTransform(
[&](llvm::orc::ThreadSafeModule TSM, const llvm::orc::MaterializationResponsibility &R) {
TSM.withModuleDo([&](llvm::Module &M) {
});
return TSM;
});
jit->getMainJITDylib().addGenerator(
ExitOnErr(llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
jit->getDataLayout().getGlobalPrefix())));
#define LOOKUP(name) \
symbols.name = (typeof(symbols.name))ExitOnErr(jit->lookup(#name)).getAddress();
LOOKUP(spv_main)
LOOKUP(get_private_size)
LOOKUP(get_input_count)
LOOKUP(get_input_stride)
LOOKUP(get_output_stride)
LOOKUP(get_export_count)
LOOKUP(get_output_count)
LOOKUP(get_export_items)
LOOKUP(get_input_slots)
LOOKUP(get_output_slots)
LOOKUP(get_subgroup_size)
#undef LOOKUP
symbols.input_item_count = symbols.get_input_count();
symbols.get_input_slots((u32 *)&symbols.input_slots[0]);
symbols.output_item_count = symbols.get_output_count();
symbols.input_stride = symbols.get_input_stride();
symbols.output_stride = symbols.get_output_stride();
symbols.subgroup_size = symbols.get_subgroup_size();
symbols.get_output_slots((u32 *)&symbols.output_slots[0]);
symbols.private_storage_size = symbols.get_private_size();
symbols.export_count = symbols.get_export_count();
symbols.get_export_items(&symbols.export_items[0]);
symbols.code_hash = code_hash;
// std::string str;
// llvm::raw_string_ostream os(str);
// jit->getMainJITDylib().dump(os);
// os.flush();
// fprintf(stdout, "%s", str.c_str());
}
MyObjectCache obj_cache;
Shader_Symbols symbols;
std::unique_ptr<llvm::orc::LLJIT> jit;
};
namespace llvm {
struct My_Dump_Pass : llvm::ModulePass {
static char ID;
u64 code_hash;
explicit My_Dump_Pass(u64 code_hash = 0) : llvm::ModulePass(ID), code_hash(code_hash) {}
virtual bool runOnModule(llvm::Module &M) override {
static u32 dump_id = 0;
TMP_STORAGE_SCOPE;
char buf[0x100];
// Print llvm dumps
{
std::string str;
llvm::raw_string_ostream os(str);
M.print(os, NULL);
os.flush();
string_ref dir = stref_s("shader_dumps/llvm/");
make_dir_recursive(dir);
snprintf(buf, sizeof(buf), "%lx.%i.ll", code_hash, dump_id++);
string_ref final_path = stref_concat(dir, stref_s(buf));
dump_file(stref_to_tmp_cstr(final_path), str.c_str(), str.length());
}
return false;
}
};
char My_Dump_Pass::ID = 0;
} // namespace llvm
llvm::My_Dump_Pass *create_my_dump_pass(u64 code_hash) { return new llvm::My_Dump_Pass(code_hash); }
//////////////////////////
// Meta data structures //
//////////////////////////
struct FunTy {
u32 id;
std::vector<u32> params;
u32 ret;
};
struct ImageTy {
u32 id;
u32 sampled_type;
spv::Dim dim;
bool depth;
bool arrayed;
bool ms;
u32 sampled;
spv::ImageFormat format;
spv::AccessQualifier access;
};
struct Sampled_ImageTy {
u32 id;
u32 sampled_image;
};
struct SamplerTy {
u32 id;
};
struct Decoration {
u32 target_id;
spv::Decoration type;
u32 param1;
u32 param2;
u32 param3;
u32 param4;
};
struct Member_Decoration {
u32 target_id;
u32 member_id;
spv::Decoration type;
u32 param1;
u32 param2;
u32 param3;
u32 param4;
};
enum class Primitive_t { I1, I8, I16, I32, I64, U8, U16, U32, U64, F8, F16, F32, F64, Void };
struct PrimitiveTy {
u32 id;
Primitive_t type;
};
struct VectorTy {
u32 id;
// Must be primitive?
u32 member_id;
// the number of rows
u32 width;
};
struct Constant {
u32 id;
u32 type;
union {
u32 i32_val;
float f32_val;
};
};
struct ConstantComposite {
u32 id;
u32 type;
std::vector<u32> components;
};
struct ArrayTy {
u32 id;
// could be anything?
u32 member_id;
// constants[width_id]
u32 width_id;
};
struct MatrixTy {
u32 id;
// vector_types[vector_id] : column type
u32 vector_id;
// the number of columns
u32 width;
};
struct StructTy {
u32 id;
bool is_builtin;
std::vector<u32> member_types;
std::vector<u32> member_offsets;
// Apparently there could be stuff like that
// out gl_PerVertex
// {
// vec4 gl_Position;
// };
std::vector<spv::BuiltIn> member_builtins;
u32 size;
};
struct PtrTy {
u32 id;
u32 target_id;
spv::StorageClass storage_class;
};
struct Variable {
u32 id;
// Must be a pointer
u32 type_id;
spv::StorageClass storage;
// Optional
u32 init_id;
};
struct FunctionParameter {
u32 id;
u32 type_id;
};
struct Function {
u32 id;
u32 result_type;
spv::FunctionControlMask control;
u32 function_type;
std::vector<FunctionParameter> params;
// Debug mapping
u32 spirv_line;
};
enum class DeclTy {
PrimitiveTy,
Variable,
Function,
PtrTy,
RuntimeArrayTy,
VectorTy,
Constant,
ConstantComposite,
ArrayTy,
ImageTy,
SamplerTy,
Sampled_ImageTy,
FunTy,
MatrixTy,
StructTy,
Unknown
};
struct Entry {
u32 id;
spv::ExecutionModel execution_model;
std::string name;
};
struct Parsed_Op {
spv::Op op;
std::vector<u32> args;
};
#include "spv_dump.hpp"
struct Spirv_Builder {
//////////////////////
// Options //
//////////////////////
u32 opt_subgroup_size = 4;
bool opt_debug_comments = false;
bool opt_debug_info = true;
bool opt_dump = false;
bool opt_llvm_dump = false;
// bool opt_deinterleave_attributes = false;
//////////////////////
// Meta information //
//////////////////////
std::map<u32, PrimitiveTy> primitive_types;
std::map<u32, Variable> variables;
std::map<u32, Function> functions;
std::map<u32, PtrTy> ptr_types;
std::map<u32, VectorTy> vector_types;
std::map<u32, Constant> constants;
std::map<u32, ConstantComposite> constants_composite;
std::map<u32, ArrayTy> array_types;
std::map<u32, ImageTy> images;
std::map<u32, SamplerTy> samplers;
std::map<u32, Sampled_ImageTy> combined_images;
std::map<u32, std::vector<Decoration>> decorations;
std::map<u32, std::vector<Member_Decoration>> member_decorations;
std::map<u32, FunTy> functypes;
std::map<u32, MatrixTy> matrix_types;
std::map<u32, StructTy> struct_types;
std::map<u32, size_t> type_sizes;
// function_id -> [var_id...]
std::map<u32, std::vector<u32>> local_variables;
std::vector<u32> global_variables;
// function_id -> [inst*...]
std::map<u32, std::vector<u32 const *>> instructions;
std::map<u32, std::string> names;
std::map<std::pair<u32, u32>, std::string> member_names;
std::map<u32, Entry> entries;
// Declaration order pairs
std::vector<std::pair<u32, DeclTy>> decl_types;
std::map<u32, DeclTy> decl_types_table;
// Offsets for private variables
std::map<u32, u32> private_offsets;
u32 private_storage_size = 0;
// Offsets for input variables
std::vector<u32> input_sizes;
std::vector<u32> input_offsets;
std::vector<VkFormat> input_formats;
u32 input_storage_size = 0;
// Offsets for ouput variables
std::vector<u32> output_sizes;
std::vector<u32> output_offsets;
std::vector<VkFormat> output_formats;
u32 output_storage_size = 0;
// Lifetime must be long enough
u32 const * code;
size_t code_size;
u64 code_hash;
char shader_dump_path[0x100];
int ATTR_USED dump_spirv_module() const {
FILE *file = fopen("shader_dump.spv", "wb");
fwrite(code, 1, code_size * 4, file);
fclose(file);
return 0;
}
//////////////////////////////
// METHODS //
//////////////////////////////
bool is_void_fn(u32 decl_id) {
if (decl_types_table[decl_id] != DeclTy::Function) return false;
Function function = functions[decl_id];
return decl_types_table[function.result_type] == DeclTy::PrimitiveTy &&
primitive_types[function.result_type].type == Primitive_t::Void;
}
auto has_decoration(spv::Decoration spv_dec, u32 val_id) -> bool {
if (!contains(decorations, val_id)) return false;
auto &decs = decorations[val_id];
for (auto &dec : decs) {
if (dec.type == spv_dec) return true;
}
return false;
}
auto find_decoration(spv::Decoration spv_dec, u32 val_id) -> Decoration {
ASSERT_ALWAYS(contains(decorations, val_id));
auto &decs = decorations[val_id];
for (auto &dec : decs) {
if (dec.type == spv_dec) return dec;
}
UNIMPLEMENTED;
}
auto has_member_decoration(spv::Decoration spv_dec, u32 type_id, u32 member_id) -> bool {
ASSERT_ALWAYS(contains(member_decorations, type_id));
for (auto &item : member_decorations[type_id]) {
if (item.type == spv_dec && item.member_id == member_id) {
return true;
}
}
return false;
}
auto find_member_decoration(spv::Decoration spv_dec, u32 type_id, u32 member_id)
-> Member_Decoration {
ASSERT_ALWAYS(contains(member_decorations, type_id));
for (auto &item : member_decorations[type_id]) {
if (item.type == spv_dec && item.member_id == member_id) {
return item;
}
}
UNIMPLEMENTED;
}
llvm::orc::ThreadSafeModule build_llvm_module_vectorized() {
std::unique_ptr<llvm::LLVMContext> context(new llvm::LLVMContext());
using LLVM_IR_Builder_t = llvm::IRBuilder<llvm::NoFolder>;
auto & c = *context;
llvm::SMDiagnostic error;
std::unique_ptr<llvm::Module> module = NULL;
// Load the stdlib for a given subgroup size
switch (opt_subgroup_size) {
case 1: {
auto mbuf = llvm::MemoryBuffer::getMemBuffer(
llvm::StringRef((char *)llvm_stdlib_1_bc, llvm_stdlib_1_bc_len), "", false);
module = llvm::parseIR(*mbuf.get(), error, c);
break;
}
case 4: {
auto mbuf = llvm::MemoryBuffer::getMemBuffer(
llvm::StringRef((char *)llvm_stdlib_4_bc, llvm_stdlib_4_bc_len), "", false);
module = llvm::parseIR(*mbuf.get(), error, c);
break;
}
case 64: {
auto mbuf = llvm::MemoryBuffer::getMemBuffer(
llvm::StringRef((char *)llvm_stdlib_64_bc, llvm_stdlib_64_bc_len), "", false);
module = llvm::parseIR(*mbuf.get(), error, c);
break;
}
default: UNIMPLEMENTED;
};
ASSERT_ALWAYS(module);
// Hide all stdlib functions
for (llvm::Function &fun : module->functions()) {
if (fun.isDeclaration()) continue;
fun.setLinkage(llvm::GlobalValue::LinkageTypes::PrivateLinkage);
fun.setVisibility(llvm::GlobalValue::VisibilityTypes::DefaultVisibility);
}
if (opt_llvm_dump) {
std::vector<const char *> argv;
argv.push_back("S2L");
argv.push_back("--print-after-all");
argv.push_back("--print-before-all");
argv.push_back(NULL);
llvm::cl::ParseCommandLineOptions(argv.size() - 1, &argv[0]);
}
llvm::PassRegistry *registry = llvm::PassRegistry::getPassRegistry();
llvm::initializeCore(*registry);
llvm::initializeScalarOpts(*registry);
llvm::initializeIPO(*registry);
llvm::initializeAnalysis(*registry);
llvm::initializeTransformUtils(*registry);
llvm::initializeInstCombine(*registry);
llvm::initializeInstrumentation(*registry);
llvm::initializeTarget(*registry);
// Debug info builder
std::unique_ptr<llvm::DIBuilder> llvm_di_builder;
// those are removed along with dibuilder
llvm::DICompileUnit *llvm_di_cuint;
llvm::DIFile * llvm_di_unit;
if (opt_debug_info) {
llvm_di_builder.reset(new llvm::DIBuilder(*module));
// those are removed along with dibuilder
llvm_di_cuint = llvm_di_builder->createCompileUnit(
llvm::dwarf::DW_LANG_C, llvm_di_builder->createFile(shader_dump_path, "."), "SPRIV JIT",
0, "", 0);
llvm_di_unit = llvm_di_builder->createFile(shader_dump_path, ".");
}
// std::map<llvm::Type *, llvm::DIType *> llvm_debug_type_table;
// std::function<llvm::DIType *(llvm::Type *)> llvm_get_debug_type =
// [&](llvm::Type *ty) {
// if (contains(llvm_debug_type_table, ty))
// return llvm_debug_type_table[ty];
// if (ty->isFloatTy()) {
// llvm::DIBasicType *bty = llvm_di_builder->createBasicType(
// "float", 32, llvm::dwarf::DW_ATE_float);
// llvm_debug_type_table[ty] = bty;
// return bty;
// } else if (ty->isVectorTy()) {
// llvm::VectorType *vtype =
// llvm::dyn_cast<llvm::VectorType>(ty); llvm::DIType *dity =
// llvm_di_builder->createVectorType(
// vtype->getElementCount(), vtype->getElementCount() * 4,
// llvm_get_deubg_type_table(vtype->getElementType()), {});
// "float", 32, llvm::dwarf::DW_ATE_float);
// llvm_debug_type_table[ty] = bty;
// return bty;
// } else {
// TRAP;
// }
// };
/////////////////////////////
llvm::install_fatal_error_handler(&llvm_fatal);
auto llvm_get_constant_i32 = [&c](u32 a) {
return llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(c), a);
};
auto llvm_get_constant_i64 = [&c](u64 a) {
return llvm::ConstantInt::get(llvm::IntegerType::getInt64Ty(c), a);
};
const u32 *pCode = this->code;
// The maximal number of IDs in this module
const u32 ID_bound = pCode[3];
auto get_spv_name = [this](u32 id) -> std::string {
if (names.find(id) == names.end()) {
names[id] = "spv_" + std::to_string(id);
}
ASSERT_ALWAYS(names.find(id) != names.end());
return "spv_" + names[id];
};
auto llvm_vec_elem_type = [](llvm::Type *ty) {
llvm::VectorType *vty = llvm::dyn_cast<llvm::VectorType>(ty);
return vty->getElementType();
};
auto llvm_vec_num_elems = [](llvm::Type *ty) {
llvm::VectorType *vty = llvm::dyn_cast<llvm::VectorType>(ty);
return vty->getElementCount().Min;
};
auto llvm_matrix_transpose = [&](llvm::Value *matrix, LLVM_IR_Builder_t *llvm_builder) {
llvm::Type *elem_type = llvm_vec_elem_type(matrix->getType()->getArrayElementType());
u32 matrix_row_size = llvm_vec_num_elems(matrix->getType()->getArrayElementType());
u32 matrix_col_size = (u32)matrix->getType()->getArrayNumElements();
llvm::Type *matrix_t_type =
llvm::ArrayType::get(llvm::VectorType::get(elem_type, matrix_col_size), matrix_row_size);
llvm::Value * result = llvm::UndefValue::get(matrix_t_type);
llvm::SmallVector<llvm::Value *, 4> rows;
jto(matrix_row_size) { rows.push_back(llvm_builder->CreateExtractValue(matrix, j)); }
ito(matrix_col_size) {
llvm::Value *result_row = llvm::UndefValue::get(matrix_t_type->getArrayElementType());
jto(matrix_row_size) {
result_row = llvm_builder->CreateInsertElement(
result_row, llvm_builder->CreateExtractElement(rows[j], i), j);
}
result = llvm_builder->CreateInsertValue(result, result_row, i);
}
return result;
};
auto llvm_dot = [&](llvm::Value *vector_0, llvm::Value *vector_1,
LLVM_IR_Builder_t *llvm_builder) {
llvm::Type * elem_type = llvm_vec_elem_type(vector_0->getType());
llvm::Value *result = llvm::ConstantFP::get(elem_type, 0.0);
u32 vector_size = llvm_vec_num_elems(vector_0->getType());
ASSERT_ALWAYS(llvm_vec_num_elems(vector_1->getType()) ==
llvm_vec_num_elems(vector_0->getType()));
jto(vector_size) {
result = llvm_builder->CreateFAdd(
result, llvm_builder->CreateFMul(llvm_builder->CreateExtractElement(vector_0, j),
llvm_builder->CreateExtractElement(vector_1, j)));
}
return result;
};
// Initialize framework functions
LOOKUP_FN(get_push_constant_ptr);
LOOKUP_FN(get_uniform_ptr);
LOOKUP_FN(get_private_ptr);
LOOKUP_FN(get_storage_ptr);
LOOKUP_FN(get_uniform_const_ptr);
LOOKUP_FN(get_input_ptr);
// Pointer to user attributes
LOOKUP_FN(get_output_ptr);
// For vertex shaders et al holds a pointer to gl_Position
LOOKUP_FN(get_builtin_output_ptr);
LOOKUP_FN(kill);
LOOKUP_FN(get_barycentrics);
LOOKUP_FN(get_derivatives);
LOOKUP_FN(get_pixel_position);
LOOKUP_FN(pixel_store_depth);
LOOKUP_FN(dump_float4x4);
LOOKUP_FN(dump_float4);
LOOKUP_FN(dump_float3);
LOOKUP_FN(dump_float2);
LOOKUP_FN(dump_float);
LOOKUP_FN(dump_string);
LOOKUP_FN(normalize_f2);
LOOKUP_FN(normalize_f3);
LOOKUP_FN(normalize_f4);
LOOKUP_FN(get_combined_image);
LOOKUP_FN(get_combined_sampler);
LOOKUP_FN(spv_image_sample_2d_float4);
LOOKUP_FN(spv_length_f2);
LOOKUP_FN(spv_length_f3);
LOOKUP_FN(spv_length_f4);
LOOKUP_FN(spv_fabs_f1);
LOOKUP_FN(spv_fabs_f2);
LOOKUP_FN(spv_fabs_f3);
LOOKUP_FN(spv_fabs_f4);
LOOKUP_FN(spv_cross);
LOOKUP_FN(spv_reflect);
LOOKUP_FN(spv_pow);
LOOKUP_FN(spv_clamp_f32);
LOOKUP_FN(dummy_sample);
LOOKUP_FN(spv_sqrt);
LOOKUP_FN(spv_dot_f2);
LOOKUP_FN(spv_dot_f3);
LOOKUP_FN(spv_dot_f4);
LOOKUP_FN(spv_get_global_invocation_id);
LOOKUP_FN(spv_get_work_group_size);
LOOKUP_FN(spv_lsb_i64);
LOOKUP_FN(spv_atomic_add_i32);
LOOKUP_FN(spv_atomic_sub_i32);
LOOKUP_FN(spv_atomic_or_i32);
LOOKUP_FN(spv_is_front_face);
// LOOKUP_FN(spv_push_mask);
// LOOKUP_FN(spv_pop_mask);
// LOOKUP_FN(spv_get_lane_mask);
// LOOKUP_FN(spv_disable_lanes);
// LOOKUP_FN(spv_set_enabled_lanes);
// LOOKUP_FN(spv_get_enabled_lanes);
LOOKUP_FN(spv_dummy_call);
LOOKUP_FN(dump_mask);
LOOKUP_FN(dump_invocation_id);
std::map<std::string, llvm::GlobalVariable *> global_strings;
auto lookup_string = [&](std::string str) {
if (contains(global_strings, str)) return global_strings[str];
llvm::Constant * msg = llvm::ConstantDataArray::getString(c, str.c_str(), true);
llvm::GlobalVariable *msg_glob = new llvm::GlobalVariable(
*module, msg->getType(), true, llvm::GlobalValue::InternalLinkage, msg);
global_strings[str] = msg_glob;
return msg_glob;
};
auto lookup_image_op = [&](llvm::Type *res_type, llvm::Type *coord_type, bool read) {
static char tmp_buf[0x100];
char const *type_names[] = {
// clang-format off
"invalid", "invalid" ,
"i32", "f32" ,
"int2", "float2" ,
"int3", "float3" ,
"int3", "float4" ,
// clang-format on
};
u32 dim = 0;
u32 components = 0;
llvm::Type *llvm_res_type = res_type;
if (res_type->isVectorTy()) {
components = llvm_vec_num_elems(llvm_res_type);
llvm_res_type = llvm_vec_elem_type(llvm_res_type);
} else {
components = 1;
}
if (coord_type->isVectorTy()) {
dim = llvm_vec_num_elems(coord_type);
} else {
dim = 1;
}
Primitive_t component_type = Primitive_t::Void;
if (llvm_res_type->isFloatTy()) {
component_type = Primitive_t::F32;
} else if (llvm_res_type->isIntegerTy()) {
ASSERT_ALWAYS(llvm_res_type->getIntegerBitWidth() == 32);
component_type = Primitive_t::U32;
} else {
UNIMPLEMENTED;
}
ASSERT_ALWAYS(dim == 1 || dim == 2 || dim == 3 || dim == 4);
ASSERT_ALWAYS(component_type == Primitive_t::F32 || component_type == Primitive_t::U32);
u32 is_float = component_type == Primitive_t::F32 ? 1 : 0;
char const *type_str = type_names[components * 2 + is_float];
snprintf(tmp_buf, sizeof(tmp_buf), "spv_image_%s_%id_%s", (read ? "read" : "write"), dim,
type_str);
llvm::Function *fun = module->getFunction(tmp_buf);
ASSERT_ALWAYS(fun != NULL);
return fun;
};
llvm::Type *state_t = module->getTypeByName("struct.Invocation_Info");
// Force 64 bit pointers
llvm::Type *llvm_int_ptr_t = llvm::Type::getInt64Ty(c);
llvm::Type *state_t_ptr = llvm::PointerType::get(state_t, 0);
llvm::Type *mask_t = llvm::Type::getInt64Ty(c);
// llvm::VectorType::get(llvm::IntegerType::getInt1Ty(c),
// opt_subgroup_size);
llvm::Type *sampler_t = llvm::IntegerType::getInt64Ty(c);
llvm::Type *image_t = llvm::IntegerType::getInt64Ty(c);
llvm::Type *combined_image_t = llvm::IntegerType::getInt64Ty(c);
// Structure member offsets for GEP
// SPIRV has ways of setting the member offset
// So in LLVM IR we need to manually insert paddings
std::map<llvm::Type *, std::vector<u32>> member_reloc;
// Matrices could be row/column. here we just default to row major and do
// the trasnpose as needed
std::map<llvm::Type *, std::set<u32>> member_transpose;
// Global type table
std::vector<llvm::Type *> llvm_types(ID_bound);
// Global value table (constants and global values)
// Each function creates a copy that inherits the global
// table
std::vector<llvm::Value *> llvm_global_values(ID_bound);
auto get_global_const_i32 = [&llvm_global_values](u32 const_id) {
llvm::ConstantInt *co = llvm::dyn_cast<llvm::ConstantInt>(llvm_global_values[const_id]);
NOTNULL(co);
return (u32)co->getLimitedValue();
};
// auto wave_local_t = [&](llvm::Type *ty) {
// return llvm::ArrayType::get(ty, opt_subgroup_size);
// };
// Map spirv types to llvm types
char name_buf[0x100];
for (auto &item : this->decl_types) {
ASSERT_ALWAYS(llvm_types[item.first] == NULL && "Types must have unique ids");
ASSERT_ALWAYS(llvm_global_values[item.first] == NULL && "Values must have unique ids");
#define ASSERT_HAS(table) ASSERT_ALWAYS(table.find(item.first) != table.end());
// Skip this declaration in this pass
bool skip = false;
switch (item.second) {
case DeclTy::FunTy: {
ASSERT_HAS(functypes);
FunTy type = functypes.find(item.first)->second;
llvm::Type *ret_type = llvm_types[type.ret];
ASSERT_ALWAYS(ret_type != NULL && "Function must have a return type defined");
llvm::SmallVector<llvm::Type *, 16> args;
// Prepend state_t* to each function type
args.push_back(state_t_ptr);
// Prepend mask to each function type
args.push_back(mask_t);
for (auto ¶m_id : type.params) {
llvm::Type *arg_type = llvm_types[param_id];
ASSERT_ALWAYS(arg_type != NULL && "Function must have all argumet types defined");
kto(opt_subgroup_size) args.push_back(arg_type);
}
if (ret_type->isVoidTy())
llvm_types[type.id] = llvm::FunctionType::get(ret_type, args, false);
else {
// Append the pointer to the returned data as the last parameter
kto(opt_subgroup_size) args.push_back(llvm::PointerType::get(ret_type, 0));
// args.push_back(
// llvm::PointerType::get(llvm::ArrayType::get(ret_type, opt_subgroup_size),
// 0));
llvm_types[type.id] = llvm::FunctionType::get(llvm::Type::getVoidTy(c), args, false);
}
break;
}
case DeclTy::Function: {
ASSERT_HAS(functions);
Function fun = functions.find(item.first)->second;
llvm::FunctionType *fun_type =
llvm::dyn_cast<llvm::FunctionType>(llvm_types[fun.function_type]);
ASSERT_ALWAYS(fun_type != NULL && "Function type must be defined");
llvm_global_values[fun.id] = llvm::Function::Create(
fun_type, llvm::GlobalValue::ExternalLinkage, get_spv_name(fun.id), module.get());
break;
}
case DeclTy::RuntimeArrayTy:
case DeclTy::PtrTy: {
ASSERT_HAS(ptr_types);
PtrTy type = ptr_types.find(item.first)->second;
llvm::Type *elem_t = llvm_types[type.target_id];
ASSERT_ALWAYS(elem_t != NULL && "Pointer target type must be defined");
llvm_types[type.id] = llvm::PointerType::get(elem_t, 0);
break;
}
case DeclTy::ArrayTy: {
ASSERT_HAS(array_types);
ArrayTy type = array_types.find(item.first)->second;
llvm::Type *elem_t = llvm_types[type.member_id];
ASSERT_ALWAYS(elem_t != NULL && "Element type must be defined");
llvm::Value *width_value = llvm_global_values[type.width_id];
ASSERT_ALWAYS(width_value != NULL && "Array width must be defined");
llvm::ConstantInt *constant = llvm::dyn_cast<llvm::ConstantInt>(width_value);
ASSERT_ALWAYS(constant != NULL && "Array width must be an integer constant");
llvm_types[type.id] = llvm::ArrayType::get(elem_t, constant->getValue().getLimitedValue());
break;
}
case DeclTy::ImageTy: {
ASSERT_HAS(images);
ImageTy type = images.find(item.first)->second;
llvm_types[type.id] = image_t;
break;
}
case DeclTy::Constant: {
ASSERT_HAS(constants);
Constant c = constants.find(item.first)->second;
llvm::Type *type = llvm_types[c.type];
ASSERT_ALWAYS(type != NULL && "Constant type must be defined");
// In LLVM float means float 32bit
if (!(type->isFloatTy()) && !(type->isIntegerTy() && (type->getIntegerBitWidth() == 32 ||
type->getIntegerBitWidth() == 1))) {
UNIMPLEMENTED;
}
if (type->isFloatTy())
llvm_global_values[c.id] = llvm::ConstantFP::get(type, llvm::APFloat(c.f32_val));
else {
llvm_global_values[c.id] = llvm::ConstantInt::get(type, c.i32_val);
}
break;
}
case DeclTy::ConstantComposite: {
ASSERT_HAS(constants_composite);
ConstantComposite c = constants_composite.find(item.first)->second;
llvm::Type * type = llvm_types[c.type];
ASSERT_ALWAYS(type != NULL && "Constant type must be defined");
llvm::SmallVector<llvm::Constant *, 4> llvm_elems;
ito(c.components.size()) {
llvm::Value * val = llvm_global_values[c.components[i]];
llvm::Constant *cnst = llvm::dyn_cast<llvm::Constant>(val);
ASSERT_ALWAYS(cnst != NULL);
llvm_elems.push_back(cnst);
}
if (type->isVectorTy())
llvm_global_values[c.id] = llvm::ConstantVector::get(llvm_elems);
else if (type->isArrayTy())
llvm_global_values[c.id] =
llvm::ConstantArray::get(llvm::dyn_cast<llvm::ArrayType>(type), llvm_elems);
else {
UNIMPLEMENTED;
}
break;
}
case DeclTy::Variable: {
ASSERT_HAS(variables);
Variable c = variables.find(item.first)->second;
switch (c.storage) {
// Uniform data visible to all invocations
case spv::StorageClass::StorageClassUniform:
// Same as uniform but read-only and may hava an initializer
case spv::StorageClass::StorageClassUniformConstant:
// Pipeline ouput
case spv::StorageClass::StorageClassOutput:
// Pipeline input
case spv::StorageClass::StorageClassInput:
// Global memory visible to the current invocation
case spv::StorageClass::StorageClassPrivate:
// Global memory visible to the current invocation
case spv::StorageClass::StorageClassStorageBuffer:
// Small chunck of data visible to anyone
case spv::StorageClass::StorageClassPushConstant: {
// Handle global variables per function
skip = true;
break;
}
case spv::StorageClass::StorageClassFunction: {
// Handle local variables at later passes per function
skip = true;
break;
}
default: UNIMPLEMENTED_(get_cstr(c.storage));
}
break;
}
case DeclTy::MatrixTy: {
ASSERT_HAS(matrix_types);
MatrixTy type = matrix_types.find(item.first)->second;
llvm::Type *elem_t = llvm_types[type.vector_id];
ASSERT_ALWAYS(elem_t != NULL && "Matrix column type must be defined");
llvm_types[type.id] = llvm::ArrayType::get(elem_t, type.width);
break;
}
case DeclTy::StructTy: {
ASSERT_HAS(struct_types);
StructTy type = struct_types.find(item.first)->second;
// For builtin structures we just emit struct <{<4 x float>}> for
// gl_Position and assume that other members are not written to
// @TODO: Implement other output structures
if (type.is_builtin) {
llvm::Type *struct_type =
llvm::StructType::create(c, {llvm::VectorType::get(llvm::Type::getFloatTy(c), 4)},
get_spv_name(type.id), true);
member_reloc[struct_type] = {0};
llvm_types[type.id] = struct_type;
break;
}
std::vector<llvm::Type *> members;
size_t offset = 0;
// We manually insert padding bytes which offsets the structure members
// for GEP instructions
std::vector<u32> member_indices;
std::set<u32> this_member_transpose;
u32 index_offset = 0;
for (u32 member_id = 0; member_id < type.member_types.size(); member_id++) {
llvm::Type *member_type = llvm_types[type.member_types[member_id]];
ASSERT_ALWAYS(member_type != NULL && "Member types must be defined");
if (!type.is_builtin && type.member_offsets[member_id] != offset) {
ASSERT_ALWAYS(type.member_offsets[member_id] > offset &&
"Can't move a member back in memory layout");
size_t diff = type.member_offsets[member_id] - offset;
// Push dummy bytes until the member offset is ok
members.push_back(llvm::ArrayType::get(llvm::Type::getInt8Ty(c), diff));
index_offset += 1;
}
if (has_member_decoration(spv::Decoration::DecorationColMajor, type.id, member_id)) {
this_member_transpose.insert(member_id);
if (has_member_decoration(spv::Decoration::DecorationMatrixStride, type.id,
member_id)) {
// do we need to change anything if that's not true?
// TODO allow 12 and 8 for mat3 and mat2
ASSERT_ALWAYS(find_member_decoration(spv::Decoration::DecorationMatrixStride, type.id,
member_id)
.param1 == 16);
}
}
size_t size = 0;
u32 member_type_id = type.member_types[member_id];
member_indices.push_back(index_offset);
index_offset += 1;
ASSERT_ALWAYS(contains(type_sizes, member_type_id));
size = type_sizes[member_type_id];
ASSERT_ALWAYS(size != 0);
offset += size;
members.push_back(member_type);
}
llvm::Type *struct_type = llvm::StructType::create(c, members, get_spv_name(type.id), true);
member_reloc[struct_type] = member_indices;
if (this_member_transpose.size() != 0)
member_transpose[struct_type] = this_member_transpose;
llvm_types[type.id] = struct_type;
break;
}
case DeclTy::VectorTy: {
ASSERT_HAS(vector_types);
VectorTy type = vector_types.find(item.first)->second;
llvm::Type *elem_t = llvm_types[type.member_id];
ASSERT_ALWAYS(elem_t != NULL && "Element type must be defined");
llvm_types[type.id] = llvm::VectorType::get(elem_t, type.width);
break;
}
case DeclTy::SamplerTy: {
ASSERT_HAS(samplers);
SamplerTy type = samplers.find(item.first)->second;
llvm_types[type.id] = sampler_t;
break;
}
case DeclTy::Sampled_ImageTy: {
ASSERT_HAS(combined_images);
Sampled_ImageTy type = combined_images.find(item.first)->second;
llvm_types[type.id] = combined_image_t;
break;
}
case DeclTy::PrimitiveTy: {
ASSERT_HAS(primitive_types);
PrimitiveTy type = primitive_types.find(item.first)->second;
switch (type.type) {
#define MAP(TY, LLVM_TY) \
case Primitive_t::TY: llvm_types[type.id] = LLVM_TY; break;
MAP(I1, llvm::Type::getInt1Ty(c));
MAP(I8, llvm::Type::getInt8Ty(c));
MAP(I16, llvm::Type::getInt16Ty(c));
MAP(I32, llvm::Type::getInt32Ty(c));