-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathspirv_compile.cpp
2453 lines (2095 loc) · 79.9 KB
/
spirv_compile.cpp
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 "precompiled.h"
#include "spirv_compile.h"
#include <set>
#include "3rdparty/GLSL.std.450.h"
#include "3rdparty/spirv.hpp"
#include "gpu.h"
#pragma warning(push)
#pragma warning(disable : 4141)
#pragma warning(disable : 4146)
#pragma warning(disable : 4244)
#pragma warning(disable : 4267)
#pragma warning(disable : 4291)
#pragma warning(disable : 4624)
#pragma warning(disable : 4800)
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/Orc/CompileUtils.h>
#include <llvm/ExecutionEngine/Orc/IRCompileLayer.h>
#include <llvm/ExecutionEngine/Orc/LambdaResolver.h>
#include <llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h>
#include <llvm/ExecutionEngine/RTDyldMemoryManager.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Mangler.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#pragma warning(pop)
typedef llvm::orc::RTDyldObjectLinkingLayer Linker;
#define DEBUG_SPIRV 0
namespace
{
llvm::LLVMContext *context = NULL;
llvm::SectionMemoryManager *memManager = NULL;
llvm::TargetMachine *target = NULL;
Linker *globallinker = NULL;
llvm::orc::SimpleCompiler *compiler = NULL;
llvm::Module *globalFunctions = NULL;
llvm::Type *t_VkImage = NULL;
llvm::Type *t_VkBuffer = NULL;
llvm::Type *t_VkDescriptorSet = NULL;
llvm::Type *t_VkPipeline = NULL;
llvm::Type *t_GPUStateRef = NULL;
llvm::Type *t_VertexCacheEntry = NULL;
llvm::Type *t_VertexShader = NULL;
llvm::Type *t_FragmentShader = NULL;
};
struct LLVMFunction
{
~LLVMFunction()
{
delete linker;
delete module;
}
Linker *linker = NULL;
llvm::Module *module = NULL;
std::string ir, optir;
};
static void llvm_fatal(void *user_data, const std::string &reason, bool gen_crash_diag)
{
assert(false);
}
static Linker *makeLinker()
{
return new Linker([] {
return std::shared_ptr<llvm::SectionMemoryManager>(memManager,
[](llvm::SectionMemoryManager *) {});
});
}
static void DeclareGlobalFunctions(llvm::Module *m)
{
using namespace llvm;
LLVMContext &c = *context;
Function::Create(FunctionType::get(Type::getVoidTy(c),
{
// uint32_t pCode0
Type::getInt32Ty(c),
// uint32_t pCode1
Type::getInt32Ty(c),
// uint32_t pCode2
Type::getInt32Ty(c),
},
false),
GlobalValue::ExternalLinkage, "DebugSPIRVOp", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float4 mat[4],
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
// float4 vec,
VectorType::get(Type::getFloatTy(c), 4),
// float4 &result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "Float4x4TimesVec4", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float3 mat[3],
PointerType::get(VectorType::get(Type::getFloatTy(c), 3), 0),
// float3 vec,
VectorType::get(Type::getFloatTy(c), 3),
// float3 &result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 3), 0),
},
false),
GlobalValue::ExternalLinkage, "Float3x3TimesVec3", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float4 mat[4],
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
// float4 vec,
VectorType::get(Type::getFloatTy(c), 4),
// float4 &result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "Vec4TimesFloat4x4", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float3 mat[3],
PointerType::get(VectorType::get(Type::getFloatTy(c), 3), 0),
// float3 vec,
VectorType::get(Type::getFloatTy(c), 3),
// float3 &result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 3), 0),
},
false),
GlobalValue::ExternalLinkage, "Vec3TimesFloat3x3", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float4 a[4],
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
// float4 b[4],
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
// float4 *result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "Float4x4TimesFloat4x4", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float4 a[4],
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
// float b,
Type::getFloatTy(c),
// float4 *result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "Float4x4TimesFloat", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float4 in[4],
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
// float4 *result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "Float4x4Transpose", m);
Function::Create(
FunctionType::get(Type::getVoidTy(c),
{
// float4 in[4],
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
// float4 *result,
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "Float4x4Inverse", m);
Function::Create(FunctionType::get(PointerType::get(Type::getInt8Ty(c), 0),
{
t_GPUStateRef, Type::getInt32Ty(c), Type::getInt32Ty(c),
},
false),
GlobalValue::ExternalLinkage, "GetDescriptorBufferPointer", m);
Function::Create(FunctionType::get(PointerType::get(Type::getVoidTy(c), 0),
{
t_GPUStateRef, Type::getInt32Ty(c), Type::getInt32Ty(c),
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "GetVertexAttributeData", m);
Function::Create(FunctionType::get(PointerType::get(Type::getInt8Ty(c), 0),
{
t_GPUStateRef, Type::getInt32Ty(c),
},
false),
GlobalValue::ExternalLinkage, "GetPushConstantPointer", m);
Function::Create(FunctionType::get(t_VkImage,
{
t_GPUStateRef, Type::getInt32Ty(c), Type::getInt32Ty(c),
},
false),
GlobalValue::ExternalLinkage, "GetDescriptorImage", m);
Function::Create(FunctionType::get(Type::getVoidTy(c),
{
// float u
Type::getFloatTy(c),
// float v
Type::getFloatTy(c),
// VkImage tex
t_VkImage,
// VkDeviceSize byteOffs
Type::getInt64Ty(c),
// float4 &out
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "sample_tex_wrapped", m);
Function::Create(FunctionType::get(Type::getVoidTy(c),
{
// float x
Type::getFloatTy(c),
// float y
Type::getFloatTy(c),
// float z
Type::getFloatTy(c),
// VkImage tex
t_VkImage,
// float4 &out
PointerType::get(VectorType::get(Type::getFloatTy(c), 4), 0),
},
false),
GlobalValue::ExternalLinkage, "sample_cube_wrapped", m);
}
void InitLLVM()
{
using namespace llvm;
install_fatal_error_handler(&llvm_fatal);
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
context = new LLVMContext();
memManager = new llvm::SectionMemoryManager();
target = EngineBuilder().selectTarget();
globallinker = makeLinker();
compiler = new llvm::orc::SimpleCompiler(*target);
std::string str;
sys::DynamicLibrary::LoadLibraryPermanently(NULL, &str);
LLVMContext &c = *context;
t_VkImage = PointerType::get(StructType::create(c, "VkImage"), 0);
t_VkBuffer = PointerType::get(StructType::create(c, "VkBuffer"), 0);
t_VkDescriptorSet = PointerType::get(StructType::create(c, "VkDescriptorSet"), 0);
t_VkPipeline = PointerType::get(StructType::create(c, "VkPipeline"), 0);
t_GPUStateRef = PointerType::get(StructType::create(c, "GPUState"), 0);
Type *t_float4 = VectorType::get(Type::getFloatTy(c), 4);
t_VertexCacheEntry = StructType::get(c,
{
// float4 position
t_float4,
// float4 interps[10]
ArrayType::get(t_float4, 10),
},
"VertexCacheEntry");
t_VertexShader = FunctionType::get(Type::getVoidTy(c),
{
// const GPUState &state
t_GPUStateRef,
// uint32_t vertexIndex
Type::getInt32Ty(c),
// VertexCacheEntry &out
PointerType::get(t_VertexCacheEntry, 0),
},
false);
t_FragmentShader = FunctionType::get(Type::getVoidTy(c),
{
// const GPUState &state
t_GPUStateRef,
// float pixdepth
Type::getFloatTy(c),
// const float4 &bary
PointerType::get(t_float4, 0),
// const VertexCacheEntry tri[3]
PointerType::get(t_VertexCacheEntry, 0),
// float4 &out
PointerType::get(t_float4, 0),
},
false);
globalFunctions = new llvm::Module("globalFunctions", c);
DeclareGlobalFunctions(globalFunctions);
IRBuilder<> builder(c, ConstantFolder());
std::vector<Function *> functions;
// we could define library functions in LLVM here instead of C to allow it to inline/optimise
{
std::string str;
raw_string_ostream os(str);
if(verifyModule(*globalFunctions, &os))
{
printf("Global Module did not verify: %s\n", os.str().c_str());
assert(false);
}
}
{
std::string str;
raw_string_ostream os(str);
globalFunctions->print(os, NULL);
}
PassManagerBuilder pm_builder;
pm_builder.OptLevel = 3;
pm_builder.SizeLevel = 0;
pm_builder.LoopVectorize = true;
pm_builder.SLPVectorize = true;
legacy::FunctionPassManager function_pm(globalFunctions);
legacy::PassManager module_pm;
pm_builder.populateFunctionPassManager(function_pm);
pm_builder.populateModulePassManager(module_pm);
function_pm.doInitialization();
for(Function *f : functions)
function_pm.run(*f);
module_pm.run(*globalFunctions);
{
std::string str;
raw_string_ostream os(str);
globalFunctions->print(os, NULL);
}
globalFunctions->setDataLayout(target->createDataLayout());
auto symbolResolver = llvm::orc::createLambdaResolver(
[](const std::string &name) { return globallinker->findSymbol(name, false); },
[](const std::string &name) {
uint64_t sym_addr = RTDyldMemoryManager::getSymbolAddressInProcess(name);
if(sym_addr)
return JITSymbol(sym_addr, JITSymbolFlags::Exported);
return JITSymbol(NULL);
});
orc::SimpleCompiler &comp = *compiler;
globallinker->addObject(
std::make_shared<orc::SimpleCompiler::CompileResult>(comp(*globalFunctions)), symbolResolver);
}
void ShutdownLLVM()
{
delete globalFunctions;
delete compiler;
delete globallinker;
delete target;
delete memManager;
delete context;
}
extern "C" __declspec(dllexport) void DebugSPIRVOp(uint32_t pCode0, uint32_t pCode1, uint32_t pCode2)
{
#if DEBUG_SPIRV
spv::Op opcode = spv::Op(pCode0 & spv::OpCodeMask);
uint16_t WordCount = pCode0 >> spv::WordCountShift;
#endif
}
extern "C" __declspec(dllexport) void Float4x4TimesVec4(float *fmat, const float4 &vec, float4 &out)
{
for(int row = 0; row < 4; row++)
{
out.v[row] = 0.0f;
for(int col = 0; col < 4; col++)
out.v[row] += fmat[col * 4 + row] * vec.v[col];
}
}
extern "C" __declspec(dllexport) void Float3x3TimesVec3(float *fmat, const float4 &vec, float4 &out)
{
for(int row = 0; row < 3; row++)
{
out.v[row] = 0.0f;
for(int col = 0; col < 3; col++)
out.v[row] += fmat[col * 4 + row] * vec.v[col];
}
}
extern "C" __declspec(dllexport) void Vec4TimesFloat4x4(float *fmat, const float4 &vec, float4 &out)
{
for(int row = 0; row < 4; row++)
{
out.v[row] = 0.0f;
for(int col = 0; col < 4; col++)
out.v[row] += fmat[row * 4 + col] * vec.v[col];
}
}
extern "C" __declspec(dllexport) void Vec3TimesFloat3x3(float *fmat, const float4 &vec, float4 &out)
{
for(int row = 0; row < 3; row++)
{
out.v[row] = 0.0f;
for(int col = 0; col < 3; col++)
out.v[row] += fmat[row * 4 + col] * vec.v[col];
}
}
extern "C" __declspec(dllexport) void Float4x4TimesFloat4x4(const float *a, const float *b, float *out)
{
for(size_t x = 0; x < 4; x++)
{
for(size_t y = 0; y < 4; y++)
{
out[x * 4 + y] = b[x * 4 + 0] * a[0 * 4 + y] + b[x * 4 + 1] * a[1 * 4 + y] +
b[x * 4 + 2] * a[2 * 4 + y] + b[x * 4 + 3] * a[3 * 4 + y];
}
}
}
extern "C" __declspec(dllexport) void Float4x4TimesFloat(const float *a, float b, float *out)
{
for(size_t x = 0; x < 4; x++)
{
for(size_t y = 0; y < 4; y++)
{
out[x * 4 + y] = a[x * 4 + y] * b;
}
}
}
extern "C" __declspec(dllexport) void Float4x4Transpose(const float *in, float *out)
{
for(size_t x = 0; x < 4; x++)
for(size_t y = 0; y < 4; y++)
out[x * 4 + y] = in[y * 4 + x];
}
extern "C" __declspec(dllexport) void Float4x4Inverse(const float *in, float *out)
{
float a0 = in[0] * in[5] - in[1] * in[4];
float a1 = in[0] * in[6] - in[2] * in[4];
float a2 = in[0] * in[7] - in[3] * in[4];
float a3 = in[1] * in[6] - in[2] * in[5];
float a4 = in[1] * in[7] - in[3] * in[5];
float a5 = in[2] * in[7] - in[3] * in[6];
float b0 = in[8] * in[13] - in[9] * in[12];
float b1 = in[8] * in[14] - in[10] * in[12];
float b2 = in[8] * in[15] - in[11] * in[12];
float b3 = in[9] * in[14] - in[10] * in[13];
float b4 = in[9] * in[15] - in[11] * in[13];
float b5 = in[10] * in[15] - in[11] * in[14];
float det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
if(fabsf(det) > FLT_EPSILON)
{
out[0] = +in[5] * b5 - in[6] * b4 + in[7] * b3;
out[4] = -in[4] * b5 + in[6] * b2 - in[7] * b1;
out[8] = +in[4] * b4 - in[5] * b2 + in[7] * b0;
out[12] = -in[4] * b3 + in[5] * b1 - in[6] * b0;
out[1] = -in[1] * b5 + in[2] * b4 - in[3] * b3;
out[5] = +in[0] * b5 - in[2] * b2 + in[3] * b1;
out[9] = -in[0] * b4 + in[1] * b2 - in[3] * b0;
out[13] = +in[0] * b3 - in[1] * b1 + in[2] * b0;
out[2] = +in[13] * a5 - in[14] * a4 + in[15] * a3;
out[6] = -in[12] * a5 + in[14] * a2 - in[15] * a1;
out[10] = +in[12] * a4 - in[13] * a2 + in[15] * a0;
out[14] = -in[12] * a3 + in[13] * a1 - in[14] * a0;
out[3] = -in[9] * a5 + in[10] * a4 - in[11] * a3;
out[7] = +in[8] * a5 - in[10] * a2 + in[11] * a1;
out[11] = -in[8] * a4 + in[9] * a2 - in[11] * a0;
out[15] = +in[8] * a3 - in[9] * a1 + in[10] * a0;
float invDet = 1.0f / det;
out[0] *= invDet;
out[1] *= invDet;
out[2] *= invDet;
out[3] *= invDet;
out[4] *= invDet;
out[5] *= invDet;
out[6] *= invDet;
out[7] *= invDet;
out[8] *= invDet;
out[9] *= invDet;
out[10] *= invDet;
out[11] *= invDet;
out[12] *= invDet;
out[13] *= invDet;
out[14] *= invDet;
out[15] *= invDet;
return;
}
memset(out, 0, sizeof(float) * 16);
}
extern "C" __declspec(dllexport) const byte *GetDescriptorBufferPointer(const GPUState &state,
uint32_t set, uint32_t bind)
{
const VkDescriptorBufferInfo &buf = state.sets[set]->binds[bind].data.bufferInfo;
return buf.buffer->bytes + buf.offset;
}
extern "C" __declspec(dllexport) VkImage
GetDescriptorImage(const GPUState &state, uint32_t set, uint32_t bind)
{
return state.sets[set]->binds[bind].data.imageInfo.imageView->image;
}
extern "C" __declspec(dllexport) const byte *GetPushConstantPointer(const GPUState &state,
uint32_t offset)
{
return state.pushconsts + offset;
}
extern "C" __declspec(dllexport) void GetVertexAttributeData(const GPUState &state,
uint32_t vertexIndex, uint32_t attr,
float4 &out)
{
out = float4(0, 0, 0, 1);
uint32_t vb = state.pipeline->vattrs[attr].vb;
byte *ptr = state.vbs[vb].buffer->bytes + state.vbs[vb].offset;
ptr += state.pipeline->vattrs[attr].offset;
ptr += state.pipeline->vattrs[attr].stride * vertexIndex;
float *f32 = (float *)ptr;
uint32_t *u32 = (uint32_t *)ptr;
switch(state.pipeline->vattrs[attr].format)
{
case VK_FORMAT_R32G32B32A32_SFLOAT:
case VK_FORMAT_R32G32B32A32_UINT:
case VK_FORMAT_R32G32B32A32_SINT:
{
out.w = f32[3];
// deliberate fallthrough
}
case VK_FORMAT_R32G32B32_SFLOAT:
case VK_FORMAT_R32G32B32_UINT:
case VK_FORMAT_R32G32B32_SINT:
{
out.z = f32[2];
// deliberate fallthrough
}
case VK_FORMAT_R32G32_SFLOAT:
case VK_FORMAT_R32G32_UINT:
case VK_FORMAT_R32G32_SINT:
{
out.y = f32[1];
// deliberate fallthrough
}
case VK_FORMAT_R32_SFLOAT:
case VK_FORMAT_R32_UINT:
case VK_FORMAT_R32_SINT:
{
out.x = f32[0];
break;
}
case VK_FORMAT_R8G8B8A8_UNORM:
{
out.x = float((u32[0] & 0x000000ff) >> 0x00) / 255.0f;
out.y = float((u32[0] & 0x0000ff00) >> 0x08) / 255.0f;
out.z = float((u32[0] & 0x00ff0000) >> 0x10) / 255.0f;
out.w = float((u32[0] & 0xff000000) >> 0x18) / 255.0f;
break;
}
default: assert(false && "Unhandled vertex attribute format");
}
}
llvm::Value *CreateDot(llvm::IRBuilder<> &builder, llvm::Value *a, llvm::Value *b, int numcomps)
{
llvm::Value *accum = builder.CreateFMul(builder.CreateExtractElement(a, 0LLU),
builder.CreateExtractElement(b, 0LLU));
if(numcomps > 1)
accum = builder.CreateFAdd(accum, builder.CreateFMul(builder.CreateExtractElement(a, 1LLU),
builder.CreateExtractElement(b, 1LLU)));
if(numcomps > 2)
accum = builder.CreateFAdd(accum, builder.CreateFMul(builder.CreateExtractElement(a, 2LLU),
builder.CreateExtractElement(b, 2LLU)));
if(numcomps > 3)
accum = builder.CreateFAdd(accum, builder.CreateFMul(builder.CreateExtractElement(a, 3LLU),
builder.CreateExtractElement(b, 3LLU)));
return accum;
}
LLVMFunction *CompileFunction(const uint32_t *pCode, size_t codeSize)
{
using namespace llvm;
LLVMContext &c = *context;
assert(pCode[0] == spv::MagicNumber);
assert(pCode[1] <= spv::Version);
const uint32_t generator = pCode[2];
const uint32_t idbound = pCode[3];
assert(pCode[4] == 0);
LLVMFunction *ret = new LLVMFunction();
char uniq_name[512];
sprintf_s(uniq_name, "visormodule_%p", ret);
ret->module = new Module(uniq_name, c);
ret->linker = makeLinker();
Module *m = ret->module;
DeclareGlobalFunctions(m);
std::vector<Function *> functions;
Function *curfunc = NULL;
BasicBlock *curlabel = NULL;
Argument *functionargs = NULL;
IRBuilder<> builder(c, ConstantFolder());
std::vector<const uint32_t *> entries;
struct IDDecoration
{
uint32_t id;
spv::Decoration dec;
uint32_t param;
uint32_t member;
bool operator<(const IDDecoration &o) const { return id < o.id; }
};
std::vector<IDDecoration> decorations;
std::set<uint32_t> blocks, cube;
// in lieu of a proper SPIR-V representation, this lets us go from pointer type -> struct type
std::map<uint32_t, uint32_t> ptrtypes;
std::vector<Value *> values;
std::vector<Type *> types;
std::map<uint32_t, std::string> names;
uint32_t GLSLstd450_instset = 0;
values.resize(idbound);
types.resize(idbound);
auto getname = [&names](uint32_t id) -> std::string {
std::string name = names[id];
if(name.empty())
name = "spv__" + std::to_string(id);
return name;
};
std::vector<Type *> globalTypes;
struct FunctionTypeInfo
{
std::vector<Type *> params;
Type *ret;
};
std::map<uint32_t, FunctionTypeInfo> functypes;
struct ExternalBinding
{
spv::StorageClass storageClass;
Value *value;
IDDecoration decoration;
};
std::vector<ExternalBinding> externals;
const uint32_t *opStart = pCode + 5;
const uint32_t *opEnd = pCode + codeSize;
// we do three passes to make things easier for instruction generation:
// 1. Gather information:
// - Parse types and create corresponding LLVM types
// - Generate LLVM constants immediately
// - Store names and debug info locally
// - Gather decoration information locally
// - Gather types of globals locally, in order
//
// Generate global struct here.
//
// 2. Function-only pass. Find functions and create them (so that if we encounter a function call
// going forward we already have the Function* ready for it). Within each function, create all
// basic blocks (again so that forward branches already have the blocks ready).
//
// 2. Process and generate LLVM functions and globals
//
// After this we generate wrapper entry points that fetch and populate globals, but that doesn't
// iterate over SPIR-V it just uses data gathered before.
pCode = opStart;
while(pCode < opEnd)
{
uint16_t WordCount = pCode[0] >> spv::WordCountShift;
spv::Op opcode = spv::Op(pCode[0] & spv::OpCodeMask);
switch(opcode)
{
////////////////////////////////////////////////
// Debug instructions
////////////////////////////////////////////////
case spv::OpName:
{
names[pCode[1]] = (const char *)&pCode[2];
break;
}
////////////////////////////////////////////////
// Globals/declarations/decorations
////////////////////////////////////////////////
case spv::OpExtInstImport:
{
GLSLstd450_instset = pCode[1];
assert(!strcmp((char *)(pCode + 2), "GLSL.std.450"));
break;
}
case spv::OpEntryPoint:
{
// we'll do this in a final pass once we have the function resolved
entries.push_back(pCode);
break;
}
case spv::OpDecorate:
{
IDDecoration search = {pCode[1]};
auto it = std::lower_bound(decorations.begin(), decorations.end(), search);
if(WordCount == 3)
{
decorations.insert(it, {pCode[1], (spv::Decoration)pCode[2], 0, ~0U});
if(pCode[2] == spv::DecorationBlock)
blocks.insert(pCode[1]);
}
else
{
decorations.insert(it, {pCode[1], (spv::Decoration)pCode[2], pCode[3], ~0U});
}
break;
}
case spv::OpMemberDecorate:
{
IDDecoration search = {pCode[1]};
auto it = std::lower_bound(decorations.begin(), decorations.end(), search);
if(WordCount == 4)
decorations.insert(it, {pCode[1], (spv::Decoration)pCode[3], 0, pCode[2]});
else
decorations.insert(it, {pCode[1], (spv::Decoration)pCode[3], pCode[4], pCode[2]});
break;
}
////////////////////////////////////////////////
// Type declarations
////////////////////////////////////////////////
case spv::OpTypeVoid:
{
types[pCode[1]] = Type::getVoidTy(c);
break;
}
case spv::OpTypeFloat:
{
if(pCode[2] == 16)
types[pCode[1]] = Type::getHalfTy(c);
else if(pCode[2] == 32)
types[pCode[1]] = Type::getFloatTy(c);
else if(pCode[2] == 64)
types[pCode[1]] = Type::getDoubleTy(c);
break;
}
case spv::OpTypeBool:
{
types[pCode[1]] = Type::getInt1Ty(c);
break;
}
case spv::OpTypeInt:
{
types[pCode[1]] = IntegerType::get(c, pCode[2]);
// ignore pCode[3] signedness
break;
}
case spv::OpTypeVector:
{
types[pCode[1]] = VectorType::get(types[pCode[2]], pCode[3]);
break;
}
case spv::OpTypeArray:
{
types[pCode[1]] = ArrayType::get(
types[pCode[2]], ((ConstantInt *)values[pCode[3]])->getValue().getLimitedValue());
break;
}
case spv::OpTypeMatrix:
{
// implement matrix as just array
types[pCode[1]] = ArrayType::get(types[pCode[2]], pCode[3]);
break;
}
case spv::OpTypePointer:
{
types[pCode[1]] = PointerType::get(types[pCode[3]], 0);
// if the pointed type is a block and this is a uniform pointer, propagate that to the
// pointer
if(blocks.find(pCode[3]) != blocks.end() &&
(pCode[2] == spv::StorageClassUniform || pCode[2] == spv::StorageClassPushConstant))
blocks.insert(pCode[1]);
ptrtypes[pCode[1]] = pCode[3];
break;
}
case spv::OpTypeStruct:
{
std::vector<Type *> members;
for(uint16_t i = 2; i < WordCount; i++)
members.push_back(types[pCode[i]]);
types[pCode[1]] = StructType::create(c, members, getname(pCode[1]));
break;
}
case spv::OpTypeFunction:
{
// to patch in the globals struct, we declare OpTypeFunction the first time we meet an
// OpFunction (after any global variables - in the second pass).
FunctionTypeInfo &f = functypes[pCode[1]];
for(uint16_t i = 3; i < WordCount; i++)
f.params.push_back(types[pCode[i]]);
f.ret = types[pCode[2]];
break;
}
case spv::OpTypeImage:
case spv::OpTypeSampledImage:
{
if(opcode == spv::OpTypeImage && pCode[3] == spv::DimCube)
cube.insert(pCode[1]);
else if(opcode == spv::OpTypeSampledImage && cube.find(pCode[2]) != cube.end())
cube.insert(pCode[1]);
// TODO proper image handling
types[pCode[1]] = t_VkImage;
break;
}
////////////////////////////////////////////////
// Variables and Constants
////////////////////////////////////////////////
case spv::OpVariable:
{
// global variable
Type *t = types[pCode[1]];
assert(isa<PointerType>(t));
bool blockbind = (blocks.find(pCode[1]) != blocks.end());
// for blocks we declare the global variable as a pointer to a struct (and the variable
// itself is a pointer), this lets us just write the pointer value of where the buffer is
// without needing to copy the whole UBO.
// for non-blocks, e.g. int gl_PerVertex we take the "pointer to int" that the SPIR-V
// declares and only declare the global variable as an int - and as above the variable
// itself is a pointer. The value then gets stored/loaded directly
if(!blockbind)
t = t->getPointerElementType();
else
blocks.insert(pCode[2]);
globalTypes.push_back(t);
// initialisers not handled
assert(WordCount == 4);
break;
}
case spv::OpConstant:
{
Type *t = types[pCode[1]];
if(t->isFloatTy())
values[pCode[2]] = ConstantFP::get(t, ((float *)pCode)[3]);
else
values[pCode[2]] = ConstantInt::get(t, pCode[3]);
break;
}
case spv::OpConstantComposite:
{
Type *t = types[pCode[1]];
assert(t->isVectorTy());
std::vector<Constant *> members;
for(uint16_t i = 3; i < WordCount; i++)
members.push_back((Constant *)values[pCode[i]]);
values[pCode[2]] = ConstantVector::get(members);
break;
}
}
// stop once we hit the functions
if(opcode == spv::OpFunction)
break;
pCode += WordCount;
}
// declare globals struct here
Type *globalStructType = StructType::create(globalTypes, "GlobalsStruct");
for(auto it = functypes.begin(); it != functypes.end(); ++it)
{
// all functions take the globals struct as the first parameter
it->second.params.insert(it->second.params.begin(), PointerType::get(globalStructType, 0));
}
std::map<uint32_t, Function *> functiondefs;
std::map<uint32_t, BasicBlock *> labels;
pCode = opStart;
while(pCode < opEnd)
{
uint16_t WordCount = pCode[0] >> spv::WordCountShift;
spv::Op opcode = spv::Op(pCode[0] & spv::OpCodeMask);
switch(opcode)
{
case spv::OpFunction:
{
sprintf_s(uniq_name, "%p_%d", ret, pCode[2]);
if(types[pCode[4]] == NULL)
{
const FunctionTypeInfo &f = functypes[pCode[4]];
types[pCode[4]] = FunctionType::get(f.ret, f.params, false);
}
curfunc = Function::Create((llvm::FunctionType *)types[pCode[4]],
llvm::GlobalValue::InternalLinkage, uniq_name, m);
functiondefs[pCode[2]] = curfunc;
break;
}
case spv::OpFunctionEnd: