Debian Codegraph @

src/gpu/graphite/vk/VulkanSpirvTransforms.cpp

raw
1 /*
2 * Copyright 2025 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/gpu/graphite/vk/VulkanSpirvTransforms.h"
9
10 #include "include/private/base/SkAssert.h"
11 #include "src/sksl/codegen/SkSLCodeGenTypes.h"
12 #include "src/sksl/spirv.h"
13
14 #ifdef SK_DEBUG
15 #include "src/gpu/graphite/Log.h"
16 #include "src/sksl/SkSLCompiler.h"
17 #include "src/sksl/codegen/SkSLSPIRVValidator.h"
18 #endif
19
20 #include <cstdint>
21 #include <vector>
22
23 namespace skgpu::graphite {
24
25 namespace {
26
27 /*
28 * The SPIR-V transformer is implemented as one main class, SpirvTransformer, and a number of
29 * logically separate transformations (currently one), such as SpirvMultisampleTransformer.
30 *
31 * SpirvTransformer is a simple loop over the SPIR-V instructions. The instructions of interest are
32 * parsed (as much as the transformations need), and passed to individual transformers.
33 *
34 * The transformers themselves may change an instruction, by generating new one(s) and dropping the
35 * original instruction, or may add instructions triggered when encountering a specific instruction.
36 *
37 * This design lets multiple transformations be done in a single pass, avoiding the need to walk
38 * over the SPIR-V again and again, most of which is uninteresting to the transformers.
39 */
40
41 using SpirvBlob = std::vector<uint32_t>;
42
43 /*
44 * SPIR-V's first five words are:
45 *
46 * Index 0: Magic number
47 * Index 1: Version number
48 * Index 2: Generator's magic number
49 * Index 3: ID bound; all ids are smaller than this
50 * Index 4: 0 (reserved)
51 *
52 * The rest of the instructions start at index 5 in sections (see 2.4. Logical Layout of a Module in
53 * the SPIR-V spec):
54 *
55 * OpCapability instructions
56 * OpExtInst instructions
57 * OpExtInstImport instructions
58 * OpMemoryModel instructions
59 * OpEntryPoint instructions
60 * OpExecutionMode instructions
61 * Debug instructions
62 * Types, constants and global variable instructions
63 * Function declarations
64 *
65 * Most instructions are uninteresting to the transformer and are skipped over.
66 */
67 constexpr uint32_t kIDBoundIndex = 3;
68 constexpr uint32_t kInstructionsStartIndex = 5;
69
70 SpvId GetNewId(SpirvBlob* blob) {
71 // Return a new ID and increase the ID bound.
72 return (*blob)[kIDBoundIndex]++;
73 }
74
75 SpvOp GetInstructionOp(const uint32_t* instruction) {
76 return static_cast<SpvOp>(instruction[0] & SpvOpCodeMask);
77 }
78 uint32_t GetInstructionWordCount(const uint32_t* instruction) {
79 return instruction[0] >> SpvWordCountShift;
80 }
81 uint32_t MakeInstructionOp(SpvOp opCode, uint32_t wordCount) {
82 return opCode | wordCount << SpvWordCountShift;
83 }
84 void CopyInstruction(const uint32_t* instruction, size_t wordCount, SpirvBlob* spirvOut) {
85 spirvOut->insert(spirvOut->end(), instruction, instruction + wordCount);
86 }
87
88 enum class TransformationState {
89 Transformed,
90 Unchanged,
91 };
92
93 /*
94 * A transformer that at a high level changes subpassLoad(input) to subpassLoad(inputMS, sample),
95 * such that shaders with input attachment are usable with multisampling. It unconditionally adds a
96 * built-in SampleId variable and the corresponding SampleRateShading capability with the assumption
97 * that the SPIR-V generator does not already produce them.
98 */
99 class SpirvMultisampleTransformer {
100 public:
101 SpirvMultisampleTransformer(uint32_t maxId) : fIsInputAttachmentImage(maxId + 1, false) {}
102
103 void transformOpCapability(SpvCapability capability, SpirvBlob* spirvOut);
104 TransformationState transformOpEntryPoint(const uint32_t* instruction, SpirvBlob* spirvOut);
105 void transformOpDecorate(SpirvBlob* spirvOut);
106 TransformationState transformOpTypePointer(const uint32_t* instruction, SpirvBlob* spirvOut);
107 TransformationState transformOpTypeImage(SpvId resultId,
108 SpvId sampledTypeId,
109 SpirvBlob* spirvOut);
110 void transformOpLoad(SpvId resultTypeId, SpvId resultId, SpvId pointerId, SpirvBlob* spirvOut);
111 TransformationState transformOpImageRead(SpvId resultTypeId,
112 SpvId resultId,
113 SpvId imageId,
114 SpvId coordinateId,
115 SpirvBlob* spirvOut);
116
117 private:
118 // Map OpLoad result to whether it was from the input attachment variable.
119 std::vector<bool> fIsInputAttachmentImage;
120 bool fHasAddedDecorations = false;
121 SpvId fSampleIdVarId = 0;
122 };
123
124 void SpirvMultisampleTransformer::transformOpCapability(SpvCapability capability,
125 SpirvBlob* spirvOut) {
126 // Add the SampleRateShading capability, once when the InputAttachment capability is encountered
127 if (capability == SpvCapabilityInputAttachment) {
128 // Generate:
129 // OpCapability SampleRateShading
130 spirvOut->push_back(MakeInstructionOp(SpvOpCapability, 2));
131 spirvOut->push_back(SpvCapabilitySampleRateShading);
132 }
133 }
134
135 TransformationState SpirvMultisampleTransformer::transformOpEntryPoint(const uint32_t* instruction,
136 SpirvBlob* spirvOut) {
137 // Keep the entry point instruction as is, just append the SampleId variable to it.
138 fSampleIdVarId = GetNewId(spirvOut);
139
140 const uint32_t originalWordCount = GetInstructionWordCount(instruction);
141
142 // The length of the instruction is increased by one
143 spirvOut->push_back(MakeInstructionOp(SpvOpEntryPoint, originalWordCount + 1));
144 // The rest of the instruction is copied verbatim
145 CopyInstruction(instruction + 1, originalWordCount - 1, spirvOut);
146 // The last word is the new variable
147 spirvOut->push_back(fSampleIdVarId);
148
149 return TransformationState::Transformed;
150 }
151
152 void SpirvMultisampleTransformer::transformOpDecorate(SpirvBlob* spirvOut) {
153 // Add decorations for the new SampleId variable as soon as the decorations section is visited.
154 // Note that there is always at least one decoration, because the shaders have _some_ input or
155 // output.
156 if (fHasAddedDecorations) {
157 return;
158 }
159
160 // Generate:
161 // OpDecorate %SampleIdVar RelaxedPrecision
162 // OpDecorate %SampleIdVar Flat
163 // OpDecorate %SampleIdVar BuiltIn SampleId
164 spirvOut->push_back(MakeInstructionOp(SpvOpDecorate, 3));
165 spirvOut->push_back(fSampleIdVarId);
166 spirvOut->push_back(SpvDecorationRelaxedPrecision);
167
168 spirvOut->push_back(MakeInstructionOp(SpvOpDecorate, 3));
169 spirvOut->push_back(fSampleIdVarId);
170 spirvOut->push_back(SpvDecorationFlat);
171
172 spirvOut->push_back(MakeInstructionOp(SpvOpDecorate, 4));
173 spirvOut->push_back(fSampleIdVarId);
174 spirvOut->push_back(SpvDecorationBuiltIn);
175 spirvOut->push_back(SpvBuiltInSampleId);
176
177 fHasAddedDecorations = true;
178 }
179
180 TransformationState SpirvMultisampleTransformer::transformOpTypePointer(const uint32_t* instruction,
181 SpirvBlob* spirvOut) {
182 // When the int pointer type declaration is encountered, declare the SampleId variable right
183 // away.
184 const SpvId resultId = instruction[1];
185 if (resultId != SkSL::spirv::kIdTypePointerInputInt) {
186 return TransformationState::Unchanged;
187 }
188
189 // Keep the int pointer declaration.
190 CopyInstruction(instruction, GetInstructionWordCount(instruction), spirvOut);
191 // Generate:
192 // %SampleIdVar = OpVariable %kIdTypePointerInputInt Input
193 spirvOut->push_back(MakeInstructionOp(SpvOpVariable, 4));
194 spirvOut->push_back(SkSL::spirv::kIdTypePointerInputInt);
195 spirvOut->push_back(fSampleIdVarId);
196 spirvOut->push_back(SpvStorageClassInput);
197
198 return TransformationState::Transformed;
199 }
200
201 TransformationState SpirvMultisampleTransformer::transformOpTypeImage(SpvId resultId,
202 SpvId sampledTypeId,
203 SpirvBlob* spirvOut) {
204 // Change the OpTypeImage instruction for the input attachment to be multisampled. The result id
205 // is untouched, so the OpTypePointer and OpVariable instructions remain as-is!
206 if (resultId != SkSL::spirv::kIdTypeImageSubpassData) {
207 return TransformationState::Unchanged;
208 }
209
210 // The instruction must have been:
211 //
212 // %resultId = OpTypeImage %sampledTypeId SubpassData 0 0 0 2 Unknown
213 //
214 // It is transformed to:
215 //
216 // %resultId = OpTypeImage %sampledTypeId SubpassData 0 0 1 2 Unknown
217 spirvOut->push_back(MakeInstructionOp(SpvOpTypeImage, 9));
218 spirvOut->push_back(resultId);
219 spirvOut->push_back(sampledTypeId);
220 spirvOut->push_back(SpvDimSubpassData);
221 spirvOut->push_back(0);
222 spirvOut->push_back(0);
223 spirvOut->push_back(1);
224 spirvOut->push_back(2);
225 spirvOut->push_back(SpvImageFormatUnknown);
226
227 return TransformationState::Transformed;
228 }
229
230 void SpirvMultisampleTransformer::transformOpLoad(SpvId resultTypeId,
231 SpvId resultId,
232 SpvId pointerId,
233 SpirvBlob* spirvOut) {
234 // If the input attachment variable is loaded, remember the result id. This is needed to know
235 // which OpImageRead instructions to transform.
236 if (pointerId == SkSL::spirv::kIdVariableImageSubpassData &&
237 resultId < fIsInputAttachmentImage.size()) {
238 fIsInputAttachmentImage[resultId] = true;
239 }
240 }
241
242 TransformationState SpirvMultisampleTransformer::transformOpImageRead(SpvId resultTypeId,
243 SpvId resultId,
244 SpvId imageId,
245 SpvId coordinateId,
246 SpirvBlob* spirvOut) {
247 // If reading from the input attachment variable, load from the SampleId variable and add a
248 // `Sample` operand to the image read operation. The result id is kept as is, so the rest of the
249 // SPIR-V is unaffected.
250 if (imageId >= fIsInputAttachmentImage.size() || !fIsInputAttachmentImage[imageId]) {
251 return TransformationState::Unchanged;
252 }
253
254 // The instruction is:
255 //
256 // %resultId = OpImageRead %resultTypeId %imageId %coordinateId
257 //
258 // It is transformed into:
259 //
260 // %sample = OpLoad %kIdTypeInt %SampleIdVar
261 // %resultId = OpImageRead %resultTypeId %imageId %coordinateId Sample %sample
262
263 const SpvId sample = GetNewId(spirvOut);
264
265 spirvOut->push_back(MakeInstructionOp(SpvOpLoad, 4));
266 spirvOut->push_back(SkSL::spirv::kIdTypeInt);
267 spirvOut->push_back(sample);
268 spirvOut->push_back(fSampleIdVarId);
269
270 spirvOut->push_back(MakeInstructionOp(SpvOpImageRead, 7));
271 spirvOut->push_back(resultTypeId);
272 spirvOut->push_back(resultId);
273 spirvOut->push_back(imageId);
274 spirvOut->push_back(coordinateId);
275 spirvOut->push_back(SpvImageOperandsSampleMask);
276 spirvOut->push_back(sample);
277
278 return TransformationState::Transformed;
279 }
280
281 // A SPIR-V transformer. It walks the instructions and modifies them as necessary, for example to
282 // modify input attachment load when multisampled.
283 class SpirvTransformer {
284 public:
285 SpirvTransformer(const SpirvBlob& spirvIn,
286 const SPIRVTransformOptions& options,
287 SpirvBlob* spirvOut)
288 : fSpirvIn(spirvIn)
289 , fSpirvOut(spirvOut)
290 , fOptions(options)
291 , fMultisampleTransformer(spirvIn[kIDBoundIndex]) {
292 // Preallocate memory for the result, with some room for additions by transformations.
293 fSpirvOut->reserve(fSpirvIn.size() + 64);
294 }
295
296 void transform();
297
298 private:
299 void onTransformBegin();
300
301 const uint32_t* getCurrentInstruction(SpvOp* opCodeOut, uint32_t* wordCountOut) const;
302
303 // Transform instructions:
304 void transformInstruction();
305
306 // SPIR-V to transform:
307 const SpirvBlob& fSpirvIn;
308
309 // Transformed SPIR-V:
310 SpirvBlob* fSpirvOut;
311
312 // Traversal state:
313 size_t fCurrentWord = 0;
314 bool fIsInFunctionSection = false;
315
316 // Transformation state:
317 SPIRVTransformOptions fOptions;
318 SpirvMultisampleTransformer fMultisampleTransformer;
319
320 // Instructions that potentially need transformation. They return Transformed if the instruction
321 // is transformed. If Unchanged is returned, the instruction should be copied as-is.
322 TransformationState transformOpCapability(const uint32_t* instruction);
323 TransformationState transformOpEntryPoint(const uint32_t* instruction);
324 TransformationState transformOpDecorate(const uint32_t* instruction);
325 TransformationState transformOpTypePointer(const uint32_t* instruction);
326 TransformationState transformOpTypeImage(const uint32_t* instruction);
327 TransformationState transformOpLoad(const uint32_t* instruction);
328 TransformationState transformOpImageRead(const uint32_t* instruction);
329 };
330
331 void SpirvTransformer::onTransformBegin() {
332 // SPIR-V is expected to be valid.
333 SkASSERT(fSpirvIn.size() >= kInstructionsStartIndex);
334 // Make sure the transformer is not reused.
335 SkASSERT(fCurrentWord == 0);
336 SkASSERT(fIsInFunctionSection == false);
337 // Make sure the output SPIR-V storage is not reused.
338 SkASSERT(fSpirvOut->empty());
339
340 // Copy the SPIR-V header to the output right away. This is needed for GetNewId() to work.
341 fSpirvOut->assign(fSpirvIn.begin(), fSpirvIn.begin() + kInstructionsStartIndex);
342
343 fCurrentWord = kInstructionsStartIndex;
344 }
345
346 const uint32_t* SpirvTransformer::getCurrentInstruction(SpvOp* opCodeOut,
347 uint32_t* wordCountOut) const {
348 SkASSERT(fCurrentWord < fSpirvIn.size());
349 const uint32_t* instruction = &fSpirvIn[fCurrentWord];
350
351 *opCodeOut = GetInstructionOp(instruction);
352 *wordCountOut = GetInstructionWordCount(instruction);
353
354 // Basic validity check, instruction cound must not exceed SPIR-V size.
355 SkASSERT(fCurrentWord + *wordCountOut <= fSpirvIn.size());
356
357 return instruction;
358 }
359
360 void SpirvTransformer::transform() {
361 this->onTransformBegin();
362
363 while (fCurrentWord < fSpirvIn.size()) {
364 this->transformInstruction();
365 }
366 }
367
368 void SpirvTransformer::transformInstruction() {
369 uint32_t wordCount;
370 SpvOp opCode;
371 const uint32_t* instruction = this->getCurrentInstruction(&opCode, &wordCount);
372
373 if (opCode == SpvOpFunction) {
374 // SPIR-V is structured in sections. Function declarations come last. Only a few
375 // instructions inside functions need to be inspected.
376 fIsInFunctionSection = true;
377 }
378
379 // Only look at interesting instructions.
380 TransformationState transformationState = TransformationState::Unchanged;
381
382 if (fIsInFunctionSection) {
383 // Look at in-function opcodes.
384 switch (opCode) {
385 case SpvOpLoad:
386 transformationState = this->transformOpLoad(instruction);
387 break;
388 case SpvOpImageRead:
389 transformationState = this->transformOpImageRead(instruction);
390 break;
391 default:
392 break;
393 }
394 } else {
395 // Look at global declaration opcodes.
396 switch (opCode) {
397 case SpvOpCapability:
398 transformationState = this->transformOpCapability(instruction);
399 break;
400 case SpvOpEntryPoint:
401 transformationState = this->transformOpEntryPoint(instruction);
402 break;
403 case SpvOpDecorate:
404 transformationState = this->transformOpDecorate(instruction);
405 break;
406 case SpvOpTypePointer:
407 transformationState = this->transformOpTypePointer(instruction);
408 break;
409 case SpvOpTypeImage:
410 transformationState = this->transformOpTypeImage(instruction);
411 break;
412 default:
413 break;
414 }
415 }
416
417 // If the instruction was not transformed, copy it to output as is.
418 if (transformationState == TransformationState::Unchanged) {
419 CopyInstruction(instruction, wordCount, fSpirvOut);
420 }
421
422 // Advance to next instruction.
423 fCurrentWord += wordCount;
424 }
425
426 TransformationState SpirvTransformer::transformOpCapability(const uint32_t* instruction) {
427 const SpvCapability capability = static_cast<SpvCapability>(instruction[1]);
428 if (fOptions.fMultisampleInputLoad) {
429 fMultisampleTransformer.transformOpCapability(capability, fSpirvOut);
430 }
431 return TransformationState::Unchanged;
432 }
433
434 TransformationState SpirvTransformer::transformOpEntryPoint(const uint32_t* instruction) {
435 // Note: currently there is only one transformer, so control can be given to that. If more
436 // transformers are added in the future, this function should instead take the list of interface
437 // ids out, pass them to each transformer for a chance to modify it, then rewrite the entry
438 // point once with the result.
439 if (fOptions.fMultisampleInputLoad) {
440 return fMultisampleTransformer.transformOpEntryPoint(instruction, fSpirvOut);
441 }
442 return TransformationState::Unchanged;
443 }
444
445 TransformationState SpirvTransformer::transformOpDecorate(const uint32_t* instruction) {
446 if (fOptions.fMultisampleInputLoad) {
447 fMultisampleTransformer.transformOpDecorate(fSpirvOut);
448 }
449 return TransformationState::Unchanged;
450 }
451
452 TransformationState SpirvTransformer::transformOpTypePointer(const uint32_t* instruction) {
453 if (fOptions.fMultisampleInputLoad) {
454 if (fMultisampleTransformer.transformOpTypePointer(instruction, fSpirvOut) ==
455 TransformationState::Transformed) {
456 return TransformationState::Transformed;
457 }
458 }
459 return TransformationState::Unchanged;
460 }
461
462 TransformationState SpirvTransformer::transformOpTypeImage(const uint32_t* instruction) {
463 const SpvId resultId = instruction[1];
464 const SpvId sampledTypeId = instruction[2];
465 if (fOptions.fMultisampleInputLoad) {
466 if (fMultisampleTransformer.transformOpTypeImage(resultId, sampledTypeId, fSpirvOut) ==
467 TransformationState::Transformed) {
468 return TransformationState::Transformed;
469 }
470 }
471 return TransformationState::Unchanged;
472 }
473
474 TransformationState SpirvTransformer::transformOpLoad(const uint32_t* instruction) {
475 const SpvId resultTypeId = instruction[1];
476 const SpvId resultId = instruction[2];
477 const SpvId pointerId = instruction[3];
478 if (fOptions.fMultisampleInputLoad) {
479 fMultisampleTransformer.transformOpLoad(resultTypeId, resultId, pointerId, fSpirvOut);
480 }
481 return TransformationState::Unchanged;
482 }
483
484 TransformationState SpirvTransformer::transformOpImageRead(const uint32_t* instruction) {
485 const SpvId resultTypeId = instruction[1];
486 const SpvId resultId = instruction[2];
487 const SpvId imageId = instruction[3];
488 const SpvId coordinateId = instruction[4];
489 if (fOptions.fMultisampleInputLoad) {
490 if (fMultisampleTransformer.transformOpImageRead(
491 resultTypeId, resultId, imageId, coordinateId, fSpirvOut) ==
492 TransformationState::Transformed) {
493 return TransformationState::Transformed;
494 }
495 }
496 return TransformationState::Unchanged;
497 }
498
499 } // anonymous namespace
500
501 SkSL::NativeShader TransformSPIRV(const SkSL::NativeShader& spirv,
502 const SPIRVTransformOptions& options) {
503 SkSL::NativeShader result;
504
505 SpirvTransformer transformer(spirv.fBinary, options, &result.fBinary);
506 transformer.transform();
507
508 #ifdef SK_DEBUG
509 // Validate the SPIR-V after performing any transformations. This is rather costly, so only
510 // do this on debug builds.
511 static SkSL::Compiler compiler;
512 if (!SkSL::ValidateSPIRV(compiler.errorReporter(), {spirv.fBinary})) {
513 SKGPU_LOG_E("SPIR-V transformations yielded invalid SPIR-V.");
514 }
515 #endif
516
517 return result;
518 }
519
520 } // namespace skgpu::graphite