Debian Codegraph @

Source/Core/VideoCommon/Spirv.cpp

raw symbols SCIP
1 // Copyright 2022 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/Spirv.h"
5
6 #include <fstream>
7
8 #include <glslang/SPIRV/GlslangToSpv.h>
9
10 #include "Common/FileUtil.h"
11 #include "Common/Logging/Log.h"
12 #include "Common/MsgHandler.h"
13 #include "Common/Version.h"
14
15 #include "VideoCommon/VideoBackendBase.h"
16 #include "VideoCommon/VideoConfig.h"
17
18 namespace
19 {
20 bool InitializeGlslang()
21 {
22 static bool glslang_initialized = false;
23 if (glslang_initialized)
24 return true;
25
26 if (!glslang::InitializeProcess())
27 {
28 PanicAlertFmt("Failed to initialize glslang shader compiler");
29 return false;
30 }
31
32 std::atexit([] { glslang::FinalizeProcess(); });
33
34 glslang_initialized = true;
35 return true;
36 }
37
38 const TBuiltInResource* GetCompilerResourceLimits()
39 {
40 static const TBuiltInResource default_resource = {
41 /* .MaxLights = */ 32,
42 /* .MaxClipPlanes = */ 6,
43 /* .MaxTextureUnits = */ 32,
44 /* .MaxTextureCoords = */ 32,
45 /* .MaxVertexAttribs = */ 64,
46 /* .MaxVertexUniformComponents = */ 4096,
47 /* .MaxVaryingFloats = */ 64,
48 /* .MaxVertexTextureImageUnits = */ 32,
49 /* .MaxCombinedTextureImageUnits = */ 80,
50 /* .MaxTextureImageUnits = */ 32,
51 /* .MaxFragmentUniformComponents = */ 4096,
52 /* .MaxDrawBuffers = */ 32,
53 /* .MaxVertexUniformVectors = */ 128,
54 /* .MaxVaryingVectors = */ 8,
55 /* .MaxFragmentUniformVectors = */ 16,
56 /* .MaxVertexOutputVectors = */ 16,
57 /* .MaxFragmentInputVectors = */ 15,
58 /* .MinProgramTexelOffset = */ -8,
59 /* .MaxProgramTexelOffset = */ 7,
60 /* .MaxClipDistances = */ 8,
61 /* .MaxComputeWorkGroupCountX = */ 65535,
62 /* .MaxComputeWorkGroupCountY = */ 65535,
63 /* .MaxComputeWorkGroupCountZ = */ 65535,
64 /* .MaxComputeWorkGroupSizeX = */ 1024,
65 /* .MaxComputeWorkGroupSizeY = */ 1024,
66 /* .MaxComputeWorkGroupSizeZ = */ 64,
67 /* .MaxComputeUniformComponents = */ 1024,
68 /* .MaxComputeTextureImageUnits = */ 16,
69 /* .MaxComputeImageUniforms = */ 8,
70 /* .MaxComputeAtomicCounters = */ 8,
71 /* .MaxComputeAtomicCounterBuffers = */ 1,
72 /* .MaxVaryingComponents = */ 60,
73 /* .MaxVertexOutputComponents = */ 64,
74 /* .MaxGeometryInputComponents = */ 64,
75 /* .MaxGeometryOutputComponents = */ 128,
76 /* .MaxFragmentInputComponents = */ 128,
77 /* .MaxImageUnits = */ 8,
78 /* .MaxCombinedImageUnitsAndFragmentOutputs = */ 8,
79 /* .MaxCombinedShaderOutputResources = */ 8,
80 /* .MaxImageSamples = */ 0,
81 /* .MaxVertexImageUniforms = */ 0,
82 /* .MaxTessControlImageUniforms = */ 0,
83 /* .MaxTessEvaluationImageUniforms = */ 0,
84 /* .MaxGeometryImageUniforms = */ 0,
85 /* .MaxFragmentImageUniforms = */ 8,
86 /* .MaxCombinedImageUniforms = */ 8,
87 /* .MaxGeometryTextureImageUnits = */ 16,
88 /* .MaxGeometryOutputVertices = */ 256,
89 /* .MaxGeometryTotalOutputComponents = */ 1024,
90 /* .MaxGeometryUniformComponents = */ 1024,
91 /* .MaxGeometryVaryingComponents = */ 64,
92 /* .MaxTessControlInputComponents = */ 128,
93 /* .MaxTessControlOutputComponents = */ 128,
94 /* .MaxTessControlTextureImageUnits = */ 16,
95 /* .MaxTessControlUniformComponents = */ 1024,
96 /* .MaxTessControlTotalOutputComponents = */ 4096,
97 /* .MaxTessEvaluationInputComponents = */ 128,
98 /* .MaxTessEvaluationOutputComponents = */ 128,
99 /* .MaxTessEvaluationTextureImageUnits = */ 16,
100 /* .MaxTessEvaluationUniformComponents = */ 1024,
101 /* .MaxTessPatchComponents = */ 120,
102 /* .MaxPatchVertices = */ 32,
103 /* .MaxTessGenLevel = */ 64,
104 /* .MaxViewports = */ 16,
105 /* .MaxVertexAtomicCounters = */ 0,
106 /* .MaxTessControlAtomicCounters = */ 0,
107 /* .MaxTessEvaluationAtomicCounters = */ 0,
108 /* .MaxGeometryAtomicCounters = */ 0,
109 /* .MaxFragmentAtomicCounters = */ 8,
110 /* .MaxCombinedAtomicCounters = */ 8,
111 /* .MaxAtomicCounterBindings = */ 1,
112 /* .MaxVertexAtomicCounterBuffers = */ 0,
113 /* .MaxTessControlAtomicCounterBuffers = */ 0,
114 /* .MaxTessEvaluationAtomicCounterBuffers = */ 0,
115 /* .MaxGeometryAtomicCounterBuffers = */ 0,
116 /* .MaxFragmentAtomicCounterBuffers = */ 1,
117 /* .MaxCombinedAtomicCounterBuffers = */ 1,
118 /* .MaxAtomicCounterBufferSize = */ 16384,
119 /* .MaxTransformFeedbackBuffers = */ 4,
120 /* .MaxTransformFeedbackInterleavedComponents = */ 64,
121 /* .MaxCullDistances = */ 8,
122 /* .MaxCombinedClipAndCullDistances = */ 8,
123 /* .MaxSamples = */ 4,
124 /* .maxMeshOutputVerticesNV = */ 256,
125 /* .maxMeshOutputPrimitivesNV = */ 512,
126 /* .maxMeshWorkGroupSizeX_NV = */ 32,
127 /* .maxMeshWorkGroupSizeY_NV = */ 1,
128 /* .maxMeshWorkGroupSizeZ_NV = */ 1,
129 /* .maxTaskWorkGroupSizeX_NV = */ 32,
130 /* .maxTaskWorkGroupSizeY_NV = */ 1,
131 /* .maxTaskWorkGroupSizeZ_NV = */ 1,
132 /* .maxMeshViewCountNV = */ 4,
133 /* .maxMeshOutputVerticesEXT = */ 256,
134 /* .maxMeshOutputPrimitivesEXT = */ 256,
135 /* .maxMeshWorkGroupSizeX_EXT = */ 128,
136 /* .maxMeshWorkGroupSizeY_EXT = */ 128,
137 /* .maxMeshWorkGroupSizeZ_EXT = */ 128,
138 /* .maxTaskWorkGroupSizeX_EXT = */ 128,
139 /* .maxTaskWorkGroupSizeY_EXT = */ 128,
140 /* .maxTaskWorkGroupSizeZ_EXT = */ 128,
141 /* .maxMeshViewCountEXT = */ 4,
142 /* .maxDualSourceDrawBuffersEXT = */ 1,
143
144 /* .limits = */
145 {
146 /* .nonInductiveForLoops = */ 1,
147 /* .whileLoops = */ 1,
148 /* .doWhileLoops = */ 1,
149 /* .generalUniformIndexing = */ 1,
150 /* .generalAttributeMatrixVectorIndexing = */ 1,
151 /* .generalVaryingIndexing = */ 1,
152 /* .generalSamplerIndexing = */ 1,
153 /* .generalVariableIndexing = */ 1,
154 /* .generalConstantMatrixVectorIndexing = */ 1,
155 }};
156 return &default_resource;
157 }
158
159 std::optional<SPIRV::CodeVector>
160 CompileShaderToSPV(EShLanguage stage, APIType api_type,
161 glslang::EShTargetLanguageVersion language_version, const char* stage_filename,
162 std::string_view source, glslang::TShader::Includer* shader_includer)
163 {
164 if (!InitializeGlslang())
165 return std::nullopt;
166
167 std::unique_ptr<glslang::TShader> shader = std::make_unique<glslang::TShader>(stage);
168 std::unique_ptr<glslang::TProgram> program;
169 glslang::TShader::ForbidIncluder forbid_includer;
170 EProfile profile = ECoreProfile;
171 EShMessages messages = static_cast<EShMessages>(EShMsgDefault | EShMsgSpvRules);
172 if (api_type == APIType::Vulkan || api_type == APIType::Metal)
173 messages = static_cast<EShMessages>(messages | EShMsgVulkanRules);
174 int default_version = 450;
175
176 const char* pass_source_code = source.data();
177 int pass_source_code_length = static_cast<int>(source.size());
178
179 shader->setEnvTarget(glslang::EShTargetSpv, language_version);
180
181 shader->setStringsWithLengths(&pass_source_code, &pass_source_code_length, 1);
182
183 auto DumpBadShader = [&](const char* msg) {
184 static int counter = 0;
185 std::string filename = VideoBackendBase::BadShaderFilename(stage_filename, counter++);
186 std::ofstream stream;
187 File::OpenFStream(stream, filename, std::ios_base::out);
188 if (stream.good())
189 {
190 stream << source << std::endl;
191 stream << msg << std::endl;
192 stream << "Shader Info Log:" << std::endl;
193 stream << shader->getInfoLog() << std::endl;
194 stream << shader->getInfoDebugLog() << std::endl;
195 if (program)
196 {
197 stream << "Program Info Log:" << std::endl;
198 stream << program->getInfoLog() << std::endl;
199 stream << program->getInfoDebugLog() << std::endl;
200 }
201 }
202
203 stream << "\n";
204 stream << "Dolphin Version: " + Common::GetScmRevStr() + "\n";
205 stream << "Video Backend: " + g_video_backend->GetDisplayName();
206 stream.close();
207
208 PanicAlertFmt("{} (written to {})\nDebug info:\n{}", msg, filename, shader->getInfoLog());
209 };
210
211 if (!shader->parse(GetCompilerResourceLimits(), default_version, profile, false, true, messages,
212 shader_includer ? *shader_includer : forbid_includer))
213 {
214 DumpBadShader("Failed to parse shader");
215 return std::nullopt;
216 }
217
218 // Even though there's only a single shader, we still need to link it to generate SPV
219 program = std::make_unique<glslang::TProgram>();
220 program->addShader(shader.get());
221 if (!program->link(messages))
222 {
223 DumpBadShader("Failed to link program");
224 return std::nullopt;
225 }
226
227 glslang::TIntermediate* intermediate = program->getIntermediate(stage);
228 if (!intermediate)
229 {
230 DumpBadShader("Failed to generate SPIR-V");
231 return std::nullopt;
232 }
233
234 SPIRV::CodeVector out_code;
235 spv::SpvBuildLogger logger;
236 glslang::SpvOptions options;
237
238 if (g_ActiveConfig.bEnableValidationLayer)
239 {
240 // Attach the source code to the SPIR-V for tools like RenderDoc.
241 shader->setSourceFile(stage_filename);
242 shader->addSourceText(pass_source_code, pass_source_code_length);
243
244 options.generateDebugInfo = true;
245 options.disableOptimizer = true;
246 options.optimizeSize = false;
247 options.disassemble = false;
248 options.validate = true;
249 }
250 else
251 {
252 options.disableOptimizer = false;
253 options.stripDebugInfo = true;
254 }
255
256 glslang::GlslangToSpv(*intermediate, out_code, &logger, &options);
257
258 // Write out messages
259 // Temporary: skip if it contains "Warning, version 450 is not yet complete; most version-specific
260 // features are present, but some are missing."
261 if (strlen(shader->getInfoLog()) > 108)
262 WARN_LOG_FMT(VIDEO, "Shader info log: {}", shader->getInfoLog());
263 if (strlen(shader->getInfoDebugLog()) > 0)
264 WARN_LOG_FMT(VIDEO, "Shader debug info log: {}", shader->getInfoDebugLog());
265 if (strlen(program->getInfoLog()) > 25)
266 WARN_LOG_FMT(VIDEO, "Program info log: {}", program->getInfoLog());
267 if (strlen(program->getInfoDebugLog()) > 0)
268 WARN_LOG_FMT(VIDEO, "Program debug info log: {}", program->getInfoDebugLog());
269 const std::string spv_messages = logger.getAllMessages();
270 if (!spv_messages.empty())
271 WARN_LOG_FMT(VIDEO, "SPIR-V conversion messages: {}", spv_messages);
272
273 return out_code;
274 }
275 } // namespace
276
277 namespace SPIRV
278 {
279 std::optional<CodeVector> CompileVertexShader(std::string_view source_code, APIType api_type,
280 glslang::EShTargetLanguageVersion language_version,
281 glslang::TShader::Includer* shader_includer)
282 {
283 return CompileShaderToSPV(EShLangVertex, api_type, language_version, "vs", source_code,
284 shader_includer);
285 }
286
287 std::optional<CodeVector> CompileGeometryShader(std::string_view source_code, APIType api_type,
288 glslang::EShTargetLanguageVersion language_version,
289 glslang::TShader::Includer* shader_includer)
290 {
291 return CompileShaderToSPV(EShLangGeometry, api_type, language_version, "gs", source_code,
292 shader_includer);
293 }
294
295 std::optional<CodeVector> CompileFragmentShader(std::string_view source_code, APIType api_type,
296 glslang::EShTargetLanguageVersion language_version,
297 glslang::TShader::Includer* shader_includer)
298 {
299 return CompileShaderToSPV(EShLangFragment, api_type, language_version, "ps", source_code,
300 shader_includer);
301 }
302
303 std::optional<CodeVector> CompileComputeShader(std::string_view source_code, APIType api_type,
304 glslang::EShTargetLanguageVersion language_version,
305 glslang::TShader::Includer* shader_includer)
306 {
307 return CompileShaderToSPV(EShLangCompute, api_type, language_version, "cs", source_code,
308 shader_includer);
309 }
310 } // namespace SPIRV