Debian Codegraph @

src/sksl/codegen/SkSLSPIRVCodeGenerator.cpp

raw
1 /*
2 * Copyright 2016 Google Inc.
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/sksl/codegen/SkSLSPIRVCodeGenerator.h"
9
10 #include "include/core/SkSpan.h"
11 #include "include/core/SkTypes.h"
12 #include "include/private/base/SkTArray.h"
13 #include "include/private/base/SkTo.h"
14 #include "src/base/SkEnumBitMask.h"
15 #include "src/core/SkChecksum.h"
16 #include "src/core/SkTHash.h"
17 #include "src/core/SkTraceEvent.h"
18 #include "src/sksl/GLSL.std.450.h"
19 #include "src/sksl/SkSLAnalysis.h"
20 #include "src/sksl/SkSLBuiltinTypes.h"
21 #include "src/sksl/SkSLCompiler.h"
22 #include "src/sksl/SkSLConstantFolder.h"
23 #include "src/sksl/SkSLContext.h"
24 #include "src/sksl/SkSLDefines.h"
25 #include "src/sksl/SkSLErrorReporter.h"
26 #include "src/sksl/SkSLIntrinsicList.h"
27 #include "src/sksl/SkSLMemoryLayout.h"
28 #include "src/sksl/SkSLOperator.h"
29 #include "src/sksl/SkSLOutputStream.h"
30 #include "src/sksl/SkSLPool.h"
31 #include "src/sksl/SkSLPosition.h"
32 #include "src/sksl/SkSLProgramSettings.h"
33 #include "src/sksl/SkSLUtil.h"
34 #include "src/sksl/analysis/SkSLSpecialization.h"
35 #include "src/sksl/codegen/SkSLCodeGenTypes.h"
36 #include "src/sksl/codegen/SkSLCodeGenerator.h"
37 #include "src/sksl/ir/SkSLBinaryExpression.h"
38 #include "src/sksl/ir/SkSLBlock.h"
39 #include "src/sksl/ir/SkSLConstructor.h"
40 #include "src/sksl/ir/SkSLConstructorArrayCast.h"
41 #include "src/sksl/ir/SkSLConstructorCompound.h"
42 #include "src/sksl/ir/SkSLConstructorCompoundCast.h"
43 #include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
44 #include "src/sksl/ir/SkSLConstructorMatrixResize.h"
45 #include "src/sksl/ir/SkSLConstructorScalarCast.h"
46 #include "src/sksl/ir/SkSLConstructorSplat.h"
47 #include "src/sksl/ir/SkSLDoStatement.h"
48 #include "src/sksl/ir/SkSLExpression.h"
49 #include "src/sksl/ir/SkSLExpressionStatement.h"
50 #include "src/sksl/ir/SkSLExtension.h"
51 #include "src/sksl/ir/SkSLFieldAccess.h"
52 #include "src/sksl/ir/SkSLFieldSymbol.h"
53 #include "src/sksl/ir/SkSLForStatement.h"
54 #include "src/sksl/ir/SkSLFunctionCall.h"
55 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
56 #include "src/sksl/ir/SkSLFunctionDefinition.h"
57 #include "src/sksl/ir/SkSLIRNode.h"
58 #include "src/sksl/ir/SkSLIfStatement.h"
59 #include "src/sksl/ir/SkSLIndexExpression.h"
60 #include "src/sksl/ir/SkSLInterfaceBlock.h"
61 #include "src/sksl/ir/SkSLLayout.h"
62 #include "src/sksl/ir/SkSLLiteral.h"
63 #include "src/sksl/ir/SkSLModifierFlags.h"
64 #include "src/sksl/ir/SkSLModifiersDeclaration.h"
65 #include "src/sksl/ir/SkSLPoison.h"
66 #include "src/sksl/ir/SkSLPostfixExpression.h"
67 #include "src/sksl/ir/SkSLPrefixExpression.h"
68 #include "src/sksl/ir/SkSLProgram.h"
69 #include "src/sksl/ir/SkSLProgramElement.h"
70 #include "src/sksl/ir/SkSLReturnStatement.h"
71 #include "src/sksl/ir/SkSLSetting.h"
72 #include "src/sksl/ir/SkSLStatement.h"
73 #include "src/sksl/ir/SkSLSwitchCase.h"
74 #include "src/sksl/ir/SkSLSwitchStatement.h"
75 #include "src/sksl/ir/SkSLSwizzle.h"
76 #include "src/sksl/ir/SkSLSymbol.h"
77 #include "src/sksl/ir/SkSLSymbolTable.h"
78 #include "src/sksl/ir/SkSLTernaryExpression.h"
79 #include "src/sksl/ir/SkSLType.h"
80 #include "src/sksl/ir/SkSLVarDeclarations.h"
81 #include "src/sksl/ir/SkSLVariable.h"
82 #include "src/sksl/ir/SkSLVariableReference.h"
83 #include "src/sksl/spirv.h"
84 #include "src/sksl/transform/SkSLTransform.h"
85 #include "src/utils/SkBitSet.h"
86
87 #include <algorithm>
88 #include <cstdint>
89 #include <cstring>
90 #include <ctype.h>
91 #include <functional>
92 #include <memory>
93 #include <set>
94 #include <string>
95 #include <string_view>
96 #include <tuple>
97 #include <utility>
98 #include <vector>
99
100 using namespace skia_private;
101
102 #define kLast_Capability SpvCapabilityMultiViewport
103
104 constexpr int DEVICE_FRAGCOORDS_BUILTIN = -1000;
105 constexpr int DEVICE_CLOCKWISE_BUILTIN = -1001;
106 static constexpr SkSL::Layout kDefaultTypeLayout;
107
108 namespace SkSL {
109
110 enum class ProgramKind : int8_t;
111
112 enum class StorageClass {
113 kUniformConstant,
114 kInput,
115 kUniform,
116 kStorageBuffer,
117 kOutput,
118 kWorkgroup,
119 kCrossWorkgroup,
120 kPrivate,
121 kFunction,
122 kGeneric,
123 kPushConstant,
124 kAtomicCounter,
125 kImage,
126 };
127
128 static SpvStorageClass get_storage_class_spv_id(StorageClass storageClass) {
129 switch (storageClass) {
130 case StorageClass::kUniformConstant: return SpvStorageClassUniformConstant;
131 case StorageClass::kInput: return SpvStorageClassInput;
132 case StorageClass::kUniform: return SpvStorageClassUniform;
133 // Note: In SPIR-V 1.3, a storage buffer can be declared with the "StorageBuffer"
134 // storage class and the "Block" decoration and the <1.3 approach we use here ("Uniform"
135 // storage class and the "BufferBlock" decoration) is deprecated. Since we target SPIR-V
136 // 1.0, we have to use the deprecated approach which is well supported in Vulkan and
137 // addresses SkSL use cases (notably SkSL currently doesn't support pointer features that
138 // would benefit from SPV_KHR_variable_pointers capabilities).
139 case StorageClass::kStorageBuffer: return SpvStorageClassUniform;
140 case StorageClass::kOutput: return SpvStorageClassOutput;
141 case StorageClass::kWorkgroup: return SpvStorageClassWorkgroup;
142 case StorageClass::kCrossWorkgroup: return SpvStorageClassCrossWorkgroup;
143 case StorageClass::kPrivate: return SpvStorageClassPrivate;
144 case StorageClass::kFunction: return SpvStorageClassFunction;
145 case StorageClass::kGeneric: return SpvStorageClassGeneric;
146 case StorageClass::kPushConstant: return SpvStorageClassPushConstant;
147 case StorageClass::kAtomicCounter: return SpvStorageClassAtomicCounter;
148 case StorageClass::kImage: return SpvStorageClassImage;
149 }
150
151 SkUNREACHABLE;
152 }
153
154 using SPIRVBlob = std::vector<uint32_t>;
155
156 static void append_blob(const SPIRVBlob& src, SPIRVBlob& dst) {
157 dst.insert(dst.end(), src.begin(), src.end());
158 }
159
160 class SPIRVCodeGenerator : public CodeGenerator {
161 public:
162 // We reserve an impossible SpvId as a sentinel. (NA meaning none, n/a, etc.)
163 static constexpr SpvId NA = (SpvId)-1;
164
165 class LValue {
166 public:
167 virtual ~LValue() {}
168
169 // returns a pointer to the lvalue, if possible. If the lvalue cannot be directly referenced
170 // by a pointer (e.g. vector swizzles), returns NA.
171 virtual SpvId getPointer() { return NA; }
172
173 // Returns true if a valid pointer returned by getPointer represents a memory object
174 // (see https://github.com/KhronosGroup/SPIRV-Tools/issues/2892). Has no meaning if
175 // getPointer() returns NA.
176 virtual bool isMemoryObjectPointer() const { return true; }
177
178 // Applies a swizzle to the components of the LValue, if possible. This is used to create
179 // LValues that are swizzes-of-swizzles. Non-swizzle LValues can just return false.
180 virtual bool applySwizzle(const ComponentArray& components, const Type& newType) {
181 return false;
182 }
183
184 // Returns the storage class of the lvalue.
185 virtual StorageClass storageClass() const = 0;
186
187 virtual SpvId load(SPIRVBlob& out) = 0;
188
189 virtual void store(SpvId value, SPIRVBlob& out) = 0;
190 };
191
192 SPIRVCodeGenerator(const Context* context,
193 const ShaderCaps* caps,
194 const Program* program,
195 SPIRVBlob* out)
196 : CodeGenerator(context, caps, program, nullptr), fOutBuffer(out) {
197
198 // Preallocate something reasonable for the different SPIR-V sections.
199 // Based on statistics from dm tests:
200 //
201 // Total word count of the shader is ~2000 on average, ~12000 max.
202 // fGlobalInitializersBuffer: Nearly empty on average, ~10 max.
203 // fConstantBuffer: ~250 average, ~1000 max.
204 // fVariableBuffer: ~30 average, ~500 max.
205 // fNameBuffer: ~200 average, ~1000 max.
206 // fDecorationBuffer: ~250 average, ~2000 max.
207 fOutBuffer->reserve(2048);
208 fGlobalInitializersBuffer.reserve(16);
209 fConstantBuffer.reserve(256);
210 fVariableBuffer.reserve(32);
211 fNameBuffer.reserve(128);
212 fDecorationBuffer.reserve(256);
213 }
214
215 bool generateCode() override;
216
217 private:
218 enum IntrinsicOpcodeKind {
219 kGLSL_STD_450_IntrinsicOpcodeKind,
220 kSPIRV_IntrinsicOpcodeKind,
221 kSpecial_IntrinsicOpcodeKind,
222 kInvalid_IntrinsicOpcodeKind,
223 };
224
225 enum SpecialIntrinsic {
226 kAtan_SpecialIntrinsic,
227 kClamp_SpecialIntrinsic,
228 kMatrixCompMult_SpecialIntrinsic,
229 kMax_SpecialIntrinsic,
230 kMin_SpecialIntrinsic,
231 kMix_SpecialIntrinsic,
232 kMod_SpecialIntrinsic,
233 kDFdy_SpecialIntrinsic,
234 kSaturate_SpecialIntrinsic,
235 kSampledImage_SpecialIntrinsic,
236 kSmoothStep_SpecialIntrinsic,
237 kStep_SpecialIntrinsic,
238 kSubpassLoad_SpecialIntrinsic,
239 kTexture_SpecialIntrinsic,
240 kTextureGrad_SpecialIntrinsic,
241 kTextureLod_SpecialIntrinsic,
242 kTextureRead_SpecialIntrinsic,
243 kTextureWrite_SpecialIntrinsic,
244 kTextureWidth_SpecialIntrinsic,
245 kTextureHeight_SpecialIntrinsic,
246 kAtomicAdd_SpecialIntrinsic,
247 kAtomicLoad_SpecialIntrinsic,
248 kAtomicStore_SpecialIntrinsic,
249 kStorageBarrier_SpecialIntrinsic,
250 kWorkgroupBarrier_SpecialIntrinsic,
251 };
252
253 enum class Precision {
254 kDefault,
255 kRelaxed,
256 };
257
258 struct TempVar {
259 SpvId spvId;
260 const Type* type;
261 std::unique_ptr<SPIRVCodeGenerator::LValue> lvalue;
262 };
263
264 /**
265 * Pass in the type to automatically add a RelaxedPrecision decoration for the id when
266 * appropriate, or null to never add one.
267 */
268 SpvId nextId(const Type* type);
269
270 SpvId nextId(Precision precision);
271
272 SpvId getType(const Type& type);
273
274 SpvId getType(const Type& type, const Layout& typeLayout, const MemoryLayout& memoryLayout);
275
276 SpvId getFunctionType(const FunctionDeclaration& function);
277
278 SpvId getFunctionParameterType(const Type& parameterType, const Layout& parameterLayout);
279
280 SpvId getPointerType(const Type& type, StorageClass storageClass);
281
282 SpvId getPointerType(const Type& type,
283 const Layout& typeLayout,
284 const MemoryLayout& memoryLayout,
285 StorageClass storageClass);
286
287 StorageClass getStorageClass(const Expression& expr);
288
289 TArray<SpvId> getAccessChain(const Expression& expr, SPIRVBlob& out);
290
291 void writeLayout(const Layout& layout, SpvId target, Position pos);
292
293 void writeFieldLayout(const Layout& layout, SpvId target, int member);
294
295 SpvId writeStruct(const Type& type, const MemoryLayout& memoryLayout);
296
297 void writeProgramElement(const ProgramElement& pe, SPIRVBlob& out);
298
299 SpvId writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTFlip = true);
300
301 void writeFunctionStart(const FunctionDeclaration& f, SPIRVBlob& out);
302
303 SpvId writeFunctionDeclaration(const FunctionDeclaration& f, SPIRVBlob& out);
304
305 void writeFunction(const FunctionDefinition& f, SPIRVBlob& out);
306
307 // Writes the function with the defined specializationIndex, if the index is -1, then it is
308 // assumed that the function has no specializations.
309 void writeFunctionInstantiation(const FunctionDefinition& f,
310 Analysis::SpecializationIndex specializationIndex,
311 const Analysis::SpecializedParameters* specializedParams,
312 SPIRVBlob& out);
313
314 bool writeGlobalVarDeclaration(ProgramKind kind, const VarDeclaration& v);
315
316 SpvId writeGlobalVar(ProgramKind kind, StorageClass, const Variable& v);
317
318 void writeVarDeclaration(const VarDeclaration& var, SPIRVBlob& out);
319
320 SpvId writeVariableReference(const VariableReference& ref, SPIRVBlob& out);
321
322 int findUniformFieldIndex(const Variable& var) const;
323
324 std::unique_ptr<LValue> getLValue(const Expression& value, SPIRVBlob& out);
325
326 SpvId writeExpression(const Expression& expr, SPIRVBlob& out);
327
328 SpvId writeIntrinsicCall(const FunctionCall& c, SPIRVBlob& out);
329
330 void writeFunctionCallArgument(TArray<SpvId>& argumentList,
331 const FunctionCall& call,
332 int argIndex,
333 std::vector<TempVar>* tempVars,
334 const SkBitSet* specializedParams,
335 SPIRVBlob& out);
336
337 void copyBackTempVars(const std::vector<TempVar>& tempVars, SPIRVBlob& out);
338
339 SpvId writeFunctionCall(const FunctionCall& c, SPIRVBlob& out);
340
341
342 void writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
343 SpvId signedInst, SpvId unsignedInst,
344 const TArray<SpvId>& args, SPIRVBlob& out);
345
346 /**
347 * Promotes an expression to a vector. If the expression is already a vector with vectorSize
348 * columns, returns it unmodified. If the expression is a scalar, either promotes it to a
349 * vector (if vectorSize > 1) or returns it unmodified (if vectorSize == 1). Asserts if the
350 * expression is already a vector and it does not have vectorSize columns.
351 */
352 SpvId vectorize(const Expression& expr, int vectorSize, SPIRVBlob& out);
353
354 /**
355 * Given a list of potentially mixed scalars and vectors, promotes the scalars to match the
356 * size of the vectors and returns the ids of the written expressions. e.g. given (float, vec2),
357 * returns (vec2(float), vec2). It is an error to use mismatched vector sizes, e.g. (float,
358 * vec2, vec3).
359 */
360 TArray<SpvId> vectorize(const ExpressionArray& args, SPIRVBlob& out);
361
362 /**
363 * Given a SpvId of a scalar, splats it across the passed-in type (scalar, vector or matrix) and
364 * returns the SpvId of the new value.
365 */
366 SpvId splat(const Type& type, SpvId id, SPIRVBlob& out);
367
368 SpvId writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind, SPIRVBlob& out);
369 SpvId writeAtomicIntrinsic(const FunctionCall& c,
370 SpecialIntrinsic kind,
371 SpvId resultId,
372 SPIRVBlob& out);
373
374 SpvId castScalarToFloat(SpvId inputId, const Type& inputType, const Type& outputType,
375 SPIRVBlob& out);
376
377 SpvId castScalarToSignedInt(SpvId inputId, const Type& inputType, const Type& outputType,
378 SPIRVBlob& out);
379
380 SpvId castScalarToUnsignedInt(SpvId inputId, const Type& inputType, const Type& outputType,
381 SPIRVBlob& out);
382
383 SpvId castScalarToBoolean(SpvId inputId, const Type& inputType, const Type& outputType,
384 SPIRVBlob& out);
385
386 SpvId castScalarToType(SpvId inputExprId, const Type& inputType, const Type& outputType,
387 SPIRVBlob& out);
388
389 /**
390 * Writes a potentially-different-sized copy of a matrix. Entries which do not exist in the
391 * source matrix are filled with zero; entries which do not exist in the destination matrix are
392 * ignored.
393 */
394 SpvId writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType, SPIRVBlob& out);
395
396 void addColumnEntry(const Type& columnType,
397 TArray<SpvId>* currentColumn,
398 TArray<SpvId>* columnIds,
399 int rows,
400 SpvId entry,
401 SPIRVBlob& out);
402
403 SpvId writeConstructorCompound(const ConstructorCompound& c, SPIRVBlob& out);
404
405 SpvId writeMatrixConstructor(const ConstructorCompound& c, SPIRVBlob& out);
406
407 SpvId writeVectorConstructor(const ConstructorCompound& c, SPIRVBlob& out);
408
409 SpvId writeCompositeConstructor(const AnyConstructor& c, SPIRVBlob& out);
410
411 SpvId writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c, SPIRVBlob& out);
412
413 SpvId writeConstructorMatrixResize(const ConstructorMatrixResize& c, SPIRVBlob& out);
414
415 SpvId writeConstructorScalarCast(const ConstructorScalarCast& c, SPIRVBlob& out);
416
417 SpvId writeConstructorSplat(const ConstructorSplat& c, SPIRVBlob& out);
418
419 SpvId writeConstructorCompoundCast(const ConstructorCompoundCast& c, SPIRVBlob& out);
420
421 SpvId writeFieldAccess(const FieldAccess& f, SPIRVBlob& out);
422
423 SpvId writeSwizzle(const Expression& baseExpr,
424 const ComponentArray& components,
425 SPIRVBlob& out);
426
427 SpvId writeSwizzle(const Swizzle& swizzle, SPIRVBlob& out);
428
429 /**
430 * Folds the potentially-vector result of a logical operation down to a single bool. If
431 * operandType is a vector type, assumes that the intermediate result in id is a bvec of the
432 * same dimensions, and applys all() to it to fold it down to a single bool value. Otherwise,
433 * returns the original id value.
434 */
435 SpvId foldToBool(SpvId id, const Type& operandType, SpvOp op, SPIRVBlob& out);
436
437 SpvId writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs, SpvOp_ floatOperator,
438 SpvOp_ intOperator, SpvOp_ vectorMergeOperator,
439 SpvOp_ mergeOperator, SPIRVBlob& out);
440
441 SpvId writeStructComparison(const Type& structType, SpvId lhs, Operator op, SpvId rhs,
442 SPIRVBlob& out);
443
444 SpvId writeArrayComparison(const Type& structType, SpvId lhs, Operator op, SpvId rhs,
445 SPIRVBlob& out);
446
447 // Used by writeStructComparison and writeArrayComparison to logically combine field-by-field
448 // comparisons into an overall comparison result.
449 // - `a.x == b.x` merged with `a.y == b.y` generates `(a.x == b.x) && (a.y == b.y)`
450 // - `a.x != b.x` merged with `a.y != b.y` generates `(a.x != b.x) || (a.y != b.y)`
451 SpvId mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op, SPIRVBlob& out);
452
453 // When the RewriteMatrixVectorMultiply caps bit is set, we manually decompose the M*V
454 // multiplication into a sum of vector-scalar products.
455 SpvId writeDecomposedMatrixVectorMultiply(const Type& leftType,
456 SpvId lhs,
457 const Type& rightType,
458 SpvId rhs,
459 const Type& resultType,
460 SPIRVBlob& out);
461
462 SpvId writeComponentwiseMatrixUnary(const Type& operandType,
463 SpvId operand,
464 SpvOp_ op,
465 SPIRVBlob& out);
466
467 SpvId writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs, SpvId rhs,
468 SpvOp_ op, SPIRVBlob& out);
469
470 SpvId writeBinaryOperationComponentwiseIfMatrix(const Type& resultType, const Type& operandType,
471 SpvId lhs, SpvId rhs,
472 SpvOp_ ifFloat, SpvOp_ ifInt,
473 SpvOp_ ifUInt, SpvOp_ ifBool,
474 SPIRVBlob& out);
475
476 SpvId writeBinaryOperation(const Type& resultType, const Type& operandType, SpvId lhs,
477 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt, SpvOp_ ifUInt,
478 SpvOp_ ifBool, SPIRVBlob& out);
479
480 SpvId writeBinaryOperation(const Type& resultType, const Type& operandType, SpvId lhs,
481 SpvId rhs, bool writeComponentwiseIfMatrix, SpvOp_ ifFloat,
482 SpvOp_ ifInt, SpvOp_ ifUInt, SpvOp_ ifBool, SPIRVBlob& out);
483
484 SpvId writeReciprocal(const Type& type, SpvId value, SPIRVBlob& out);
485
486 SpvId writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
487 const Type& rightType, SpvId rhs, const Type& resultType,
488 SPIRVBlob& out);
489
490 SpvId writeBinaryExpression(const BinaryExpression& b, SPIRVBlob& out);
491
492 SpvId writeTernaryExpression(const TernaryExpression& t, SPIRVBlob& out);
493
494 SpvId writeIndexExpression(const IndexExpression& expr, SPIRVBlob& out);
495
496 SpvId writeLogicalAnd(const Expression& left, const Expression& right, SPIRVBlob& out);
497
498 SpvId writeLogicalOr(const Expression& left, const Expression& right, SPIRVBlob& out);
499
500 SpvId writePrefixExpression(const PrefixExpression& p, SPIRVBlob& out);
501
502 SpvId writePostfixExpression(const PostfixExpression& p, SPIRVBlob& out);
503
504 SpvId writeLiteral(const Literal& f);
505
506 SpvId writeLiteral(double value, const Type& type);
507
508 void writeStatement(const Statement& s, SPIRVBlob& out);
509
510 void writeBlock(const Block& b, SPIRVBlob& out);
511
512 void writeIfStatement(const IfStatement& stmt, SPIRVBlob& out);
513
514 void writeForStatement(const ForStatement& f, SPIRVBlob& out);
515
516 void writeDoStatement(const DoStatement& d, SPIRVBlob& out);
517
518 void writeSwitchStatement(const SwitchStatement& s, SPIRVBlob& out);
519
520 void writeReturnStatement(const ReturnStatement& r, SPIRVBlob& out);
521
522 void writeCapabilities(SPIRVBlob& out);
523
524 void writeInstructions(const Program& program, SPIRVBlob& out);
525
526 void writeOpCode(SpvOp_ opCode, int length, SPIRVBlob& out);
527
528 void writeWord(int32_t word, SPIRVBlob& out);
529
530 void writeString(std::string_view s, SPIRVBlob& out);
531
532 void writeInstruction(SpvOp_ opCode, SPIRVBlob& out);
533
534 void writeInstruction(SpvOp_ opCode, std::string_view string, SPIRVBlob& out);
535
536 void writeInstruction(SpvOp_ opCode, int32_t word1, SPIRVBlob& out);
537
538 void writeInstruction(SpvOp_ opCode, int32_t word1, std::string_view string,
539 SPIRVBlob& out);
540
541 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, std::string_view string,
542 SPIRVBlob& out);
543
544 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, SPIRVBlob& out);
545
546 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, int32_t word3,
547 SPIRVBlob& out);
548
549 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, int32_t word3, int32_t word4,
550 SPIRVBlob& out);
551
552 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, int32_t word3, int32_t word4,
553 int32_t word5, SPIRVBlob& out);
554
555 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, int32_t word3, int32_t word4,
556 int32_t word5, int32_t word6, SPIRVBlob& out);
557
558 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, int32_t word3, int32_t word4,
559 int32_t word5, int32_t word6, int32_t word7, SPIRVBlob& out);
560
561 void writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2, int32_t word3, int32_t word4,
562 int32_t word5, int32_t word6, int32_t word7, int32_t word8,
563 SPIRVBlob& out);
564
565 // This form of writeInstruction can deduplicate redundant ops.
566 struct Word;
567 // 8 Words is enough for nearly all instructions (except variable-length instructions like
568 // OpAccessChain or OpConstantComposite).
569 using Words = STArray<8, Word, true>;
570 SpvId writeInstruction(SpvOp_ opCode, const TArray<Word, true>& words, SPIRVBlob& out);
571
572 struct Instruction {
573 SpvId fOp;
574 int32_t fResultKind;
575 STArray<8, int32_t> fWords;
576
577 bool operator==(const Instruction& that) const;
578 struct Hash;
579 };
580
581 static Instruction BuildInstructionKey(SpvOp_ opCode,
582 const TArray<Word, true>& words,
583 SpvId* predefinedResultId);
584
585 // The writeOpXxxxx calls will simplify and deduplicate ops where possible.
586 SpvId writeOpConstantTrue(const Type& type);
587 SpvId writeOpConstantFalse(const Type& type);
588 SpvId writeOpConstant(const Type& type, int32_t valueBits);
589 SpvId writeOpConstantComposite(const Type& type, const TArray<SpvId>& values);
590 SpvId writeOpCompositeConstruct(const Type& type, const TArray<SpvId>&, SPIRVBlob& out);
591 SpvId writeOpCompositeExtract(const Type& type, SpvId base, int component, SPIRVBlob& out);
592 SpvId writeOpCompositeExtract(const Type& type, SpvId base, int componentA, int componentB,
593 SPIRVBlob& out);
594 SpvId writeOpLoad(SpvId type, Precision precision, SpvId pointer, SPIRVBlob& out);
595 void writeOpStore(StorageClass storageClass, SpvId pointer, SpvId value, SPIRVBlob& out);
596
597 // Converts the provided SpvId(s) into an array of scalar OpConstants, if it can be done.
598 bool toConstants(SpvId value, TArray<SpvId>* constants);
599 bool toConstants(SkSpan<const SpvId> values, TArray<SpvId>* constants);
600
601 // Extracts the requested component SpvId from a composite instruction, if it can be done.
602 Instruction* resultTypeForInstruction(const Instruction& instr);
603 int numComponentsForVecInstruction(const Instruction& instr);
604 SpvId toComponent(SpvId id, int component);
605
606 struct ConditionalOpCounts {
607 int numReachableOps;
608 int numStoreOps;
609 };
610 ConditionalOpCounts getConditionalOpCounts();
611 void pruneConditionalOps(ConditionalOpCounts ops);
612
613 enum StraightLineLabelType {
614 // Use "BranchlessBlock" for blocks which are never explicitly branched-to at all. This
615 // happens at the start of a function, or when we find unreachable code.
616 kBranchlessBlock,
617
618 // Use "BranchIsOnPreviousLine" when writing a label that comes immediately after its
619 // associated branch. Example usage:
620 // - SPIR-V does not implicitly fall through from one block to the next, so you may need to
621 // use an OpBranch to explicitly jump to the next block, even when they are adjacent in
622 // the code.
623 // - The block immediately following an OpBranchConditional or OpSwitch.
624 kBranchIsOnPreviousLine,
625 };
626
627 enum BranchingLabelType {
628 // Use "BranchIsAbove" for labels which are referenced by OpBranch or OpBranchConditional
629 // ops that are above the label in the code--i.e., the branch skips forward in the code.
630 kBranchIsAbove,
631
632 // Use "BranchIsBelow" for labels which are referenced by OpBranch or OpBranchConditional
633 // ops below the label in the code--i.e., the branch jumps backward in the code.
634 kBranchIsBelow,
635
636 // Use "BranchesOnBothSides" for labels which have branches coming from both directions.
637 kBranchesOnBothSides,
638 };
639 void writeLabel(SpvId label, StraightLineLabelType type, SPIRVBlob& out);
640 void writeLabel(SpvId label, BranchingLabelType type, ConditionalOpCounts ops,
641 SPIRVBlob& out);
642
643 MemoryLayout memoryLayoutForStorageClass(StorageClass storageClass);
644 MemoryLayout memoryLayoutForVariable(const Variable&) const;
645
646 struct EntrypointAdapter {
647 std::unique_ptr<FunctionDefinition> entrypointDef;
648 std::unique_ptr<FunctionDeclaration> entrypointDecl;
649 };
650
651 EntrypointAdapter writeEntrypointAdapter(const FunctionDeclaration& main);
652
653 struct UniformBuffer {
654 std::unique_ptr<InterfaceBlock> fInterfaceBlock;
655 std::unique_ptr<Variable> fInnerVariable;
656 std::unique_ptr<Type> fStruct;
657 };
658
659 void writeUniformBuffer(SymbolTable* topLevelSymbolTable);
660
661 void addRTFlipUniform(Position pos);
662
663 std::unique_ptr<Expression> identifier(std::string_view name);
664
665 std::tuple<const Variable*, const Variable*> synthesizeTextureAndSampler(
666 const Variable& combinedSampler);
667
668 const MemoryLayout fDefaultMemoryLayout{MemoryLayout::Standard::k140};
669
670 uint64_t fCapabilities = 0;
671 SpvId fIdCount = spirv::kIdFirstUnreserved;
672 SpvId fGLSLExtendedInstructions;
673 struct Intrinsic {
674 IntrinsicOpcodeKind opKind;
675 int32_t floatOp;
676 int32_t signedOp;
677 int32_t unsignedOp;
678 int32_t boolOp;
679 };
680 Intrinsic getIntrinsic(IntrinsicKind) const;
681
682 THashMap<Analysis::SpecializedFunctionKey, SpvId, Analysis::SpecializedFunctionKey::Hash>
683 fFunctionMap;
684
685 Analysis::SpecializationInfo fSpecializationInfo;
686 Analysis::SpecializationIndex fActiveSpecializationIndex = Analysis::kUnspecialized;
687 const Analysis::SpecializedParameters* fActiveSpecialization = nullptr;
688
689 THashMap<const Variable*, SpvId> fVariableMap;
690 THashMap<const Type*, SpvId> fStructMap;
691
692 // SPIR-V is defined in 32-bit words, so this generator directly uses std::vector<uint32_t>
693 // instead of an OutputStream.
694 SPIRVBlob* fOutBuffer;
695 SPIRVBlob fGlobalInitializersBuffer;
696 SPIRVBlob fConstantBuffer;
697 SPIRVBlob fVariableBuffer;
698 SPIRVBlob fNameBuffer;
699 SPIRVBlob fDecorationBuffer;
700
701 // Mapping from combined sampler declarations to synthesized texture/sampler variables.
702 // This is used when the sampler is declared as `layout(webgpu)` or `layout(direct3d)`.
703 bool fUseTextureSamplerPairs = false;
704 struct SynthesizedTextureSamplerPair {
705 // The names of the synthesized variables. The Variable objects themselves store string
706 // views referencing these strings. It is important for the std::string instances to have a
707 // fixed memory location after the string views get created, which is why
708 // `fSynthesizedSamplerMap` stores unique_ptr instead of values.
709 std::string fTextureName;
710 std::string fSamplerName;
711 std::unique_ptr<Variable> fTexture;
712 std::unique_ptr<Variable> fSampler;
713 };
714 THashMap<const Variable*, std::unique_ptr<SynthesizedTextureSamplerPair>>
715 fSynthesizedSamplerMap;
716
717 // These caches map SpvIds to Instructions, and vice-versa. This enables us to deduplicate code
718 // (by detecting an Instruction we've already issued and reusing the SpvId), and to introspect
719 // and simplify code we've already emitted (by taking a SpvId from an Instruction and following
720 // it back to its source).
721
722 // A map of instruction -> SpvId:
723 THashMap<Instruction, SpvId, Instruction::Hash> fOpCache;
724 // A map of SpvId -> instruction:
725 THashMap<SpvId, Instruction> fSpvIdCache;
726 // A map of SpvId -> value SpvId:
727 THashMap<SpvId, SpvId> fStoreCache;
728
729 // "Reachable" ops are instructions which can safely be accessed from the current block.
730 // For instance, if our SPIR-V contains `%3 = OpFAdd %1 %2`, we would be able to access and
731 // reuse that computation on following lines. However, if that Add operation occurred inside an
732 // `if` block, then its SpvId becomes inaccessible once we complete the if statement (since
733 // depending on the if condition, we may or may not have actually done that computation). The
734 // same logic applies to other control-flow blocks as well. Once an instruction becomes
735 // unreachable, we remove it from both op-caches.
736 TArray<SpvId> fReachableOps;
737
738 // The "store-ops" list contains a running list of all the pointers in the store cache. If a
739 // store occurs inside of a conditional block, once that block exits, we no longer know what is
740 // stored in that particular SpvId. At that point, we must remove any associated entry from the
741 // store cache.
742 TArray<SpvId> fStoreOps;
743
744 // label of the current block, or 0 if we are not in a block
745 SpvId fCurrentBlock = 0;
746 TArray<SpvId> fBreakTarget;
747 TArray<SpvId> fContinueTarget;
748 bool fWroteRTFlip = false;
749 // holds variables synthesized during output, for lifetime purposes
750 SymbolTable fSynthetics{/*builtin=*/true};
751 // Holds a list of uniforms that were declared as globals at the top-level instead of in an
752 // interface block.
753 UniformBuffer fUniformBuffer;
754 std::vector<const VarDeclaration*> fTopLevelUniforms;
755 THashMap<const Variable*, int> fTopLevelUniformMap; // <var, UniformBuffer field index>
756 SpvId fUniformBufferId = NA;
757
758 friend class PointerLValue;
759 friend class SwizzleLValue;
760 };
761
762 // Equality and hash operators for Instructions.
763 bool SPIRVCodeGenerator::Instruction::operator==(const SPIRVCodeGenerator::Instruction& that) const {
764 return fOp == that.fOp &&
765 fResultKind == that.fResultKind &&
766 fWords == that.fWords;
767 }
768
769 struct SPIRVCodeGenerator::Instruction::Hash {
770 uint32_t operator()(const SPIRVCodeGenerator::Instruction& key) const {
771 uint32_t hash = key.fResultKind;
772 hash = SkChecksum::Hash32(&key.fOp, sizeof(key.fOp), hash);
773 hash = SkChecksum::Hash32(key.fWords.data(), key.fWords.size() * sizeof(int32_t), hash);
774 return hash;
775 }
776 };
777
778 // This class is used to pass values and result placeholder slots to writeInstruction.
779 struct SPIRVCodeGenerator::Word {
780 enum Kind {
781 kNone, // intended for use as a sentinel, not part of any Instruction
782 kSpvId,
783 kNumber,
784 kDefaultPrecisionResult,
785 kRelaxedPrecisionResult,
786 kUniqueResult,
787 kKeyedResult,
788 kReservedResult,
789 };
790
791 Word(SpvId id) : fValue(id), fKind(Kind::kSpvId) {}
792 Word(int32_t val, Kind kind) : fValue(val), fKind(kind) {}
793
794 static Word Number(int32_t val) {
795 return Word{val, Kind::kNumber};
796 }
797
798 static Word Result(const Type& type) {
799 return (type.hasPrecision() && !type.highPrecision()) ? RelaxedResult() : Result();
800 }
801
802 static Word RelaxedResult() {
803 return Word{(int32_t)NA, kRelaxedPrecisionResult};
804 }
805
806 static Word UniqueResult() {
807 return Word{(int32_t)NA, kUniqueResult};
808 }
809
810 static Word Result() {
811 return Word{(int32_t)NA, kDefaultPrecisionResult};
812 }
813
814 static Word ReservedResult(spirv::ReservedId id) { return Word{(int32_t)id, kReservedResult}; }
815
816 // Unlike a Result (where the result ID is always deduplicated to its first instruction) or a
817 // UniqueResult (which always produces a new instruction), a KeyedResult allows an instruction
818 // to be deduplicated among those that share the same `key`.
819 static Word KeyedResult(int32_t key) { return Word{key, Kind::kKeyedResult}; }
820
821 bool isResult() const { return fKind >= Kind::kDefaultPrecisionResult; }
822
823 int32_t fValue;
824 Kind fKind;
825 };
826
827 // Skia's magic number is 31 and goes in the top 16 bits. We can use the lower bits to version the
828 // sksl generator if we want.
829 // https://github.com/KhronosGroup/SPIRV-Headers/blob/master/include/spirv/spir-v.xml#L84
830 static const int32_t SKSL_MAGIC = 0x001F0000;
831
832 SPIRVCodeGenerator::Intrinsic SPIRVCodeGenerator::getIntrinsic(IntrinsicKind ik) const {
833
834 #define ALL_GLSL(x) Intrinsic{kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
835 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x}
836 #define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) Intrinsic{kGLSL_STD_450_IntrinsicOpcodeKind, \
837 GLSLstd450 ## ifFloat, \
838 GLSLstd450 ## ifInt, \
839 GLSLstd450 ## ifUInt, \
840 SpvOpUndef}
841 #define ALL_SPIRV(x) Intrinsic{kSPIRV_IntrinsicOpcodeKind, \
842 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x}
843 #define BOOL_SPIRV(x) Intrinsic{kSPIRV_IntrinsicOpcodeKind, \
844 SpvOpUndef, SpvOpUndef, SpvOpUndef, SpvOp ## x}
845 #define FLOAT_SPIRV(x) Intrinsic{kSPIRV_IntrinsicOpcodeKind, \
846 SpvOp ## x, SpvOpUndef, SpvOpUndef, SpvOpUndef}
847 #define SPECIAL(x) Intrinsic{kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
848 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
849 k ## x ## _SpecialIntrinsic}
850
851 switch (ik) {
852 case k_round_IntrinsicKind: return ALL_GLSL(Round);
853 case k_roundEven_IntrinsicKind: return ALL_GLSL(RoundEven);
854 case k_trunc_IntrinsicKind: return ALL_GLSL(Trunc);
855 case k_abs_IntrinsicKind: return BY_TYPE_GLSL(FAbs, SAbs, SAbs);
856 case k_sign_IntrinsicKind: return BY_TYPE_GLSL(FSign, SSign, SSign);
857 case k_floor_IntrinsicKind: return ALL_GLSL(Floor);
858 case k_ceil_IntrinsicKind: return ALL_GLSL(Ceil);
859 case k_fract_IntrinsicKind: return ALL_GLSL(Fract);
860 case k_radians_IntrinsicKind: return ALL_GLSL(Radians);
861 case k_degrees_IntrinsicKind: return ALL_GLSL(Degrees);
862 case k_sin_IntrinsicKind: return ALL_GLSL(Sin);
863 case k_cos_IntrinsicKind: return ALL_GLSL(Cos);
864 case k_tan_IntrinsicKind: return ALL_GLSL(Tan);
865 case k_asin_IntrinsicKind: return ALL_GLSL(Asin);
866 case k_acos_IntrinsicKind: return ALL_GLSL(Acos);
867 case k_atan_IntrinsicKind: return SPECIAL(Atan);
868 case k_sinh_IntrinsicKind: return ALL_GLSL(Sinh);
869 case k_cosh_IntrinsicKind: return ALL_GLSL(Cosh);
870 case k_tanh_IntrinsicKind: return ALL_GLSL(Tanh);
871 case k_asinh_IntrinsicKind: return ALL_GLSL(Asinh);
872 case k_acosh_IntrinsicKind: return ALL_GLSL(Acosh);
873 case k_atanh_IntrinsicKind: return ALL_GLSL(Atanh);
874 case k_pow_IntrinsicKind: return ALL_GLSL(Pow);
875 case k_exp_IntrinsicKind: return ALL_GLSL(Exp);
876 case k_log_IntrinsicKind: return ALL_GLSL(Log);
877 case k_exp2_IntrinsicKind: return ALL_GLSL(Exp2);
878 case k_log2_IntrinsicKind: return ALL_GLSL(Log2);
879 case k_sqrt_IntrinsicKind: return ALL_GLSL(Sqrt);
880 case k_inverse_IntrinsicKind: return ALL_GLSL(MatrixInverse);
881 case k_outerProduct_IntrinsicKind: return ALL_SPIRV(OuterProduct);
882 case k_transpose_IntrinsicKind: return ALL_SPIRV(Transpose);
883 case k_isinf_IntrinsicKind: return ALL_SPIRV(IsInf);
884 case k_isnan_IntrinsicKind: return ALL_SPIRV(IsNan);
885 case k_inversesqrt_IntrinsicKind: return ALL_GLSL(InverseSqrt);
886 case k_determinant_IntrinsicKind: return ALL_GLSL(Determinant);
887 case k_matrixCompMult_IntrinsicKind: return SPECIAL(MatrixCompMult);
888 case k_matrixInverse_IntrinsicKind: return ALL_GLSL(MatrixInverse);
889 case k_mod_IntrinsicKind: return SPECIAL(Mod);
890 case k_modf_IntrinsicKind: return ALL_GLSL(Modf);
891 case k_min_IntrinsicKind: return SPECIAL(Min);
892 case k_max_IntrinsicKind: return SPECIAL(Max);
893 case k_clamp_IntrinsicKind: return SPECIAL(Clamp);
894 case k_saturate_IntrinsicKind: return SPECIAL(Saturate);
895 case k_dot_IntrinsicKind: return FLOAT_SPIRV(Dot);
896 case k_mix_IntrinsicKind: return SPECIAL(Mix);
897 case k_step_IntrinsicKind: return SPECIAL(Step);
898 case k_smoothstep_IntrinsicKind: return SPECIAL(SmoothStep);
899 case k_fma_IntrinsicKind: return ALL_GLSL(Fma);
900 case k_frexp_IntrinsicKind: return ALL_GLSL(Frexp);
901 case k_ldexp_IntrinsicKind: return ALL_GLSL(Ldexp);
902
903 #define PACK(type) case k_pack##type##_IntrinsicKind: return ALL_GLSL(Pack##type); \
904 case k_unpack##type##_IntrinsicKind: return ALL_GLSL(Unpack##type)
905 PACK(Snorm4x8);
906 PACK(Unorm4x8);
907 PACK(Snorm2x16);
908 PACK(Unorm2x16);
909 PACK(Half2x16);
910 #undef PACK
911
912 case k_length_IntrinsicKind: return ALL_GLSL(Length);
913 case k_distance_IntrinsicKind: return ALL_GLSL(Distance);
914 case k_cross_IntrinsicKind: return ALL_GLSL(Cross);
915 case k_normalize_IntrinsicKind: return ALL_GLSL(Normalize);
916 case k_faceforward_IntrinsicKind: return ALL_GLSL(FaceForward);
917 case k_reflect_IntrinsicKind: return ALL_GLSL(Reflect);
918 case k_refract_IntrinsicKind: return ALL_GLSL(Refract);
919 case k_bitCount_IntrinsicKind: return ALL_SPIRV(BitCount);
920 case k_findLSB_IntrinsicKind: return ALL_GLSL(FindILsb);
921 case k_findMSB_IntrinsicKind: return BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
922 case k_dFdx_IntrinsicKind: return FLOAT_SPIRV(DPdx);
923 case k_dFdy_IntrinsicKind: return SPECIAL(DFdy);
924 case k_fwidth_IntrinsicKind: return FLOAT_SPIRV(Fwidth);
925
926 case k_sample_IntrinsicKind: return SPECIAL(Texture);
927 case k_sampleGrad_IntrinsicKind: return SPECIAL(TextureGrad);
928 case k_sampleLod_IntrinsicKind: return SPECIAL(TextureLod);
929 case k_subpassLoad_IntrinsicKind: return SPECIAL(SubpassLoad);
930
931 case k_textureRead_IntrinsicKind: return SPECIAL(TextureRead);
932 case k_textureWrite_IntrinsicKind: return SPECIAL(TextureWrite);
933 case k_textureWidth_IntrinsicKind: return SPECIAL(TextureWidth);
934 case k_textureHeight_IntrinsicKind: return SPECIAL(TextureHeight);
935
936 case k_floatBitsToInt_IntrinsicKind: return ALL_SPIRV(Bitcast);
937 case k_floatBitsToUint_IntrinsicKind: return ALL_SPIRV(Bitcast);
938 case k_intBitsToFloat_IntrinsicKind: return ALL_SPIRV(Bitcast);
939 case k_uintBitsToFloat_IntrinsicKind: return ALL_SPIRV(Bitcast);
940
941 case k_any_IntrinsicKind: return BOOL_SPIRV(Any);
942 case k_all_IntrinsicKind: return BOOL_SPIRV(All);
943 case k_not_IntrinsicKind: return BOOL_SPIRV(LogicalNot);
944
945 case k_equal_IntrinsicKind:
946 return Intrinsic{kSPIRV_IntrinsicOpcodeKind,
947 SpvOpFOrdEqual,
948 SpvOpIEqual,
949 SpvOpIEqual,
950 SpvOpLogicalEqual};
951 case k_notEqual_IntrinsicKind:
952 return Intrinsic{kSPIRV_IntrinsicOpcodeKind,
953 SpvOpFUnordNotEqual,
954 SpvOpINotEqual,
955 SpvOpINotEqual,
956 SpvOpLogicalNotEqual};
957 case k_lessThan_IntrinsicKind:
958 return Intrinsic{kSPIRV_IntrinsicOpcodeKind,
959 SpvOpFOrdLessThan,
960 SpvOpSLessThan,
961 SpvOpULessThan,
962 SpvOpUndef};
963 case k_lessThanEqual_IntrinsicKind:
964 return Intrinsic{kSPIRV_IntrinsicOpcodeKind,
965 SpvOpFOrdLessThanEqual,
966 SpvOpSLessThanEqual,
967 SpvOpULessThanEqual,
968 SpvOpUndef};
969 case k_greaterThan_IntrinsicKind:
970 return Intrinsic{kSPIRV_IntrinsicOpcodeKind,
971 SpvOpFOrdGreaterThan,
972 SpvOpSGreaterThan,
973 SpvOpUGreaterThan,
974 SpvOpUndef};
975 case k_greaterThanEqual_IntrinsicKind:
976 return Intrinsic{kSPIRV_IntrinsicOpcodeKind,
977 SpvOpFOrdGreaterThanEqual,
978 SpvOpSGreaterThanEqual,
979 SpvOpUGreaterThanEqual,
980 SpvOpUndef};
981
982 case k_atomicAdd_IntrinsicKind: return SPECIAL(AtomicAdd);
983 case k_atomicLoad_IntrinsicKind: return SPECIAL(AtomicLoad);
984 case k_atomicStore_IntrinsicKind: return SPECIAL(AtomicStore);
985
986 case k_storageBarrier_IntrinsicKind: return SPECIAL(StorageBarrier);
987 case k_workgroupBarrier_IntrinsicKind: return SPECIAL(WorkgroupBarrier);
988
989 default:
990 return Intrinsic{kInvalid_IntrinsicOpcodeKind, 0, 0, 0, 0};
991 }
992 }
993
994 void SPIRVCodeGenerator::writeWord(int32_t word, SPIRVBlob& out) {
995 out.push_back(word);
996 }
997
998 static bool is_float(const Type& type) {
999 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
1000 type.componentType().isFloat();
1001 }
1002
1003 static bool is_signed(const Type& type) {
1004 return (type.isScalar() || type.isVector()) && type.componentType().isSigned();
1005 }
1006
1007 static bool is_unsigned(const Type& type) {
1008 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
1009 }
1010
1011 static bool is_bool(const Type& type) {
1012 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
1013 }
1014
1015 template <typename T>
1016 static T pick_by_type(const Type& type, T ifFloat, T ifInt, T ifUInt, T ifBool) {
1017 if (is_float(type)) {
1018 return ifFloat;
1019 }
1020 if (is_signed(type)) {
1021 return ifInt;
1022 }
1023 if (is_unsigned(type)) {
1024 return ifUInt;
1025 }
1026 if (is_bool(type)) {
1027 return ifBool;
1028 }
1029 SkDEBUGFAIL("unrecognized type");
1030 return ifFloat;
1031 }
1032
1033 static bool is_out(ModifierFlags f) {
1034 return SkToBool(f & ModifierFlag::kOut);
1035 }
1036
1037 static bool is_in(ModifierFlags f) {
1038 if (f & ModifierFlag::kIn) {
1039 return true; // `in` and `inout` both count
1040 }
1041 // If neither in/out flag is set, the type is implicitly `in`.
1042 return !SkToBool(f & ModifierFlag::kOut);
1043 }
1044
1045 static bool is_control_flow_op(SpvOp_ op) {
1046 switch (op) {
1047 case SpvOpReturn:
1048 case SpvOpReturnValue:
1049 case SpvOpKill:
1050 case SpvOpSwitch:
1051 case SpvOpBranch:
1052 case SpvOpBranchConditional:
1053 return true;
1054 default:
1055 return false;
1056 }
1057 }
1058
1059 static bool is_globally_reachable_op(SpvOp_ op) {
1060 switch (op) {
1061 case SpvOpConstant:
1062 case SpvOpConstantTrue:
1063 case SpvOpConstantFalse:
1064 case SpvOpConstantComposite:
1065 case SpvOpTypeVoid:
1066 case SpvOpTypeInt:
1067 case SpvOpTypeFloat:
1068 case SpvOpTypeBool:
1069 case SpvOpTypeVector:
1070 case SpvOpTypeMatrix:
1071 case SpvOpTypeArray:
1072 case SpvOpTypePointer:
1073 case SpvOpTypeFunction:
1074 case SpvOpTypeRuntimeArray:
1075 case SpvOpTypeStruct:
1076 case SpvOpTypeImage:
1077 case SpvOpTypeSampledImage:
1078 case SpvOpTypeSampler:
1079 case SpvOpVariable:
1080 case SpvOpFunction:
1081 case SpvOpFunctionParameter:
1082 case SpvOpFunctionEnd:
1083 case SpvOpExecutionMode:
1084 case SpvOpMemoryModel:
1085 case SpvOpCapability:
1086 case SpvOpExtInstImport:
1087 case SpvOpEntryPoint:
1088 case SpvOpSource:
1089 case SpvOpSourceExtension:
1090 case SpvOpName:
1091 case SpvOpMemberName:
1092 case SpvOpDecorate:
1093 case SpvOpMemberDecorate:
1094 return true;
1095 default:
1096 return false;
1097 }
1098 }
1099
1100 void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, SPIRVBlob& out) {
1101 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
1102 SkASSERT(opCode != SpvOpUndef);
1103 bool foundDeadCode = false;
1104 if (is_control_flow_op(opCode)) {
1105 // This instruction causes us to leave the current block.
1106 foundDeadCode = (fCurrentBlock == 0);
1107 fCurrentBlock = 0;
1108 } else if (!is_globally_reachable_op(opCode)) {
1109 foundDeadCode = (fCurrentBlock == 0);
1110 }
1111
1112 if (foundDeadCode) {
1113 // We just encountered dead code--an instruction that don't have an associated block.
1114 // Synthesize a label if this happens; this is necessary to satisfy the validator.
1115 this->writeLabel(this->nextId(nullptr), kBranchlessBlock, out);
1116 }
1117
1118 this->writeWord((length << 16) | opCode, out);
1119 }
1120
1121 void SPIRVCodeGenerator::writeLabel(SpvId label, StraightLineLabelType, SPIRVBlob& out) {
1122 // The straight-line label type is not important; in any case, no caches are invalidated.
1123 SkASSERT(!fCurrentBlock);
1124 fCurrentBlock = label;
1125 this->writeInstruction(SpvOpLabel, label, out);
1126 }
1127
1128 void SPIRVCodeGenerator::writeLabel(SpvId label, BranchingLabelType type,
1129 ConditionalOpCounts ops, SPIRVBlob& out) {
1130 switch (type) {
1131 case kBranchIsBelow:
1132 case kBranchesOnBothSides:
1133 // With a backward or bidirectional branch, we haven't seen the code between the label
1134 // and the branch yet, so any stored value is potentially suspect. Without scanning
1135 // ahead to check, the only safe option is to ditch the store cache entirely.
1136 fStoreCache.reset();
1137 [[fallthrough]];
1138
1139 case kBranchIsAbove:
1140 // With a forward branch, we can rely on stores that we had cached at the start of the
1141 // statement/expression, if they haven't been touched yet. Anything newer than that is
1142 // pruned.
1143 this->pruneConditionalOps(ops);
1144 break;
1145 }
1146
1147 // Emit the label.
1148 this->writeLabel(label, kBranchlessBlock, out);
1149 }
1150
1151 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, SPIRVBlob& out) {
1152 this->writeOpCode(opCode, 1, out);
1153 }
1154
1155 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, SPIRVBlob& out) {
1156 this->writeOpCode(opCode, 2, out);
1157 this->writeWord(word1, out);
1158 }
1159
1160 void SPIRVCodeGenerator::writeString(std::string_view s, SPIRVBlob& out) {
1161 size_t offset = out.size();
1162 // Add storage for the string + space for the nul character. Memory is zero-initialized so
1163 // nul-termination is not needed later.
1164 out.resize(offset + s.size() / 4 + 1, 0);
1165 memcpy(out.data() + offset, s.data(), s.size());
1166 }
1167
1168 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, std::string_view string,
1169 SPIRVBlob& out) {
1170 this->writeOpCode(opCode, 1 + (string.length() + 4) / 4, out);
1171 this->writeString(string, out);
1172 }
1173
1174 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, std::string_view string,
1175 SPIRVBlob& out) {
1176 this->writeOpCode(opCode, 2 + (string.length() + 4) / 4, out);
1177 this->writeWord(word1, out);
1178 this->writeString(string, out);
1179 }
1180
1181 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1182 std::string_view string, SPIRVBlob& out) {
1183 this->writeOpCode(opCode, 3 + (string.length() + 4) / 4, out);
1184 this->writeWord(word1, out);
1185 this->writeWord(word2, out);
1186 this->writeString(string, out);
1187 }
1188
1189 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1190 SPIRVBlob& out) {
1191 this->writeOpCode(opCode, 3, out);
1192 this->writeWord(word1, out);
1193 this->writeWord(word2, out);
1194 }
1195
1196 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1197 int32_t word3, SPIRVBlob& out) {
1198 this->writeOpCode(opCode, 4, out);
1199 this->writeWord(word1, out);
1200 this->writeWord(word2, out);
1201 this->writeWord(word3, out);
1202 }
1203
1204 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1205 int32_t word3, int32_t word4, SPIRVBlob& out) {
1206 this->writeOpCode(opCode, 5, out);
1207 this->writeWord(word1, out);
1208 this->writeWord(word2, out);
1209 this->writeWord(word3, out);
1210 this->writeWord(word4, out);
1211 }
1212
1213 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1214 int32_t word3, int32_t word4, int32_t word5,
1215 SPIRVBlob& out) {
1216 this->writeOpCode(opCode, 6, out);
1217 this->writeWord(word1, out);
1218 this->writeWord(word2, out);
1219 this->writeWord(word3, out);
1220 this->writeWord(word4, out);
1221 this->writeWord(word5, out);
1222 }
1223
1224 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1225 int32_t word3, int32_t word4, int32_t word5,
1226 int32_t word6, SPIRVBlob& out) {
1227 this->writeOpCode(opCode, 7, out);
1228 this->writeWord(word1, out);
1229 this->writeWord(word2, out);
1230 this->writeWord(word3, out);
1231 this->writeWord(word4, out);
1232 this->writeWord(word5, out);
1233 this->writeWord(word6, out);
1234 }
1235
1236 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1237 int32_t word3, int32_t word4, int32_t word5,
1238 int32_t word6, int32_t word7, SPIRVBlob& out) {
1239 this->writeOpCode(opCode, 8, out);
1240 this->writeWord(word1, out);
1241 this->writeWord(word2, out);
1242 this->writeWord(word3, out);
1243 this->writeWord(word4, out);
1244 this->writeWord(word5, out);
1245 this->writeWord(word6, out);
1246 this->writeWord(word7, out);
1247 }
1248
1249 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
1250 int32_t word3, int32_t word4, int32_t word5,
1251 int32_t word6, int32_t word7, int32_t word8,
1252 SPIRVBlob& out) {
1253 this->writeOpCode(opCode, 9, out);
1254 this->writeWord(word1, out);
1255 this->writeWord(word2, out);
1256 this->writeWord(word3, out);
1257 this->writeWord(word4, out);
1258 this->writeWord(word5, out);
1259 this->writeWord(word6, out);
1260 this->writeWord(word7, out);
1261 this->writeWord(word8, out);
1262 }
1263
1264 SPIRVCodeGenerator::Instruction SPIRVCodeGenerator::BuildInstructionKey(SpvOp_ opCode,
1265 const TArray<Word>& words,
1266 SpvId* predefinedResultId) {
1267 // Assemble a cache key for this instruction.
1268 Instruction key;
1269 key.fOp = opCode;
1270 key.fWords.resize(words.size());
1271 key.fResultKind = Word::Kind::kNone;
1272
1273 *predefinedResultId = NA;
1274
1275 for (int index = 0; index < words.size(); ++index) {
1276 const Word& word = words[index];
1277 key.fWords[index] = word.fValue;
1278 if (word.isResult()) {
1279 SkASSERT(key.fResultKind == Word::Kind::kNone);
1280 key.fResultKind = word.fKind;
1281 *predefinedResultId = word.fValue;
1282 }
1283 }
1284
1285 return key;
1286 }
1287
1288 SpvId SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode,
1289 const TArray<Word>& words,
1290 SPIRVBlob& out) {
1291 // writeOpLoad and writeOpStore have dedicated code.
1292 SkASSERT(opCode != SpvOpLoad);
1293 SkASSERT(opCode != SpvOpStore);
1294
1295 // If this instruction exists in our op cache, return the cached SpvId.
1296 SpvId predefinedResultId = NA;
1297 Instruction key = BuildInstructionKey(opCode, words, &predefinedResultId);
1298 if (SpvId* cachedOp = fOpCache.find(key)) {
1299 return *cachedOp;
1300 }
1301
1302 SpvId result = NA;
1303 Precision precision = Precision::kDefault;
1304
1305 switch (key.fResultKind) {
1306 case Word::Kind::kUniqueResult:
1307 // The instruction returns a SpvId, but we do not want deduplication.
1308 result = this->nextId(Precision::kDefault);
1309 fSpvIdCache.set(result, key);
1310 break;
1311
1312 case Word::Kind::kNone:
1313 // The instruction doesn't return a SpvId, but we can still cache and deduplicate it.
1314 fOpCache.set(key, result);
1315 break;
1316
1317 case Word::Kind::kRelaxedPrecisionResult:
1318 precision = Precision::kRelaxed;
1319 [[fallthrough]];
1320
1321 case Word::Kind::kKeyedResult:
1322 [[fallthrough]];
1323
1324 case Word::Kind::kDefaultPrecisionResult:
1325 // Consume a new SpvId.
1326 result = this->nextId(precision);
1327 fOpCache.set(key, result);
1328 fSpvIdCache.set(result, key);
1329
1330 // Globally-reachable ops are not subject to the whims of flow control.
1331 if (!is_globally_reachable_op(opCode)) {
1332 fReachableOps.push_back(result);
1333 }
1334 break;
1335
1336 case Word::Kind::kReservedResult:
1337 // The SpvId is predetermined in spirv::ReservedId.
1338 SkASSERT(predefinedResultId != NA);
1339 result = predefinedResultId;
1340 fOpCache.set(key, result);
1341 fSpvIdCache.set(result, key);
1342 // Reserved IDs only make sense for globally-reachable ops; the ops in function bodies
1343 // can never guarantee uniqueness.
1344 SkASSERT(is_globally_reachable_op(opCode));
1345 break;
1346
1347 default:
1348 SkDEBUGFAIL("unexpected result kind");
1349 break;
1350 }
1351
1352 // Write the requested instruction.
1353 this->writeOpCode(opCode, words.size() + 1, out);
1354 for (const Word& word : words) {
1355 if (word.isResult()) {
1356 SkASSERT(result != NA);
1357 this->writeWord(result, out);
1358 } else {
1359 this->writeWord(word.fValue, out);
1360 }
1361 }
1362
1363 // Return the result.
1364 return result;
1365 }
1366
1367 SpvId SPIRVCodeGenerator::writeOpLoad(SpvId type,
1368 Precision precision,
1369 SpvId pointer,
1370 SPIRVBlob& out) {
1371 // Look for this pointer in our load-cache.
1372 if (SpvId* cachedOp = fStoreCache.find(pointer)) {
1373 return *cachedOp;
1374 }
1375
1376 // Write the requested OpLoad instruction.
1377 SpvId result = this->nextId(precision);
1378 this->writeInstruction(SpvOpLoad, type, result, pointer, out);
1379 return result;
1380 }
1381
1382 void SPIRVCodeGenerator::writeOpStore(StorageClass storageClass,
1383 SpvId pointer,
1384 SpvId value,
1385 SPIRVBlob& out) {
1386 // Write the uncached SpvOpStore directly.
1387 this->writeInstruction(SpvOpStore, pointer, value, out);
1388
1389 if (storageClass == StorageClass::kFunction) {
1390 // Insert a pointer-to-SpvId mapping into the load cache. A writeOpLoad to this pointer will
1391 // return the cached value as-is.
1392 fStoreCache.set(pointer, value);
1393 fStoreOps.push_back(pointer);
1394 }
1395 }
1396
1397 SpvId SPIRVCodeGenerator::writeOpConstantTrue(const Type& type) {
1398 return this->writeInstruction(SpvOpConstantTrue,
1399 Words{this->getType(type), Word::Result()},
1400 fConstantBuffer);
1401 }
1402
1403 SpvId SPIRVCodeGenerator::writeOpConstantFalse(const Type& type) {
1404 return this->writeInstruction(SpvOpConstantFalse,
1405 Words{this->getType(type), Word::Result()},
1406 fConstantBuffer);
1407 }
1408
1409 SpvId SPIRVCodeGenerator::writeOpConstant(const Type& type, int32_t valueBits) {
1410 return this->writeInstruction(
1411 SpvOpConstant,
1412 Words{this->getType(type), Word::Result(), Word::Number(valueBits)},
1413 fConstantBuffer);
1414 }
1415
1416 SpvId SPIRVCodeGenerator::writeOpConstantComposite(const Type& type,
1417 const TArray<SpvId>& values) {
1418 SkASSERT(values.size() == (type.isStruct() ? SkToInt(type.fields().size()) : type.columns()));
1419
1420 Words words;
1421 words.push_back(this->getType(type));
1422 words.push_back(Word::Result());
1423 for (SpvId value : values) {
1424 words.push_back(value);
1425 }
1426 return this->writeInstruction(SpvOpConstantComposite, words, fConstantBuffer);
1427 }
1428
1429 bool SPIRVCodeGenerator::toConstants(SpvId value, TArray<SpvId>* constants) {
1430 Instruction* instr = fSpvIdCache.find(value);
1431 if (!instr) {
1432 return false;
1433 }
1434 switch (instr->fOp) {
1435 case SpvOpConstant:
1436 case SpvOpConstantTrue:
1437 case SpvOpConstantFalse:
1438 constants->push_back(value);
1439 return true;
1440
1441 case SpvOpConstantComposite: // OpConstantComposite ResultType ResultID Constituents...
1442 // Start at word 2 to skip past ResultType and ResultID.
1443 for (int i = 2; i < instr->fWords.size(); ++i) {
1444 if (!this->toConstants(instr->fWords[i], constants)) {
1445 return false;
1446 }
1447 }
1448 return true;
1449
1450 default:
1451 return false;
1452 }
1453 }
1454
1455 bool SPIRVCodeGenerator::toConstants(SkSpan<const SpvId> values, TArray<SpvId>* constants) {
1456 for (SpvId value : values) {
1457 if (!this->toConstants(value, constants)) {
1458 return false;
1459 }
1460 }
1461 return true;
1462 }
1463
1464 SpvId SPIRVCodeGenerator::writeOpCompositeConstruct(const Type& type,
1465 const TArray<SpvId>& values,
1466 SPIRVBlob& out) {
1467 // If this is a vector composed entirely of literals, write a constant-composite instead.
1468 if (type.isVector()) {
1469 STArray<4, SpvId> constants;
1470 if (this->toConstants(SkSpan(values), &constants)) {
1471 // Create a vector from literals.
1472 return this->writeOpConstantComposite(type, constants);
1473 }
1474 }
1475
1476 // If this is a matrix composed entirely of literals, constant-composite them instead.
1477 if (type.isMatrix()) {
1478 STArray<16, SpvId> constants;
1479 if (this->toConstants(SkSpan(values), &constants)) {
1480 // Create each matrix column.
1481 SkASSERT(type.isMatrix());
1482 const Type& vecType = type.columnType(fContext);
1483 STArray<4, SpvId> columnIDs;
1484 for (int index=0; index < type.columns(); ++index) {
1485 STArray<4, SpvId> columnConstants(&constants[index * type.rows()],
1486 type.rows());
1487 columnIDs.push_back(this->writeOpConstantComposite(vecType, columnConstants));
1488 }
1489 // Compose the matrix from its columns.
1490 return this->writeOpConstantComposite(type, columnIDs);
1491 }
1492 }
1493
1494 Words words;
1495 words.push_back(this->getType(type));
1496 words.push_back(Word::Result(type));
1497 for (SpvId value : values) {
1498 words.push_back(value);
1499 }
1500
1501 return this->writeInstruction(SpvOpCompositeConstruct, words, out);
1502 }
1503
1504 SPIRVCodeGenerator::Instruction* SPIRVCodeGenerator::resultTypeForInstruction(
1505 const Instruction& instr) {
1506 // This list should contain every op that we cache that has a result and result-type.
1507 // (If one is missing, we will not find some optimization opportunities.)
1508 // Generally, the result type of an op is in the 0th word, but I'm not sure if this is
1509 // universally true, so it's configurable on a per-op basis.
1510 int resultTypeWord;
1511 switch (instr.fOp) {
1512 case SpvOpConstant:
1513 case SpvOpConstantTrue:
1514 case SpvOpConstantFalse:
1515 case SpvOpConstantComposite:
1516 case SpvOpCompositeConstruct:
1517 case SpvOpCompositeExtract:
1518 case SpvOpLoad:
1519 resultTypeWord = 0;
1520 break;
1521
1522 default:
1523 return nullptr;
1524 }
1525
1526 Instruction* typeInstr = fSpvIdCache.find(instr.fWords[resultTypeWord]);
1527 SkASSERT(typeInstr);
1528 return typeInstr;
1529 }
1530
1531 int SPIRVCodeGenerator::numComponentsForVecInstruction(const Instruction& instr) {
1532 // If an instruction is in the op cache, its type should be as well.
1533 Instruction* typeInstr = this->resultTypeForInstruction(instr);
1534 SkASSERT(typeInstr);
1535 SkASSERT(typeInstr->fOp == SpvOpTypeVector || typeInstr->fOp == SpvOpTypeFloat ||
1536 typeInstr->fOp == SpvOpTypeInt || typeInstr->fOp == SpvOpTypeBool);
1537
1538 // For vectors, extract their column count. Scalars have one component by definition.
1539 // SpvOpTypeVector ResultID ComponentType NumComponents
1540 return (typeInstr->fOp == SpvOpTypeVector) ? typeInstr->fWords[2]
1541 : 1;
1542 }
1543
1544 SpvId SPIRVCodeGenerator::toComponent(SpvId id, int component) {
1545 Instruction* instr = fSpvIdCache.find(id);
1546 if (!instr) {
1547 return NA;
1548 }
1549 if (instr->fOp == SpvOpConstantComposite) {
1550 // SpvOpConstantComposite ResultType ResultID [components...]
1551 // Add 2 to the component index to skip past ResultType and ResultID.
1552 return instr->fWords[2 + component];
1553 }
1554 if (instr->fOp == SpvOpCompositeConstruct) {
1555 // SpvOpCompositeConstruct ResultType ResultID [components...]
1556 // Vectors have special rules; check to see if we are composing a vector.
1557 Instruction* composedType = fSpvIdCache.find(instr->fWords[0]);
1558 SkASSERT(composedType);
1559
1560 // When composing a non-vector, each instruction word maps 1:1 to the component index.
1561 // We can just extract out the associated component directly.
1562 if (composedType->fOp != SpvOpTypeVector) {
1563 return instr->fWords[2 + component];
1564 }
1565
1566 // When composing a vector, components can be either scalars or vectors.
1567 // This means we need to check the op type on each component. (+2 to skip ResultType/Result)
1568 for (int index = 2; index < instr->fWords.size(); ++index) {
1569 int32_t currentWord = instr->fWords[index];
1570
1571 // Retrieve the sub-instruction pointed to by OpCompositeConstruct.
1572 Instruction* subinstr = fSpvIdCache.find(currentWord);
1573 if (!subinstr) {
1574 return NA;
1575 }
1576 // If this subinstruction contains the component we're looking for...
1577 int numComponents = this->numComponentsForVecInstruction(*subinstr);
1578 if (component < numComponents) {
1579 if (numComponents == 1) {
1580 // ... it's a scalar. Return it.
1581 SkASSERT(component == 0);
1582 return currentWord;
1583 } else {
1584 // ... it's a vector. Recurse into it.
1585 return this->toComponent(currentWord, component);
1586 }
1587 }
1588 // This sub-instruction doesn't contain our component. Keep walking forward.
1589 component -= numComponents;
1590 }
1591 SkDEBUGFAIL("component index goes past the end of this composite value");
1592 return NA;
1593 }
1594 return NA;
1595 }
1596
1597 SpvId SPIRVCodeGenerator::writeOpCompositeExtract(const Type& type,
1598 SpvId base,
1599 int component,
1600 SPIRVBlob& out) {
1601 // If the base op is a composite, we can extract from it directly.
1602 SpvId result = this->toComponent(base, component);
1603 if (result != NA) {
1604 return result;
1605 }
1606 return this->writeInstruction(
1607 SpvOpCompositeExtract,
1608 {this->getType(type), Word::Result(type), base, Word::Number(component)},
1609 out);
1610 }
1611
1612 SpvId SPIRVCodeGenerator::writeOpCompositeExtract(const Type& type,
1613 SpvId base,
1614 int componentA,
1615 int componentB,
1616 SPIRVBlob& out) {
1617 // If the base op is a composite, we can extract from it directly.
1618 SpvId result = this->toComponent(base, componentA);
1619 if (result != NA) {
1620 return this->writeOpCompositeExtract(type, result, componentB, out);
1621 }
1622 return this->writeInstruction(SpvOpCompositeExtract,
1623 {this->getType(type),
1624 Word::Result(type),
1625 base,
1626 Word::Number(componentA),
1627 Word::Number(componentB)},
1628 out);
1629 }
1630
1631 void SPIRVCodeGenerator::writeCapabilities(SPIRVBlob& out) {
1632 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
1633 if (fCapabilities & bit) {
1634 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
1635 }
1636 }
1637 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
1638 }
1639
1640 SpvId SPIRVCodeGenerator::nextId(const Type* type) {
1641 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
1642 ? Precision::kRelaxed
1643 : Precision::kDefault);
1644 }
1645
1646 SpvId SPIRVCodeGenerator::nextId(Precision precision) {
1647 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
1648 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
1649 fDecorationBuffer);
1650 }
1651 return fIdCount++;
1652 }
1653
1654 SpvId SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout) {
1655 // If we've already written out this struct, return its existing SpvId.
1656 if (SpvId* cachedStructId = fStructMap.find(&type)) {
1657 return *cachedStructId;
1658 }
1659
1660 // Write all of the field types first, so we don't inadvertently write them while we're in the
1661 // middle of writing the struct instruction.
1662 Words words;
1663 words.push_back(Word::UniqueResult());
1664 for (const auto& f : type.fields()) {
1665 words.push_back(this->getType(*f.fType, f.fLayout, memoryLayout));
1666 }
1667 SpvId resultId = this->writeInstruction(SpvOpTypeStruct, words, fConstantBuffer);
1668 this->writeInstruction(SpvOpName, resultId, type.name(), fNameBuffer);
1669 fStructMap.set(&type, resultId);
1670
1671 size_t offset = 0;
1672 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
1673 const Field& field = type.fields()[i];
1674 if (!memoryLayout.isSupported(*field.fType)) {
1675 fContext.fErrors->error(type.fPosition, "type '" + field.fType->displayName() +
1676 "' is not permitted here");
1677 return resultId;
1678 }
1679 size_t size = memoryLayout.size(*field.fType);
1680 size_t alignment = memoryLayout.alignment(*field.fType);
1681 const Layout& fieldLayout = field.fLayout;
1682 if (fieldLayout.fOffset >= 0) {
1683 if (fieldLayout.fOffset < (int) offset) {
1684 fContext.fErrors->error(field.fPosition, "offset of field '" +
1685 std::string(field.fName) + "' must be at least " + std::to_string(offset));
1686 }
1687 if (fieldLayout.fOffset % alignment) {
1688 fContext.fErrors->error(field.fPosition,
1689 "offset of field '" + std::string(field.fName) +
1690 "' must be a multiple of " + std::to_string(alignment));
1691 }
1692 offset = fieldLayout.fOffset;
1693 } else {
1694 size_t mod = offset % alignment;
1695 if (mod) {
1696 offset += alignment - mod;
1697 }
1698 }
1699 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
1700 this->writeFieldLayout(fieldLayout, resultId, i);
1701 if (field.fLayout.fBuiltin < 0) {
1702 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
1703 (SpvId) offset, fDecorationBuffer);
1704 }
1705 if (field.fType->isMatrix()) {
1706 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
1707 fDecorationBuffer);
1708 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
1709 (SpvId) memoryLayout.stride(*field.fType),
1710 fDecorationBuffer);
1711 }
1712 if (!field.fType->highPrecision()) {
1713 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
1714 SpvDecorationRelaxedPrecision, fDecorationBuffer);
1715 }
1716 offset += size;
1717 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
1718 offset += alignment - offset % alignment;
1719 }
1720 }
1721
1722 return resultId;
1723 }
1724
1725 SpvId SPIRVCodeGenerator::getType(const Type& type) {
1726 return this->getType(type, kDefaultTypeLayout, fDefaultMemoryLayout);
1727 }
1728
1729 static SpvImageFormat layout_flags_to_image_format(LayoutFlags flags) {
1730 flags &= LayoutFlag::kAllPixelFormats;
1731 switch (flags.value()) {
1732 case (int)LayoutFlag::kRGBA8:
1733 return SpvImageFormatRgba8;
1734
1735 case (int)LayoutFlag::kRGBA32F:
1736 return SpvImageFormatRgba32f;
1737
1738 case (int)LayoutFlag::kR32F:
1739 return SpvImageFormatR32f;
1740
1741 default:
1742 return SpvImageFormatUnknown;
1743 }
1744
1745 SkUNREACHABLE;
1746 }
1747
1748 SpvId SPIRVCodeGenerator::getType(const Type& rawType,
1749 const Layout& typeLayout,
1750 const MemoryLayout& memoryLayout) {
1751 const Type* type = &rawType;
1752
1753 switch (type->typeKind()) {
1754 case Type::TypeKind::kVoid: {
1755 return this->writeInstruction(SpvOpTypeVoid, Words{Word::Result()}, fConstantBuffer);
1756 }
1757 case Type::TypeKind::kScalar:
1758 case Type::TypeKind::kLiteral: {
1759 if (type->isBoolean()) {
1760 return this->writeInstruction(SpvOpTypeBool, {Word::Result()}, fConstantBuffer);
1761 }
1762 if (type->isSigned()) {
1763 // Predefined type
1764 return spirv::kIdTypeInt;
1765 }
1766 if (type->isUnsigned()) {
1767 return this->writeInstruction(
1768 SpvOpTypeInt,
1769 Words{Word::Result(), Word::Number(32), Word::Number(0)},
1770 fConstantBuffer);
1771 }
1772 if (type->isFloat()) {
1773 return this->writeInstruction(
1774 SpvOpTypeFloat,
1775 Words{Word::Result(), Word::Number(32)},
1776 fConstantBuffer);
1777 }
1778 SkDEBUGFAILF("unrecognized scalar type '%s'", type->description().c_str());
1779 return NA;
1780 }
1781 case Type::TypeKind::kVector: {
1782 SpvId scalarTypeId = this->getType(type->componentType(), typeLayout, memoryLayout);
1783 return this->writeInstruction(
1784 SpvOpTypeVector,
1785 Words{Word::Result(), scalarTypeId, Word::Number(type->columns())},
1786 fConstantBuffer);
1787 }
1788 case Type::TypeKind::kMatrix: {
1789 SpvId vectorTypeId = this->getType(IndexExpression::IndexType(fContext, *type),
1790 typeLayout,
1791 memoryLayout);
1792 return this->writeInstruction(
1793 SpvOpTypeMatrix,
1794 Words{Word::Result(), vectorTypeId, Word::Number(type->columns())},
1795 fConstantBuffer);
1796 }
1797 case Type::TypeKind::kArray: {
1798 const MemoryLayout arrayMemoryLayout =
1799 fCaps.fForceStd430ArrayLayout
1800 ? MemoryLayout(MemoryLayout::Standard::k430)
1801 : memoryLayout;
1802
1803 if (!arrayMemoryLayout.isSupported(*type)) {
1804 fContext.fErrors->error(type->fPosition, "type '" + type->displayName() +
1805 "' is not permitted here");
1806 return NA;
1807 }
1808 size_t stride = arrayMemoryLayout.stride(*type);
1809 SpvId typeId = this->getType(type->componentType(), typeLayout, arrayMemoryLayout);
1810 SpvId result = NA;
1811 if (type->isUnsizedArray()) {
1812 result = this->writeInstruction(SpvOpTypeRuntimeArray,
1813 Words{Word::KeyedResult(stride), typeId},
1814 fConstantBuffer);
1815 } else {
1816 SpvId countId = this->writeLiteral(type->columns(), *fContext.fTypes.fInt);
1817 result = this->writeInstruction(SpvOpTypeArray,
1818 Words{Word::KeyedResult(stride), typeId, countId},
1819 fConstantBuffer);
1820 }
1821 this->writeInstruction(SpvOpDecorate,
1822 {result, SpvDecorationArrayStride, Word::Number(stride)},
1823 fDecorationBuffer);
1824 return result;
1825 }
1826 case Type::TypeKind::kStruct: {
1827 return this->writeStruct(*type, memoryLayout);
1828 }
1829 case Type::TypeKind::kSeparateSampler: {
1830 return this->writeInstruction(SpvOpTypeSampler, Words{Word::Result()}, fConstantBuffer);
1831 }
1832 case Type::TypeKind::kSampler: {
1833 if (SpvDimBuffer == type->dimensions()) {
1834 fCapabilities |= 1ULL << SpvCapabilitySampledBuffer;
1835 }
1836 SpvId imageTypeId = this->getType(type->textureType(), typeLayout, memoryLayout);
1837 return this->writeInstruction(SpvOpTypeSampledImage,
1838 Words{Word::Result(), imageTypeId},
1839 fConstantBuffer);
1840 }
1841 case Type::TypeKind::kTexture: {
1842 SpvId floatTypeId = this->getType(*fContext.fTypes.fFloat,
1843 kDefaultTypeLayout,
1844 memoryLayout);
1845
1846 bool sampled = (type->textureAccess() == Type::TextureAccess::kSample);
1847 SpvImageFormat format = (!sampled && type->dimensions() != SpvDimSubpassData)
1848 ? layout_flags_to_image_format(typeLayout.fFlags)
1849 : SpvImageFormatUnknown;
1850
1851 // Input attachments have a reserved ID.
1852 Word result = Word::Result();
1853 if (type->dimensions() == SpvDimSubpassData) {
1854 // Only a single input attachment is currently supported.
1855 SkASSERT(typeLayout.fInputAttachmentIndex == 0);
1856 result = Word::ReservedResult(spirv::kIdTypeImageSubpassData);
1857 }
1858
1859 return this->writeInstruction(SpvOpTypeImage,
1860 Words{result,
1861 floatTypeId,
1862 Word::Number(type->dimensions()),
1863 Word::Number(type->isDepth()),
1864 Word::Number(type->isArrayedTexture()),
1865 Word::Number(type->isMultisampled()),
1866 Word::Number(sampled ? 1 : 2),
1867 format},
1868 fConstantBuffer);
1869 }
1870 case Type::TypeKind::kAtomic: {
1871 // SkSL currently only supports the atomicUint type.
1872 SkASSERT(type->matches(*fContext.fTypes.fAtomicUInt));
1873 // SPIR-V doesn't have atomic types. Rather, it allows atomic operations on primitive
1874 // types. The SPIR-V type of an SkSL atomic is simply the underlying type.
1875 return this->writeInstruction(SpvOpTypeInt,
1876 Words{Word::Result(), Word::Number(32), Word::Number(0)},
1877 fConstantBuffer);
1878 }
1879 default: {
1880 SkDEBUGFAILF("invalid type: %s", type->description().c_str());
1881 return NA;
1882 }
1883 }
1884 }
1885
1886 SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
1887 Words words;
1888 words.push_back(Word::Result());
1889 words.push_back(this->getType(function.returnType()));
1890 for (const Variable* parameter : function.parameters()) {
1891 bool paramIsSpecialized = fActiveSpecialization && fActiveSpecialization->find(parameter);
1892 if (fUseTextureSamplerPairs && parameter->type().isSampler()) {
1893 words.push_back(this->getFunctionParameterType(parameter->type().textureType(),
1894 parameter->layout()));
1895 if (!paramIsSpecialized) {
1896 words.push_back(this->getFunctionParameterType(*fContext.fTypes.fSampler,
1897 kDefaultTypeLayout));
1898 }
1899 } else if (!paramIsSpecialized) {
1900 words.push_back(this->getFunctionParameterType(parameter->type(), parameter->layout()));
1901 }
1902 }
1903 return this->writeInstruction(SpvOpTypeFunction, words, fConstantBuffer);
1904 }
1905
1906 SpvId SPIRVCodeGenerator::getFunctionParameterType(const Type& parameterType,
1907 const Layout& parameterLayout) {
1908 // glslang treats all function arguments as pointers whether they need to be or
1909 // not. I was initially puzzled by this until I ran bizarre failures with certain
1910 // patterns of function calls and control constructs, as exemplified by this minimal
1911 // failure case:
1912 //
1913 // void sphere(float x) {
1914 // }
1915 //
1916 // void map() {
1917 // sphere(1.0);
1918 // }
1919 //
1920 // void main() {
1921 // for (int i = 0; i < 1; i++) {
1922 // map();
1923 // }
1924 // }
1925 //
1926 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
1927 // crashes. Making it take a float* and storing the argument in a temporary variable,
1928 // as glslang does, fixes it.
1929 //
1930 // The consensus among shader compiler authors seems to be that GPU driver generally don't
1931 // handle value-based parameters consistently. It is highly likely that they fit their
1932 // implementations to conform to glslang. We take care to do so ourselves.
1933 //
1934 // Our implementation first stores every parameter value into a function storage-class pointer
1935 // before calling a function. The exception is for opaque handle types (samplers and textures)
1936 // which must be stored in a pointer with UniformConstant storage-class. This prevents
1937 // unnecessary temporaries (becuase opaque handles are always rooted in a pointer variable),
1938 // matches glslang's behavior, and translates into WGSL more easily when targeting Dawn.
1939 StorageClass storageClass;
1940 if (parameterType.typeKind() == Type::TypeKind::kSampler ||
1941 parameterType.typeKind() == Type::TypeKind::kSeparateSampler ||
1942 parameterType.typeKind() == Type::TypeKind::kTexture) {
1943 storageClass = StorageClass::kUniformConstant;
1944 } else {
1945 storageClass = StorageClass::kFunction;
1946 }
1947 return this->getPointerType(parameterType,
1948 parameterLayout,
1949 this->memoryLayoutForStorageClass(storageClass),
1950 storageClass);
1951 }
1952
1953 SpvId SPIRVCodeGenerator::getPointerType(const Type& type, StorageClass storageClass) {
1954 return this->getPointerType(type,
1955 kDefaultTypeLayout,
1956 this->memoryLayoutForStorageClass(storageClass),
1957 storageClass);
1958 }
1959
1960 SpvId SPIRVCodeGenerator::getPointerType(const Type& type,
1961 const Layout& typeLayout,
1962 const MemoryLayout& memoryLayout,
1963 StorageClass storageClass) {
1964 return this->writeInstruction(SpvOpTypePointer,
1965 Words{Word::Result(),
1966 Word::Number(get_storage_class_spv_id(storageClass)),
1967 this->getType(type, typeLayout, memoryLayout)},
1968 fConstantBuffer);
1969 }
1970
1971 SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, SPIRVBlob& out) {
1972 switch (expr.kind()) {
1973 case Expression::Kind::kBinary:
1974 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
1975 case Expression::Kind::kConstructorArrayCast:
1976 return this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), out);
1977 case Expression::Kind::kConstructorArray:
1978 case Expression::Kind::kConstructorStruct:
1979 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
1980 case Expression::Kind::kConstructorDiagonalMatrix:
1981 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
1982 case Expression::Kind::kConstructorMatrixResize:
1983 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
1984 case Expression::Kind::kConstructorScalarCast:
1985 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
1986 case Expression::Kind::kConstructorSplat:
1987 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
1988 case Expression::Kind::kConstructorCompound:
1989 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
1990 case Expression::Kind::kConstructorCompoundCast:
1991 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
1992 case Expression::Kind::kEmpty:
1993 return NA;
1994 case Expression::Kind::kFieldAccess:
1995 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
1996 case Expression::Kind::kFunctionCall:
1997 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
1998 case Expression::Kind::kLiteral:
1999 return this->writeLiteral(expr.as<Literal>());
2000 case Expression::Kind::kPrefix:
2001 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
2002 case Expression::Kind::kPostfix:
2003 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
2004 case Expression::Kind::kSwizzle:
2005 return this->writeSwizzle(expr.as<Swizzle>(), out);
2006 case Expression::Kind::kVariableReference:
2007 return this->writeVariableReference(expr.as<VariableReference>(), out);
2008 case Expression::Kind::kTernary:
2009 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
2010 case Expression::Kind::kIndex:
2011 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
2012 case Expression::Kind::kSetting:
2013 return this->writeExpression(*expr.as<Setting>().toLiteral(fCaps), out);
2014 default:
2015 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
2016 break;
2017 }
2018 return NA;
2019 }
2020
2021 SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, SPIRVBlob& out) {
2022 const FunctionDeclaration& function = c.function();
2023 Intrinsic intrinsic = this->getIntrinsic(function.intrinsicKind());
2024 if (intrinsic.opKind == kInvalid_IntrinsicOpcodeKind) {
2025 fContext.fErrors->error(c.fPosition, "unsupported intrinsic '" + function.description() +
2026 "'");
2027 return NA;
2028 }
2029 const ExpressionArray& arguments = c.arguments();
2030 int32_t intrinsicId = intrinsic.floatOp;
2031 if (!arguments.empty()) {
2032 const Type& type = arguments[0]->type();
2033 if (intrinsic.opKind == kSpecial_IntrinsicOpcodeKind) {
2034 // Keep the default float op.
2035 } else {
2036 intrinsicId = pick_by_type(type, intrinsic.floatOp, intrinsic.signedOp,
2037 intrinsic.unsignedOp, intrinsic.boolOp);
2038 }
2039 }
2040 switch (intrinsic.opKind) {
2041 case kGLSL_STD_450_IntrinsicOpcodeKind: {
2042 SpvId result = this->nextId(&c.type());
2043 TArray<SpvId> argumentIds;
2044 argumentIds.reserve_exact(arguments.size());
2045 std::vector<TempVar> tempVars;
2046 for (int i = 0; i < arguments.size(); i++) {
2047 this->writeFunctionCallArgument(argumentIds, c, i, &tempVars,
2048 /*specializedParams=*/nullptr, out);
2049 }
2050 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
2051 this->writeWord(this->getType(c.type()), out);
2052 this->writeWord(result, out);
2053 this->writeWord(fGLSLExtendedInstructions, out);
2054 this->writeWord(intrinsicId, out);
2055 for (SpvId id : argumentIds) {
2056 this->writeWord(id, out);
2057 }
2058 this->copyBackTempVars(tempVars, out);
2059 return result;
2060 }
2061 case kSPIRV_IntrinsicOpcodeKind: {
2062 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
2063 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
2064 intrinsicId = SpvOpFMul;
2065 }
2066 SpvId result = this->nextId(&c.type());
2067 TArray<SpvId> argumentIds;
2068 argumentIds.reserve_exact(arguments.size());
2069 std::vector<TempVar> tempVars;
2070 for (int i = 0; i < arguments.size(); i++) {
2071 this->writeFunctionCallArgument(argumentIds, c, i, &tempVars,
2072 /*specializedParams=*/nullptr, out);
2073 }
2074 if (!c.type().isVoid()) {
2075 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
2076 this->writeWord(this->getType(c.type()), out);
2077 this->writeWord(result, out);
2078 } else {
2079 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
2080 }
2081 for (SpvId id : argumentIds) {
2082 this->writeWord(id, out);
2083 }
2084 this->copyBackTempVars(tempVars, out);
2085 return result;
2086 }
2087 case kSpecial_IntrinsicOpcodeKind:
2088 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
2089 default:
2090 fContext.fErrors->error(c.fPosition, "unsupported intrinsic '" +
2091 function.description() + "'");
2092 return NA;
2093 }
2094 }
2095
2096 SpvId SPIRVCodeGenerator::vectorize(const Expression& arg, int vectorSize, SPIRVBlob& out) {
2097 SkASSERT(vectorSize >= 1 && vectorSize <= 4);
2098 const Type& argType = arg.type();
2099 if (argType.isScalar() && vectorSize > 1) {
2100 SpvId argID = this->writeExpression(arg, out);
2101 return this->splat(argType.toCompound(fContext, vectorSize, /*rows=*/1), argID, out);
2102 }
2103
2104 SkASSERT(vectorSize == argType.columns());
2105 return this->writeExpression(arg, out);
2106 }
2107
2108 TArray<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, SPIRVBlob& out) {
2109 int vectorSize = 1;
2110 for (const auto& a : args) {
2111 if (a->type().isVector()) {
2112 if (vectorSize > 1) {
2113 SkASSERT(a->type().columns() == vectorSize);
2114 } else {
2115 vectorSize = a->type().columns();
2116 }
2117 }
2118 }
2119 TArray<SpvId> result;
2120 result.reserve_exact(args.size());
2121 for (const auto& arg : args) {
2122 result.push_back(this->vectorize(*arg, vectorSize, out));
2123 }
2124 return result;
2125 }
2126
2127 void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
2128 SpvId signedInst, SpvId unsignedInst,
2129 const TArray<SpvId>& args,
2130 SPIRVBlob& out) {
2131 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
2132 this->writeWord(this->getType(type), out);
2133 this->writeWord(id, out);
2134 this->writeWord(fGLSLExtendedInstructions, out);
2135 this->writeWord(pick_by_type(type, floatInst, signedInst, unsignedInst, NA), out);
2136 for (SpvId a : args) {
2137 this->writeWord(a, out);
2138 }
2139 }
2140
2141 SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
2142 SPIRVBlob& out) {
2143 const ExpressionArray& arguments = c.arguments();
2144 const Type& callType = c.type();
2145 // Note: MatrixCompMult creates its own result ID, avoid calling nextId as it could generate a
2146 // RelaxedPrecision decoration on an ID that would never be used.
2147 SpvId result = 0;
2148 switch (kind) {
2149 case kAtan_SpecialIntrinsic: {
2150 result = this->nextId(&callType);
2151 STArray<2, SpvId> argumentIds;
2152 for (const std::unique_ptr<Expression>& arg : arguments) {
2153 argumentIds.push_back(this->writeExpression(*arg, out));
2154 }
2155 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
2156 this->writeWord(this->getType(callType), out);
2157 this->writeWord(result, out);
2158 this->writeWord(fGLSLExtendedInstructions, out);
2159 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
2160 for (SpvId id : argumentIds) {
2161 this->writeWord(id, out);
2162 }
2163 break;
2164 }
2165 case kSampledImage_SpecialIntrinsic: {
2166 result = this->nextId(&callType);
2167 SkASSERT(arguments.size() == 2);
2168 SpvId img = this->writeExpression(*arguments[0], out);
2169 SpvId sampler = this->writeExpression(*arguments[1], out);
2170 this->writeInstruction(SpvOpSampledImage,
2171 this->getType(callType),
2172 result,
2173 img,
2174 sampler,
2175 out);
2176 break;
2177 }
2178 case kSubpassLoad_SpecialIntrinsic: {
2179 result = this->nextId(&callType);
2180 SpvId img = this->writeExpression(*arguments[0], out);
2181 ExpressionArray args;
2182 args.reserve_exact(2);
2183 args.push_back(Literal::MakeInt(fContext, Position(), /*value=*/0));
2184 args.push_back(Literal::MakeInt(fContext, Position(), /*value=*/0));
2185 ConstructorCompound ctor(Position(), *fContext.fTypes.fInt2, std::move(args));
2186 SpvId coords = this->writeExpression(ctor, out);
2187 if (arguments.size() == 1) {
2188 this->writeInstruction(SpvOpImageRead,
2189 this->getType(callType),
2190 result,
2191 img,
2192 coords,
2193 out);
2194 } else {
2195 SkASSERT(arguments.size() == 2);
2196 SpvId sample = this->writeExpression(*arguments[1], out);
2197 this->writeInstruction(SpvOpImageRead,
2198 this->getType(callType),
2199 result,
2200 img,
2201 coords,
2202 SpvImageOperandsSampleMask,
2203 sample,
2204 out);
2205 }
2206 break;
2207 }
2208 case kTexture_SpecialIntrinsic: {
2209 SpvOp_ op = SpvOpImageSampleImplicitLod;
2210 const Type& arg1Type = arguments[1]->type();
2211 switch (arguments[0]->type().dimensions()) {
2212 case SpvDim1D:
2213 if (arg1Type.matches(*fContext.fTypes.fFloat2)) {
2214 op = SpvOpImageSampleProjImplicitLod;
2215 } else {
2216 SkASSERT(arg1Type.matches(*fContext.fTypes.fFloat));
2217 }
2218 break;
2219 case SpvDim2D:
2220 if (arg1Type.matches(*fContext.fTypes.fFloat3)) {
2221 op = SpvOpImageSampleProjImplicitLod;
2222 } else {
2223 SkASSERT(arg1Type.matches(*fContext.fTypes.fFloat2));
2224 }
2225 break;
2226 case SpvDim3D:
2227 if (arg1Type.matches(*fContext.fTypes.fFloat4)) {
2228 op = SpvOpImageSampleProjImplicitLod;
2229 } else {
2230 SkASSERT(arg1Type.matches(*fContext.fTypes.fFloat3));
2231 }
2232 break;
2233 case SpvDimCube: // fall through
2234 case SpvDimRect: // fall through
2235 case SpvDimBuffer: // fall through
2236 case SpvDimSubpassData:
2237 break;
2238 }
2239 // Work around Nvidia bug when RelaxedPrecision is applied to
2240 // YCbCr texture sampling op. (skbug.com/421927604)
2241 const bool avoidRelaxedPrecision = op == SpvOpImageSampleImplicitLod &&
2242 fCaps.fCannotUseRelaxedPrecisionOnImageSample;
2243 result = this->nextId(avoidRelaxedPrecision ? nullptr : &callType);
2244
2245 SpvId type = this->getType(callType);
2246 SpvId sampler = this->writeExpression(*arguments[0], out);
2247 SpvId uv = this->writeExpression(*arguments[1], out);
2248 if (arguments.size() == 3) {
2249 this->writeInstruction(op, type, result, sampler, uv,
2250 SpvImageOperandsBiasMask,
2251 this->writeExpression(*arguments[2], out),
2252 out);
2253 } else {
2254 SkASSERT(arguments.size() == 2);
2255 if (fProgram.fConfig->fSettings.fSharpenTextures) {
2256 SpvId lodBias = this->writeLiteral(kSharpenTexturesBias,
2257 *fContext.fTypes.fFloat);
2258 this->writeInstruction(op, type, result, sampler, uv,
2259 SpvImageOperandsBiasMask, lodBias, out);
2260 } else {
2261 this->writeInstruction(op, type, result, sampler, uv,
2262 out);
2263 }
2264 }
2265 break;
2266 }
2267 case kTextureGrad_SpecialIntrinsic: {
2268 result = this->nextId(&callType);
2269 SpvOp_ op = SpvOpImageSampleExplicitLod;
2270 SkASSERT(arguments.size() == 4);
2271 SkASSERT(arguments[0]->type().dimensions() == SpvDim2D);
2272 SkASSERT(arguments[1]->type().matches(*fContext.fTypes.fFloat2));
2273 SkASSERT(arguments[2]->type().matches(*fContext.fTypes.fFloat2));
2274 SkASSERT(arguments[3]->type().matches(*fContext.fTypes.fFloat2));
2275 SpvId type = this->getType(callType);
2276 SpvId sampler = this->writeExpression(*arguments[0], out);
2277 SpvId uv = this->writeExpression(*arguments[1], out);
2278 SpvId dPdx = this->writeExpression(*arguments[2], out);
2279 SpvId dPdy = this->writeExpression(*arguments[3], out);
2280 this->writeInstruction(op, type, result, sampler, uv, SpvImageOperandsGradMask,
2281 dPdx, dPdy, out);
2282 break;
2283 }
2284 case kTextureLod_SpecialIntrinsic: {
2285 result = this->nextId(&callType);
2286 SpvOp_ op = SpvOpImageSampleExplicitLod;
2287 SkASSERT(arguments.size() == 3);
2288 SkASSERT(arguments[0]->type().dimensions() == SpvDim2D);
2289 SkASSERT(arguments[2]->type().matches(*fContext.fTypes.fFloat));
2290 const Type& arg1Type = arguments[1]->type();
2291 if (arg1Type.matches(*fContext.fTypes.fFloat3)) {
2292 op = SpvOpImageSampleProjExplicitLod;
2293 } else {
2294 SkASSERT(arg1Type.matches(*fContext.fTypes.fFloat2));
2295 }
2296 SpvId type = this->getType(callType);
2297 SpvId sampler = this->writeExpression(*arguments[0], out);
2298 SpvId uv = this->writeExpression(*arguments[1], out);
2299 this->writeInstruction(op, type, result, sampler, uv,
2300 SpvImageOperandsLodMask,
2301 this->writeExpression(*arguments[2], out),
2302 out);
2303 break;
2304 }
2305 case kTextureRead_SpecialIntrinsic: {
2306 result = this->nextId(&callType);
2307 SkASSERT(arguments[0]->type().dimensions() == SpvDim2D);
2308 SkASSERT(arguments[1]->type().matches(*fContext.fTypes.fUInt2));
2309
2310 SpvId type = this->getType(callType);
2311 SpvId image = this->writeExpression(*arguments[0], out);
2312 SpvId coord = this->writeExpression(*arguments[1], out);
2313
2314 const Type& arg0Type = arguments[0]->type();
2315 SkASSERT(arg0Type.typeKind() == Type::TypeKind::kTexture);
2316
2317 switch (arg0Type.textureAccess()) {
2318 case Type::TextureAccess::kSample:
2319 this->writeInstruction(SpvOpImageFetch, type, result, image, coord,
2320 SpvImageOperandsLodMask,
2321 this->writeOpConstant(*fContext.fTypes.fInt, 0),
2322 out);
2323 break;
2324 case Type::TextureAccess::kRead:
2325 case Type::TextureAccess::kReadWrite:
2326 this->writeInstruction(SpvOpImageRead, type, result, image, coord, out);
2327 break;
2328 case Type::TextureAccess::kWrite:
2329 default:
2330 SkDEBUGFAIL("'textureRead' called on writeonly texture type");
2331 break;
2332 }
2333
2334 break;
2335 }
2336 case kTextureWrite_SpecialIntrinsic: {
2337 SkASSERT(arguments[0]->type().dimensions() == SpvDim2D);
2338 SkASSERT(arguments[1]->type().matches(*fContext.fTypes.fUInt2));
2339 SkASSERT(arguments[2]->type().matches(*fContext.fTypes.fHalf4));
2340 SkASSERT(!callType.hasPrecision());
2341
2342 SpvId image = this->writeExpression(*arguments[0], out);
2343 SpvId coord = this->writeExpression(*arguments[1], out);
2344 SpvId texel = this->writeExpression(*arguments[2], out);
2345
2346 this->writeInstruction(SpvOpImageWrite, image, coord, texel, out);
2347 break;
2348 }
2349 case kTextureWidth_SpecialIntrinsic:
2350 case kTextureHeight_SpecialIntrinsic: {
2351 result = this->nextId(&callType);
2352 SkASSERT(arguments[0]->type().dimensions() == SpvDim2D);
2353 fCapabilities |= 1ULL << SpvCapabilityImageQuery;
2354
2355 SpvId dimsType = this->getType(*fContext.fTypes.fUInt2);
2356 SpvId dims = this->nextId(&callType);
2357 SpvId image = this->writeExpression(*arguments[0], out);
2358 this->writeInstruction(SpvOpImageQuerySize, dimsType, dims, image, out);
2359
2360 SpvId type = this->getType(callType);
2361 int32_t index = (kind == kTextureWidth_SpecialIntrinsic) ? 0 : 1;
2362 this->writeInstruction(SpvOpCompositeExtract, type, result, dims, index, out);
2363 break;
2364 }
2365 case kMod_SpecialIntrinsic: {
2366 result = this->nextId(&callType);
2367 TArray<SpvId> args = this->vectorize(arguments, out);
2368 SkASSERT(args.size() == 2);
2369 const Type& operandType = arguments[0]->type();
2370 SpvOp_ op = pick_by_type(operandType, SpvOpFMod, SpvOpSMod, SpvOpUMod, SpvOpUndef);
2371 SkASSERT(op != SpvOpUndef);
2372 this->writeOpCode(op, 5, out);
2373 this->writeWord(this->getType(operandType), out);
2374 this->writeWord(result, out);
2375 this->writeWord(args[0], out);
2376 this->writeWord(args[1], out);
2377 break;
2378 }
2379 case kDFdy_SpecialIntrinsic: {
2380 result = this->nextId(&callType);
2381 SpvId fn = this->writeExpression(*arguments[0], out);
2382 this->writeOpCode(SpvOpDPdy, 4, out);
2383 this->writeWord(this->getType(callType), out);
2384 this->writeWord(result, out);
2385 this->writeWord(fn, out);
2386 if (!fProgram.fConfig->fSettings.fForceNoRTFlip) {
2387 this->addRTFlipUniform(c.fPosition);
2388 ComponentArray componentArray;
2389 for (int index = 0; index < callType.columns(); ++index) {
2390 componentArray.push_back(SwizzleComponent::Y);
2391 }
2392 SpvId rtFlipY = this->writeSwizzle(*this->identifier(SKSL_RTFLIP_NAME),
2393 componentArray, out);
2394 SpvId flipped = this->nextId(&callType);
2395 this->writeInstruction(SpvOpFMul, this->getType(callType), flipped, result,
2396 rtFlipY, out);
2397 result = flipped;
2398 }
2399 break;
2400 }
2401 case kClamp_SpecialIntrinsic: {
2402 result = this->nextId(&callType);
2403 TArray<SpvId> args = this->vectorize(arguments, out);
2404 SkASSERT(args.size() == 3);
2405 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
2406 GLSLstd450UClamp, args, out);
2407 break;
2408 }
2409 case kMax_SpecialIntrinsic: {
2410 result = this->nextId(&callType);
2411 TArray<SpvId> args = this->vectorize(arguments, out);
2412 SkASSERT(args.size() == 2);
2413 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
2414 GLSLstd450UMax, args, out);
2415 break;
2416 }
2417 case kMin_SpecialIntrinsic: {
2418 result = this->nextId(&callType);
2419 TArray<SpvId> args = this->vectorize(arguments, out);
2420 SkASSERT(args.size() == 2);
2421 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
2422 GLSLstd450UMin, args, out);
2423 break;
2424 }
2425 case kMix_SpecialIntrinsic: {
2426 result = this->nextId(&callType);
2427 TArray<SpvId> args = this->vectorize(arguments, out);
2428 SkASSERT(args.size() == 3);
2429 if (arguments[2]->type().componentType().isBoolean()) {
2430 // Use OpSelect to implement Boolean mix().
2431 SpvId falseId = this->writeExpression(*arguments[0], out);
2432 SpvId trueId = this->writeExpression(*arguments[1], out);
2433 SpvId conditionId = this->writeExpression(*arguments[2], out);
2434 this->writeInstruction(SpvOpSelect, this->getType(arguments[0]->type()), result,
2435 conditionId, trueId, falseId, out);
2436 } else {
2437 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
2438 SpvOpUndef, args, out);
2439 }
2440 break;
2441 }
2442 case kSaturate_SpecialIntrinsic: {
2443 result = this->nextId(&callType);
2444 SkASSERT(arguments.size() == 1);
2445 int width = arguments[0]->type().columns();
2446 STArray<3, SpvId> spvArgs{
2447 this->vectorize(*arguments[0], width, out),
2448 this->vectorize(*Literal::MakeFloat(fContext, Position(), /*value=*/0), width, out),
2449 this->vectorize(*Literal::MakeFloat(fContext, Position(), /*value=*/1), width, out),
2450 };
2451 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
2452 GLSLstd450UClamp, spvArgs, out);
2453 break;
2454 }
2455 case kSmoothStep_SpecialIntrinsic: {
2456 result = this->nextId(&callType);
2457 TArray<SpvId> args = this->vectorize(arguments, out);
2458 SkASSERT(args.size() == 3);
2459 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
2460 SpvOpUndef, args, out);
2461 break;
2462 }
2463 case kStep_SpecialIntrinsic: {
2464 result = this->nextId(&callType);
2465 TArray<SpvId> args = this->vectorize(arguments, out);
2466 SkASSERT(args.size() == 2);
2467 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
2468 SpvOpUndef, args, out);
2469 break;
2470 }
2471 case kMatrixCompMult_SpecialIntrinsic: {
2472 SkASSERT(arguments.size() == 2);
2473 SpvId lhs = this->writeExpression(*arguments[0], out);
2474 SpvId rhs = this->writeExpression(*arguments[1], out);
2475 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
2476 break;
2477 }
2478 case kAtomicAdd_SpecialIntrinsic:
2479 case kAtomicLoad_SpecialIntrinsic:
2480 case kAtomicStore_SpecialIntrinsic:
2481 result = this->nextId(&callType);
2482 result = this->writeAtomicIntrinsic(c, kind, result, out);
2483 break;
2484 case kStorageBarrier_SpecialIntrinsic:
2485 case kWorkgroupBarrier_SpecialIntrinsic: {
2486 // Both barrier types operate in the workgroup execution and memory scope and differ
2487 // only in memory semantics. storageBarrier() is not a device-scope barrier.
2488 SkASSERT(!callType.hasPrecision());
2489 SpvId scopeId =
2490 this->writeOpConstant(*fContext.fTypes.fUInt, (int32_t)SpvScopeWorkgroup);
2491 int32_t memSemMask = (kind == kStorageBarrier_SpecialIntrinsic)
2492 ? SpvMemorySemanticsAcquireReleaseMask |
2493 SpvMemorySemanticsUniformMemoryMask
2494 : SpvMemorySemanticsAcquireReleaseMask |
2495 SpvMemorySemanticsWorkgroupMemoryMask;
2496 SpvId memorySemanticsId = this->writeOpConstant(*fContext.fTypes.fUInt, memSemMask);
2497 this->writeInstruction(SpvOpControlBarrier,
2498 scopeId, // execution scope
2499 scopeId, // memory scope
2500 memorySemanticsId,
2501 out);
2502 break;
2503 }
2504 default:
2505 SkUNREACHABLE;
2506 }
2507 return result;
2508 }
2509
2510 SpvId SPIRVCodeGenerator::writeAtomicIntrinsic(const FunctionCall& c,
2511 SpecialIntrinsic kind,
2512 SpvId resultId,
2513 SPIRVBlob& out) {
2514 const ExpressionArray& arguments = c.arguments();
2515 SkASSERT(!arguments.empty());
2516
2517 std::unique_ptr<LValue> atomicPtr = this->getLValue(*arguments[0], out);
2518 SpvId atomicPtrId = atomicPtr->getPointer();
2519 if (atomicPtrId == NA) {
2520 SkDEBUGFAILF("atomic intrinsic expected a pointer argument: %s",
2521 arguments[0]->description().c_str());
2522 return NA;
2523 }
2524
2525 SpvId memoryScopeId = NA;
2526 {
2527 // In SkSL, the atomicUint type can only be declared as a workgroup variable or SSBO block
2528 // member. The two memory scopes that these map to are "workgroup" and "device",
2529 // respectively.
2530 SpvScope memoryScope;
2531 switch (atomicPtr->storageClass()) {
2532 case StorageClass::kUniform:
2533 case StorageClass::kStorageBuffer:
2534 // We encode storage buffers in the uniform address space (with the BufferBlock
2535 // decorator).
2536 memoryScope = SpvScopeDevice;
2537 break;
2538 case StorageClass::kWorkgroup:
2539 memoryScope = SpvScopeWorkgroup;
2540 break;
2541 default:
2542 SkDEBUGFAILF("atomic argument has invalid storage class: %d",
2543 get_storage_class_spv_id(atomicPtr->storageClass()));
2544 return NA;
2545 }
2546 memoryScopeId = this->writeOpConstant(*fContext.fTypes.fUInt, (int32_t)memoryScope);
2547 }
2548
2549 SpvId relaxedMemoryOrderId =
2550 this->writeOpConstant(*fContext.fTypes.fUInt, (int32_t)SpvMemorySemanticsMaskNone);
2551
2552 switch (kind) {
2553 case kAtomicAdd_SpecialIntrinsic:
2554 SkASSERT(arguments.size() == 2);
2555 this->writeInstruction(SpvOpAtomicIAdd,
2556 this->getType(c.type()),
2557 resultId,
2558 atomicPtrId,
2559 memoryScopeId,
2560 relaxedMemoryOrderId,
2561 this->writeExpression(*arguments[1], out),
2562 out);
2563 break;
2564 case kAtomicLoad_SpecialIntrinsic:
2565 SkASSERT(arguments.size() == 1);
2566 this->writeInstruction(SpvOpAtomicLoad,
2567 this->getType(c.type()),
2568 resultId,
2569 atomicPtrId,
2570 memoryScopeId,
2571 relaxedMemoryOrderId,
2572 out);
2573 break;
2574 case kAtomicStore_SpecialIntrinsic:
2575 SkASSERT(arguments.size() == 2);
2576 this->writeInstruction(SpvOpAtomicStore,
2577 atomicPtrId,
2578 memoryScopeId,
2579 relaxedMemoryOrderId,
2580 this->writeExpression(*arguments[1], out),
2581 out);
2582 break;
2583 default:
2584 SkUNREACHABLE;
2585 }
2586
2587 return resultId;
2588 }
2589
2590 void SPIRVCodeGenerator::writeFunctionCallArgument(TArray<SpvId>& argumentList,
2591 const FunctionCall& call,
2592 int argIndex,
2593 std::vector<TempVar>* tempVars,
2594 const SkBitSet* specializedParams,
2595 SPIRVBlob& out) {
2596 const FunctionDeclaration& funcDecl = call.function();
2597 const Expression& arg = *call.arguments()[argIndex];
2598 const Variable* param = funcDecl.parameters()[argIndex];
2599 bool paramIsSpecialized = specializedParams && specializedParams->test(argIndex);
2600 ModifierFlags paramFlags = param->modifierFlags();
2601
2602 // Ignore the argument since it is specialized, if fUseTextureSamplerPairs is true and this
2603 // argument is a sampler, handle ignoring the sampler below when generating the texture and
2604 // sampler pair arguments.
2605 if (paramIsSpecialized && !(param->type().isSampler() && fUseTextureSamplerPairs)) {
2606 return;
2607 }
2608
2609 if (arg.is<VariableReference>() && (arg.type().typeKind() == Type::TypeKind::kSampler ||
2610 arg.type().typeKind() == Type::TypeKind::kSeparateSampler ||
2611 arg.type().typeKind() == Type::TypeKind::kTexture)) {
2612 // Opaque handle (sampler/texture) arguments are always declared as pointers but never
2613 // stored in intermediates when calling user-defined functions.
2614 //
2615 // The case for intrinsics (which take opaque arguments by value) is handled above just like
2616 // regular pointers.
2617 //
2618 // See getFunctionParameterType for further explanation.
2619 const Variable* var = arg.as<VariableReference>().variable();
2620
2621 // In Dawn-mode the texture and sampler arguments are forwarded to the helper function.
2622 if (fUseTextureSamplerPairs && var->type().isSampler()) {
2623 if (const auto* p = fSynthesizedSamplerMap.find(var)) {
2624 SpvId* img = fVariableMap.find((*p)->fTexture.get());
2625 SkASSERT(img);
2626
2627 argumentList.push_back(*img);
2628
2629 if (!paramIsSpecialized) {
2630 SpvId* sampler = fVariableMap.find((*p)->fSampler.get());
2631 SkASSERT(sampler);
2632 argumentList.push_back(*sampler);
2633 }
2634 return;
2635 }
2636 SkDEBUGFAIL("sampler missing from fSynthesizedSamplerMap");
2637 }
2638
2639 SpvId* entry = fVariableMap.find(var);
2640 SkASSERTF(entry, "%s", arg.description().c_str());
2641 argumentList.push_back(*entry);
2642 return;
2643 }
2644 SkASSERT(!paramIsSpecialized);
2645
2646 // ID of temporary variable that we will use to hold this argument, or 0 if it is being
2647 // passed directly
2648 SpvId tmpVar = NA;
2649 // if we need a temporary var to store this argument, this is the value to store in the var
2650 SpvId tmpValueId = NA;
2651
2652 if (is_out(paramFlags)) {
2653 std::unique_ptr<LValue> lv = this->getLValue(arg, out);
2654 // We handle out params with a temp var that we copy back to the original variable at the
2655 // end of the call. GLSL guarantees that the original variable will be unchanged until the
2656 // end of the call, and also that out params are written back to their original variables in
2657 // a specific order (left-to-right), so it's unsafe to pass a pointer to the original value.
2658 if (is_in(paramFlags)) {
2659 tmpValueId = lv->load(out);
2660 }
2661 tmpVar = this->nextId(&arg.type());
2662 tempVars->push_back(TempVar{tmpVar, &arg.type(), std::move(lv)});
2663 } else if (funcDecl.isIntrinsic()) {
2664 // Unlike user function calls, non-out intrinsic arguments don't need pointer parameters.
2665 argumentList.push_back(this->writeExpression(arg, out));
2666 return;
2667 } else {
2668 // We always use pointer parameters when calling user functions.
2669 // See getFunctionParameterType for further explanation.
2670 tmpValueId = this->writeExpression(arg, out);
2671 tmpVar = this->nextId(nullptr);
2672 }
2673 this->writeInstruction(SpvOpVariable,
2674 this->getPointerType(arg.type(), StorageClass::kFunction),
2675 tmpVar,
2676 SpvStorageClassFunction,
2677 fVariableBuffer);
2678 if (tmpValueId != NA) {
2679 this->writeOpStore(StorageClass::kFunction, tmpVar, tmpValueId, out);
2680 }
2681 argumentList.push_back(tmpVar);
2682 }
2683
2684 void SPIRVCodeGenerator::copyBackTempVars(const std::vector<TempVar>& tempVars, SPIRVBlob& out) {
2685 for (const TempVar& tempVar : tempVars) {
2686 SpvId load = this->nextId(tempVar.type);
2687 this->writeInstruction(SpvOpLoad, this->getType(*tempVar.type), load, tempVar.spvId, out);
2688 tempVar.lvalue->store(load, out);
2689 }
2690 }
2691
2692 SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, SPIRVBlob& out) {
2693 // Handle intrinsics.
2694 const FunctionDeclaration& function = c.function();
2695 if (function.isIntrinsic() && !function.definition()) {
2696 return this->writeIntrinsicCall(c, out);
2697 }
2698
2699 // Look up this function (or its specialization, if any) in our map of function SpvIds.
2700 Analysis::SpecializationIndex specializationIndex = Analysis::FindSpecializationIndexForCall(
2701 c, fSpecializationInfo, fActiveSpecializationIndex);
2702 SpvId* entry = fFunctionMap.find({&function, specializationIndex});
2703 if (!entry) {
2704 fContext.fErrors->error(c.fPosition, "function '" + function.description() +
2705 "' is not defined");
2706 return NA;
2707 }
2708
2709 // If we are calling a specialized function, we need to gather the specialized parameters
2710 // so we can remove them from the argument list.
2711 SkBitSet specializedParams =
2712 Analysis::FindSpecializedParametersForFunction(c.function(), fSpecializationInfo);
2713
2714 // Temp variables are used to write back out-parameters after the function call is complete.
2715 const ExpressionArray& arguments = c.arguments();
2716 std::vector<TempVar> tempVars;
2717 TArray<SpvId> argumentIds;
2718 argumentIds.reserve_exact(arguments.size());
2719 for (int i = 0; i < arguments.size(); i++) {
2720 this->writeFunctionCallArgument(argumentIds, c, i, &tempVars, &specializedParams, out);
2721 }
2722 SpvId result = this->nextId(nullptr);
2723 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t)argumentIds.size(), out);
2724 this->writeWord(this->getType(c.type()), out);
2725 this->writeWord(result, out);
2726 this->writeWord(*entry, out);
2727 for (SpvId id : argumentIds) {
2728 this->writeWord(id, out);
2729 }
2730 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
2731 this->copyBackTempVars(tempVars, out);
2732 return result;
2733 }
2734
2735 SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
2736 const Type& inputType,
2737 const Type& outputType,
2738 SPIRVBlob& out) {
2739 if (outputType.isFloat()) {
2740 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
2741 }
2742 if (outputType.isSigned()) {
2743 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
2744 }
2745 if (outputType.isUnsigned()) {
2746 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
2747 }
2748 if (outputType.isBoolean()) {
2749 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
2750 }
2751
2752 fContext.fErrors->error(Position(), "unsupported cast: " + inputType.description() + " to " +
2753 outputType.description());
2754 return inputExprId;
2755 }
2756
2757 SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
2758 const Type& outputType, SPIRVBlob& out) {
2759 // Casting a float to float is a no-op.
2760 if (inputType.isFloat()) {
2761 return inputId;
2762 }
2763
2764 // Given the input type, generate the appropriate instruction to cast to float.
2765 SpvId result = this->nextId(&outputType);
2766 if (inputType.isBoolean()) {
2767 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
2768 const SpvId oneID = this->writeLiteral(1.0, *fContext.fTypes.fFloat);
2769 const SpvId zeroID = this->writeLiteral(0.0, *fContext.fTypes.fFloat);
2770 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
2771 inputId, oneID, zeroID, out);
2772 } else if (inputType.isSigned()) {
2773 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
2774 } else if (inputType.isUnsigned()) {
2775 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
2776 } else {
2777 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
2778 return NA;
2779 }
2780 return result;
2781 }
2782
2783 SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
2784 const Type& outputType, SPIRVBlob& out) {
2785 // Casting a signed int to signed int is a no-op.
2786 if (inputType.isSigned()) {
2787 return inputId;
2788 }
2789
2790 // Given the input type, generate the appropriate instruction to cast to signed int.
2791 SpvId result = this->nextId(&outputType);
2792 if (inputType.isBoolean()) {
2793 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
2794 const SpvId oneID = this->writeLiteral(1.0, *fContext.fTypes.fInt);
2795 const SpvId zeroID = this->writeLiteral(0.0, *fContext.fTypes.fInt);
2796 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
2797 inputId, oneID, zeroID, out);
2798 } else if (inputType.isFloat()) {
2799 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
2800 } else if (inputType.isUnsigned()) {
2801 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
2802 } else {
2803 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
2804 inputType.description().c_str());
2805 return NA;
2806 }
2807 return result;
2808 }
2809
2810 SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
2811 const Type& outputType, SPIRVBlob& out) {
2812 // Casting an unsigned int to unsigned int is a no-op.
2813 if (inputType.isUnsigned()) {
2814 return inputId;
2815 }
2816
2817 // Given the input type, generate the appropriate instruction to cast to unsigned int.
2818 SpvId result = this->nextId(&outputType);
2819 if (inputType.isBoolean()) {
2820 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
2821 const SpvId oneID = this->writeLiteral(1.0, *fContext.fTypes.fUInt);
2822 const SpvId zeroID = this->writeLiteral(0.0, *fContext.fTypes.fUInt);
2823 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
2824 inputId, oneID, zeroID, out);
2825 } else if (inputType.isFloat()) {
2826 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
2827 } else if (inputType.isSigned()) {
2828 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
2829 } else {
2830 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
2831 inputType.description().c_str());
2832 return NA;
2833 }
2834 return result;
2835 }
2836
2837 SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
2838 const Type& outputType, SPIRVBlob& out) {
2839 // Casting a bool to bool is a no-op.
2840 if (inputType.isBoolean()) {
2841 return inputId;
2842 }
2843
2844 // Given the input type, generate the appropriate instruction to cast to bool.
2845 SpvId result = this->nextId(nullptr);
2846 if (inputType.isSigned()) {
2847 // Synthesize a boolean result by comparing the input against a signed zero literal.
2848 const SpvId zeroID = this->writeLiteral(0.0, *fContext.fTypes.fInt);
2849 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
2850 inputId, zeroID, out);
2851 } else if (inputType.isUnsigned()) {
2852 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
2853 const SpvId zeroID = this->writeLiteral(0.0, *fContext.fTypes.fUInt);
2854 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
2855 inputId, zeroID, out);
2856 } else if (inputType.isFloat()) {
2857 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
2858 const SpvId zeroID = this->writeLiteral(0.0, *fContext.fTypes.fFloat);
2859 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
2860 inputId, zeroID, out);
2861 } else {
2862 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
2863 return NA;
2864 }
2865 return result;
2866 }
2867
2868 SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
2869 SPIRVBlob& out) {
2870 SkASSERT(srcType.isMatrix());
2871 SkASSERT(dstType.isMatrix());
2872 SkASSERT(srcType.componentType().matches(dstType.componentType()));
2873 const Type& srcColumnType = srcType.componentType().toCompound(fContext, srcType.rows(), 1);
2874 const Type& dstColumnType = dstType.componentType().toCompound(fContext, dstType.rows(), 1);
2875 SkASSERT(dstType.componentType().isFloat());
2876 SpvId dstColumnTypeId = this->getType(dstColumnType);
2877 const SpvId zeroId = this->writeLiteral(0.0, dstType.componentType());
2878 const SpvId oneId = this->writeLiteral(1.0, dstType.componentType());
2879
2880 STArray<4, SpvId> columns;
2881 for (int i = 0; i < dstType.columns(); i++) {
2882 if (i < srcType.columns()) {
2883 // we're still inside the src matrix, copy the column
2884 SpvId srcColumn = this->writeOpCompositeExtract(srcColumnType, src, i, out);
2885 SpvId dstColumn;
2886 if (srcType.rows() == dstType.rows()) {
2887 // columns are equal size, don't need to do anything
2888 dstColumn = srcColumn;
2889 }
2890 else if (dstType.rows() > srcType.rows()) {
2891 // dst column is bigger, need to zero-pad it
2892 STArray<4, SpvId> values;
2893 values.push_back(srcColumn);
2894 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
2895 values.push_back((i == j) ? oneId : zeroId);
2896 }
2897 dstColumn = this->writeOpCompositeConstruct(dstColumnType, values, out);
2898 }
2899 else {
2900 // dst column is smaller, need to swizzle the src column
2901 dstColumn = this->nextId(&dstType);
2902 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
2903 this->writeWord(dstColumnTypeId, out);
2904 this->writeWord(dstColumn, out);
2905 this->writeWord(srcColumn, out);
2906 this->writeWord(srcColumn, out);
2907 for (int j = 0; j < dstType.rows(); j++) {
2908 this->writeWord(j, out);
2909 }
2910 }
2911 columns.push_back(dstColumn);
2912 } else {
2913 // we're past the end of the src matrix, need to synthesize an identity-matrix column
2914 STArray<4, SpvId> values;
2915 for (int j = 0; j < dstType.rows(); ++j) {
2916 values.push_back((i == j) ? oneId : zeroId);
2917 }
2918 columns.push_back(this->writeOpCompositeConstruct(dstColumnType, values, out));
2919 }
2920 }
2921
2922 return this->writeOpCompositeConstruct(dstType, columns, out);
2923 }
2924
2925 void SPIRVCodeGenerator::addColumnEntry(const Type& columnType,
2926 TArray<SpvId>* currentColumn,
2927 TArray<SpvId>* columnIds,
2928 int rows,
2929 SpvId entry,
2930 SPIRVBlob& out) {
2931 SkASSERT(currentColumn->size() < rows);
2932 currentColumn->push_back(entry);
2933 if (currentColumn->size() == rows) {
2934 // Synthesize this column into a vector.
2935 SpvId columnId = this->writeOpCompositeConstruct(columnType, *currentColumn, out);
2936 columnIds->push_back(columnId);
2937 currentColumn->clear();
2938 }
2939 }
2940
2941 SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, SPIRVBlob& out) {
2942 const Type& type = c.type();
2943 SkASSERT(type.isMatrix());
2944 SkASSERT(!c.arguments().empty());
2945 const Type& arg0Type = c.arguments()[0]->type();
2946 // go ahead and write the arguments so we don't try to write new instructions in the middle of
2947 // an instruction
2948 STArray<16, SpvId> arguments;
2949 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
2950 arguments.push_back(this->writeExpression(*arg, out));
2951 }
2952
2953 if (arguments.size() == 1 && arg0Type.isVector()) {
2954 // Special-case handling of float4 -> mat2x2.
2955 SkASSERT(type.rows() == 2 && type.columns() == 2);
2956 SkASSERT(arg0Type.columns() == 4);
2957 SpvId v[4];
2958 for (int i = 0; i < 4; ++i) {
2959 v[i] = this->writeOpCompositeExtract(type.componentType(), arguments[0], i, out);
2960 }
2961 const Type& vecType = type.columnType(fContext);
2962 SpvId v0v1 = this->writeOpCompositeConstruct(vecType, {v[0], v[1]}, out);
2963 SpvId v2v3 = this->writeOpCompositeConstruct(vecType, {v[2], v[3]}, out);
2964 return this->writeOpCompositeConstruct(type, {v0v1, v2v3}, out);
2965 }
2966
2967 int rows = type.rows();
2968 const Type& columnType = type.columnType(fContext);
2969 // SpvIds of completed columns of the matrix.
2970 STArray<4, SpvId> columnIds;
2971 // SpvIds of scalars we have written to the current column so far.
2972 STArray<4, SpvId> currentColumn;
2973 for (int i = 0; i < arguments.size(); i++) {
2974 const Type& argType = c.arguments()[i]->type();
2975 if (currentColumn.empty() && argType.isVector() && argType.columns() == rows) {
2976 // This vector is a complete matrix column by itself and can be used as-is.
2977 columnIds.push_back(arguments[i]);
2978 } else if (argType.columns() == 1) {
2979 // This argument is a lone scalar and can be added to the current column as-is.
2980 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, arguments[i], out);
2981 } else {
2982 // This argument needs to be decomposed into its constituent scalars.
2983 for (int j = 0; j < argType.columns(); ++j) {
2984 SpvId swizzle = this->writeOpCompositeExtract(argType.componentType(),
2985 arguments[i], j, out);
2986 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, swizzle, out);
2987 }
2988 }
2989 }
2990 SkASSERT(columnIds.size() == type.columns());
2991 return this->writeOpCompositeConstruct(type, columnIds, out);
2992 }
2993
2994 SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
2995 SPIRVBlob& out) {
2996 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
2997 : this->writeVectorConstructor(c, out);
2998 }
2999
3000 SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, SPIRVBlob& out) {
3001 const Type& type = c.type();
3002 const Type& componentType = type.componentType();
3003 SkASSERT(type.isVector());
3004
3005 STArray<4, SpvId> arguments;
3006 for (int i = 0; i < c.arguments().size(); i++) {
3007 const Type& argType = c.arguments()[i]->type();
3008 SkASSERT(componentType.numberKind() == argType.componentType().numberKind());
3009
3010 SpvId arg = this->writeExpression(*c.arguments()[i], out);
3011 if (argType.isMatrix()) {
3012 // CompositeConstruct cannot take a 2x2 matrix as an input, so we need to extract out
3013 // each scalar separately.
3014 SkASSERT(argType.rows() == 2);
3015 SkASSERT(argType.columns() == 2);
3016 for (int j = 0; j < 4; ++j) {
3017 arguments.push_back(this->writeOpCompositeExtract(componentType, arg,
3018 j / 2, j % 2, out));
3019 }
3020 } else if (argType.isVector()) {
3021 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
3022 // vector arguments at all, so we always extract each vector component and pass them
3023 // into OpCompositeConstruct individually.
3024 for (int j = 0; j < argType.columns(); j++) {
3025 arguments.push_back(this->writeOpCompositeExtract(componentType, arg, j, out));
3026 }
3027 } else {
3028 arguments.push_back(arg);
3029 }
3030 }
3031
3032 return this->writeOpCompositeConstruct(type, arguments, out);
3033 }
3034
3035 SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, SPIRVBlob& out) {
3036 // Write the splat argument as a scalar, then splat it.
3037 SpvId argument = this->writeExpression(*c.argument(), out);
3038 return this->splat(c.type(), argument, out);
3039 }
3040
3041 SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, SPIRVBlob& out) {
3042 SkASSERT(c.type().isArray() || c.type().isStruct());
3043 auto ctorArgs = c.argumentSpan();
3044
3045 STArray<4, SpvId> arguments;
3046 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
3047 arguments.push_back(this->writeExpression(*arg, out));
3048 }
3049
3050 return this->writeOpCompositeConstruct(c.type(), arguments, out);
3051 }
3052
3053 SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
3054 SPIRVBlob& out) {
3055 const Type& type = c.type();
3056 if (type.componentType().numberKind() == c.argument()->type().componentType().numberKind()) {
3057 return this->writeExpression(*c.argument(), out);
3058 }
3059
3060 const Expression& ctorExpr = *c.argument();
3061 SpvId expressionId = this->writeExpression(ctorExpr, out);
3062 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
3063 }
3064
3065 SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
3066 SPIRVBlob& out) {
3067 const Type& ctorType = c.type();
3068 const Type& argType = c.argument()->type();
3069 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
3070
3071 // Write the composite that we are casting. If the actual type matches, we are done.
3072 SpvId compositeId = this->writeExpression(*c.argument(), out);
3073 if (ctorType.componentType().numberKind() == argType.componentType().numberKind()) {
3074 return compositeId;
3075 }
3076
3077 // writeMatrixCopy can cast matrices to a different type.
3078 if (ctorType.isMatrix()) {
3079 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
3080 }
3081
3082 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
3083 // components and convert each one manually.
3084 const Type& srcType = argType.componentType();
3085 const Type& dstType = ctorType.componentType();
3086
3087 STArray<4, SpvId> arguments;
3088 for (int index = 0; index < argType.columns(); ++index) {
3089 SpvId componentId = this->writeOpCompositeExtract(srcType, compositeId, index, out);
3090 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
3091 }
3092
3093 return this->writeOpCompositeConstruct(ctorType, arguments, out);
3094 }
3095
3096 SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
3097 SPIRVBlob& out) {
3098 const Type& type = c.type();
3099 SkASSERT(type.isMatrix());
3100 SkASSERT(c.argument()->type().isScalar());
3101
3102 // Write out the scalar argument.
3103 SpvId diagonal = this->writeExpression(*c.argument(), out);
3104
3105 // Build the diagonal matrix.
3106 SpvId zeroId = this->writeLiteral(0.0, *fContext.fTypes.fFloat);
3107
3108 const Type& vecType = type.columnType(fContext);
3109 STArray<4, SpvId> columnIds;
3110 STArray<4, SpvId> arguments;
3111 arguments.resize(type.rows());
3112 for (int column = 0; column < type.columns(); column++) {
3113 for (int row = 0; row < type.rows(); row++) {
3114 arguments[row] = (row == column) ? diagonal : zeroId;
3115 }
3116 columnIds.push_back(this->writeOpCompositeConstruct(vecType, arguments, out));
3117 }
3118 return this->writeOpCompositeConstruct(type, columnIds, out);
3119 }
3120
3121 SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
3122 SPIRVBlob& out) {
3123 // Write the input matrix.
3124 SpvId argument = this->writeExpression(*c.argument(), out);
3125
3126 // Use matrix-copy to resize the input matrix to its new size.
3127 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
3128 }
3129
3130 static StorageClass get_storage_class_for_global_variable(
3131 const Variable& var, StorageClass fallbackStorageClass) {
3132 SkASSERT(var.storage() == Variable::Storage::kGlobal);
3133
3134 if (var.type().typeKind() == Type::TypeKind::kSampler ||
3135 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
3136 var.type().typeKind() == Type::TypeKind::kTexture) {
3137 return StorageClass::kUniformConstant;
3138 }
3139
3140 const Layout& layout = var.layout();
3141 ModifierFlags flags = var.modifierFlags();
3142 if (flags & ModifierFlag::kIn) {
3143 SkASSERT(!(layout.fFlags & LayoutFlag::kPushConstant));
3144 return StorageClass::kInput;
3145 }
3146 if (flags & ModifierFlag::kOut) {
3147 SkASSERT(!(layout.fFlags & LayoutFlag::kPushConstant));
3148 return StorageClass::kOutput;
3149 }
3150 if (flags.isUniform()) {
3151 if (layout.fFlags & LayoutFlag::kPushConstant) {
3152 return StorageClass::kPushConstant;
3153 }
3154 return StorageClass::kUniform;
3155 }
3156 if (flags.isBuffer()) {
3157 return StorageClass::kStorageBuffer;
3158 }
3159 if (flags.isWorkgroup()) {
3160 return StorageClass::kWorkgroup;
3161 }
3162 return fallbackStorageClass;
3163 }
3164
3165 StorageClass SPIRVCodeGenerator::getStorageClass(const Expression& expr) {
3166 switch (expr.kind()) {
3167 case Expression::Kind::kVariableReference: {
3168 const Variable& var = *expr.as<VariableReference>().variable();
3169 if (fActiveSpecialization) {
3170 const Expression** specializedExpr = fActiveSpecialization->find(&var);
3171 if (specializedExpr && (*specializedExpr)->is<FieldAccess>()) {
3172 return this->getStorageClass(**specializedExpr);
3173 }
3174 }
3175 if (var.storage() != Variable::Storage::kGlobal) {
3176 return StorageClass::kFunction;
3177 }
3178 return get_storage_class_for_global_variable(var, StorageClass::kPrivate);
3179 }
3180 case Expression::Kind::kFieldAccess:
3181 return this->getStorageClass(*expr.as<FieldAccess>().base());
3182 case Expression::Kind::kIndex:
3183 return this->getStorageClass(*expr.as<IndexExpression>().base());
3184 default:
3185 return StorageClass::kFunction;
3186 }
3187 }
3188
3189 TArray<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, SPIRVBlob& out) {
3190 switch (expr.kind()) {
3191 case Expression::Kind::kIndex: {
3192 const IndexExpression& indexExpr = expr.as<IndexExpression>();
3193 if (indexExpr.base()->is<Swizzle>()) {
3194 // Access chains don't directly support dynamically indexing into a swizzle, but we
3195 // can rewrite them into a supported form.
3196 return this->getAccessChain(*Transform::RewriteIndexedSwizzle(fContext, indexExpr),
3197 out);
3198 }
3199 // All other index-expressions can be represented as typical access chains.
3200 TArray<SpvId> chain = this->getAccessChain(*indexExpr.base(), out);
3201 chain.push_back(this->writeExpression(*indexExpr.index(), out));
3202 return chain;
3203 }
3204 case Expression::Kind::kFieldAccess: {
3205 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
3206 TArray<SpvId> chain = this->getAccessChain(*fieldExpr.base(), out);
3207 chain.push_back(this->writeLiteral(fieldExpr.fieldIndex(), *fContext.fTypes.fInt));
3208 return chain;
3209 }
3210 case Expression::Kind::kVariableReference: {
3211 if (fActiveSpecialization) {
3212 const Expression** specializedFieldIndex =
3213 fActiveSpecialization->find(expr.as<VariableReference>().variable());
3214 if (specializedFieldIndex && (*specializedFieldIndex)->is<FieldAccess>()) {
3215 return this->getAccessChain(**specializedFieldIndex, out);
3216 }
3217 }
3218 [[fallthrough]];
3219 }
3220 default: {
3221 SpvId id = this->getLValue(expr, out)->getPointer();
3222 SkASSERT(id != NA);
3223 return TArray<SpvId>{id};
3224 }
3225 }
3226 SkUNREACHABLE;
3227 }
3228
3229 class PointerLValue : public SPIRVCodeGenerator::LValue {
3230 public:
3231 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
3232 SPIRVCodeGenerator::Precision precision, StorageClass storageClass)
3233 : fGen(gen)
3234 , fPointer(pointer)
3235 , fIsMemoryObject(isMemoryObject)
3236 , fType(type)
3237 , fPrecision(precision)
3238 , fStorageClass(storageClass) {}
3239
3240 SpvId getPointer() override {
3241 return fPointer;
3242 }
3243
3244 bool isMemoryObjectPointer() const override {
3245 return fIsMemoryObject;
3246 }
3247
3248 StorageClass storageClass() const override {
3249 return fStorageClass;
3250 }
3251
3252 SpvId load(SPIRVBlob& out) override {
3253 return fGen.writeOpLoad(fType, fPrecision, fPointer, out);
3254 }
3255
3256 void store(SpvId value, SPIRVBlob& out) override {
3257 if (!fIsMemoryObject) {
3258 // We are going to write into an access chain; this could represent one component of a
3259 // vector, or one element of an array. This has the potential to invalidate other,
3260 // *unknown* elements of our store cache. (e.g. if the store cache holds `%50 = myVec4`,
3261 // and we store `%60 = myVec4.z`, this invalidates the cached value for %50.) To avoid
3262 // relying on stale data, reset the store cache entirely when this happens.
3263 fGen.fStoreCache.reset();
3264 }
3265
3266 fGen.writeOpStore(fStorageClass, fPointer, value, out);
3267 }
3268
3269 private:
3270 SPIRVCodeGenerator& fGen;
3271 const SpvId fPointer;
3272 const bool fIsMemoryObject;
3273 const SpvId fType;
3274 const SPIRVCodeGenerator::Precision fPrecision;
3275 const StorageClass fStorageClass;
3276 };
3277
3278 class SwizzleLValue : public SPIRVCodeGenerator::LValue {
3279 public:
3280 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
3281 const Type& baseType, const Type& swizzleType, StorageClass storageClass)
3282 : fGen(gen)
3283 , fVecPointer(vecPointer)
3284 , fComponents(components)
3285 , fBaseType(&baseType)
3286 , fSwizzleType(&swizzleType)
3287 , fStorageClass(storageClass) {}
3288
3289 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
3290 ComponentArray updatedSwizzle;
3291 for (int8_t component : components) {
3292 if (component < 0 || component >= fComponents.size()) {
3293 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
3294 return false;
3295 }
3296 updatedSwizzle.push_back(fComponents[component]);
3297 }
3298 fComponents = updatedSwizzle;
3299 fSwizzleType = &newType;
3300 return true;
3301 }
3302
3303 StorageClass storageClass() const override {
3304 return fStorageClass;
3305 }
3306
3307 SpvId load(SPIRVBlob& out) override {
3308 SpvId base = fGen.nextId(fBaseType);
3309 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
3310 SpvId result = fGen.nextId(fBaseType);
3311 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
3312 fGen.writeWord(fGen.getType(*fSwizzleType), out);
3313 fGen.writeWord(result, out);
3314 fGen.writeWord(base, out);
3315 fGen.writeWord(base, out);
3316 for (int component : fComponents) {
3317 fGen.writeWord(component, out);
3318 }
3319 return result;
3320 }
3321
3322 void store(SpvId value, SPIRVBlob& out) override {
3323 // use OpVectorShuffle to mix and match the vector components. We effectively create
3324 // a virtual vector out of the concatenation of the left and right vectors, and then
3325 // select components from this virtual vector to make the result vector. For
3326 // instance, given:
3327 // float3L = ...;
3328 // float3R = ...;
3329 // L.xz = R.xy;
3330 // we end up with the virtual vector (L.x, L.y, L.z, R.x, R.y, R.z). Then we want
3331 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
3332 // (3, 1, 4).
3333 SpvId base = fGen.nextId(fBaseType);
3334 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
3335 SpvId shuffle = fGen.nextId(fBaseType);
3336 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
3337 fGen.writeWord(fGen.getType(*fBaseType), out);
3338 fGen.writeWord(shuffle, out);
3339 fGen.writeWord(base, out);
3340 fGen.writeWord(value, out);
3341 for (int i = 0; i < fBaseType->columns(); i++) {
3342 // current offset into the virtual vector, defaults to pulling the unmodified
3343 // value from the left side
3344 int offset = i;
3345 // check to see if we are writing this component
3346 for (int j = 0; j < fComponents.size(); j++) {
3347 if (fComponents[j] == i) {
3348 // we're writing to this component, so adjust the offset to pull from
3349 // the correct component of the right side instead of preserving the
3350 // value from the left
3351 offset = (int) (j + fBaseType->columns());
3352 break;
3353 }
3354 }
3355 fGen.writeWord(offset, out);
3356 }
3357 fGen.writeOpStore(fStorageClass, fVecPointer, shuffle, out);
3358 }
3359
3360 private:
3361 SPIRVCodeGenerator& fGen;
3362 const SpvId fVecPointer;
3363 ComponentArray fComponents;
3364 const Type* fBaseType;
3365 const Type* fSwizzleType;
3366 const StorageClass fStorageClass;
3367 };
3368
3369 int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
3370 int* fieldIndex = fTopLevelUniformMap.find(&var);
3371 return fieldIndex ? *fieldIndex : -1;
3372 }
3373
3374 std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
3375 SPIRVBlob& out) {
3376 const Type& type = expr.type();
3377 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
3378 switch (expr.kind()) {
3379 case Expression::Kind::kVariableReference: {
3380 const Variable& var = *expr.as<VariableReference>().variable();
3381 int uniformIdx = this->findUniformFieldIndex(var);
3382 if (uniformIdx >= 0) {
3383 // Access uniforms via an AccessChain into the uniform-buffer struct.
3384 SpvId memberId = this->nextId(nullptr);
3385 SpvId typeId = this->getPointerType(type, StorageClass::kUniform);
3386 SpvId uniformIdxId = this->writeLiteral((double)uniformIdx, *fContext.fTypes.fInt);
3387 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
3388 uniformIdxId, out);
3389 return std::make_unique<PointerLValue>(
3390 *this,
3391 memberId,
3392 /*isMemoryObjectPointer=*/true,
3393 this->getType(type, kDefaultTypeLayout, this->memoryLayoutForVariable(var)),
3394 precision,
3395 StorageClass::kUniform);
3396 }
3397
3398 SpvId* entry = fVariableMap.find(&var);
3399 SkASSERTF(entry, "%s", expr.description().c_str());
3400
3401 if (var.layout().fBuiltin == SK_SAMPLEMASKIN_BUILTIN ||
3402 var.layout().fBuiltin == SK_SAMPLEMASK_BUILTIN) {
3403 // Access sk_SampleMask and sk_SampleMaskIn via an array access, since Vulkan
3404 // represents sample masks as an array of uints.
3405 StorageClass storageClass =
3406 get_storage_class_for_global_variable(var, StorageClass::kPrivate);
3407 SkASSERT(storageClass != StorageClass::kPrivate);
3408 SkASSERT(type.matches(*fContext.fTypes.fUInt));
3409
3410 SpvId accessId = this->nextId(nullptr);
3411 SpvId typeId = this->getPointerType(type, storageClass);
3412 SpvId indexId = this->writeLiteral(0.0, *fContext.fTypes.fInt);
3413 this->writeInstruction(SpvOpAccessChain, typeId, accessId, *entry, indexId, out);
3414 return std::make_unique<PointerLValue>(*this,
3415 accessId,
3416 /*isMemoryObjectPointer=*/true,
3417 this->getType(type),
3418 precision,
3419 storageClass);
3420 }
3421
3422 SpvId typeId = this->getType(type, var.layout(), this->memoryLayoutForVariable(var));
3423 return std::make_unique<PointerLValue>(*this, *entry,
3424 /*isMemoryObjectPointer=*/true,
3425 typeId, precision, this->getStorageClass(expr));
3426 }
3427 case Expression::Kind::kIndex: // fall through
3428 case Expression::Kind::kFieldAccess: {
3429 TArray<SpvId> chain = this->getAccessChain(expr, out);
3430 SpvId member = this->nextId(nullptr);
3431 StorageClass storageClass = this->getStorageClass(expr);
3432 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
3433 this->writeWord(this->getPointerType(type, storageClass), out);
3434 this->writeWord(member, out);
3435 for (SpvId idx : chain) {
3436 this->writeWord(idx, out);
3437 }
3438 return std::make_unique<PointerLValue>(
3439 *this,
3440 member,
3441 /*isMemoryObjectPointer=*/false,
3442 this->getType(type,
3443 kDefaultTypeLayout,
3444 this->memoryLayoutForStorageClass(storageClass)),
3445 precision,
3446 storageClass);
3447 }
3448 case Expression::Kind::kSwizzle: {
3449 const Swizzle& swizzle = expr.as<Swizzle>();
3450 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
3451 if (lvalue->applySwizzle(swizzle.components(), type)) {
3452 return lvalue;
3453 }
3454 SpvId base = lvalue->getPointer();
3455 if (base == NA) {
3456 fContext.fErrors->error(swizzle.fPosition,
3457 "unable to retrieve lvalue from swizzle");
3458 }
3459 StorageClass storageClass = this->getStorageClass(*swizzle.base());
3460 if (swizzle.components().size() == 1) {
3461 SpvId member = this->nextId(nullptr);
3462 SpvId typeId = this->getPointerType(type, storageClass);
3463 SpvId indexId = this->writeLiteral(swizzle.components()[0], *fContext.fTypes.fInt);
3464 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
3465 return std::make_unique<PointerLValue>(*this, member,
3466 /*isMemoryObjectPointer=*/false,
3467 this->getType(type),
3468 precision, storageClass);
3469 } else {
3470 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
3471 swizzle.base()->type(), type, storageClass);
3472 }
3473 }
3474 default: {
3475 // expr isn't actually an lvalue, create a placeholder variable for it. This case
3476 // happens due to the need to store values in temporary variables during function
3477 // calls (see comments in getFunctionParameterType); erroneous uses of rvalues as
3478 // lvalues should have been caught before code generation.
3479 //
3480 // This is with the exception of opaque handle types (textures/samplers) which are
3481 // always defined as UniformConstant pointers and don't need to be explicitly stored
3482 // into a temporary (which is handled explicitly in writeFunctionCallArgument).
3483 SpvId result = this->nextId(nullptr);
3484 SpvId pointerType = this->getPointerType(type, StorageClass::kFunction);
3485 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
3486 fVariableBuffer);
3487 this->writeOpStore(StorageClass::kFunction, result, this->writeExpression(expr, out),
3488 out);
3489 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
3490 this->getType(type), precision,
3491 StorageClass::kFunction);
3492 }
3493 }
3494 }
3495
3496 std::unique_ptr<Expression> SPIRVCodeGenerator::identifier(std::string_view name) {
3497 std::unique_ptr<Expression> expr =
3498 fProgram.fSymbols->instantiateSymbolRef(fContext, name, Position());
3499 return expr ? std::move(expr)
3500 : Poison::Make(Position(), fContext);
3501 }
3502
3503 SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, SPIRVBlob& out) {
3504 const Variable* variable = ref.variable();
3505 switch (variable->layout().fBuiltin) {
3506 case DEVICE_FRAGCOORDS_BUILTIN: {
3507 // Down below, we rewrite raw references to sk_FragCoord with expressions that reference
3508 // DEVICE_FRAGCOORDS_BUILTIN. This is a fake variable that means we need to directly
3509 // access the fragcoord; do so now.
3510 return this->getLValue(*this->identifier("sk_FragCoord"), out)->load(out);
3511 }
3512 case DEVICE_CLOCKWISE_BUILTIN: {
3513 // Down below, we rewrite raw references to sk_Clockwise with expressions that reference
3514 // DEVICE_CLOCKWISE_BUILTIN. This is a fake variable that means we need to directly
3515 // access front facing; do so now.
3516 return this->getLValue(*this->identifier("sk_Clockwise"), out)->load(out);
3517 }
3518 case SK_SECONDARYFRAGCOLOR_BUILTIN: {
3519 if (fCaps.fDualSourceBlendingSupport) {
3520 return this->getLValue(*this->identifier("sk_SecondaryFragColor"), out)->load(out);
3521 } else {
3522 fContext.fErrors->error(ref.position(), "'sk_SecondaryFragColor' not supported");
3523 return NA;
3524 }
3525 }
3526 case SK_FRAGCOORD_BUILTIN: {
3527 if (fProgram.fConfig->fSettings.fForceNoRTFlip) {
3528 return this->getLValue(*this->identifier("sk_FragCoord"), out)->load(out);
3529 }
3530
3531 // Handle inserting use of uniform to flip y when referencing sk_FragCoord.
3532 this->addRTFlipUniform(ref.fPosition);
3533 // Use sk_RTAdjust to compute the flipped coordinate
3534 // Use a uniform to flip the Y coordinate. The new expression will be written in
3535 // terms of $device_FragCoords, which is a fake variable that means "access the
3536 // underlying fragcoords directly without flipping it".
3537 static constexpr char DEVICE_COORDS_NAME[] = "$device_FragCoords";
3538 if (!fProgram.fSymbols->find(DEVICE_COORDS_NAME)) {
3539 AutoAttachPoolToThread attach(fProgram.fPool.get());
3540 Layout layout;
3541 layout.fBuiltin = DEVICE_FRAGCOORDS_BUILTIN;
3542 auto coordsVar = Variable::Make(/*pos=*/Position(),
3543 /*modifiersPosition=*/Position(),
3544 layout,
3545 ModifierFlag::kNone,
3546 fContext.fTypes.fFloat4.get(),
3547 DEVICE_COORDS_NAME,
3548 /*mangledName=*/"",
3549 /*builtin=*/true,
3550 Variable::Storage::kGlobal);
3551 fProgram.fSymbols->add(fContext, std::move(coordsVar));
3552 }
3553 std::unique_ptr<Expression> deviceCoord = this->identifier(DEVICE_COORDS_NAME);
3554 std::unique_ptr<Expression> rtFlip = this->identifier(SKSL_RTFLIP_NAME);
3555 SpvId rtFlipX = this->writeSwizzle(*rtFlip, {SwizzleComponent::X}, out);
3556 SpvId rtFlipY = this->writeSwizzle(*rtFlip, {SwizzleComponent::Y}, out);
3557 SpvId deviceCoordX = this->writeSwizzle(*deviceCoord, {SwizzleComponent::X}, out);
3558 SpvId deviceCoordY = this->writeSwizzle(*deviceCoord, {SwizzleComponent::Y}, out);
3559 SpvId deviceCoordZW = this->writeSwizzle(*deviceCoord, {SwizzleComponent::Z,
3560 SwizzleComponent::W}, out);
3561 // Compute `flippedY = u_RTFlip.y * $device_FragCoords.y`.
3562 SpvId flippedY = this->writeBinaryExpression(
3563 *fContext.fTypes.fFloat, rtFlipY, OperatorKind::STAR,
3564 *fContext.fTypes.fFloat, deviceCoordY,
3565 *fContext.fTypes.fFloat, out);
3566
3567 // Compute `flippedY = u_RTFlip.x + flippedY`.
3568 flippedY = this->writeBinaryExpression(
3569 *fContext.fTypes.fFloat, rtFlipX, OperatorKind::PLUS,
3570 *fContext.fTypes.fFloat, flippedY,
3571 *fContext.fTypes.fFloat, out);
3572
3573 // Return `float4(deviceCoord.x, flippedY, deviceCoord.zw)`.
3574 return this->writeOpCompositeConstruct(*fContext.fTypes.fFloat4,
3575 {deviceCoordX, flippedY, deviceCoordZW},
3576 out);
3577 }
3578 case SK_CLOCKWISE_BUILTIN: {
3579 if (fProgram.fConfig->fSettings.fForceNoRTFlip) {
3580 return this->getLValue(*this->identifier("sk_Clockwise"), out)->load(out);
3581 }
3582
3583 // Apply RTFlip to sk_Clockwise.
3584 this->addRTFlipUniform(ref.fPosition);
3585 // Use a uniform to flip the Y coordinate. The new expression will be written in
3586 // terms of $device_Clockwise, which is a fake variable that means "access the
3587 // underlying FrontFacing directly".
3588 static constexpr char DEVICE_CLOCKWISE_NAME[] = "$device_Clockwise";
3589 if (!fProgram.fSymbols->find(DEVICE_CLOCKWISE_NAME)) {
3590 AutoAttachPoolToThread attach(fProgram.fPool.get());
3591 Layout layout;
3592 layout.fBuiltin = DEVICE_CLOCKWISE_BUILTIN;
3593 auto clockwiseVar = Variable::Make(/*pos=*/Position(),
3594 /*modifiersPosition=*/Position(),
3595 layout,
3596 ModifierFlag::kNone,
3597 fContext.fTypes.fBool.get(),
3598 DEVICE_CLOCKWISE_NAME,
3599 /*mangledName=*/"",
3600 /*builtin=*/true,
3601 Variable::Storage::kGlobal);
3602 fProgram.fSymbols->add(fContext, std::move(clockwiseVar));
3603 }
3604 // FrontFacing in Vulkan is defined in terms of a top-down render target. In Skia,
3605 // we use the default convention of "counter-clockwise face is front".
3606
3607 // Compute `positiveRTFlip = (rtFlip.y > 0)`.
3608 std::unique_ptr<Expression> rtFlip = this->identifier(SKSL_RTFLIP_NAME);
3609 SpvId rtFlipY = this->writeSwizzle(*rtFlip, {SwizzleComponent::Y}, out);
3610 SpvId zero = this->writeLiteral(0.0, *fContext.fTypes.fFloat);
3611 SpvId positiveRTFlip = this->writeBinaryExpression(
3612 *fContext.fTypes.fFloat, rtFlipY, OperatorKind::GT,
3613 *fContext.fTypes.fFloat, zero,
3614 *fContext.fTypes.fBool, out);
3615
3616 // Compute `positiveRTFlip ^^ $device_Clockwise`.
3617 std::unique_ptr<Expression> deviceClockwise = this->identifier(DEVICE_CLOCKWISE_NAME);
3618 SpvId deviceClockwiseID = this->writeExpression(*deviceClockwise, out);
3619 return this->writeBinaryExpression(
3620 *fContext.fTypes.fBool, positiveRTFlip, OperatorKind::LOGICALXOR,
3621 *fContext.fTypes.fBool, deviceClockwiseID,
3622 *fContext.fTypes.fBool, out);
3623 }
3624 default: {
3625 // Constant-propagate variables that have a known compile-time value.
3626 if (const Expression* expr = ConstantFolder::GetConstantValueOrNull(ref)) {
3627 return this->writeExpression(*expr, out);
3628 }
3629
3630 // A reference to a sampler variable at global scope with synthesized texture/sampler
3631 // backing should construct a function-scope combined image-sampler from the synthesized
3632 // constituents. This is the case in which a sample intrinsic was invoked.
3633 //
3634 // Variable references to opaque handles (texture/sampler) that appear as the argument
3635 // of a user-defined function call are explicitly handled in writeFunctionCallArgument.
3636 if (fUseTextureSamplerPairs && variable->type().isSampler()) {
3637 if (const auto* p = fSynthesizedSamplerMap.find(variable)) {
3638 SpvId* imgPtr = fVariableMap.find((*p)->fTexture.get());
3639 SpvId* samplerPtr = fVariableMap.find((*p)->fSampler.get());
3640 SkASSERT(imgPtr);
3641 SkASSERT(samplerPtr);
3642
3643 SpvId img = this->writeOpLoad(this->getType((*p)->fTexture->type()),
3644 Precision::kDefault, *imgPtr, out);
3645 SpvId sampler = this->writeOpLoad(this->getType((*p)->fSampler->type()),
3646 Precision::kDefault,
3647 *samplerPtr,
3648 out);
3649 SpvId result = this->nextId(nullptr);
3650 this->writeInstruction(SpvOpSampledImage,
3651 this->getType(variable->type()),
3652 result,
3653 img,
3654 sampler,
3655 out);
3656 return result;
3657 }
3658 SkDEBUGFAIL("sampler missing from fSynthesizedSamplerMap");
3659 }
3660 return this->getLValue(ref, out)->load(out);
3661 }
3662 }
3663 }
3664
3665 SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, SPIRVBlob& out) {
3666 if (expr.base()->type().isVector()) {
3667 SpvId base = this->writeExpression(*expr.base(), out);
3668 SpvId index = this->writeExpression(*expr.index(), out);
3669 SpvId result = this->nextId(nullptr);
3670 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
3671 index, out);
3672 return result;
3673 }
3674 return getLValue(expr, out)->load(out);
3675 }
3676
3677 SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, SPIRVBlob& out) {
3678 return getLValue(f, out)->load(out);
3679 }
3680
3681 SpvId SPIRVCodeGenerator::writeSwizzle(const Expression& baseExpr,
3682 const ComponentArray& components,
3683 SPIRVBlob& out) {
3684 size_t count = components.size();
3685 const Type& type = baseExpr.type().componentType().toCompound(fContext, count, /*rows=*/1);
3686 SpvId base = this->writeExpression(baseExpr, out);
3687 if (count == 1) {
3688 return this->writeOpCompositeExtract(type, base, components[0], out);
3689 }
3690
3691 SpvId result = this->nextId(&type);
3692 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
3693 this->writeWord(this->getType(type), out);
3694 this->writeWord(result, out);
3695 this->writeWord(base, out);
3696 this->writeWord(base, out);
3697 for (int component : components) {
3698 this->writeWord(component, out);
3699 }
3700 return result;
3701 }
3702
3703 SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, SPIRVBlob& out) {
3704 return this->writeSwizzle(*swizzle.base(), swizzle.components(), out);
3705 }
3706
3707 SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType, const Type& operandType,
3708 SpvId lhs, SpvId rhs,
3709 bool writeComponentwiseIfMatrix,
3710 SpvOp_ ifFloat, SpvOp_ ifInt, SpvOp_ ifUInt,
3711 SpvOp_ ifBool, SPIRVBlob& out) {
3712 SpvOp_ op = pick_by_type(operandType, ifFloat, ifInt, ifUInt, ifBool);
3713 if (op == SpvOpUndef) {
3714 fContext.fErrors->error(operandType.fPosition,
3715 "unsupported operand for binary expression: " + operandType.description());
3716 return NA;
3717 }
3718 if (writeComponentwiseIfMatrix && operandType.isMatrix()) {
3719 return this->writeComponentwiseMatrixBinary(resultType, lhs, rhs, op, out);
3720 }
3721 SpvId result = this->nextId(&resultType);
3722 this->writeInstruction(op, this->getType(resultType), result, lhs, rhs, out);
3723 return result;
3724 }
3725
3726 SpvId SPIRVCodeGenerator::writeBinaryOperationComponentwiseIfMatrix(const Type& resultType,
3727 const Type& operandType,
3728 SpvId lhs, SpvId rhs,
3729 SpvOp_ ifFloat, SpvOp_ ifInt,
3730 SpvOp_ ifUInt, SpvOp_ ifBool,
3731 SPIRVBlob& out) {
3732 return this->writeBinaryOperation(resultType, operandType, lhs, rhs,
3733 /*writeComponentwiseIfMatrix=*/true,
3734 ifFloat, ifInt, ifUInt, ifBool, out);
3735 }
3736
3737 SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType, const Type& operandType,
3738 SpvId lhs, SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
3739 SpvOp_ ifUInt, SpvOp_ ifBool, SPIRVBlob& out) {
3740 return this->writeBinaryOperation(resultType, operandType, lhs, rhs,
3741 /*writeComponentwiseIfMatrix=*/false,
3742 ifFloat, ifInt, ifUInt, ifBool, out);
3743 }
3744
3745 SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
3746 SPIRVBlob& out) {
3747 if (operandType.isVector()) {
3748 SpvId result = this->nextId(nullptr);
3749 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
3750 return result;
3751 }
3752 return id;
3753 }
3754
3755 SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
3756 SpvOp_ floatOperator, SpvOp_ intOperator,
3757 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
3758 SPIRVBlob& out) {
3759 SpvOp_ compareOp = is_float(operandType) ? floatOperator : intOperator;
3760 SkASSERT(operandType.isMatrix());
3761 const Type& columnType = operandType.componentType().toCompound(fContext,
3762 operandType.rows(),
3763 1);
3764 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
3765 operandType.rows(),
3766 1));
3767 SpvId boolType = this->getType(*fContext.fTypes.fBool);
3768 SpvId result = 0;
3769 for (int i = 0; i < operandType.columns(); i++) {
3770 SpvId columnL = this->writeOpCompositeExtract(columnType, lhs, i, out);
3771 SpvId columnR = this->writeOpCompositeExtract(columnType, rhs, i, out);
3772 SpvId compare = this->nextId(&operandType);
3773 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
3774 SpvId merge = this->nextId(nullptr);
3775 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
3776 if (result != 0) {
3777 SpvId next = this->nextId(nullptr);
3778 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
3779 result = next;
3780 } else {
3781 result = merge;
3782 }
3783 }
3784 return result;
3785 }
3786
3787 SpvId SPIRVCodeGenerator::writeComponentwiseMatrixUnary(const Type& operandType,
3788 SpvId operand,
3789 SpvOp_ op,
3790 SPIRVBlob& out) {
3791 SkASSERT(operandType.isMatrix());
3792 const Type& columnType = operandType.columnType(fContext);
3793 SpvId columnTypeId = this->getType(columnType);
3794
3795 STArray<4, SpvId> columns;
3796 for (int i = 0; i < operandType.columns(); i++) {
3797 SpvId srcColumn = this->writeOpCompositeExtract(columnType, operand, i, out);
3798 SpvId dstColumn = this->nextId(&operandType);
3799 this->writeInstruction(op, columnTypeId, dstColumn, srcColumn, out);
3800 columns.push_back(dstColumn);
3801 }
3802
3803 return this->writeOpCompositeConstruct(operandType, columns, out);
3804 }
3805
3806 SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
3807 SpvId rhs, SpvOp_ op, SPIRVBlob& out) {
3808 SkASSERT(operandType.isMatrix());
3809 const Type& columnType = operandType.columnType(fContext);
3810 SpvId columnTypeId = this->getType(columnType);
3811
3812 STArray<4, SpvId> columns;
3813 for (int i = 0; i < operandType.columns(); i++) {
3814 SpvId columnL = this->writeOpCompositeExtract(columnType, lhs, i, out);
3815 SpvId columnR = this->writeOpCompositeExtract(columnType, rhs, i, out);
3816 columns.push_back(this->nextId(&operandType));
3817 this->writeInstruction(op, columnTypeId, columns[i], columnL, columnR, out);
3818 }
3819 return this->writeOpCompositeConstruct(operandType, columns, out);
3820 }
3821
3822 SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, SPIRVBlob& out) {
3823 SkASSERT(type.isFloat());
3824 SpvId one = this->writeLiteral(1.0, type);
3825 SpvId reciprocal = this->nextId(&type);
3826 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
3827 return reciprocal;
3828 }
3829
3830 SpvId SPIRVCodeGenerator::splat(const Type& type, SpvId id, SPIRVBlob& out) {
3831 if (type.isScalar()) {
3832 // Scalars require no additional work; we can return the passed-in ID as is.
3833 } else {
3834 SkASSERT(type.isVector() || type.isMatrix());
3835 bool isMatrix = type.isMatrix();
3836
3837 // Splat the input scalar across a vector.
3838 int vectorSize = (isMatrix ? type.rows() : type.columns());
3839 const Type& vectorType = type.componentType().toCompound(fContext, vectorSize, /*rows=*/1);
3840
3841 STArray<4, SpvId> values;
3842 values.push_back_n(/*n=*/vectorSize, /*t=*/id);
3843 id = this->writeOpCompositeConstruct(vectorType, values, out);
3844
3845 if (isMatrix) {
3846 // Splat the newly-synthesized vector into a matrix.
3847 STArray<4, SpvId> matArguments;
3848 matArguments.push_back_n(/*n=*/type.columns(), /*t=*/id);
3849 id = this->writeOpCompositeConstruct(type, matArguments, out);
3850 }
3851 }
3852
3853 return id;
3854 }
3855
3856 static bool types_match(const Type& a, const Type& b) {
3857 if (a.matches(b)) {
3858 return true;
3859 }
3860 return (a.typeKind() == b.typeKind()) &&
3861 (a.isScalar() || a.isVector() || a.isMatrix()) &&
3862 (a.columns() == b.columns() && a.rows() == b.rows()) &&
3863 a.componentType().numberKind() == b.componentType().numberKind();
3864 }
3865
3866 SpvId SPIRVCodeGenerator::writeDecomposedMatrixVectorMultiply(const Type& leftType,
3867 SpvId lhs,
3868 const Type& rightType,
3869 SpvId rhs,
3870 const Type& resultType,
3871 SPIRVBlob& out) {
3872 SpvId sum = NA;
3873 const Type& columnType = leftType.columnType(fContext);
3874 const Type& scalarType = rightType.componentType();
3875
3876 for (int n = 0; n < leftType.rows(); ++n) {
3877 // Extract mat[N] from the matrix.
3878 SpvId matN = this->writeOpCompositeExtract(columnType, lhs, n, out);
3879
3880 // Extract vec[N] from the vector.
3881 SpvId vecN = this->writeOpCompositeExtract(scalarType, rhs, n, out);
3882
3883 // Multiply them together.
3884 SpvId product = this->writeBinaryExpression(columnType, matN, OperatorKind::STAR,
3885 scalarType, vecN,
3886 columnType, out);
3887
3888 // Sum all the components together.
3889 if (sum == NA) {
3890 sum = product;
3891 } else {
3892 sum = this->writeBinaryExpression(columnType, sum, OperatorKind::PLUS,
3893 columnType, product,
3894 columnType, out);
3895 }
3896 }
3897
3898 return sum;
3899 }
3900
3901 SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
3902 const Type& rightType, SpvId rhs,
3903 const Type& resultType, SPIRVBlob& out) {
3904 // The comma operator ignores the type of the left-hand side entirely.
3905 if (op.kind() == Operator::Kind::COMMA) {
3906 return rhs;
3907 }
3908 // overall type we are operating on: float2, int, uint4...
3909 const Type* operandType;
3910 if (types_match(leftType, rightType)) {
3911 operandType = &leftType;
3912 } else {
3913 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
3914 // handling in SPIR-V
3915 if (leftType.isVector() && rightType.isNumber()) {
3916 if (resultType.componentType().isFloat()) {
3917 switch (op.kind()) {
3918 case Operator::Kind::SLASH: {
3919 rhs = this->writeReciprocal(rightType, rhs, out);
3920 [[fallthrough]];
3921 }
3922 case Operator::Kind::STAR: {
3923 SpvId result = this->nextId(&resultType);
3924 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
3925 result, lhs, rhs, out);
3926 return result;
3927 }
3928 default:
3929 break;
3930 }
3931 }
3932 // Vectorize the right-hand side.
3933 STArray<4, SpvId> arguments;
3934 arguments.push_back_n(/*n=*/leftType.columns(), /*t=*/rhs);
3935 rhs = this->writeOpCompositeConstruct(leftType, arguments, out);
3936 operandType = &leftType;
3937 } else if (rightType.isVector() && leftType.isNumber()) {
3938 if (resultType.componentType().isFloat()) {
3939 if (op.kind() == Operator::Kind::STAR) {
3940 SpvId result = this->nextId(&resultType);
3941 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
3942 result, rhs, lhs, out);
3943 return result;
3944 }
3945 }
3946 // Vectorize the left-hand side.
3947 STArray<4, SpvId> arguments;
3948 arguments.push_back_n(/*n=*/rightType.columns(), /*t=*/lhs);
3949 lhs = this->writeOpCompositeConstruct(rightType, arguments, out);
3950 operandType = &rightType;
3951 } else if (leftType.isMatrix()) {
3952 if (op.kind() == Operator::Kind::STAR) {
3953 // When the rewriteMatrixVectorMultiply bit is set, we rewrite medium-precision
3954 // matrix * vector multiplication as (mat[0]*vec[0] + ... + mat[N]*vec[N]).
3955 if (fCaps.fRewriteMatrixVectorMultiply &&
3956 rightType.isVector() &&
3957 !resultType.highPrecision()) {
3958 return this->writeDecomposedMatrixVectorMultiply(leftType, lhs, rightType, rhs,
3959 resultType, out);
3960 }
3961
3962 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
3963 SpvOp_ spvop;
3964 if (rightType.isMatrix()) {
3965 spvop = SpvOpMatrixTimesMatrix;
3966 } else if (rightType.isVector()) {
3967 spvop = SpvOpMatrixTimesVector;
3968 } else {
3969 SkASSERT(rightType.isScalar());
3970 spvop = SpvOpMatrixTimesScalar;
3971 }
3972 SpvId result = this->nextId(&resultType);
3973 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
3974 return result;
3975 } else {
3976 // Matrix-op-vector is not supported in GLSL/SkSL for non-multiplication ops; we
3977 // expect to have a scalar here.
3978 SkASSERT(rightType.isScalar());
3979
3980 // Splat rhs across an entire matrix so we can reuse the matrix-op-matrix path.
3981 SpvId rhsMatrix = this->splat(leftType, rhs, out);
3982
3983 // Perform this operation as matrix-op-matrix.
3984 return this->writeBinaryExpression(leftType, lhs, op, leftType, rhsMatrix,
3985 resultType, out);
3986 }
3987 } else if (rightType.isMatrix()) {
3988 if (op.kind() == Operator::Kind::STAR) {
3989 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
3990 SpvId result = this->nextId(&resultType);
3991 if (leftType.isVector()) {
3992 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType),
3993 result, lhs, rhs, out);
3994 } else {
3995 SkASSERT(leftType.isScalar());
3996 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType),
3997 result, rhs, lhs, out);
3998 }
3999 return result;
4000 } else {
4001 // Vector-op-matrix is not supported in GLSL/SkSL for non-multiplication ops; we
4002 // expect to have a scalar here.
4003 SkASSERT(leftType.isScalar());
4004
4005 // Splat lhs across an entire matrix so we can reuse the matrix-op-matrix path.
4006 SpvId lhsMatrix = this->splat(rightType, lhs, out);
4007
4008 // Perform this operation as matrix-op-matrix.
4009 return this->writeBinaryExpression(rightType, lhsMatrix, op, rightType, rhs,
4010 resultType, out);
4011 }
4012 } else {
4013 fContext.fErrors->error(leftType.fPosition, "unsupported mixed-type expression");
4014 return NA;
4015 }
4016 }
4017
4018 switch (op.kind()) {
4019 case Operator::Kind::EQEQ: {
4020 if (operandType->isMatrix()) {
4021 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
4022 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
4023 }
4024 if (operandType->isStruct()) {
4025 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
4026 }
4027 if (operandType->isArray()) {
4028 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
4029 }
4030 SkASSERT(resultType.isBoolean());
4031 const Type* tmpType;
4032 if (operandType->isVector()) {
4033 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
4034 operandType->columns(),
4035 operandType->rows());
4036 } else {
4037 tmpType = &resultType;
4038 }
4039 if (lhs == rhs) {
4040 // This ignores the effects of NaN.
4041 return this->writeOpConstantTrue(*fContext.fTypes.fBool);
4042 }
4043 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
4044 SpvOpFOrdEqual, SpvOpIEqual,
4045 SpvOpIEqual, SpvOpLogicalEqual, out),
4046 *operandType, SpvOpAll, out);
4047 }
4048 case Operator::Kind::NEQ:
4049 if (operandType->isMatrix()) {
4050 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFUnordNotEqual,
4051 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
4052 }
4053 if (operandType->isStruct()) {
4054 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
4055 }
4056 if (operandType->isArray()) {
4057 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
4058 }
4059 [[fallthrough]];
4060 case Operator::Kind::LOGICALXOR:
4061 SkASSERT(resultType.isBoolean());
4062 const Type* tmpType;
4063 if (operandType->isVector()) {
4064 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
4065 operandType->columns(),
4066 operandType->rows());
4067 } else {
4068 tmpType = &resultType;
4069 }
4070 if (lhs == rhs) {
4071 // This ignores the effects of NaN.
4072 return this->writeOpConstantFalse(*fContext.fTypes.fBool);
4073 }
4074 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
4075 SpvOpFUnordNotEqual, SpvOpINotEqual,
4076 SpvOpINotEqual, SpvOpLogicalNotEqual,
4077 out),
4078 *operandType, SpvOpAny, out);
4079 case Operator::Kind::GT:
4080 SkASSERT(resultType.isBoolean());
4081 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
4082 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
4083 SpvOpUGreaterThan, SpvOpUndef, out);
4084 case Operator::Kind::LT:
4085 SkASSERT(resultType.isBoolean());
4086 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
4087 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
4088 case Operator::Kind::GTEQ:
4089 SkASSERT(resultType.isBoolean());
4090 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
4091 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
4092 SpvOpUGreaterThanEqual, SpvOpUndef, out);
4093 case Operator::Kind::LTEQ:
4094 SkASSERT(resultType.isBoolean());
4095 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
4096 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
4097 SpvOpULessThanEqual, SpvOpUndef, out);
4098 case Operator::Kind::PLUS:
4099 return this->writeBinaryOperationComponentwiseIfMatrix(resultType, *operandType,
4100 lhs, rhs, SpvOpFAdd, SpvOpIAdd,
4101 SpvOpIAdd, SpvOpUndef, out);
4102 case Operator::Kind::MINUS:
4103 return this->writeBinaryOperationComponentwiseIfMatrix(resultType, *operandType,
4104 lhs, rhs, SpvOpFSub, SpvOpISub,
4105 SpvOpISub, SpvOpUndef, out);
4106 case Operator::Kind::STAR:
4107 if (leftType.isMatrix() && rightType.isMatrix()) {
4108 // matrix multiply
4109 SpvId result = this->nextId(&resultType);
4110 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
4111 lhs, rhs, out);
4112 return result;
4113 }
4114 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
4115 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
4116 case Operator::Kind::SLASH:
4117 return this->writeBinaryOperationComponentwiseIfMatrix(resultType, *operandType,
4118 lhs, rhs, SpvOpFDiv, SpvOpSDiv,
4119 SpvOpUDiv, SpvOpUndef, out);
4120 case Operator::Kind::PERCENT:
4121 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
4122 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
4123 case Operator::Kind::SHL:
4124 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
4125 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
4126 SpvOpUndef, out);
4127 case Operator::Kind::SHR:
4128 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
4129 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
4130 SpvOpUndef, out);
4131 case Operator::Kind::BITWISEAND:
4132 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
4133 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
4134 case Operator::Kind::BITWISEOR:
4135 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
4136 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
4137 case Operator::Kind::BITWISEXOR:
4138 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
4139 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
4140 default:
4141 fContext.fErrors->error(Position(), "unsupported token");
4142 return NA;
4143 }
4144 }
4145
4146 SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
4147 SpvId rhs, SPIRVBlob& out) {
4148 // The inputs must be arrays, and the op must be == or !=.
4149 SkASSERT(op.kind() == Operator::Kind::EQEQ || op.kind() == Operator::Kind::NEQ);
4150 SkASSERT(arrayType.isArray());
4151 const Type& componentType = arrayType.componentType();
4152 const int arraySize = arrayType.columns();
4153 SkASSERT(arraySize > 0);
4154
4155 // Synthesize equality checks for each item in the array.
4156 const Type& boolType = *fContext.fTypes.fBool;
4157 SpvId allComparisons = NA;
4158 for (int index = 0; index < arraySize; ++index) {
4159 // Get the left and right item in the array.
4160 SpvId itemL = this->writeOpCompositeExtract(componentType, lhs, index, out);
4161 SpvId itemR = this->writeOpCompositeExtract(componentType, rhs, index, out);
4162 // Use `writeBinaryExpression` with the requested == or != operator on these items.
4163 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
4164 componentType, itemR, boolType, out);
4165 // Merge this comparison result with all the other comparisons we've done.
4166 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
4167 }
4168 return allComparisons;
4169 }
4170
4171 SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
4172 SpvId rhs, SPIRVBlob& out) {
4173 // The inputs must be structs containing fields, and the op must be == or !=.
4174 SkASSERT(op.kind() == Operator::Kind::EQEQ || op.kind() == Operator::Kind::NEQ);
4175 SkASSERT(structType.isStruct());
4176 SkSpan<const Field> fields = structType.fields();
4177 SkASSERT(!fields.empty());
4178
4179 // Synthesize equality checks for each field in the struct.
4180 const Type& boolType = *fContext.fTypes.fBool;
4181 SpvId allComparisons = NA;
4182 for (int index = 0; index < (int)fields.size(); ++index) {
4183 // Get the left and right versions of this field.
4184 const Type& fieldType = *fields[index].fType;
4185
4186 SpvId fieldL = this->writeOpCompositeExtract(fieldType, lhs, index, out);
4187 SpvId fieldR = this->writeOpCompositeExtract(fieldType, rhs, index, out);
4188 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
4189 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
4190 boolType, out);
4191 // Merge this comparison result with all the other comparisons we've done.
4192 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
4193 }
4194 return allComparisons;
4195 }
4196
4197 SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
4198 SPIRVBlob& out) {
4199 // If this is the first entry, we don't need to merge comparison results with anything.
4200 if (allComparisons == NA) {
4201 return comparison;
4202 }
4203 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
4204 const Type& boolType = *fContext.fTypes.fBool;
4205 SpvId boolTypeId = this->getType(boolType);
4206 SpvId logicalOp = this->nextId(&boolType);
4207 switch (op.kind()) {
4208 case Operator::Kind::EQEQ:
4209 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
4210 comparison, allComparisons, out);
4211 break;
4212 case Operator::Kind::NEQ:
4213 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
4214 comparison, allComparisons, out);
4215 break;
4216 default:
4217 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
4218 return NA;
4219 }
4220 return logicalOp;
4221 }
4222
4223 SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, SPIRVBlob& out) {
4224 const Expression* left = b.left().get();
4225 const Expression* right = b.right().get();
4226 Operator op = b.getOperator();
4227
4228 switch (op.kind()) {
4229 case Operator::Kind::EQ: {
4230 // Handles assignment.
4231 SpvId rhs = this->writeExpression(*right, out);
4232 this->getLValue(*left, out)->store(rhs, out);
4233 return rhs;
4234 }
4235 case Operator::Kind::LOGICALAND:
4236 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
4237 return this->writeLogicalAnd(*b.left(), *b.right(), out);
4238
4239 case Operator::Kind::LOGICALOR:
4240 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
4241 return this->writeLogicalOr(*b.left(), *b.right(), out);
4242
4243 default:
4244 break;
4245 }
4246
4247 std::unique_ptr<LValue> lvalue;
4248 SpvId lhs;
4249 if (op.isAssignment()) {
4250 lvalue = this->getLValue(*left, out);
4251 lhs = lvalue->load(out);
4252 } else {
4253 lvalue = nullptr;
4254 lhs = this->writeExpression(*left, out);
4255 }
4256
4257 SpvId rhs = this->writeExpression(*right, out);
4258 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
4259 right->type(), rhs, b.type(), out);
4260 if (lvalue) {
4261 lvalue->store(result, out);
4262 }
4263 return result;
4264 }
4265
4266 SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
4267 SPIRVBlob& out) {
4268 SpvId falseConstant = this->writeLiteral(0.0, *fContext.fTypes.fBool);
4269 SpvId lhs = this->writeExpression(left, out);
4270
4271 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
4272
4273 SpvId rhsLabel = this->nextId(nullptr);
4274 SpvId end = this->nextId(nullptr);
4275 SpvId lhsBlock = fCurrentBlock;
4276 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
4277 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
4278 this->writeLabel(rhsLabel, kBranchIsOnPreviousLine, out);
4279 SpvId rhs = this->writeExpression(right, out);
4280 SpvId rhsBlock = fCurrentBlock;
4281 this->writeInstruction(SpvOpBranch, end, out);
4282 this->writeLabel(end, kBranchIsAbove, conditionalOps, out);
4283 SpvId result = this->nextId(nullptr);
4284 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
4285 lhsBlock, rhs, rhsBlock, out);
4286
4287 return result;
4288 }
4289
4290 SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
4291 SPIRVBlob& out) {
4292 SpvId trueConstant = this->writeLiteral(1.0, *fContext.fTypes.fBool);
4293 SpvId lhs = this->writeExpression(left, out);
4294
4295 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
4296
4297 SpvId rhsLabel = this->nextId(nullptr);
4298 SpvId end = this->nextId(nullptr);
4299 SpvId lhsBlock = fCurrentBlock;
4300 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
4301 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
4302 this->writeLabel(rhsLabel, kBranchIsOnPreviousLine, out);
4303 SpvId rhs = this->writeExpression(right, out);
4304 SpvId rhsBlock = fCurrentBlock;
4305 this->writeInstruction(SpvOpBranch, end, out);
4306 this->writeLabel(end, kBranchIsAbove, conditionalOps, out);
4307 SpvId result = this->nextId(nullptr);
4308 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
4309 lhsBlock, rhs, rhsBlock, out);
4310
4311 return result;
4312 }
4313
4314 SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, SPIRVBlob& out) {
4315 const Type& type = t.type();
4316 SpvId test = this->writeExpression(*t.test(), out);
4317 if (t.ifTrue()->type().columns() == 1 &&
4318 Analysis::IsCompileTimeConstant(*t.ifTrue()) &&
4319 Analysis::IsCompileTimeConstant(*t.ifFalse())) {
4320 // both true and false are constants, can just use OpSelect
4321 SpvId result = this->nextId(nullptr);
4322 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
4323 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
4324 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
4325 out);
4326 return result;
4327 }
4328
4329 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
4330
4331 // was originally using OpPhi to choose the result, but for some reason that is crashing on
4332 // Adreno. Switched to storing the result in a temp variable as glslang does.
4333 SpvId var = this->nextId(nullptr);
4334 this->writeInstruction(SpvOpVariable, this->getPointerType(type, StorageClass::kFunction),
4335 var, SpvStorageClassFunction, fVariableBuffer);
4336 SpvId trueLabel = this->nextId(nullptr);
4337 SpvId falseLabel = this->nextId(nullptr);
4338 SpvId end = this->nextId(nullptr);
4339 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
4340 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
4341 this->writeLabel(trueLabel, kBranchIsOnPreviousLine, out);
4342 this->writeOpStore(StorageClass::kFunction, var, this->writeExpression(*t.ifTrue(), out), out);
4343 this->writeInstruction(SpvOpBranch, end, out);
4344 this->writeLabel(falseLabel, kBranchIsAbove, conditionalOps, out);
4345 this->writeOpStore(StorageClass::kFunction, var, this->writeExpression(*t.ifFalse(), out), out);
4346 this->writeInstruction(SpvOpBranch, end, out);
4347 this->writeLabel(end, kBranchIsAbove, conditionalOps, out);
4348 SpvId result = this->nextId(&type);
4349 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
4350
4351 return result;
4352 }
4353
4354 SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, SPIRVBlob& out) {
4355 const Type& type = p.type();
4356 if (p.getOperator().kind() == Operator::Kind::MINUS) {
4357 SpvOp_ negateOp = pick_by_type(type, SpvOpFNegate, SpvOpSNegate, SpvOpSNegate, SpvOpUndef);
4358 SkASSERT(negateOp != SpvOpUndef);
4359 SpvId expr = this->writeExpression(*p.operand(), out);
4360 if (type.isMatrix()) {
4361 return this->writeComponentwiseMatrixUnary(type, expr, negateOp, out);
4362 }
4363 SpvId result = this->nextId(&type);
4364 SpvId typeId = this->getType(type);
4365 this->writeInstruction(negateOp, typeId, result, expr, out);
4366 return result;
4367 }
4368 switch (p.getOperator().kind()) {
4369 case Operator::Kind::PLUS:
4370 return this->writeExpression(*p.operand(), out);
4371
4372 case Operator::Kind::PLUSPLUS: {
4373 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
4374 SpvId one = this->writeLiteral(1.0, type.componentType());
4375 one = this->splat(type, one, out);
4376 SpvId result = this->writeBinaryOperationComponentwiseIfMatrix(type, type,
4377 lv->load(out), one,
4378 SpvOpFAdd, SpvOpIAdd,
4379 SpvOpIAdd, SpvOpUndef,
4380 out);
4381 lv->store(result, out);
4382 return result;
4383 }
4384 case Operator::Kind::MINUSMINUS: {
4385 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
4386 SpvId one = this->writeLiteral(1.0, type.componentType());
4387 one = this->splat(type, one, out);
4388 SpvId result = this->writeBinaryOperationComponentwiseIfMatrix(type, type,
4389 lv->load(out), one,
4390 SpvOpFSub, SpvOpISub,
4391 SpvOpISub, SpvOpUndef,
4392 out);
4393 lv->store(result, out);
4394 return result;
4395 }
4396 case Operator::Kind::LOGICALNOT: {
4397 SkASSERT(p.operand()->type().isBoolean());
4398 SpvId result = this->nextId(nullptr);
4399 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
4400 this->writeExpression(*p.operand(), out), out);
4401 return result;
4402 }
4403 case Operator::Kind::BITWISENOT: {
4404 SpvId result = this->nextId(nullptr);
4405 this->writeInstruction(SpvOpNot, this->getType(type), result,
4406 this->writeExpression(*p.operand(), out), out);
4407 return result;
4408 }
4409 default:
4410 SkDEBUGFAILF("unsupported prefix expression: %s",
4411 p.description(OperatorPrecedence::kExpression).c_str());
4412 return NA;
4413 }
4414 }
4415
4416 SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, SPIRVBlob& out) {
4417 const Type& type = p.type();
4418 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
4419 SpvId result = lv->load(out);
4420 SpvId one = this->writeLiteral(1.0, type.componentType());
4421 one = this->splat(type, one, out);
4422 switch (p.getOperator().kind()) {
4423 case Operator::Kind::PLUSPLUS: {
4424 SpvId temp = this->writeBinaryOperationComponentwiseIfMatrix(type, type, result, one,
4425 SpvOpFAdd, SpvOpIAdd,
4426 SpvOpIAdd, SpvOpUndef,
4427 out);
4428 lv->store(temp, out);
4429 return result;
4430 }
4431 case Operator::Kind::MINUSMINUS: {
4432 SpvId temp = this->writeBinaryOperationComponentwiseIfMatrix(type, type, result, one,
4433 SpvOpFSub, SpvOpISub,
4434 SpvOpISub, SpvOpUndef,
4435 out);
4436 lv->store(temp, out);
4437 return result;
4438 }
4439 default:
4440 SkDEBUGFAILF("unsupported postfix expression %s",
4441 p.description(OperatorPrecedence::kExpression).c_str());
4442 return NA;
4443 }
4444 }
4445
4446 SpvId SPIRVCodeGenerator::writeLiteral(const Literal& l) {
4447 return this->writeLiteral(l.value(), l.type());
4448 }
4449
4450 SpvId SPIRVCodeGenerator::writeLiteral(double value, const Type& type) {
4451 switch (type.numberKind()) {
4452 case Type::NumberKind::kFloat: {
4453 float floatVal = value;
4454 int32_t valueBits;
4455 memcpy(&valueBits, &floatVal, sizeof(valueBits));
4456 return this->writeOpConstant(type, valueBits);
4457 }
4458 case Type::NumberKind::kBoolean: {
4459 return value ? this->writeOpConstantTrue(type)
4460 : this->writeOpConstantFalse(type);
4461 }
4462 default: {
4463 return this->writeOpConstant(type, (SKSL_INT)value);
4464 }
4465 }
4466 }
4467
4468 void SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, SPIRVBlob& out) {
4469 SpvId result = fFunctionMap[{&f, fActiveSpecializationIndex}];
4470 SpvId returnTypeId = this->getType(f.returnType());
4471 SpvId functionTypeId = this->getFunctionType(f);
4472 this->writeInstruction(SpvOpFunction, returnTypeId, result,
4473 SpvFunctionControlMaskNone, functionTypeId, out);
4474 std::string mangledName = f.mangledName();
4475
4476 // For specialized functions, tack on `_param1_param2` to the function name.
4477 Analysis::GetParameterMappingsForFunction(
4478 f, fSpecializationInfo, fActiveSpecializationIndex,
4479 [&](int, const Variable*, const Expression* expr) {
4480 std::string name = expr->description();
4481 std::replace_if(name.begin(), name.end(), [](char c) { return !isalnum(c); }, '_');
4482
4483 mangledName += "_" + name;
4484 });
4485
4486 this->writeInstruction(SpvOpName,
4487 result,
4488 std::string_view(mangledName.c_str(), mangledName.size()),
4489 fNameBuffer);
4490 for (const Variable* parameter : f.parameters()) {
4491 const Variable* specializedVar = nullptr;
4492 if (fActiveSpecialization) {
4493 if (const Expression** specializedExpr = fActiveSpecialization->find(parameter)) {
4494 if ((*specializedExpr)->is<FieldAccess>()) {
4495 continue;
4496 }
4497 SkASSERT((*specializedExpr)->is<VariableReference>());
4498 specializedVar = (*specializedExpr)->as<VariableReference>().variable();
4499 }
4500 }
4501
4502 if (fUseTextureSamplerPairs && parameter->type().isSampler()) {
4503 auto [texture, sampler] = this->synthesizeTextureAndSampler(*parameter);
4504
4505 SpvId textureId = this->nextId(&parameter->type());
4506 fVariableMap.set(texture, textureId);
4507
4508 SpvId textureType = this->getFunctionParameterType(texture->type(), texture->layout());
4509 this->writeInstruction(SpvOpFunctionParameter, textureType, textureId, out);
4510
4511 if (specializedVar) {
4512 const auto* p = fSynthesizedSamplerMap.find(specializedVar);
4513 SkASSERT(p);
4514 const SpvId* uniformId = fVariableMap.find((*p)->fSampler.get());
4515 SkASSERT(uniformId);
4516 fVariableMap.set(sampler, *uniformId);
4517 } else {
4518 SpvId samplerId = this->nextId(&parameter->type());
4519 fVariableMap.set(sampler, samplerId);
4520
4521 SpvId samplerType =
4522 this->getFunctionParameterType(sampler->type(), kDefaultTypeLayout);
4523 this->writeInstruction(SpvOpFunctionParameter, samplerType, samplerId, out);
4524 }
4525 } else {
4526 if (specializedVar) {
4527 const SpvId* uniformId = fVariableMap.find(specializedVar);
4528 SkASSERT(uniformId);
4529 fVariableMap.set(parameter, *uniformId);
4530 } else {
4531 SpvId id = this->nextId(&parameter->type());
4532 fVariableMap.set(parameter, id);
4533
4534 SpvId type = this->getFunctionParameterType(parameter->type(), parameter->layout());
4535 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
4536 }
4537 }
4538 }
4539 }
4540
4541 void SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, SPIRVBlob& out) {
4542 if (const Analysis::Specializations* specializations =
4543 fSpecializationInfo.fSpecializationMap.find(&f.declaration())) {
4544 for (int i = 0; i < specializations->size(); i++) {
4545 this->writeFunctionInstantiation(f, i, &specializations->at(i), out);
4546 }
4547 } else {
4548 this->writeFunctionInstantiation(f,
4549 Analysis::kUnspecialized,
4550 /*specializedParams=*/nullptr,
4551 out);
4552 }
4553 }
4554
4555 void SPIRVCodeGenerator::writeFunctionInstantiation(
4556 const FunctionDefinition& f,
4557 Analysis::SpecializationIndex specializationIndex,
4558 const Analysis::SpecializedParameters* specializedParams,
4559 SPIRVBlob& out) {
4560 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
4561
4562 fVariableBuffer.clear();
4563 fActiveSpecialization = specializedParams;
4564 fActiveSpecializationIndex = specializationIndex;
4565 this->writeFunctionStart(f.declaration(), out);
4566 fCurrentBlock = 0;
4567 this->writeLabel(this->nextId(nullptr), kBranchlessBlock, out);
4568 SPIRVBlob bodyBuffer;
4569 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
4570 fActiveSpecialization = nullptr;
4571 fActiveSpecializationIndex = Analysis::kUnspecialized;
4572 append_blob(fVariableBuffer, out);
4573 if (f.declaration().isMain()) {
4574 append_blob(fGlobalInitializersBuffer, out);
4575 }
4576 append_blob(bodyBuffer, out);
4577 if (fCurrentBlock) {
4578 if (f.declaration().returnType().isVoid()) {
4579 this->writeInstruction(SpvOpReturn, out);
4580 } else {
4581 this->writeInstruction(SpvOpUnreachable, out);
4582 }
4583 }
4584 this->writeInstruction(SpvOpFunctionEnd, out);
4585 this->pruneConditionalOps(conditionalOps);
4586 }
4587
4588 void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, Position pos) {
4589 bool isPushConstant = SkToBool(layout.fFlags & LayoutFlag::kPushConstant);
4590 if (layout.fLocation >= 0) {
4591 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
4592 fDecorationBuffer);
4593 }
4594 if (layout.fBinding >= 0) {
4595 if (isPushConstant) {
4596 fContext.fErrors->error(pos, "Can't apply 'binding' to push constants");
4597 } else {
4598 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
4599 fDecorationBuffer);
4600 }
4601 }
4602 if (layout.fIndex >= 0) {
4603 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
4604 fDecorationBuffer);
4605 }
4606 if (layout.fSet >= 0) {
4607 if (isPushConstant) {
4608 fContext.fErrors->error(pos, "Can't apply 'set' to push constants");
4609 } else {
4610 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
4611 fDecorationBuffer);
4612 }
4613 }
4614 if (layout.fInputAttachmentIndex >= 0) {
4615 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
4616 layout.fInputAttachmentIndex, fDecorationBuffer);
4617 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
4618 }
4619 if (layout.fBuiltin >= 0 && (layout.fBuiltin != SK_FRAGCOLOR_BUILTIN &&
4620 layout.fBuiltin != SK_SECONDARYFRAGCOLOR_BUILTIN)) {
4621 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
4622 fDecorationBuffer);
4623 }
4624 }
4625
4626 void SPIRVCodeGenerator::writeFieldLayout(const Layout& layout, SpvId target, int member) {
4627 // 'binding' and 'set' can not be applied to struct members
4628 SkASSERT(layout.fBinding == -1);
4629 SkASSERT(layout.fSet == -1);
4630 if (layout.fLocation >= 0) {
4631 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
4632 layout.fLocation, fDecorationBuffer);
4633 }
4634 if (layout.fIndex >= 0) {
4635 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
4636 layout.fIndex, fDecorationBuffer);
4637 }
4638 if (layout.fInputAttachmentIndex >= 0) {
4639 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
4640 layout.fInputAttachmentIndex, fDecorationBuffer);
4641 }
4642 if (layout.fBuiltin >= 0) {
4643 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
4644 layout.fBuiltin, fDecorationBuffer);
4645 }
4646 }
4647
4648 MemoryLayout SPIRVCodeGenerator::memoryLayoutForStorageClass(StorageClass storageClass) {
4649 return storageClass == StorageClass::kPushConstant ||
4650 storageClass == StorageClass::kStorageBuffer
4651 ? MemoryLayout(MemoryLayout::Standard::k430)
4652 : fDefaultMemoryLayout;
4653 }
4654
4655 MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
4656 bool pushConstant = SkToBool(v.layout().fFlags & LayoutFlag::kPushConstant);
4657 bool buffer = v.modifierFlags().isBuffer();
4658 return pushConstant || buffer ? MemoryLayout(MemoryLayout::Standard::k430)
4659 : fDefaultMemoryLayout;
4660 }
4661
4662 SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTFlip) {
4663 MemoryLayout memoryLayout = this->memoryLayoutForVariable(*intf.var());
4664 SpvId result = this->nextId(nullptr);
4665 const Variable& intfVar = *intf.var();
4666 const Type& type = intfVar.type();
4667 if (!memoryLayout.isSupported(type)) {
4668 fContext.fErrors->error(type.fPosition, "type '" + type.displayName() +
4669 "' is not permitted here");
4670 return this->nextId(nullptr);
4671 }
4672 StorageClass storageClass =
4673 get_storage_class_for_global_variable(intfVar, StorageClass::kFunction);
4674 if (fProgram.fInterface.fRTFlipUniform != Program::Interface::kRTFlip_None && appendRTFlip &&
4675 !fWroteRTFlip && type.isStruct()) {
4676 // We can only have one interface block (because we use push_constant and that is limited
4677 // to one per program), so we need to append rtflip to this one rather than synthesize an
4678 // entirely new block when the variable is referenced. And we can't modify the existing
4679 // block, so we instead create a modified copy of it and write that.
4680 SkSpan<const Field> fieldSpan = type.fields();
4681 TArray<Field> fields(fieldSpan.data(), fieldSpan.size());
4682 fields.emplace_back(Position(),
4683 Layout(LayoutFlag::kNone,
4684 /*location=*/-1,
4685 fProgram.fConfig->fSettings.fRTFlipOffset,
4686 /*binding=*/-1,
4687 /*index=*/-1,
4688 /*set=*/-1,
4689 /*builtin=*/-1,
4690 /*inputAttachmentIndex=*/-1),
4691 ModifierFlag::kNone,
4692 SKSL_RTFLIP_NAME,
4693 fContext.fTypes.fFloat2.get());
4694 {
4695 AutoAttachPoolToThread attach(fProgram.fPool.get());
4696 const Type* rtFlipStructType = fProgram.fSymbols->takeOwnershipOfSymbol(
4697 Type::MakeStructType(fContext,
4698 type.fPosition,
4699 type.name(),
4700 std::move(fields),
4701 /*interfaceBlock=*/true));
4702 Variable* modifiedVar = fProgram.fSymbols->takeOwnershipOfSymbol(
4703 Variable::Make(intfVar.fPosition,
4704 intfVar.modifiersPosition(),
4705 intfVar.layout(),
4706 intfVar.modifierFlags(),
4707 rtFlipStructType,
4708 intfVar.name(),
4709 /*mangledName=*/"",
4710 intfVar.isBuiltin(),
4711 intfVar.storage()));
4712 InterfaceBlock modifiedCopy(intf.fPosition, modifiedVar);
4713 result = this->writeInterfaceBlock(modifiedCopy, /*appendRTFlip=*/false);
4714 fProgram.fSymbols->add(fContext, std::make_unique<FieldSymbol>(
4715 Position(), modifiedVar, rtFlipStructType->fields().size() - 1));
4716 }
4717 fVariableMap.set(&intfVar, result);
4718 fWroteRTFlip = true;
4719 return result;
4720 }
4721 SpvId typeId = this->getType(type, kDefaultTypeLayout, memoryLayout);
4722 if (intfVar.layout().fBuiltin == -1) {
4723 // Note: In SPIR-V 1.3, a storage buffer can be declared with the "StorageBuffer"
4724 // storage class and the "Block" decoration and the <1.3 approach we use here ("Uniform"
4725 // storage class and the "BufferBlock" decoration) is deprecated. Since we target SPIR-V
4726 // 1.0, we have to use the deprecated approach which is well supported in Vulkan and
4727 // addresses SkSL use cases (notably SkSL currently doesn't support pointer features that
4728 // would benefit from SPV_KHR_variable_pointers capabilities).
4729 bool isStorageBuffer = intfVar.modifierFlags().isBuffer();
4730 this->writeInstruction(SpvOpDecorate,
4731 typeId,
4732 isStorageBuffer ? SpvDecorationBufferBlock : SpvDecorationBlock,
4733 fDecorationBuffer);
4734 }
4735 SpvId ptrType = this->nextId(nullptr);
4736 this->writeInstruction(SpvOpTypePointer, ptrType,
4737 get_storage_class_spv_id(storageClass), typeId, fConstantBuffer);
4738 this->writeInstruction(SpvOpVariable, ptrType, result,
4739 get_storage_class_spv_id(storageClass), fConstantBuffer);
4740 Layout layout = intfVar.layout();
4741 if ((storageClass == StorageClass::kUniform ||
4742 storageClass == StorageClass::kStorageBuffer) && layout.fSet < 0) {
4743 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
4744 }
4745 this->writeLayout(layout, result, intfVar.fPosition);
4746 fVariableMap.set(&intfVar, result);
4747 return result;
4748 }
4749
4750 // This function determines whether to skip an OpVariable (of pointer type) declaration for
4751 // compile-time constant scalars and vectors which we turn into OpConstant/OpConstantComposite and
4752 // always reference by value.
4753 //
4754 // Accessing a matrix or array member with a dynamic index requires the use of OpAccessChain which
4755 // requires a base operand of pointer type. However, a vector can always be accessed by value using
4756 // OpVectorExtractDynamic (see writeIndexExpression).
4757 //
4758 // This is why we always emit an OpVariable for all non-scalar and non-vector types in case they get
4759 // accessed via a dynamic index.
4760 static bool is_vardecl_compile_time_constant(const VarDeclaration& varDecl) {
4761 return varDecl.var()->modifierFlags().isConst() &&
4762 (varDecl.var()->type().isScalar() || varDecl.var()->type().isVector()) &&
4763 (ConstantFolder::GetConstantValueOrNull(*varDecl.value()) ||
4764 Analysis::IsCompileTimeConstant(*varDecl.value()));
4765 }
4766
4767 bool SPIRVCodeGenerator::writeGlobalVarDeclaration(ProgramKind kind,
4768 const VarDeclaration& varDecl) {
4769 const Variable* var = varDecl.var();
4770 const LayoutFlags backendFlags = var->layout().fFlags & LayoutFlag::kAllBackends;
4771 const LayoutFlags kPermittedBackendFlags =
4772 LayoutFlag::kVulkan | LayoutFlag::kWebGPU | LayoutFlag::kDirect3D;
4773 if (backendFlags & ~kPermittedBackendFlags) {
4774 fContext.fErrors->error(var->fPosition, "incompatible backend flag in SPIR-V codegen");
4775 return false;
4776 }
4777
4778 // If this global variable is a compile-time constant then we'll emit OpConstant or
4779 // OpConstantComposite later when the variable is referenced. Avoid declaring an OpVariable now.
4780 if (is_vardecl_compile_time_constant(varDecl)) {
4781 return true;
4782 }
4783
4784 StorageClass storageClass =
4785 get_storage_class_for_global_variable(*var, StorageClass::kPrivate);
4786 if (storageClass == StorageClass::kUniform || storageClass == StorageClass::kStorageBuffer) {
4787 // Top-level uniforms are emitted in writeUniformBuffer.
4788 fTopLevelUniforms.push_back(&varDecl);
4789 return true;
4790 }
4791
4792 if (fUseTextureSamplerPairs && var->type().isSampler()) {
4793 if (var->layout().fTexture == -1 || var->layout().fSampler == -1) {
4794 fContext.fErrors->error(var->fPosition, "selected backend requires separate texture "
4795 "and sampler indices");
4796 return false;
4797 }
4798 SkASSERT(storageClass == StorageClass::kUniformConstant);
4799
4800 auto [texture, sampler] = this->synthesizeTextureAndSampler(*var);
4801 this->writeGlobalVar(kind, storageClass, *texture);
4802 this->writeGlobalVar(kind, storageClass, *sampler);
4803
4804 return true;
4805 }
4806
4807 SpvId id = this->writeGlobalVar(kind, storageClass, *var);
4808 if (id != NA && varDecl.value()) {
4809 SkASSERT(!fCurrentBlock);
4810 fCurrentBlock = NA;
4811 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
4812 this->writeOpStore(storageClass, id, value, fGlobalInitializersBuffer);
4813 fCurrentBlock = 0;
4814 }
4815 return true;
4816 }
4817
4818 SpvId SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind,
4819 StorageClass storageClass,
4820 const Variable& var) {
4821 Layout layout = var.layout();
4822 const ModifierFlags flags = var.modifierFlags();
4823 const Type* type = &var.type();
4824 switch (layout.fBuiltin) {
4825 case SK_FRAGCOLOR_BUILTIN:
4826 case SK_SECONDARYFRAGCOLOR_BUILTIN:
4827 if (!ProgramConfig::IsFragment(kind)) {
4828 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
4829 return NA;
4830 }
4831 break;
4832
4833 case SK_SAMPLEMASKIN_BUILTIN:
4834 case SK_SAMPLEMASK_BUILTIN:
4835 // SkSL exposes this as a `uint` but SPIR-V, like GLSL, uses an array of signed `uint`
4836 // decorated with SpvBuiltinSampleMask.
4837 type = fSynthetics.addArrayDimension(fContext, type, /*arraySize=*/1);
4838 layout.fBuiltin = SpvBuiltInSampleMask;
4839 break;
4840 }
4841
4842 // Input attachments have a reserved ID.
4843 const bool isInputAttachment =
4844 type->typeKind() == Type::TypeKind::kTexture && type->dimensions() == SpvDimSubpassData;
4845
4846 // Add this global to the variable map.
4847 SpvId id = isInputAttachment ? (SpvId)spirv::kIdVariableImageSubpassData : this->nextId(type);
4848 fVariableMap.set(&var, id);
4849
4850 if (layout.fSet < 0 && storageClass == StorageClass::kUniformConstant) {
4851 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
4852 }
4853
4854 // Input int pointers have a reserved ID
4855 SpvId typeId;
4856 if (type->typeKind() == Type::TypeKind::kScalar && type->isSigned() &&
4857 storageClass == StorageClass::kInput) {
4858 // Predefined type pointer
4859 typeId = spirv::kIdTypePointerInputInt;
4860 } else {
4861 typeId = this->getPointerType(
4862 *type, layout, this->memoryLayoutForStorageClass(storageClass), storageClass);
4863 }
4864 this->writeInstruction(SpvOpVariable, typeId, id,
4865 get_storage_class_spv_id(storageClass), fConstantBuffer);
4866 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
4867 this->writeLayout(layout, id, var.fPosition);
4868 if (flags & ModifierFlag::kFlat) {
4869 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
4870 }
4871 if (flags & ModifierFlag::kNoPerspective) {
4872 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
4873 fDecorationBuffer);
4874 }
4875 if (flags.isWriteOnly()) {
4876 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNonReadable, fDecorationBuffer);
4877 } else if (flags.isReadOnly()) {
4878 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNonWritable, fDecorationBuffer);
4879 }
4880
4881 return id;
4882 }
4883
4884 void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, SPIRVBlob& out) {
4885 // If this variable is a compile-time constant then we'll emit OpConstant or
4886 // OpConstantComposite later when the variable is referenced. Avoid declaring an OpVariable now.
4887 if (is_vardecl_compile_time_constant(varDecl)) {
4888 return;
4889 }
4890
4891 const Variable* var = varDecl.var();
4892 SpvId id = this->nextId(&var->type());
4893 fVariableMap.set(var, id);
4894 SpvId type = this->getPointerType(var->type(), StorageClass::kFunction);
4895 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
4896 this->writeInstruction(SpvOpName, id, var->name(), fNameBuffer);
4897 if (varDecl.value()) {
4898 SpvId value = this->writeExpression(*varDecl.value(), out);
4899 this->writeOpStore(StorageClass::kFunction, id, value, out);
4900 }
4901 }
4902
4903 void SPIRVCodeGenerator::writeStatement(const Statement& s, SPIRVBlob& out) {
4904 switch (s.kind()) {
4905 case Statement::Kind::kNop:
4906 break;
4907 case Statement::Kind::kBlock:
4908 this->writeBlock(s.as<Block>(), out);
4909 break;
4910 case Statement::Kind::kExpression:
4911 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
4912 break;
4913 case Statement::Kind::kReturn:
4914 this->writeReturnStatement(s.as<ReturnStatement>(), out);
4915 break;
4916 case Statement::Kind::kVarDeclaration:
4917 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
4918 break;
4919 case Statement::Kind::kIf:
4920 this->writeIfStatement(s.as<IfStatement>(), out);
4921 break;
4922 case Statement::Kind::kFor:
4923 this->writeForStatement(s.as<ForStatement>(), out);
4924 break;
4925 case Statement::Kind::kDo:
4926 this->writeDoStatement(s.as<DoStatement>(), out);
4927 break;
4928 case Statement::Kind::kSwitch:
4929 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
4930 break;
4931 case Statement::Kind::kBreak:
4932 this->writeInstruction(SpvOpBranch, fBreakTarget.back(), out);
4933 break;
4934 case Statement::Kind::kContinue:
4935 this->writeInstruction(SpvOpBranch, fContinueTarget.back(), out);
4936 break;
4937 case Statement::Kind::kDiscard:
4938 this->writeInstruction(SpvOpKill, out);
4939 break;
4940 default:
4941 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
4942 break;
4943 }
4944 }
4945
4946 void SPIRVCodeGenerator::writeBlock(const Block& b, SPIRVBlob& out) {
4947 for (const std::unique_ptr<Statement>& stmt : b.children()) {
4948 this->writeStatement(*stmt, out);
4949 }
4950 }
4951
4952 SPIRVCodeGenerator::ConditionalOpCounts SPIRVCodeGenerator::getConditionalOpCounts() {
4953 return {fReachableOps.size(), fStoreOps.size()};
4954 }
4955
4956 void SPIRVCodeGenerator::pruneConditionalOps(ConditionalOpCounts ops) {
4957 // Remove ops which are no longer reachable.
4958 while (fReachableOps.size() > ops.numReachableOps) {
4959 SpvId prunableSpvId = fReachableOps.back();
4960 const Instruction* prunableOp = fSpvIdCache.find(prunableSpvId);
4961
4962 if (prunableOp) {
4963 fOpCache.remove(*prunableOp);
4964 fSpvIdCache.remove(prunableSpvId);
4965 } else {
4966 SkDEBUGFAIL("reachable-op list contains unrecognized SpvId");
4967 }
4968
4969 fReachableOps.pop_back();
4970 }
4971
4972 // Remove any cached stores that occurred during the conditional block.
4973 while (fStoreOps.size() > ops.numStoreOps) {
4974 if (fStoreCache.find(fStoreOps.back())) {
4975 fStoreCache.remove(fStoreOps.back());
4976 }
4977 fStoreOps.pop_back();
4978 }
4979 }
4980
4981 void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, SPIRVBlob& out) {
4982 SpvId test = this->writeExpression(*stmt.test(), out);
4983 SpvId ifTrue = this->nextId(nullptr);
4984 SpvId ifFalse = this->nextId(nullptr);
4985
4986 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
4987
4988 if (stmt.ifFalse()) {
4989 SpvId end = this->nextId(nullptr);
4990 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
4991 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
4992 this->writeLabel(ifTrue, kBranchIsOnPreviousLine, out);
4993 this->writeStatement(*stmt.ifTrue(), out);
4994 if (fCurrentBlock) {
4995 this->writeInstruction(SpvOpBranch, end, out);
4996 }
4997 this->writeLabel(ifFalse, kBranchIsAbove, conditionalOps, out);
4998 this->writeStatement(*stmt.ifFalse(), out);
4999 if (fCurrentBlock) {
5000 this->writeInstruction(SpvOpBranch, end, out);
5001 }
5002 this->writeLabel(end, kBranchIsAbove, conditionalOps, out);
5003 } else {
5004 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
5005 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
5006 this->writeLabel(ifTrue, kBranchIsOnPreviousLine, out);
5007 this->writeStatement(*stmt.ifTrue(), out);
5008 if (fCurrentBlock) {
5009 this->writeInstruction(SpvOpBranch, ifFalse, out);
5010 }
5011 this->writeLabel(ifFalse, kBranchIsAbove, conditionalOps, out);
5012 }
5013 }
5014
5015 void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, SPIRVBlob& out) {
5016 if (f.initializer()) {
5017 this->writeStatement(*f.initializer(), out);
5018 }
5019
5020 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
5021
5022 // The store cache isn't trustworthy in the presence of branches; store caching only makes sense
5023 // in the context of linear straight-line execution. If we wanted to be more clever, we could
5024 // only invalidate store cache entries for variables affected by the loop body, but for now we
5025 // simply clear the entire cache whenever branching occurs.
5026 SpvId header = this->nextId(nullptr);
5027 SpvId start = this->nextId(nullptr);
5028 SpvId body = this->nextId(nullptr);
5029 SpvId next = this->nextId(nullptr);
5030 fContinueTarget.push_back(next);
5031 SpvId end = this->nextId(nullptr);
5032 fBreakTarget.push_back(end);
5033 this->writeInstruction(SpvOpBranch, header, out);
5034 this->writeLabel(header, kBranchIsBelow, conditionalOps, out);
5035 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
5036 this->writeInstruction(SpvOpBranch, start, out);
5037 this->writeLabel(start, kBranchIsOnPreviousLine, out);
5038 if (f.test()) {
5039 SpvId test = this->writeExpression(*f.test(), out);
5040 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
5041 } else {
5042 this->writeInstruction(SpvOpBranch, body, out);
5043 }
5044 this->writeLabel(body, kBranchIsOnPreviousLine, out);
5045 this->writeStatement(*f.statement(), out);
5046 if (fCurrentBlock) {
5047 this->writeInstruction(SpvOpBranch, next, out);
5048 }
5049 this->writeLabel(next, kBranchIsAbove, conditionalOps, out);
5050 if (f.next()) {
5051 this->writeExpression(*f.next(), out);
5052 }
5053 this->writeInstruction(SpvOpBranch, header, out);
5054 this->writeLabel(end, kBranchIsAbove, conditionalOps, out);
5055 fBreakTarget.pop_back();
5056 fContinueTarget.pop_back();
5057 }
5058
5059 void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, SPIRVBlob& out) {
5060 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
5061
5062 // The store cache isn't trustworthy in the presence of branches; store caching only makes sense
5063 // in the context of linear straight-line execution. If we wanted to be more clever, we could
5064 // only invalidate store cache entries for variables affected by the loop body, but for now we
5065 // simply clear the entire cache whenever branching occurs.
5066 SpvId header = this->nextId(nullptr);
5067 SpvId start = this->nextId(nullptr);
5068 SpvId next = this->nextId(nullptr);
5069 SpvId continueTarget = this->nextId(nullptr);
5070 fContinueTarget.push_back(continueTarget);
5071 SpvId end = this->nextId(nullptr);
5072 fBreakTarget.push_back(end);
5073 this->writeInstruction(SpvOpBranch, header, out);
5074 this->writeLabel(header, kBranchIsBelow, conditionalOps, out);
5075 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
5076 this->writeInstruction(SpvOpBranch, start, out);
5077 this->writeLabel(start, kBranchIsOnPreviousLine, out);
5078 this->writeStatement(*d.statement(), out);
5079 if (fCurrentBlock) {
5080 this->writeInstruction(SpvOpBranch, next, out);
5081 this->writeLabel(next, kBranchIsOnPreviousLine, out);
5082 this->writeInstruction(SpvOpBranch, continueTarget, out);
5083 }
5084 this->writeLabel(continueTarget, kBranchIsAbove, conditionalOps, out);
5085 SpvId test = this->writeExpression(*d.test(), out);
5086 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
5087 this->writeLabel(end, kBranchIsAbove, conditionalOps, out);
5088 fBreakTarget.pop_back();
5089 fContinueTarget.pop_back();
5090 }
5091
5092 void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, SPIRVBlob& out) {
5093 SpvId value = this->writeExpression(*s.value(), out);
5094
5095 ConditionalOpCounts conditionalOps = this->getConditionalOpCounts();
5096
5097 // The store cache isn't trustworthy in the presence of branches; store caching only makes sense
5098 // in the context of linear straight-line execution. If we wanted to be more clever, we could
5099 // only invalidate store cache entries for variables affected by the switch body, but for now we
5100 // simply clear the entire cache whenever branching occurs.
5101 TArray<SpvId> labels;
5102 SpvId end = this->nextId(nullptr);
5103 SpvId defaultLabel = end;
5104 fBreakTarget.push_back(end);
5105 int size = 3;
5106 const StatementArray& cases = s.cases();
5107 for (const std::unique_ptr<Statement>& stmt : cases) {
5108 const SwitchCase& c = stmt->as<SwitchCase>();
5109 SpvId label = this->nextId(nullptr);
5110 labels.push_back(label);
5111 if (!c.isDefault()) {
5112 size += 2;
5113 } else {
5114 defaultLabel = label;
5115 }
5116 }
5117
5118 // We should have exactly one label for each case.
5119 SkASSERT(labels.size() == cases.size());
5120
5121 // Collapse adjacent switch-cases into one; that is, reduce `case 1: case 2: case 3:` into a
5122 // single OpLabel. The Tint SPIR-V reader does not support switch-case fallthrough, but it
5123 // does support multiple switch-cases branching to the same label.
5124 SkBitSet caseIsCollapsed(cases.size());
5125 for (int index = cases.size() - 2; index >= 0; index--) {
5126 if (cases[index]->as<SwitchCase>().statement()->isEmpty()) {
5127 caseIsCollapsed.set(index);
5128 labels[index] = labels[index + 1];
5129 }
5130 }
5131
5132 labels.push_back(end);
5133
5134 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
5135 this->writeOpCode(SpvOpSwitch, size, out);
5136 this->writeWord(value, out);
5137 this->writeWord(defaultLabel, out);
5138 for (int i = 0; i < cases.size(); ++i) {
5139 const SwitchCase& c = cases[i]->as<SwitchCase>();
5140 if (c.isDefault()) {
5141 continue;
5142 }
5143 this->writeWord(c.value(), out);
5144 this->writeWord(labels[i], out);
5145 }
5146 for (int i = 0; i < cases.size(); ++i) {
5147 if (caseIsCollapsed.test(i)) {
5148 continue;
5149 }
5150 const SwitchCase& c = cases[i]->as<SwitchCase>();
5151 if (i == 0) {
5152 this->writeLabel(labels[i], kBranchIsOnPreviousLine, out);
5153 } else {
5154 this->writeLabel(labels[i], kBranchIsAbove, conditionalOps, out);
5155 }
5156 this->writeStatement(*c.statement(), out);
5157 if (fCurrentBlock) {
5158 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
5159 }
5160 }
5161 this->writeLabel(end, kBranchIsAbove, conditionalOps, out);
5162 fBreakTarget.pop_back();
5163 }
5164
5165 void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, SPIRVBlob& out) {
5166 if (r.expression()) {
5167 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
5168 out);
5169 } else {
5170 this->writeInstruction(SpvOpReturn, out);
5171 }
5172 }
5173
5174 // Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
5175 static SymbolTable* get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
5176 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
5177 }
5178
5179 SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
5180 const FunctionDeclaration& main) {
5181 // Our goal is to synthesize a tiny helper function which looks like this:
5182 // void _entrypoint() { sk_FragColor = main(); }
5183
5184 // Fish a symbol table out of main().
5185 SymbolTable* symbolTable = get_top_level_symbol_table(main);
5186
5187 // Get `sk_FragColor` as a writable reference.
5188 const Symbol* skFragColorSymbol = symbolTable->find("sk_FragColor");
5189 SkASSERT(skFragColorSymbol);
5190 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
5191 auto skFragColorRef = std::make_unique<VariableReference>(Position(), &skFragColorVar,
5192 VariableReference::RefKind::kWrite);
5193
5194 // TODO get secondary frag color as one as well?
5195
5196 // Synthesize a call to the `main()` function.
5197 if (!main.returnType().matches(skFragColorRef->type())) {
5198 fContext.fErrors->error(main.fPosition, "SPIR-V does not support returning '" +
5199 main.returnType().description() + "' from main()");
5200 return {};
5201 }
5202 ExpressionArray args;
5203 if (main.parameters().size() == 1) {
5204 if (!main.parameters()[0]->type().matches(*fContext.fTypes.fFloat2)) {
5205 fContext.fErrors->error(main.fPosition,
5206 "SPIR-V does not support parameter of type '" +
5207 main.parameters()[0]->type().description() + "' to main()");
5208 return {};
5209 }
5210 double kZero[2] = {0.0, 0.0};
5211 args.push_back(ConstructorCompound::MakeFromConstants(fContext, Position{},
5212 *fContext.fTypes.fFloat2, kZero));
5213 }
5214 auto callMainFn = FunctionCall::Make(fContext, Position(), &main.returnType(),
5215 main, std::move(args));
5216
5217 // Synthesize `skFragColor = main()` as a BinaryExpression.
5218 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
5219 Position(),
5220 std::move(skFragColorRef),
5221 Operator::Kind::EQ,
5222 std::move(callMainFn),
5223 &main.returnType()));
5224
5225 // Function bodies are always wrapped in a Block.
5226 StatementArray entrypointStmts;
5227 entrypointStmts.push_back(std::move(assignmentStmt));
5228 auto entrypointBlock = Block::Make(Position(), std::move(entrypointStmts),
5229 Block::Kind::kBracedScope, /*symbols=*/nullptr);
5230 // Declare an entrypoint function.
5231 EntrypointAdapter adapter;
5232 adapter.entrypointDecl =
5233 std::make_unique<FunctionDeclaration>(fContext,
5234 Position(),
5235 ModifierFlag::kNone,
5236 "_entrypoint",
5237 /*parameters=*/TArray<Variable*>{},
5238 /*returnType=*/fContext.fTypes.fVoid.get(),
5239 kNotIntrinsic);
5240 // Define it.
5241 adapter.entrypointDef = FunctionDefinition::Convert(fContext,
5242 Position(),
5243 *adapter.entrypointDecl,
5244 std::move(entrypointBlock));
5245
5246 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
5247 return adapter;
5248 }
5249
5250 void SPIRVCodeGenerator::writeUniformBuffer(SymbolTable* topLevelSymbolTable) {
5251 SkASSERT(!fTopLevelUniforms.empty());
5252 static constexpr char kUniformBufferName[] = "_UniformBuffer";
5253
5254 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
5255 // a lookup table of variables to UniformBuffer field indices.
5256 TArray<Field> fields;
5257 fields.reserve_exact(fTopLevelUniforms.size());
5258 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
5259 const Variable* var = topLevelUniform->var();
5260 fTopLevelUniformMap.set(var, (int)fields.size());
5261 ModifierFlags flags = var->modifierFlags() & ~ModifierFlag::kUniform;
5262 fields.emplace_back(var->fPosition, var->layout(), flags, var->name(), &var->type());
5263 }
5264 fUniformBuffer.fStruct = Type::MakeStructType(fContext,
5265 Position(),
5266 kUniformBufferName,
5267 std::move(fields),
5268 /*interfaceBlock=*/true);
5269
5270 // Create a global variable to contain this struct.
5271 Layout layout;
5272 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
5273 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
5274
5275 fUniformBuffer.fInnerVariable = Variable::Make(/*pos=*/Position(),
5276 /*modifiersPosition=*/Position(),
5277 layout,
5278 ModifierFlag::kUniform,
5279 fUniformBuffer.fStruct.get(),
5280 kUniformBufferName,
5281 /*mangledName=*/"",
5282 /*builtin=*/false,
5283 Variable::Storage::kGlobal);
5284
5285 // Create an interface block object for this global variable.
5286 fUniformBuffer.fInterfaceBlock =
5287 std::make_unique<InterfaceBlock>(Position(), fUniformBuffer.fInnerVariable.get());
5288
5289 // Generate an interface block and hold onto its ID.
5290 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
5291 }
5292
5293 void SPIRVCodeGenerator::addRTFlipUniform(Position pos) {
5294 SkASSERT(!fProgram.fConfig->fSettings.fForceNoRTFlip);
5295
5296 if (fWroteRTFlip) {
5297 return;
5298 }
5299 // Flip variable hasn't been written yet. This means we don't have an existing
5300 // interface block, so we're free to just synthesize one.
5301 fWroteRTFlip = true;
5302 TArray<Field> fields;
5303 if (fProgram.fConfig->fSettings.fRTFlipOffset < 0) {
5304 fContext.fErrors->error(pos, "RTFlipOffset is negative");
5305 }
5306 fields.emplace_back(pos,
5307 Layout(LayoutFlag::kNone,
5308 /*location=*/-1,
5309 fProgram.fConfig->fSettings.fRTFlipOffset,
5310 /*binding=*/-1,
5311 /*index=*/-1,
5312 /*set=*/-1,
5313 /*builtin=*/-1,
5314 /*inputAttachmentIndex=*/-1),
5315 ModifierFlag::kNone,
5316 SKSL_RTFLIP_NAME,
5317 fContext.fTypes.fFloat2.get());
5318 std::string_view name = "sksl_synthetic_uniforms";
5319 const Type* intfStruct = fSynthetics.takeOwnershipOfSymbol(Type::MakeStructType(
5320 fContext, Position(), name, std::move(fields), /*interfaceBlock=*/true));
5321 bool usePushConstants = fProgram.fConfig->fSettings.fUseVulkanPushConstantsForGaneshRTAdjust;
5322 int binding = -1, set = -1;
5323 if (!usePushConstants) {
5324 binding = fProgram.fConfig->fSettings.fRTFlipBinding;
5325 if (binding == -1) {
5326 fContext.fErrors->error(pos, "layout(binding=...) is required in SPIR-V");
5327 }
5328 set = fProgram.fConfig->fSettings.fRTFlipSet;
5329 if (set == -1) {
5330 fContext.fErrors->error(pos, "layout(set=...) is required in SPIR-V");
5331 }
5332 }
5333 Layout layout(/*flags=*/usePushConstants ? LayoutFlag::kPushConstant : LayoutFlag::kNone,
5334 /*location=*/-1,
5335 /*offset=*/-1,
5336 binding,
5337 /*index=*/-1,
5338 set,
5339 /*builtin=*/-1,
5340 /*inputAttachmentIndex=*/-1);
5341 Variable* intfVar =
5342 fSynthetics.takeOwnershipOfSymbol(Variable::Make(/*pos=*/Position(),
5343 /*modifiersPosition=*/Position(),
5344 layout,
5345 ModifierFlag::kUniform,
5346 intfStruct,
5347 name,
5348 /*mangledName=*/"",
5349 /*builtin=*/false,
5350 Variable::Storage::kGlobal));
5351 {
5352 AutoAttachPoolToThread attach(fProgram.fPool.get());
5353 fProgram.fSymbols->add(fContext,
5354 std::make_unique<FieldSymbol>(Position(), intfVar, /*field=*/0));
5355 }
5356 InterfaceBlock intf(Position(), intfVar);
5357 this->writeInterfaceBlock(intf, false);
5358 }
5359
5360 std::tuple<const Variable*, const Variable*> SPIRVCodeGenerator::synthesizeTextureAndSampler(
5361 const Variable& combinedSampler) {
5362 SkASSERT(fUseTextureSamplerPairs);
5363 SkASSERT(combinedSampler.type().typeKind() == Type::TypeKind::kSampler);
5364
5365 if (std::unique_ptr<SynthesizedTextureSamplerPair>* existingData =
5366 fSynthesizedSamplerMap.find(&combinedSampler)) {
5367 return {(*existingData)->fTexture.get(), (*existingData)->fSampler.get()};
5368 }
5369
5370 auto data = std::make_unique<SynthesizedTextureSamplerPair>();
5371
5372 Layout texLayout = combinedSampler.layout();
5373 texLayout.fBinding = texLayout.fTexture;
5374 data->fTextureName = std::string(combinedSampler.name()) + "_texture";
5375
5376 auto texture = Variable::Make(/*pos=*/Position(),
5377 /*modifiersPosition=*/Position(),
5378 texLayout,
5379 combinedSampler.modifierFlags(),
5380 &combinedSampler.type().textureType(),
5381 data->fTextureName,
5382 /*mangledName=*/"",
5383 /*builtin=*/false,
5384 Variable::Storage::kGlobal);
5385
5386 Layout samplerLayout = combinedSampler.layout();
5387 samplerLayout.fBinding = samplerLayout.fSampler;
5388 samplerLayout.fFlags &= ~LayoutFlag::kAllPixelFormats;
5389 data->fSamplerName = std::string(combinedSampler.name()) + "_sampler";
5390
5391 auto sampler = Variable::Make(/*pos=*/Position(),
5392 /*modifiersPosition=*/Position(),
5393 samplerLayout,
5394 combinedSampler.modifierFlags(),
5395 fContext.fTypes.fSampler.get(),
5396 data->fSamplerName,
5397 /*mangledName=*/"",
5398 /*builtin=*/false,
5399 Variable::Storage::kGlobal);
5400
5401 const Variable* t = texture.get();
5402 const Variable* s = sampler.get();
5403 data->fTexture = std::move(texture);
5404 data->fSampler = std::move(sampler);
5405 fSynthesizedSamplerMap.set(&combinedSampler, std::move(data));
5406
5407 return {t, s};
5408 }
5409
5410 void SPIRVCodeGenerator::writeInstructions(const Program& program, SPIRVBlob& out) {
5411 Analysis::FindFunctionsToSpecialize(program, &fSpecializationInfo, [](const Variable& param) {
5412 return param.type().isSampler() || param.type().isUnsizedArray();
5413 });
5414
5415 // Pre-declare some types that the SPIR-V transformer expects to always be present.
5416 // int:
5417 this->writeInstruction(
5418 SpvOpTypeInt,
5419 Words{Word::ReservedResult(spirv::kIdTypeInt), Word::Number(32), Word::Number(1)},
5420 fConstantBuffer);
5421 // int pointer:
5422 this->writeInstruction(SpvOpTypePointer,
5423 Words{Word::ReservedResult(spirv::kIdTypePointerInputInt),
5424 Word::Number(SpvStorageClassInput),
5425 (SpvId)spirv::kIdTypeInt},
5426 fConstantBuffer);
5427
5428 fGLSLExtendedInstructions = this->nextId(nullptr);
5429 SPIRVBlob body;
5430 // Based on statistics from dm tests:
5431 // Total word count of the shader's function bodies is ~1300 on average, ~10000 max.
5432 body.reserve(1024);
5433
5434 // Do an initial pass over the program elements to establish some baseline info.
5435 const FunctionDeclaration* main = nullptr;
5436 int localSizeX = 1, localSizeY = 1, localSizeZ = 1;
5437 Position combinedSamplerPos;
5438 Position separateSamplerPos;
5439 for (const ProgramElement* e : program.elements()) {
5440 switch (e->kind()) {
5441 case ProgramElement::Kind::kFunction: {
5442 // Assign SpvIds to functions.
5443 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
5444 const FunctionDeclaration& funcDecl = funcDef.declaration();
5445 if (const Analysis::Specializations* specializations =
5446 fSpecializationInfo.fSpecializationMap.find(&funcDecl)) {
5447 for (int i = 0; i < specializations->size(); i++) {
5448 fFunctionMap.set({&funcDecl, i}, this->nextId(&funcDecl.returnType()));
5449 }
5450 } else {
5451 fFunctionMap.set({&funcDecl, Analysis::kUnspecialized},
5452 this->nextId(&funcDecl.returnType()));
5453 }
5454 if (funcDecl.isMain()) {
5455 main = &funcDecl;
5456 }
5457 break;
5458 }
5459 case ProgramElement::Kind::kGlobalVar: {
5460 // Look for sampler variables and determine whether or not this program uses
5461 // combined samplers or separate samplers. The layout backend will be marked as
5462 // WebGPU for separate samplers, or Vulkan for combined samplers.
5463 const GlobalVarDeclaration& decl = e->as<GlobalVarDeclaration>();
5464 const Variable& var = *decl.varDeclaration().var();
5465 if (var.type().isSampler()) {
5466 if (var.layout().fFlags & LayoutFlag::kVulkan) {
5467 combinedSamplerPos = decl.position();
5468 }
5469 if (var.layout().fFlags & (LayoutFlag::kWebGPU | LayoutFlag::kDirect3D)) {
5470 separateSamplerPos = decl.position();
5471 }
5472 }
5473 break;
5474 }
5475 case ProgramElement::Kind::kModifiers: {
5476 // If this is a compute program, collect the local-size values. Dimensions that are
5477 // not present will be assigned a value of 1.
5478 if (ProgramConfig::IsCompute(program.fConfig->fKind)) {
5479 const ModifiersDeclaration& modifiers = e->as<ModifiersDeclaration>();
5480 if (modifiers.layout().fLocalSizeX >= 0) {
5481 localSizeX = modifiers.layout().fLocalSizeX;
5482 }
5483 if (modifiers.layout().fLocalSizeY >= 0) {
5484 localSizeY = modifiers.layout().fLocalSizeY;
5485 }
5486 if (modifiers.layout().fLocalSizeZ >= 0) {
5487 localSizeZ = modifiers.layout().fLocalSizeZ;
5488 }
5489 }
5490 break;
5491 }
5492 default:
5493 break;
5494 }
5495 }
5496
5497 // Make sure we have a main() function.
5498 if (!main) {
5499 fContext.fErrors->error(Position(), "program does not contain a main() function");
5500 return;
5501 }
5502 // Make sure our program's sampler usage is consistent.
5503 if (combinedSamplerPos.valid() && separateSamplerPos.valid()) {
5504 fContext.fErrors->error(Position(), "programs cannot contain a mixture of sampler types");
5505 fContext.fErrors->error(combinedSamplerPos, "combined sampler found here:");
5506 fContext.fErrors->error(separateSamplerPos, "separate sampler found here:");
5507 return;
5508 }
5509 fUseTextureSamplerPairs = separateSamplerPos.valid();
5510
5511 // Emit interface blocks.
5512 std::set<SpvId> interfaceVars;
5513 for (const ProgramElement* e : program.elements()) {
5514 if (e->is<InterfaceBlock>()) {
5515 const InterfaceBlock& intf = e->as<InterfaceBlock>();
5516 SpvId id = this->writeInterfaceBlock(intf);
5517
5518 if ((intf.var()->modifierFlags() & (ModifierFlag::kIn | ModifierFlag::kOut)) &&
5519 intf.var()->layout().fBuiltin == -1) {
5520 interfaceVars.insert(id);
5521 }
5522 }
5523 }
5524 // If MustDeclareFragmentFrontFacing is set, the front-facing flag (sk_Clockwise) needs to be
5525 // explicitly declared in the output, whether or not the program explicitly references it.
5526 // However, if the program naturally declares it, we don't want to include it a second time;
5527 // we keep track of the real global variable declarations to see if sk_Clockwise is emitted.
5528 const VarDeclaration* missingClockwiseDecl = nullptr;
5529 if (fCaps.fMustDeclareFragmentFrontFacing) {
5530 if (const Symbol* clockwise = program.fSymbols->findBuiltinSymbol("sk_Clockwise")) {
5531 missingClockwiseDecl = clockwise->as<Variable>().varDeclaration();
5532 }
5533 }
5534 // Emit global variable declarations.
5535 for (const ProgramElement* e : program.elements()) {
5536 if (e->is<GlobalVarDeclaration>()) {
5537 const VarDeclaration& decl = e->as<GlobalVarDeclaration>().varDeclaration();
5538 if (!this->writeGlobalVarDeclaration(program.fConfig->fKind, decl)) {
5539 return;
5540 }
5541 if (missingClockwiseDecl == &decl) {
5542 // We emitted an sk_Clockwise declaration naturally, so we don't need a workaround.
5543 missingClockwiseDecl = nullptr;
5544 }
5545 }
5546 }
5547 // All the global variables have been declared. If sk_Clockwise was not naturally included in
5548 // the output, but MustDeclareFragmentFrontFacing was set, we need to bodge it in ourselves.
5549 if (missingClockwiseDecl) {
5550 if (!this->writeGlobalVarDeclaration(program.fConfig->fKind, *missingClockwiseDecl)) {
5551 return;
5552 }
5553 missingClockwiseDecl = nullptr;
5554 }
5555 // Emit top-level uniforms into a dedicated uniform buffer.
5556 if (!fTopLevelUniforms.empty()) {
5557 this->writeUniformBuffer(get_top_level_symbol_table(*main));
5558 }
5559 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
5560 // main() and stores the result into sk_FragColor.
5561 EntrypointAdapter adapter;
5562 if (main->returnType().matches(*fContext.fTypes.fHalf4)) {
5563 adapter = this->writeEntrypointAdapter(*main);
5564 if (adapter.entrypointDecl) {
5565 fFunctionMap.set({adapter.entrypointDecl.get(), Analysis::kUnspecialized},
5566 this->nextId(nullptr));
5567 this->writeFunction(*adapter.entrypointDef, body);
5568 main = adapter.entrypointDecl.get();
5569 }
5570 }
5571 // Emit all the functions.
5572 for (const ProgramElement* e : program.elements()) {
5573 if (e->is<FunctionDefinition>()) {
5574 this->writeFunction(e->as<FunctionDefinition>(), body);
5575 }
5576 }
5577 // Add global in/out variables to the list of interface variables.
5578 for (const auto& [var, spvId] : fVariableMap) {
5579 if (var->storage() == Variable::Storage::kGlobal &&
5580 (var->modifierFlags() & (ModifierFlag::kIn | ModifierFlag::kOut))) {
5581 interfaceVars.insert(spvId);
5582 }
5583 }
5584 this->writeCapabilities(out);
5585 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
5586 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
5587 this->writeOpCode(SpvOpEntryPoint,
5588 (SpvId)(3 + (main->name().length() + 4) / 4) + (int32_t)interfaceVars.size(),
5589 out);
5590 if (ProgramConfig::IsVertex(program.fConfig->fKind)) {
5591 this->writeWord(SpvExecutionModelVertex, out);
5592 } else if (ProgramConfig::IsFragment(program.fConfig->fKind)) {
5593 this->writeWord(SpvExecutionModelFragment, out);
5594 } else if (ProgramConfig::IsCompute(program.fConfig->fKind)) {
5595 this->writeWord(SpvExecutionModelGLCompute, out);
5596 } else {
5597 SK_ABORT("cannot write this kind of program to SPIR-V\n");
5598 }
5599 const Analysis::SpecializedFunctionKey mainKey{main, Analysis::kUnspecialized};
5600 SpvId entryPoint = fFunctionMap[mainKey];
5601 this->writeWord(entryPoint, out);
5602 this->writeString(main->name(), out);
5603 for (int var : interfaceVars) {
5604 this->writeWord(var, out);
5605 }
5606 if (ProgramConfig::IsFragment(program.fConfig->fKind)) {
5607 this->writeInstruction(SpvOpExecutionMode,
5608 fFunctionMap[mainKey],
5609 SpvExecutionModeOriginUpperLeft,
5610 out);
5611 } else if (ProgramConfig::IsCompute(program.fConfig->fKind)) {
5612 this->writeInstruction(SpvOpExecutionMode,
5613 fFunctionMap[mainKey],
5614 SpvExecutionModeLocalSize,
5615 localSizeX, localSizeY, localSizeZ,
5616 out);
5617 }
5618 for (const ProgramElement* e : program.elements()) {
5619 if (e->is<Extension>()) {
5620 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name(), out);
5621 }
5622 }
5623
5624 append_blob(fNameBuffer, out);
5625 append_blob(fDecorationBuffer, out);
5626 append_blob(fConstantBuffer, out);
5627 append_blob(body, out);
5628 }
5629
5630 bool SPIRVCodeGenerator::generateCode() {
5631 SkASSERT(!fContext.fErrors->errorCount());
5632 this->writeWord(SpvMagicNumber, *fOutBuffer);
5633 this->writeWord(SpvVersion, *fOutBuffer);
5634 this->writeWord(SKSL_MAGIC, *fOutBuffer);
5635 // Placeholder for id count, to be determined after writeInstruction.
5636 this->writeWord(0, *fOutBuffer);
5637 // reserved, always zero
5638 this->writeWord(0, *fOutBuffer);
5639 this->writeInstructions(fProgram, *fOutBuffer);
5640 // Set the id count now that it's determined.
5641 (*fOutBuffer)[3] = fIdCount;
5642 return fContext.fErrors->errorCount() == 0;
5643 }
5644
5645 bool ToSPIRV(Program& program,
5646 const ShaderCaps* caps,
5647 OutputStream& out,
5648 ValidateSPIRVProc validateSPIRV) {
5649 std::vector<uint32_t> buffer;
5650 if (!ToSPIRV(program, caps, &buffer, validateSPIRV)) {
5651 return false;
5652 }
5653 out.write(buffer.data(), buffer.size() * sizeof(uint32_t));
5654 return true;
5655 }
5656
5657 bool ToSPIRV(Program& program,
5658 const ShaderCaps* caps,
5659 std::vector<uint32_t>* out,
5660 ValidateSPIRVProc validateSPIRV) {
5661 TRACE_EVENT0("skia.shaders", "SkSL::ToSPIRV");
5662 SkASSERT(caps != nullptr);
5663
5664 out->clear();
5665 program.fContext->fErrors->setSource(*program.fSource);
5666
5667 SPIRVCodeGenerator cg(program.fContext.get(), caps, &program, out);
5668 bool result = cg.generateCode();
5669
5670 if (validateSPIRV) {
5671 if (result && program.fConfig->fSettings.fValidateSPIRV) {
5672 result = validateSPIRV(*program.fContext->fErrors, *out);
5673 }
5674 }
5675
5676 program.fContext->fErrors->setSource(std::string_view());
5677
5678 return result;
5679 }
5680
5681 } // namespace SkSL