This repository was archived by the owner on Aug 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathShaderConductor.cpp
More file actions
969 lines (832 loc) · 31.5 KB
/
ShaderConductor.cpp
File metadata and controls
969 lines (832 loc) · 31.5 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
/*
* ShaderConductor
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <ShaderConductor/ShaderConductor.hpp>
#include <dxc/Support/Global.h>
#include <dxc/Support/Unicode.h>
#include <dxc/Support/WinAdapter.h>
#include <dxc/Support/WinIncludes.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <fstream>
#include <memory>
#include <dxc/dxcapi.h>
#include <llvm/Support/ErrorHandling.h>
#include <spirv-tools/libspirv.h>
#include <spirv.hpp>
#include <spirv_cross.hpp>
#include <spirv_glsl.hpp>
#include <spirv_hlsl.hpp>
#include <spirv_msl.hpp>
#define SC_UNUSED(x) (void)(x);
using namespace ShaderConductor;
namespace
{
bool dllDetaching = false;
class Dxcompiler
{
public:
~Dxcompiler()
{
this->Destroy();
}
static Dxcompiler& Instance()
{
static Dxcompiler instance;
return instance;
}
IDxcLibrary* Library() const
{
return m_library;
}
IDxcCompiler* Compiler() const
{
return m_compiler;
}
void Destroy()
{
if (m_dxcompilerDll)
{
m_compiler = nullptr;
m_library = nullptr;
m_createInstanceFunc = nullptr;
#ifdef _WIN32
::FreeLibrary(m_dxcompilerDll);
#else
::dlclose(m_dxcompilerDll);
#endif
m_dxcompilerDll = nullptr;
}
}
void Terminate()
{
if (m_dxcompilerDll)
{
m_compiler.Detach();
m_library.Detach();
m_createInstanceFunc = nullptr;
m_dxcompilerDll = nullptr;
}
}
private:
Dxcompiler()
{
if (dllDetaching)
{
return;
}
#ifdef _WIN32
const char* dllName = "dxcompiler.dll";
#elif __APPLE__
const char* dllName = "libdxcompiler.dylib";
#else
const char* dllName = "libdxcompiler.so";
#endif
const char* functionName = "DxcCreateInstance";
#ifdef _WIN32
HMODULE hm = NULL;
if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR) "DllMain",
&hm) != 0)
{
char path[MAX_PATH];
if (GetModuleFileName(hm, path, sizeof(path)) != 0)
{
PathRemoveFileSpec(path);
char finalPath[MAX_PATH];
m_dxcompilerDll = ::LoadLibraryA(PathCombine(finalPath, path, dllName));
}
}
if (m_dxcompilerDll == nullptr)
{
m_dxcompilerDll = ::LoadLibraryA(dllName);
}
#else
m_dxcompilerDll = ::dlopen(dllName, RTLD_LAZY);
#endif
if (m_dxcompilerDll != nullptr)
{
#ifdef _WIN32
m_createInstanceFunc = (DxcCreateInstanceProc)::GetProcAddress(m_dxcompilerDll, functionName);
#else
m_createInstanceFunc = (DxcCreateInstanceProc)::dlsym(m_dxcompilerDll, functionName);
#endif
if (m_createInstanceFunc != nullptr)
{
IFT(m_createInstanceFunc(CLSID_DxcLibrary, __uuidof(IDxcLibrary), reinterpret_cast<void**>(&m_library)));
IFT(m_createInstanceFunc(CLSID_DxcCompiler, __uuidof(IDxcCompiler), reinterpret_cast<void**>(&m_compiler)));
}
else
{
this->Destroy();
throw std::runtime_error(std::string("COULDN'T get ") + functionName + " from dxcompiler.");
}
}
else
{
throw std::runtime_error("COULDN'T load dxcompiler.");
}
}
private:
HMODULE m_dxcompilerDll = nullptr;
DxcCreateInstanceProc m_createInstanceFunc = nullptr;
CComPtr<IDxcLibrary> m_library;
CComPtr<IDxcCompiler> m_compiler;
};
class ScIncludeHandler : public IDxcIncludeHandler
{
public:
explicit ScIncludeHandler(std::function<Blob*(const char* includeName)> loadCallback) : m_loadCallback(std::move(loadCallback))
{
}
HRESULT STDMETHODCALLTYPE LoadSource(LPCWSTR fileName, IDxcBlob** includeSource) override
{
if ((fileName[0] == L'.') && (fileName[1] == L'/'))
{
fileName += 2;
}
std::string utf8FileName;
if (!Unicode::UTF16ToUTF8String(fileName, &utf8FileName))
{
return E_FAIL;
}
auto blobDeleter = [](Blob* blob) { DestroyBlob(blob); };
std::unique_ptr<Blob, decltype(blobDeleter)> source(nullptr, blobDeleter);
try
{
source.reset(m_loadCallback(utf8FileName.c_str()));
}
catch (...)
{
return E_FAIL;
}
*includeSource = nullptr;
return Dxcompiler::Instance().Library()->CreateBlobWithEncodingOnHeapCopy(source->Data(), source->Size(), CP_UTF8,
reinterpret_cast<IDxcBlobEncoding**>(includeSource));
}
ULONG STDMETHODCALLTYPE AddRef() override
{
++m_ref;
return m_ref;
}
ULONG STDMETHODCALLTYPE Release() override
{
--m_ref;
ULONG result = m_ref;
if (result == 0)
{
delete this;
}
return result;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** object) override
{
if (IsEqualIID(iid, __uuidof(IDxcIncludeHandler)))
{
*object = dynamic_cast<IDxcIncludeHandler*>(this);
this->AddRef();
return S_OK;
}
else if (IsEqualIID(iid, __uuidof(IUnknown)))
{
*object = dynamic_cast<IUnknown*>(this);
this->AddRef();
return S_OK;
}
else
{
return E_NOINTERFACE;
}
}
private:
std::function<Blob*(const char* includeName)> m_loadCallback;
std::atomic<ULONG> m_ref = 0;
};
Blob* DefaultLoadCallback(const char* includeName)
{
std::vector<char> ret;
std::ifstream includeFile(includeName, std::ios_base::in);
if (includeFile)
{
includeFile.seekg(0, std::ios::end);
ret.resize(static_cast<size_t>(includeFile.tellg()));
includeFile.seekg(0, std::ios::beg);
includeFile.read(ret.data(), ret.size());
ret.resize(static_cast<size_t>(includeFile.gcount()));
}
else
{
throw std::runtime_error(std::string("COULDN'T load included file ") + includeName + ".");
}
return CreateBlob(ret.data(), static_cast<uint32_t>(ret.size()));
}
class ScBlob : public Blob
{
public:
ScBlob(const void* data, uint32_t size)
: data_(reinterpret_cast<const uint8_t*>(data), reinterpret_cast<const uint8_t*>(data) + size)
{
}
const void* Data() const override
{
return data_.data();
}
uint32_t Size() const override
{
return static_cast<uint32_t>(data_.size());
}
private:
std::vector<uint8_t> data_;
};
void AppendError(Compiler::ResultDesc& result, const std::string& msg)
{
std::string errorMSg;
if (result.errorWarningMsg != nullptr)
{
errorMSg.assign(reinterpret_cast<const char*>(result.errorWarningMsg->Data()), result.errorWarningMsg->Size());
}
if (!errorMSg.empty())
{
errorMSg += "\n";
}
errorMSg += msg;
DestroyBlob(result.errorWarningMsg);
result.errorWarningMsg = CreateBlob(errorMSg.data(), static_cast<uint32_t>(errorMSg.size()));
result.hasError = true;
}
Compiler::ResultDesc CompileToBinary(const Compiler::SourceDesc& source, const Compiler::Options& options,
ShadingLanguage targetLanguage)
{
assert((targetLanguage == ShadingLanguage::Dxil) || (targetLanguage == ShadingLanguage::SpirV));
std::wstring shaderProfile;
switch (source.stage)
{
case ShaderStage::VertexShader:
shaderProfile = L"vs";
break;
case ShaderStage::PixelShader:
shaderProfile = L"ps";
break;
case ShaderStage::GeometryShader:
shaderProfile = L"gs";
break;
case ShaderStage::HullShader:
shaderProfile = L"hs";
break;
case ShaderStage::DomainShader:
shaderProfile = L"ds";
break;
case ShaderStage::ComputeShader:
shaderProfile = L"cs";
break;
default:
llvm_unreachable("Invalid shader stage.");
}
shaderProfile.push_back(L'_');
shaderProfile.push_back(L'0' + options.shaderModel.major_ver);
shaderProfile.push_back(L'_');
shaderProfile.push_back(L'0' + options.shaderModel.minor_ver);
std::vector<DxcDefine> dxcDefines;
std::vector<std::wstring> dxcDefineStrings;
// Need to reserve capacity so that small-string optimization does not
// invalidate the pointers to internal string data while resizing.
dxcDefineStrings.reserve(source.numDefines * 2);
for (size_t i = 0; i < source.numDefines; ++i)
{
const auto& define = source.defines[i];
std::wstring nameUtf16Str;
Unicode::UTF8ToUTF16String(define.name, &nameUtf16Str);
dxcDefineStrings.emplace_back(std::move(nameUtf16Str));
const wchar_t* nameUtf16 = dxcDefineStrings.back().c_str();
const wchar_t* valueUtf16;
if (define.value != nullptr)
{
std::wstring valueUtf16Str;
Unicode::UTF8ToUTF16String(define.value, &valueUtf16Str);
dxcDefineStrings.emplace_back(std::move(valueUtf16Str));
valueUtf16 = dxcDefineStrings.back().c_str();
}
else
{
valueUtf16 = nullptr;
}
dxcDefines.push_back({ nameUtf16, valueUtf16 });
}
CComPtr<IDxcBlobEncoding> sourceBlob;
IFT(Dxcompiler::Instance().Library()->CreateBlobWithEncodingOnHeapCopy(source.source, static_cast<UINT32>(strlen(source.source)),
CP_UTF8, &sourceBlob));
IFTARG(sourceBlob->GetBufferSize() >= 4);
std::wstring shaderNameUtf16;
Unicode::UTF8ToUTF16String(source.fileName, &shaderNameUtf16);
std::wstring entryPointUtf16;
Unicode::UTF8ToUTF16String(source.entryPoint, &entryPointUtf16);
std::vector<std::wstring> dxcArgStrings;
// HLSL matrices are translated into SPIR-V OpTypeMatrixs in a transposed manner,
// See also https://antiagainst.github.io/post/hlsl-for-vulkan-matrices/
if (options.packMatricesInRowMajor)
{
dxcArgStrings.push_back(L"-Zpr");
}
else
{
dxcArgStrings.push_back(L"-Zpc");
}
if (options.enable16bitTypes)
{
if (options.shaderModel >= Compiler::ShaderModel{ 6, 2 })
{
dxcArgStrings.push_back(L"-enable-16bit-types");
}
else
{
throw std::runtime_error("16-bit types requires shader model 6.2 or up.");
}
}
if (options.enableDebugInfo)
{
dxcArgStrings.push_back(L"-Zi");
}
if (options.disableOptimizations)
{
dxcArgStrings.push_back(L"-Od");
}
else
{
if (options.optimizationLevel < 4)
{
dxcArgStrings.push_back(std::wstring(L"-O") + static_cast<wchar_t>(L'0' + options.optimizationLevel));
}
else
{
llvm_unreachable("Invalid optimization level.");
}
}
if (options.shiftAllCBuffersBindings > 0)
{
dxcArgStrings.push_back(L"-fvk-b-shift");
dxcArgStrings.push_back(std::to_wstring(options.shiftAllCBuffersBindings));
dxcArgStrings.push_back(L"all");
}
if (options.shiftAllUABuffersBindings > 0)
{
dxcArgStrings.push_back(L"-fvk-u-shift");
dxcArgStrings.push_back(std::to_wstring(options.shiftAllUABuffersBindings));
dxcArgStrings.push_back(L"all");
}
if (options.shiftAllSamplersBindings > 0)
{
dxcArgStrings.push_back(L"-fvk-s-shift");
dxcArgStrings.push_back(std::to_wstring(options.shiftAllSamplersBindings));
dxcArgStrings.push_back(L"all");
}
if (options.shiftAllTexturesBindings > 0)
{
dxcArgStrings.push_back(L"-fvk-t-shift");
dxcArgStrings.push_back(std::to_wstring(options.shiftAllTexturesBindings));
dxcArgStrings.push_back(L"all");
}
switch (targetLanguage)
{
case ShadingLanguage::Dxil:
break;
case ShadingLanguage::SpirV:
case ShadingLanguage::Hlsl:
case ShadingLanguage::Glsl:
case ShadingLanguage::Essl:
case ShadingLanguage::Msl_macOS:
case ShadingLanguage::Msl_iOS:
dxcArgStrings.push_back(L"-spirv");
break;
default:
llvm_unreachable("Invalid shading language.");
}
std::vector<const wchar_t*> dxcArgs;
dxcArgs.reserve(dxcArgStrings.size());
for (const auto& arg : dxcArgStrings)
{
dxcArgs.push_back(arg.c_str());
}
CComPtr<IDxcIncludeHandler> includeHandler = new ScIncludeHandler(std::move(source.loadIncludeCallback));
CComPtr<IDxcOperationResult> compileResult;
IFT(Dxcompiler::Instance().Compiler()->Compile(sourceBlob, shaderNameUtf16.c_str(), entryPointUtf16.c_str(), shaderProfile.c_str(),
dxcArgs.data(), static_cast<UINT32>(dxcArgs.size()), dxcDefines.data(),
static_cast<UINT32>(dxcDefines.size()), includeHandler, &compileResult));
HRESULT status;
IFT(compileResult->GetStatus(&status));
Compiler::ResultDesc ret;
ret.target = nullptr;
ret.isText = false;
ret.errorWarningMsg = nullptr;
CComPtr<IDxcBlobEncoding> errors;
IFT(compileResult->GetErrorBuffer(&errors));
if (errors != nullptr)
{
if (errors->GetBufferSize() > 0)
{
ret.errorWarningMsg = CreateBlob(errors->GetBufferPointer(), static_cast<uint32_t>(errors->GetBufferSize()));
}
errors = nullptr;
}
ret.hasError = true;
if (SUCCEEDED(status))
{
CComPtr<IDxcBlob> program;
IFT(compileResult->GetResult(&program));
compileResult = nullptr;
if (program != nullptr)
{
ret.target = CreateBlob(program->GetBufferPointer(), static_cast<uint32_t>(program->GetBufferSize()));
ret.hasError = false;
}
}
return ret;
}
Compiler::ResultDesc ConvertBinary(const Compiler::ResultDesc& binaryResult, const Compiler::SourceDesc& source,
const Compiler::TargetDesc& target)
{
assert((target.language != ShadingLanguage::Dxil) && (target.language != ShadingLanguage::SpirV));
assert((binaryResult.target->Size() & (sizeof(uint32_t) - 1)) == 0);
Compiler::ResultDesc ret;
ret.target = nullptr;
ret.errorWarningMsg = binaryResult.errorWarningMsg;
ret.isText = true;
uint32_t intVersion = 0;
if (target.version != nullptr)
{
intVersion = std::stoi(target.version);
}
const uint32_t* spirvIr = reinterpret_cast<const uint32_t*>(binaryResult.target->Data());
const size_t spirvSize = binaryResult.target->Size() / sizeof(uint32_t);
std::unique_ptr<spirv_cross::CompilerGLSL> compiler;
bool combinedImageSamplers = false;
bool buildDummySampler = false;
switch (target.language)
{
case ShadingLanguage::Hlsl:
if ((source.stage == ShaderStage::GeometryShader) || (source.stage == ShaderStage::HullShader) ||
(source.stage == ShaderStage::DomainShader))
{
// Check https://github.com/KhronosGroup/SPIRV-Cross/issues/121 for details
AppendError(ret, "GS, HS, and DS has not been supported yet.");
return ret;
}
if ((source.stage == ShaderStage::GeometryShader) && (intVersion < 40))
{
AppendError(ret, "HLSL shader model earlier than 4.0 doesn't have GS or CS.");
return ret;
}
if ((source.stage == ShaderStage::ComputeShader) && (intVersion < 50))
{
AppendError(ret, "CS in HLSL shader model earlier than 5.0 is not supported.");
return ret;
}
if (((source.stage == ShaderStage::HullShader) || (source.stage == ShaderStage::DomainShader)) && (intVersion < 50))
{
AppendError(ret, "HLSL shader model earlier than 5.0 doesn't have HS or DS.");
return ret;
}
compiler = std::make_unique<spirv_cross::CompilerHLSL>(spirvIr, spirvSize);
break;
case ShadingLanguage::Glsl:
case ShadingLanguage::Essl:
compiler = std::make_unique<spirv_cross::CompilerGLSL>(spirvIr, spirvSize);
combinedImageSamplers = true;
buildDummySampler = true;
break;
case ShadingLanguage::Msl_macOS:
case ShadingLanguage::Msl_iOS:
if (source.stage == ShaderStage::GeometryShader)
{
AppendError(ret, "MSL doesn't have GS.");
return ret;
}
compiler = std::make_unique<spirv_cross::CompilerMSL>(spirvIr, spirvSize);
break;
default:
llvm_unreachable("Invalid target language.");
}
spv::ExecutionModel model;
switch (source.stage)
{
case ShaderStage::VertexShader:
model = spv::ExecutionModelVertex;
break;
case ShaderStage::HullShader:
model = spv::ExecutionModelTessellationControl;
break;
case ShaderStage::DomainShader:
model = spv::ExecutionModelTessellationEvaluation;
break;
case ShaderStage::GeometryShader:
model = spv::ExecutionModelGeometry;
break;
case ShaderStage::PixelShader:
model = spv::ExecutionModelFragment;
break;
case ShaderStage::ComputeShader:
model = spv::ExecutionModelGLCompute;
break;
default:
llvm_unreachable("Invalid shader stage.");
}
compiler->set_entry_point(source.entryPoint, model);
spirv_cross::CompilerGLSL::Options opts = compiler->get_common_options();
if (target.version != nullptr)
{
opts.version = intVersion;
}
opts.es = (target.language == ShadingLanguage::Essl);
opts.force_temporary = false;
opts.separate_shader_objects = true;
opts.flatten_multidimensional_arrays = false;
opts.enable_420pack_extension =
(target.language == ShadingLanguage::Glsl) && ((target.version == nullptr) || (opts.version >= 420));
opts.vulkan_semantics = false;
opts.vertex.fixup_clipspace = false;
opts.vertex.flip_vert_y = false;
opts.vertex.support_nonzero_base_instance = true;
compiler->set_common_options(opts);
if (target.language == ShadingLanguage::Hlsl)
{
auto* hlslCompiler = static_cast<spirv_cross::CompilerHLSL*>(compiler.get());
auto hlslOpts = hlslCompiler->get_hlsl_options();
if (target.version != nullptr)
{
if (opts.version < 30)
{
AppendError(ret, "HLSL shader model earlier than 3.0 is not supported.");
return ret;
}
hlslOpts.shader_model = opts.version;
}
if (hlslOpts.shader_model <= 30)
{
combinedImageSamplers = true;
buildDummySampler = true;
}
hlslCompiler->set_hlsl_options(hlslOpts);
}
else if ((target.language == ShadingLanguage::Msl_macOS) || (target.language == ShadingLanguage::Msl_iOS))
{
auto* mslCompiler = static_cast<spirv_cross::CompilerMSL*>(compiler.get());
auto mslOpts = mslCompiler->get_msl_options();
if (target.version != nullptr)
{
mslOpts.msl_version = opts.version;
}
mslOpts.swizzle_texture_samples = false;
mslOpts.platform = (target.language == ShadingLanguage::Msl_iOS) ? spirv_cross::CompilerMSL::Options::iOS
: spirv_cross::CompilerMSL::Options::macOS;
mslCompiler->set_msl_options(mslOpts);
const auto& resources = mslCompiler->get_shader_resources();
uint32_t textureBinding = 0;
for (const auto& image : resources.separate_images)
{
mslCompiler->set_decoration(image.id, spv::DecorationBinding, textureBinding);
++textureBinding;
}
uint32_t samplerBinding = 0;
for (const auto& sampler : resources.separate_samplers)
{
mslCompiler->set_decoration(sampler.id, spv::DecorationBinding, samplerBinding);
++samplerBinding;
}
}
if (buildDummySampler)
{
const uint32_t sampler = compiler->build_dummy_sampler_for_combined_images();
if (sampler != 0)
{
compiler->set_decoration(sampler, spv::DecorationDescriptorSet, 0);
compiler->set_decoration(sampler, spv::DecorationBinding, 0);
}
}
if (combinedImageSamplers)
{
compiler->build_combined_image_samplers();
for (auto& remap : compiler->get_combined_image_samplers())
{
uint32_t binding = compiler->get_decoration(remap.image_id, spv::DecorationBinding); // or sampler_id.
compiler->set_decoration(remap.combined_id, spv::DecorationBinding, binding);
compiler->set_name(remap.combined_id,
"SPIRV_Cross_Combined" + compiler->get_name(remap.image_id) + compiler->get_name(remap.sampler_id));
}
}
if (target.language == ShadingLanguage::Hlsl)
{
auto* hlslCompiler = static_cast<spirv_cross::CompilerHLSL*>(compiler.get());
const uint32_t newBuiltin = hlslCompiler->remap_num_workgroups_builtin();
if (newBuiltin)
{
compiler->set_decoration(newBuiltin, spv::DecorationDescriptorSet, 0);
compiler->set_decoration(newBuiltin, spv::DecorationBinding, 0);
}
}
try
{
const std::string targetStr = compiler->compile();
ret.target = CreateBlob(targetStr.data(), static_cast<uint32_t>(targetStr.size()));
ret.hasError = false;
}
catch (spirv_cross::CompilerError& error)
{
const char* errorMsg = error.what();
DestroyBlob(ret.errorWarningMsg);
ret.errorWarningMsg = CreateBlob(errorMsg, static_cast<uint32_t>(strlen(errorMsg)));
ret.hasError = true;
}
return ret;
}
} // namespace
namespace ShaderConductor
{
Blob::~Blob() = default;
Blob* CreateBlob(const void* data, uint32_t size)
{
return new ScBlob(data, size);
}
void DestroyBlob(Blob* blob)
{
delete blob;
}
Compiler::ResultDesc Compiler::Compile(const SourceDesc& source, const Options& options, const TargetDesc& target)
{
ResultDesc result;
Compiler::Compile(source, options, &target, 1, &result);
return result;
}
void Compiler::Compile(const SourceDesc& source, const Options& options, const TargetDesc* targets, uint32_t numTargets,
ResultDesc* results)
{
SourceDesc sourceOverride = source;
if (!sourceOverride.entryPoint || (strlen(sourceOverride.entryPoint) == 0))
{
sourceOverride.entryPoint = "main";
}
if (!sourceOverride.loadIncludeCallback)
{
sourceOverride.loadIncludeCallback = DefaultLoadCallback;
}
bool hasDxil = false;
bool hasSpirV = false;
for (uint32_t i = 0; i < numTargets; ++i)
{
if (targets[i].language == ShadingLanguage::Dxil)
{
hasDxil = true;
}
else
{
hasSpirV = true;
}
}
ResultDesc dxilBinaryResult{};
if (hasDxil)
{
dxilBinaryResult = CompileToBinary(sourceOverride, options, ShadingLanguage::Dxil);
}
ResultDesc spirvBinaryResult{};
if (hasSpirV)
{
spirvBinaryResult = CompileToBinary(sourceOverride, options, ShadingLanguage::SpirV);
}
for (uint32_t i = 0; i < numTargets; ++i)
{
ResultDesc binaryResult = targets[i].language == ShadingLanguage::Dxil ? dxilBinaryResult : spirvBinaryResult;
if (binaryResult.target)
{
binaryResult.target = CreateBlob(binaryResult.target->Data(), binaryResult.target->Size());
}
if (binaryResult.errorWarningMsg)
{
binaryResult.errorWarningMsg = CreateBlob(binaryResult.errorWarningMsg->Data(), binaryResult.errorWarningMsg->Size());
}
if (!binaryResult.hasError)
{
switch (targets[i].language)
{
case ShadingLanguage::Dxil:
case ShadingLanguage::SpirV:
results[i] = binaryResult;
break;
case ShadingLanguage::Hlsl:
case ShadingLanguage::Glsl:
case ShadingLanguage::Essl:
case ShadingLanguage::Msl_macOS:
case ShadingLanguage::Msl_iOS:
results[i] = ConvertBinary(binaryResult, sourceOverride, targets[i]);
break;
default:
llvm_unreachable("Invalid shading language.");
break;
}
}
else
{
results[i] = binaryResult;
}
}
if (hasDxil)
{
DestroyBlob(dxilBinaryResult.target);
DestroyBlob(dxilBinaryResult.errorWarningMsg);
}
if (hasSpirV)
{
DestroyBlob(spirvBinaryResult.target);
DestroyBlob(spirvBinaryResult.errorWarningMsg);
}
}
Compiler::ResultDesc Compiler::Disassemble(const DisassembleDesc& source)
{
assert((source.language == ShadingLanguage::SpirV) || (source.language == ShadingLanguage::Dxil));
Compiler::ResultDesc ret;
ret.target = nullptr;
ret.isText = true;
ret.errorWarningMsg = nullptr;
if (source.language == ShadingLanguage::SpirV)
{
const uint32_t* spirvIr = reinterpret_cast<const uint32_t*>(source.binary);
const size_t spirvSize = source.binarySize / sizeof(uint32_t);
spv_context context = spvContextCreate(SPV_ENV_UNIVERSAL_1_3);
uint32_t options = SPV_BINARY_TO_TEXT_OPTION_NONE | SPV_BINARY_TO_TEXT_OPTION_INDENT | SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES;
spv_text text = nullptr;
spv_diagnostic diagnostic = nullptr;
spv_result_t error = spvBinaryToText(context, spirvIr, spirvSize, options, &text, &diagnostic);
spvContextDestroy(context);
if (error)
{
ret.errorWarningMsg = CreateBlob(diagnostic->error, static_cast<uint32_t>(strlen(diagnostic->error)));
ret.hasError = true;
spvDiagnosticDestroy(diagnostic);
}
else
{
const std::string disassemble = text->str;
ret.target = CreateBlob(disassemble.data(), static_cast<uint32_t>(disassemble.size()));
ret.hasError = false;
}
spvTextDestroy(text);
}
else
{
CComPtr<IDxcBlobEncoding> blob;
CComPtr<IDxcBlobEncoding> disassembly;
IFT(Dxcompiler::Instance().Library()->CreateBlobWithEncodingOnHeapCopy(source.binary, source.binarySize, CP_UTF8, &blob));
IFT(Dxcompiler::Instance().Compiler()->Disassemble(blob, &disassembly));
if (disassembly != nullptr)
{
ret.target = CreateBlob(disassembly->GetBufferPointer(), static_cast<uint32_t>(disassembly->GetBufferSize()));
ret.hasError = false;
}
else
{
ret.hasError = true;
}
}
return ret;
}
} // namespace ShaderConductor
#ifdef _WIN32
BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)
{
SC_UNUSED(instance);
BOOL result = TRUE;
if (reason == DLL_PROCESS_DETACH)
{
dllDetaching = true;
if (reserved == 0)
{
// FreeLibrary has been called or the DLL load failed
Dxcompiler::Instance().Destroy();
}
else
{
// Process termination. We should not call FreeLibrary()
Dxcompiler::Instance().Terminate();
}
}
return result;
}
#endif