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/SkSLSPIRVCodeGenerator.h"
9
10#include "src/sksl/GLSL.std.450.h"
11
12#include "src/sksl/SkSLCompiler.h"
13#include "src/sksl/ir/SkSLExpressionStatement.h"
14#include "src/sksl/ir/SkSLExtension.h"
15#include "src/sksl/ir/SkSLIndexExpression.h"
16#include "src/sksl/ir/SkSLVariableReference.h"
17
18#ifdef SK_VULKAN
19#include "src/gpu/vk/GrVkCaps.h"
20#endif
21
22namespace SkSL {
23
24static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
25
26void SPIRVCodeGenerator::setupIntrinsics() {
27#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicKind, GLSLstd450 ## x, GLSLstd450 ## x, \
28 GLSLstd450 ## x, GLSLstd450 ## x)
29#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicKind, \
30 GLSLstd450 ## ifFloat, \
31 GLSLstd450 ## ifInt, \
32 GLSLstd450 ## ifUInt, \
33 SpvOpUndef)
34#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicKind, SpvOp ## x, SpvOp ## x, SpvOp ## x, \
35 SpvOp ## x)
36#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic, \
37 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
38 k ## x ## _SpecialIntrinsic)
39 fIntrinsicMap[String("round")] = ALL_GLSL(Round);
40 fIntrinsicMap[String("roundEven")] = ALL_GLSL(RoundEven);
41 fIntrinsicMap[String("trunc")] = ALL_GLSL(Trunc);
42 fIntrinsicMap[String("abs")] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
43 fIntrinsicMap[String("sign")] = BY_TYPE_GLSL(FSign, SSign, SSign);
44 fIntrinsicMap[String("floor")] = ALL_GLSL(Floor);
45 fIntrinsicMap[String("ceil")] = ALL_GLSL(Ceil);
46 fIntrinsicMap[String("fract")] = ALL_GLSL(Fract);
47 fIntrinsicMap[String("radians")] = ALL_GLSL(Radians);
48 fIntrinsicMap[String("degrees")] = ALL_GLSL(Degrees);
49 fIntrinsicMap[String("sin")] = ALL_GLSL(Sin);
50 fIntrinsicMap[String("cos")] = ALL_GLSL(Cos);
51 fIntrinsicMap[String("tan")] = ALL_GLSL(Tan);
52 fIntrinsicMap[String("asin")] = ALL_GLSL(Asin);
53 fIntrinsicMap[String("acos")] = ALL_GLSL(Acos);
54 fIntrinsicMap[String("atan")] = SPECIAL(Atan);
55 fIntrinsicMap[String("sinh")] = ALL_GLSL(Sinh);
56 fIntrinsicMap[String("cosh")] = ALL_GLSL(Cosh);
57 fIntrinsicMap[String("tanh")] = ALL_GLSL(Tanh);
58 fIntrinsicMap[String("asinh")] = ALL_GLSL(Asinh);
59 fIntrinsicMap[String("acosh")] = ALL_GLSL(Acosh);
60 fIntrinsicMap[String("atanh")] = ALL_GLSL(Atanh);
61 fIntrinsicMap[String("pow")] = ALL_GLSL(Pow);
62 fIntrinsicMap[String("exp")] = ALL_GLSL(Exp);
63 fIntrinsicMap[String("log")] = ALL_GLSL(Log);
64 fIntrinsicMap[String("exp2")] = ALL_GLSL(Exp2);
65 fIntrinsicMap[String("log2")] = ALL_GLSL(Log2);
66 fIntrinsicMap[String("sqrt")] = ALL_GLSL(Sqrt);
67 fIntrinsicMap[String("inverse")] = ALL_GLSL(MatrixInverse);
68 fIntrinsicMap[String("transpose")] = ALL_SPIRV(Transpose);
69 fIntrinsicMap[String("inversesqrt")] = ALL_GLSL(InverseSqrt);
70 fIntrinsicMap[String("determinant")] = ALL_GLSL(Determinant);
71 fIntrinsicMap[String("matrixInverse")] = ALL_GLSL(MatrixInverse);
72 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
73 fIntrinsicMap[String("min")] = SPECIAL(Min);
74 fIntrinsicMap[String("max")] = SPECIAL(Max);
75 fIntrinsicMap[String("clamp")] = SPECIAL(Clamp);
76 fIntrinsicMap[String("saturate")] = SPECIAL(Saturate);
77 fIntrinsicMap[String("dot")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpDot,
78 SpvOpUndef, SpvOpUndef, SpvOpUndef);
79 fIntrinsicMap[String("mix")] = SPECIAL(Mix);
80 fIntrinsicMap[String("step")] = ALL_GLSL(Step);
81 fIntrinsicMap[String("smoothstep")] = ALL_GLSL(SmoothStep);
82 fIntrinsicMap[String("fma")] = ALL_GLSL(Fma);
83 fIntrinsicMap[String("frexp")] = ALL_GLSL(Frexp);
84 fIntrinsicMap[String("ldexp")] = ALL_GLSL(Ldexp);
85
86#define PACK(type) fIntrinsicMap[String("pack" #type)] = ALL_GLSL(Pack ## type); \
87 fIntrinsicMap[String("unpack" #type)] = ALL_GLSL(Unpack ## type)
88 PACK(Snorm4x8);
89 PACK(Unorm4x8);
90 PACK(Snorm2x16);
91 PACK(Unorm2x16);
92 PACK(Half2x16);
93 PACK(Double2x32);
94 fIntrinsicMap[String("length")] = ALL_GLSL(Length);
95 fIntrinsicMap[String("distance")] = ALL_GLSL(Distance);
96 fIntrinsicMap[String("cross")] = ALL_GLSL(Cross);
97 fIntrinsicMap[String("normalize")] = ALL_GLSL(Normalize);
98 fIntrinsicMap[String("faceForward")] = ALL_GLSL(FaceForward);
99 fIntrinsicMap[String("reflect")] = ALL_GLSL(Reflect);
100 fIntrinsicMap[String("refract")] = ALL_GLSL(Refract);
101 fIntrinsicMap[String("findLSB")] = ALL_GLSL(FindILsb);
102 fIntrinsicMap[String("findMSB")] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
103 fIntrinsicMap[String("dFdx")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpDPdx,
104 SpvOpUndef, SpvOpUndef, SpvOpUndef);
105 fIntrinsicMap[String("dFdy")] = SPECIAL(DFdy);
106 fIntrinsicMap[String("fwidth")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpFwidth,
107 SpvOpUndef, SpvOpUndef, SpvOpUndef);
108 fIntrinsicMap[String("makeSampler2D")] = SPECIAL(SampledImage);
109
110 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
111 fIntrinsicMap[String("subpassLoad")] = SPECIAL(SubpassLoad);
112
113 fIntrinsicMap[String("any")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpUndef,
114 SpvOpUndef, SpvOpUndef, SpvOpAny);
115 fIntrinsicMap[String("all")] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpUndef,
116 SpvOpUndef, SpvOpUndef, SpvOpAll);
117 fIntrinsicMap[String("equal")] = std::make_tuple(kSPIRV_IntrinsicKind,
118 SpvOpFOrdEqual, SpvOpIEqual,
119 SpvOpIEqual, SpvOpLogicalEqual);
120 fIntrinsicMap[String("notEqual")] = std::make_tuple(kSPIRV_IntrinsicKind,
121 SpvOpFOrdNotEqual, SpvOpINotEqual,
122 SpvOpINotEqual,
123 SpvOpLogicalNotEqual);
124 fIntrinsicMap[String("lessThan")] = std::make_tuple(kSPIRV_IntrinsicKind,
125 SpvOpFOrdLessThan, SpvOpSLessThan,
126 SpvOpULessThan, SpvOpUndef);
127 fIntrinsicMap[String("lessThanEqual")] = std::make_tuple(kSPIRV_IntrinsicKind,
128 SpvOpFOrdLessThanEqual,
129 SpvOpSLessThanEqual,
130 SpvOpULessThanEqual,
131 SpvOpUndef);
132 fIntrinsicMap[String("greaterThan")] = std::make_tuple(kSPIRV_IntrinsicKind,
133 SpvOpFOrdGreaterThan,
134 SpvOpSGreaterThan,
135 SpvOpUGreaterThan,
136 SpvOpUndef);
137 fIntrinsicMap[String("greaterThanEqual")] = std::make_tuple(kSPIRV_IntrinsicKind,
138 SpvOpFOrdGreaterThanEqual,
139 SpvOpSGreaterThanEqual,
140 SpvOpUGreaterThanEqual,
141 SpvOpUndef);
142 fIntrinsicMap[String("EmitVertex")] = ALL_SPIRV(EmitVertex);
143 fIntrinsicMap[String("EndPrimitive")] = ALL_SPIRV(EndPrimitive);
144// interpolateAt* not yet supported...
145}
146
147void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
148 out.write((const char*) &word, sizeof(word));
149}
150
151static bool is_float(const Context& context, const Type& type) {
152 if (type.columns() > 1) {
153 return is_float(context, type.componentType());
154 }
155 return type == *context.fFloat_Type || type == *context.fHalf_Type;
156}
157
158static bool is_signed(const Context& context, const Type& type) {
159 if (type.kind() == Type::kVector_Kind) {
160 return is_signed(context, type.componentType());
161 }
162 return type == *context.fInt_Type || type == *context.fShort_Type ||
163 type == *context.fByte_Type;
164}
165
166static bool is_unsigned(const Context& context, const Type& type) {
167 if (type.kind() == Type::kVector_Kind) {
168 return is_unsigned(context, type.componentType());
169 }
170 return type == *context.fUInt_Type || type == *context.fUShort_Type ||
171 type == *context.fUByte_Type;
172}
173
174static bool is_bool(const Context& context, const Type& type) {
175 if (type.kind() == Type::kVector_Kind) {
176 return is_bool(context, type.componentType());
177 }
178 return type == *context.fBool_Type;
179}
180
181static bool is_out(const Variable& var) {
182 return (var.fModifiers.fFlags & Modifiers::kOut_Flag) != 0;
183}
184
185void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
186 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
187 SkASSERT(opCode != SpvOpUndef);
188 switch (opCode) {
189 case SpvOpReturn: // fall through
190 case SpvOpReturnValue: // fall through
191 case SpvOpKill: // fall through
192 case SpvOpBranch: // fall through
193 case SpvOpBranchConditional:
194 SkASSERT(fCurrentBlock);
195 fCurrentBlock = 0;
196 break;
197 case SpvOpConstant: // fall through
198 case SpvOpConstantTrue: // fall through
199 case SpvOpConstantFalse: // fall through
200 case SpvOpConstantComposite: // fall through
201 case SpvOpTypeVoid: // fall through
202 case SpvOpTypeInt: // fall through
203 case SpvOpTypeFloat: // fall through
204 case SpvOpTypeBool: // fall through
205 case SpvOpTypeVector: // fall through
206 case SpvOpTypeMatrix: // fall through
207 case SpvOpTypeArray: // fall through
208 case SpvOpTypePointer: // fall through
209 case SpvOpTypeFunction: // fall through
210 case SpvOpTypeRuntimeArray: // fall through
211 case SpvOpTypeStruct: // fall through
212 case SpvOpTypeImage: // fall through
213 case SpvOpTypeSampledImage: // fall through
214 case SpvOpTypeSampler: // fall through
215 case SpvOpVariable: // fall through
216 case SpvOpFunction: // fall through
217 case SpvOpFunctionParameter: // fall through
218 case SpvOpFunctionEnd: // fall through
219 case SpvOpExecutionMode: // fall through
220 case SpvOpMemoryModel: // fall through
221 case SpvOpCapability: // fall through
222 case SpvOpExtInstImport: // fall through
223 case SpvOpEntryPoint: // fall through
224 case SpvOpSource: // fall through
225 case SpvOpSourceExtension: // fall through
226 case SpvOpName: // fall through
227 case SpvOpMemberName: // fall through
228 case SpvOpDecorate: // fall through
229 case SpvOpMemberDecorate:
230 break;
231 default:
232 SkASSERT(fCurrentBlock);
233 }
234 this->writeWord((length << 16) | opCode, out);
235}
236
237void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
238 fCurrentBlock = label;
239 this->writeInstruction(SpvOpLabel, label, out);
240}
241
242void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
243 this->writeOpCode(opCode, 1, out);
244}
245
246void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
247 this->writeOpCode(opCode, 2, out);
248 this->writeWord(word1, out);
249}
250
251void SPIRVCodeGenerator::writeString(const char* string, size_t length, OutputStream& out) {
252 out.write(string, length);
253 switch (length % 4) {
254 case 1:
255 out.write8(0);
256 [[fallthrough]];
257 case 2:
258 out.write8(0);
259 [[fallthrough]];
260 case 3:
261 out.write8(0);
262 break;
263 default:
264 this->writeWord(0, out);
265 }
266}
267
268void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, StringFragment string, OutputStream& out) {
269 this->writeOpCode(opCode, 1 + (string.fLength + 4) / 4, out);
270 this->writeString(string.fChars, string.fLength, out);
271}
272
273
274void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, StringFragment string,
275 OutputStream& out) {
276 this->writeOpCode(opCode, 2 + (string.fLength + 4) / 4, out);
277 this->writeWord(word1, out);
278 this->writeString(string.fChars, string.fLength, out);
279}
280
281void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
282 StringFragment string, OutputStream& out) {
283 this->writeOpCode(opCode, 3 + (string.fLength + 4) / 4, out);
284 this->writeWord(word1, out);
285 this->writeWord(word2, out);
286 this->writeString(string.fChars, string.fLength, out);
287}
288
289void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
290 OutputStream& out) {
291 this->writeOpCode(opCode, 3, out);
292 this->writeWord(word1, out);
293 this->writeWord(word2, out);
294}
295
296void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
297 int32_t word3, OutputStream& out) {
298 this->writeOpCode(opCode, 4, out);
299 this->writeWord(word1, out);
300 this->writeWord(word2, out);
301 this->writeWord(word3, out);
302}
303
304void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
305 int32_t word3, int32_t word4, OutputStream& out) {
306 this->writeOpCode(opCode, 5, out);
307 this->writeWord(word1, out);
308 this->writeWord(word2, out);
309 this->writeWord(word3, out);
310 this->writeWord(word4, out);
311}
312
313void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
314 int32_t word3, int32_t word4, int32_t word5,
315 OutputStream& out) {
316 this->writeOpCode(opCode, 6, out);
317 this->writeWord(word1, out);
318 this->writeWord(word2, out);
319 this->writeWord(word3, out);
320 this->writeWord(word4, out);
321 this->writeWord(word5, out);
322}
323
324void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
325 int32_t word3, int32_t word4, int32_t word5,
326 int32_t word6, OutputStream& out) {
327 this->writeOpCode(opCode, 7, out);
328 this->writeWord(word1, out);
329 this->writeWord(word2, out);
330 this->writeWord(word3, out);
331 this->writeWord(word4, out);
332 this->writeWord(word5, out);
333 this->writeWord(word6, out);
334}
335
336void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
337 int32_t word3, int32_t word4, int32_t word5,
338 int32_t word6, int32_t word7, OutputStream& out) {
339 this->writeOpCode(opCode, 8, out);
340 this->writeWord(word1, out);
341 this->writeWord(word2, out);
342 this->writeWord(word3, out);
343 this->writeWord(word4, out);
344 this->writeWord(word5, out);
345 this->writeWord(word6, out);
346 this->writeWord(word7, out);
347}
348
349void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
350 int32_t word3, int32_t word4, int32_t word5,
351 int32_t word6, int32_t word7, int32_t word8,
352 OutputStream& out) {
353 this->writeOpCode(opCode, 9, out);
354 this->writeWord(word1, out);
355 this->writeWord(word2, out);
356 this->writeWord(word3, out);
357 this->writeWord(word4, out);
358 this->writeWord(word5, out);
359 this->writeWord(word6, out);
360 this->writeWord(word7, out);
361 this->writeWord(word8, out);
362}
363
364void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
365 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
366 if (fCapabilities & bit) {
367 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
368 }
369 }
370 if (fProgram.fKind == Program::kGeometry_Kind) {
371 this->writeInstruction(SpvOpCapability, SpvCapabilityGeometry, out);
372 }
373 else {
374 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
375 }
376}
377
378SpvId SPIRVCodeGenerator::nextId() {
379 return fIdCount++;
380}
381
382void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
383 SpvId resultId) {
384 this->writeInstruction(SpvOpName, resultId, type.name().c_str(), fNameBuffer);
385 // go ahead and write all of the field types, so we don't inadvertently write them while we're
386 // in the middle of writing the struct instruction
387 std::vector<SpvId> types;
388 for (const auto& f : type.fields()) {
389 types.push_back(this->getType(*f.fType, memoryLayout));
390 }
391 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
392 this->writeWord(resultId, fConstantBuffer);
393 for (SpvId id : types) {
394 this->writeWord(id, fConstantBuffer);
395 }
396 size_t offset = 0;
397 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
398 const Type::Field& field = type.fields()[i];
399 size_t size = memoryLayout.size(*field.fType);
400 size_t alignment = memoryLayout.alignment(*field.fType);
401 const Layout& fieldLayout = field.fModifiers.fLayout;
402 if (fieldLayout.fOffset >= 0) {
403 if (fieldLayout.fOffset < (int) offset) {
404 fErrors.error(type.fOffset,
405 "offset of field '" + field.fName + "' must be at "
406 "least " + to_string((int) offset));
407 }
408 if (fieldLayout.fOffset % alignment) {
409 fErrors.error(type.fOffset,
410 "offset of field '" + field.fName + "' must be a multiple"
411 " of " + to_string((int) alignment));
412 }
413 offset = fieldLayout.fOffset;
414 } else {
415 size_t mod = offset % alignment;
416 if (mod) {
417 offset += alignment - mod;
418 }
419 }
420 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
421 this->writeLayout(fieldLayout, resultId, i);
422 if (field.fModifiers.fLayout.fBuiltin < 0) {
423 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
424 (SpvId) offset, fDecorationBuffer);
425 }
426 if (field.fType->kind() == Type::kMatrix_Kind) {
427 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
428 fDecorationBuffer);
429 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
430 (SpvId) memoryLayout.stride(*field.fType),
431 fDecorationBuffer);
432 }
433 if (!field.fType->highPrecision()) {
434 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
435 SpvDecorationRelaxedPrecision, fDecorationBuffer);
436 }
437 offset += size;
438 Type::Kind kind = field.fType->kind();
439 if ((kind == Type::kArray_Kind || kind == Type::kStruct_Kind) && offset % alignment != 0) {
440 offset += alignment - offset % alignment;
441 }
442 }
443}
444
445Type SPIRVCodeGenerator::getActualType(const Type& type) {
446 if (type.isFloat()) {
447 return *fContext.fFloat_Type;
448 }
449 if (type.isSigned()) {
450 return *fContext.fInt_Type;
451 }
452 if (type.isUnsigned()) {
453 return *fContext.fUInt_Type;
454 }
455 if (type.kind() == Type::kMatrix_Kind || type.kind() == Type::kVector_Kind) {
456 if (type.componentType() == *fContext.fHalf_Type) {
457 return fContext.fFloat_Type->toCompound(fContext, type.columns(), type.rows());
458 }
459 if (type.componentType() == *fContext.fShort_Type ||
460 type.componentType() == *fContext.fByte_Type) {
461 return fContext.fInt_Type->toCompound(fContext, type.columns(), type.rows());
462 }
463 if (type.componentType() == *fContext.fUShort_Type ||
464 type.componentType() == *fContext.fUByte_Type) {
465 return fContext.fUInt_Type->toCompound(fContext, type.columns(), type.rows());
466 }
467 }
468 return type;
469}
470
471SpvId SPIRVCodeGenerator::getType(const Type& type) {
472 return this->getType(type, fDefaultLayout);
473}
474
475SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
476 Type type = this->getActualType(rawType);
477 String key = type.name() + to_string((int) layout.fStd);
478 auto entry = fTypeMap.find(key);
479 if (entry == fTypeMap.end()) {
480 SpvId result = this->nextId();
481 switch (type.kind()) {
482 case Type::kScalar_Kind:
483 if (type == *fContext.fBool_Type) {
484 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
485 } else if (type == *fContext.fInt_Type || type == *fContext.fShort_Type ||
486 type == *fContext.fIntLiteral_Type) {
487 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
488 } else if (type == *fContext.fUInt_Type || type == *fContext.fUShort_Type) {
489 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
490 } else if (type == *fContext.fFloat_Type || type == *fContext.fHalf_Type ||
491 type == *fContext.fFloatLiteral_Type) {
492 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
493 } else {
494 SkASSERT(false);
495 }
496 break;
497 case Type::kVector_Kind:
498 this->writeInstruction(SpvOpTypeVector, result,
499 this->getType(type.componentType(), layout),
500 type.columns(), fConstantBuffer);
501 break;
502 case Type::kMatrix_Kind:
503 this->writeInstruction(SpvOpTypeMatrix, result,
504 this->getType(index_type(fContext, type), layout),
505 type.columns(), fConstantBuffer);
506 break;
507 case Type::kStruct_Kind:
508 this->writeStruct(type, layout, result);
509 break;
510 case Type::kArray_Kind: {
511 if (type.columns() > 0) {
512 IntLiteral count(fContext, -1, type.columns());
513 this->writeInstruction(SpvOpTypeArray, result,
514 this->getType(type.componentType(), layout),
515 this->writeIntLiteral(count), fConstantBuffer);
516 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
517 (int32_t) layout.stride(type),
518 fDecorationBuffer);
519 } else {
520 SkASSERT(false); // we shouldn't have any runtime-sized arrays right now
521 this->writeInstruction(SpvOpTypeRuntimeArray, result,
522 this->getType(type.componentType(), layout),
523 fConstantBuffer);
524 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
525 (int32_t) layout.stride(type),
526 fDecorationBuffer);
527 }
528 break;
529 }
530 case Type::kSampler_Kind: {
531 SpvId image = result;
532 if (SpvDimSubpassData != type.dimensions()) {
533 image = this->getType(type.textureType(), layout);
534 }
535 if (SpvDimBuffer == type.dimensions()) {
536 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
537 }
538 if (SpvDimSubpassData != type.dimensions()) {
539 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
540 }
541 break;
542 }
543 case Type::kSeparateSampler_Kind: {
544 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
545 break;
546 }
547 case Type::kTexture_Kind: {
548 this->writeInstruction(SpvOpTypeImage, result,
549 this->getType(*fContext.fFloat_Type, layout),
550 type.dimensions(), type.isDepth(), type.isArrayed(),
551 type.isMultisampled(), type.isSampled() ? 1 : 2,
552 SpvImageFormatUnknown, fConstantBuffer);
553 fImageTypeMap[key] = result;
554 break;
555 }
556 default:
557 if (type == *fContext.fVoid_Type) {
558 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
559 } else {
560#ifdef SK_DEBUG
561 ABORT("invalid type: %s", type.description().c_str());
562#endif
563 }
564 }
565 fTypeMap[key] = result;
566 return result;
567 }
568 return entry->second;
569}
570
571SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
572 SkASSERT(type.kind() == Type::kSampler_Kind);
573 this->getType(type);
574 String key = type.name() + to_string((int) fDefaultLayout.fStd);
575 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
576 return fImageTypeMap[key];
577}
578
579SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
580 String key = to_string(this->getType(function.fReturnType)) + "(";
581 String separator;
582 for (size_t i = 0; i < function.fParameters.size(); i++) {
583 key += separator;
584 separator = ", ";
585 key += to_string(this->getType(function.fParameters[i]->fType));
586 }
587 key += ")";
588 auto entry = fTypeMap.find(key);
589 if (entry == fTypeMap.end()) {
590 SpvId result = this->nextId();
591 int32_t length = 3 + (int32_t) function.fParameters.size();
592 SpvId returnType = this->getType(function.fReturnType);
593 std::vector<SpvId> parameterTypes;
594 for (size_t i = 0; i < function.fParameters.size(); i++) {
595 // glslang seems to treat all function arguments as pointers whether they need to be or
596 // not. I was initially puzzled by this until I ran bizarre failures with certain
597 // patterns of function calls and control constructs, as exemplified by this minimal
598 // failure case:
599 //
600 // void sphere(float x) {
601 // }
602 //
603 // void map() {
604 // sphere(1.0);
605 // }
606 //
607 // void main() {
608 // for (int i = 0; i < 1; i++) {
609 // map();
610 // }
611 // }
612 //
613 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
614 // crashes. Making it take a float* and storing the argument in a temporary variable,
615 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
616 // the spec makes this make sense.
617// if (is_out(function->fParameters[i])) {
618 parameterTypes.push_back(this->getPointerType(function.fParameters[i]->fType,
619 SpvStorageClassFunction));
620// } else {
621// parameterTypes.push_back(this->getType(function.fParameters[i]->fType));
622// }
623 }
624 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
625 this->writeWord(result, fConstantBuffer);
626 this->writeWord(returnType, fConstantBuffer);
627 for (SpvId id : parameterTypes) {
628 this->writeWord(id, fConstantBuffer);
629 }
630 fTypeMap[key] = result;
631 return result;
632 }
633 return entry->second;
634}
635
636SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
637 return this->getPointerType(type, fDefaultLayout, storageClass);
638}
639
640SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
641 SpvStorageClass_ storageClass) {
642 Type type = this->getActualType(rawType);
643 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
644 auto entry = fTypeMap.find(key);
645 if (entry == fTypeMap.end()) {
646 SpvId result = this->nextId();
647 this->writeInstruction(SpvOpTypePointer, result, storageClass,
648 this->getType(type), fConstantBuffer);
649 fTypeMap[key] = result;
650 return result;
651 }
652 return entry->second;
653}
654
655SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
656 switch (expr.fKind) {
657 case Expression::kBinary_Kind:
658 return this->writeBinaryExpression((BinaryExpression&) expr, out);
659 case Expression::kBoolLiteral_Kind:
660 return this->writeBoolLiteral((BoolLiteral&) expr);
661 case Expression::kConstructor_Kind:
662 return this->writeConstructor((Constructor&) expr, out);
663 case Expression::kIntLiteral_Kind:
664 return this->writeIntLiteral((IntLiteral&) expr);
665 case Expression::kFieldAccess_Kind:
666 return this->writeFieldAccess(((FieldAccess&) expr), out);
667 case Expression::kFloatLiteral_Kind:
668 return this->writeFloatLiteral(((FloatLiteral&) expr));
669 case Expression::kFunctionCall_Kind:
670 return this->writeFunctionCall((FunctionCall&) expr, out);
671 case Expression::kPrefix_Kind:
672 return this->writePrefixExpression((PrefixExpression&) expr, out);
673 case Expression::kPostfix_Kind:
674 return this->writePostfixExpression((PostfixExpression&) expr, out);
675 case Expression::kSwizzle_Kind:
676 return this->writeSwizzle((Swizzle&) expr, out);
677 case Expression::kVariableReference_Kind:
678 return this->writeVariableReference((VariableReference&) expr, out);
679 case Expression::kTernary_Kind:
680 return this->writeTernaryExpression((TernaryExpression&) expr, out);
681 case Expression::kIndex_Kind:
682 return this->writeIndexExpression((IndexExpression&) expr, out);
683 default:
684#ifdef SK_DEBUG
685 ABORT("unsupported expression: %s", expr.description().c_str());
686#endif
687 break;
688 }
689 return -1;
690}
691
692SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
693 auto intrinsic = fIntrinsicMap.find(c.fFunction.fName);
694 SkASSERT(intrinsic != fIntrinsicMap.end());
695 int32_t intrinsicId;
696 if (c.fArguments.size() > 0) {
697 const Type& type = c.fArguments[0]->fType;
698 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicKind || is_float(fContext, type)) {
699 intrinsicId = std::get<1>(intrinsic->second);
700 } else if (is_signed(fContext, type)) {
701 intrinsicId = std::get<2>(intrinsic->second);
702 } else if (is_unsigned(fContext, type)) {
703 intrinsicId = std::get<3>(intrinsic->second);
704 } else if (is_bool(fContext, type)) {
705 intrinsicId = std::get<4>(intrinsic->second);
706 } else {
707 intrinsicId = std::get<1>(intrinsic->second);
708 }
709 } else {
710 intrinsicId = std::get<1>(intrinsic->second);
711 }
712 switch (std::get<0>(intrinsic->second)) {
713 case kGLSL_STD_450_IntrinsicKind: {
714 SpvId result = this->nextId();
715 std::vector<SpvId> arguments;
716 for (size_t i = 0; i < c.fArguments.size(); i++) {
717 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
718 arguments.push_back(this->getLValue(*c.fArguments[i], out)->getPointer());
719 } else {
720 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
721 }
722 }
723 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) arguments.size(), out);
724 this->writeWord(this->getType(c.fType), out);
725 this->writeWord(result, out);
726 this->writeWord(fGLSLExtendedInstructions, out);
727 this->writeWord(intrinsicId, out);
728 for (SpvId id : arguments) {
729 this->writeWord(id, out);
730 }
731 return result;
732 }
733 case kSPIRV_IntrinsicKind: {
734 SpvId result = this->nextId();
735 std::vector<SpvId> arguments;
736 for (size_t i = 0; i < c.fArguments.size(); i++) {
737 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
738 arguments.push_back(this->getLValue(*c.fArguments[i], out)->getPointer());
739 } else {
740 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
741 }
742 }
743 if (c.fType != *fContext.fVoid_Type) {
744 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
745 this->writeWord(this->getType(c.fType), out);
746 this->writeWord(result, out);
747 } else {
748 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
749 }
750 for (SpvId id : arguments) {
751 this->writeWord(id, out);
752 }
753 return result;
754 }
755 case kSpecial_IntrinsicKind:
756 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
757 default:
758 ABORT("unsupported intrinsic kind");
759 }
760}
761
762std::vector<SpvId> SPIRVCodeGenerator::vectorize(
763 const std::vector<std::unique_ptr<Expression>>& args,
764 OutputStream& out) {
765 int vectorSize = 0;
766 for (const auto& a : args) {
767 if (a->fType.kind() == Type::kVector_Kind) {
768 if (vectorSize) {
769 SkASSERT(a->fType.columns() == vectorSize);
770 }
771 else {
772 vectorSize = a->fType.columns();
773 }
774 }
775 }
776 std::vector<SpvId> result;
777 for (const auto& a : args) {
778 SpvId raw = this->writeExpression(*a, out);
779 if (vectorSize && a->fType.kind() == Type::kScalar_Kind) {
780 SpvId vector = this->nextId();
781 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
782 this->writeWord(this->getType(a->fType.toCompound(fContext, vectorSize, 1)), out);
783 this->writeWord(vector, out);
784 for (int i = 0; i < vectorSize; i++) {
785 this->writeWord(raw, out);
786 }
787 this->writePrecisionModifier(a->fType, vector);
788 result.push_back(vector);
789 } else {
790 result.push_back(raw);
791 }
792 }
793 return result;
794}
795
796void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
797 SpvId signedInst, SpvId unsignedInst,
798 const std::vector<SpvId>& args,
799 OutputStream& out) {
800 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
801 this->writeWord(this->getType(type), out);
802 this->writeWord(id, out);
803 this->writeWord(fGLSLExtendedInstructions, out);
804
805 if (is_float(fContext, type)) {
806 this->writeWord(floatInst, out);
807 } else if (is_signed(fContext, type)) {
808 this->writeWord(signedInst, out);
809 } else if (is_unsigned(fContext, type)) {
810 this->writeWord(unsignedInst, out);
811 } else {
812 SkASSERT(false);
813 }
814 for (SpvId a : args) {
815 this->writeWord(a, out);
816 }
817}
818
819SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
820 OutputStream& out) {
821 SpvId result = this->nextId();
822 switch (kind) {
823 case kAtan_SpecialIntrinsic: {
824 std::vector<SpvId> arguments;
825 for (size_t i = 0; i < c.fArguments.size(); i++) {
826 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
827 }
828 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) arguments.size(), out);
829 this->writeWord(this->getType(c.fType), out);
830 this->writeWord(result, out);
831 this->writeWord(fGLSLExtendedInstructions, out);
832 this->writeWord(arguments.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
833 for (SpvId id : arguments) {
834 this->writeWord(id, out);
835 }
836 break;
837 }
838 case kSampledImage_SpecialIntrinsic: {
839 SkASSERT(2 == c.fArguments.size());
840 SpvId img = this->writeExpression(*c.fArguments[0], out);
841 SpvId sampler = this->writeExpression(*c.fArguments[1], out);
842 this->writeInstruction(SpvOpSampledImage,
843 this->getType(c.fType),
844 result,
845 img,
846 sampler,
847 out);
848 break;
849 }
850 case kSubpassLoad_SpecialIntrinsic: {
851 SpvId img = this->writeExpression(*c.fArguments[0], out);
852 std::vector<std::unique_ptr<Expression>> args;
853 args.emplace_back(new FloatLiteral(fContext, -1, 0.0));
854 args.emplace_back(new FloatLiteral(fContext, -1, 0.0));
855 Constructor ctor(-1, *fContext.fFloat2_Type, std::move(args));
856 SpvId coords = this->writeConstantVector(ctor);
857 if (1 == c.fArguments.size()) {
858 this->writeInstruction(SpvOpImageRead,
859 this->getType(c.fType),
860 result,
861 img,
862 coords,
863 out);
864 } else {
865 SkASSERT(2 == c.fArguments.size());
866 SpvId sample = this->writeExpression(*c.fArguments[1], out);
867 this->writeInstruction(SpvOpImageRead,
868 this->getType(c.fType),
869 result,
870 img,
871 coords,
872 SpvImageOperandsSampleMask,
873 sample,
874 out);
875 }
876 break;
877 }
878 case kTexture_SpecialIntrinsic: {
879 SpvOp_ op = SpvOpImageSampleImplicitLod;
880 switch (c.fArguments[0]->fType.dimensions()) {
881 case SpvDim1D:
882 if (c.fArguments[1]->fType == *fContext.fFloat2_Type) {
883 op = SpvOpImageSampleProjImplicitLod;
884 } else {
885 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat_Type);
886 }
887 break;
888 case SpvDim2D:
889 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
890 op = SpvOpImageSampleProjImplicitLod;
891 } else {
892 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
893 }
894 break;
895 case SpvDim3D:
896 if (c.fArguments[1]->fType == *fContext.fFloat4_Type) {
897 op = SpvOpImageSampleProjImplicitLod;
898 } else {
899 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat3_Type);
900 }
901 break;
902 case SpvDimCube: // fall through
903 case SpvDimRect: // fall through
904 case SpvDimBuffer: // fall through
905 case SpvDimSubpassData:
906 break;
907 }
908 SpvId type = this->getType(c.fType);
909 SpvId sampler = this->writeExpression(*c.fArguments[0], out);
910 SpvId uv = this->writeExpression(*c.fArguments[1], out);
911 if (c.fArguments.size() == 3) {
912 this->writeInstruction(op, type, result, sampler, uv,
913 SpvImageOperandsBiasMask,
914 this->writeExpression(*c.fArguments[2], out),
915 out);
916 } else {
917 SkASSERT(c.fArguments.size() == 2);
918 if (fProgram.fSettings.fSharpenTextures) {
919 FloatLiteral lodBias(fContext, -1, -0.5);
920 this->writeInstruction(op, type, result, sampler, uv,
921 SpvImageOperandsBiasMask,
922 this->writeFloatLiteral(lodBias),
923 out);
924 } else {
925 this->writeInstruction(op, type, result, sampler, uv,
926 out);
927 }
928 }
929 break;
930 }
931 case kMod_SpecialIntrinsic: {
932 std::vector<SpvId> args = this->vectorize(c.fArguments, out);
933 SkASSERT(args.size() == 2);
934 const Type& operandType = c.fArguments[0]->fType;
935 SpvOp_ op;
936 if (is_float(fContext, operandType)) {
937 op = SpvOpFMod;
938 } else if (is_signed(fContext, operandType)) {
939 op = SpvOpSMod;
940 } else if (is_unsigned(fContext, operandType)) {
941 op = SpvOpUMod;
942 } else {
943 SkASSERT(false);
944 return 0;
945 }
946 this->writeOpCode(op, 5, out);
947 this->writeWord(this->getType(operandType), out);
948 this->writeWord(result, out);
949 this->writeWord(args[0], out);
950 this->writeWord(args[1], out);
951 break;
952 }
953 case kDFdy_SpecialIntrinsic: {
954 SpvId fn = this->writeExpression(*c.fArguments[0], out);
955 this->writeOpCode(SpvOpDPdy, 4, out);
956 this->writeWord(this->getType(c.fType), out);
957 this->writeWord(result, out);
958 this->writeWord(fn, out);
959 if (fProgram.fSettings.fFlipY) {
960 // Flipping Y also negates the Y derivatives.
961 SpvId flipped = this->nextId();
962 this->writeInstruction(SpvOpFNegate, this->getType(c.fType), flipped, result, out);
963 this->writePrecisionModifier(c.fType, flipped);
964 return flipped;
965 }
966 break;
967 }
968 case kClamp_SpecialIntrinsic: {
969 std::vector<SpvId> args = this->vectorize(c.fArguments, out);
970 SkASSERT(args.size() == 3);
971 this->writeGLSLExtendedInstruction(c.fType, result, GLSLstd450FClamp, GLSLstd450SClamp,
972 GLSLstd450UClamp, args, out);
973 break;
974 }
975 case kMax_SpecialIntrinsic: {
976 std::vector<SpvId> args = this->vectorize(c.fArguments, out);
977 SkASSERT(args.size() == 2);
978 this->writeGLSLExtendedInstruction(c.fType, result, GLSLstd450FMax, GLSLstd450SMax,
979 GLSLstd450UMax, args, out);
980 break;
981 }
982 case kMin_SpecialIntrinsic: {
983 std::vector<SpvId> args = this->vectorize(c.fArguments, out);
984 SkASSERT(args.size() == 2);
985 this->writeGLSLExtendedInstruction(c.fType, result, GLSLstd450FMin, GLSLstd450SMin,
986 GLSLstd450UMin, args, out);
987 break;
988 }
989 case kMix_SpecialIntrinsic: {
990 std::vector<SpvId> args = this->vectorize(c.fArguments, out);
991 SkASSERT(args.size() == 3);
992 this->writeGLSLExtendedInstruction(c.fType, result, GLSLstd450FMix, SpvOpUndef,
993 SpvOpUndef, args, out);
994 break;
995 }
996 case kSaturate_SpecialIntrinsic: {
997 SkASSERT(c.fArguments.size() == 1);
998 std::vector<std::unique_ptr<Expression>> finalArgs;
999 finalArgs.push_back(c.fArguments[0]->clone());
1000 finalArgs.emplace_back(new FloatLiteral(fContext, -1, 0));
1001 finalArgs.emplace_back(new FloatLiteral(fContext, -1, 1));
1002 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
1003 this->writeGLSLExtendedInstruction(c.fType, result, GLSLstd450FClamp, GLSLstd450SClamp,
1004 GLSLstd450UClamp, spvArgs, out);
1005 break;
1006 }
1007 }
1008 return result;
1009}
1010
1011SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
1012 const auto& entry = fFunctionMap.find(&c.fFunction);
1013 if (entry == fFunctionMap.end()) {
1014 return this->writeIntrinsicCall(c, out);
1015 }
1016 // stores (variable, type, lvalue) pairs to extract and save after the function call is complete
1017 std::vector<std::tuple<SpvId, const Type*, std::unique_ptr<LValue>>> lvalues;
1018 std::vector<SpvId> arguments;
1019 for (size_t i = 0; i < c.fArguments.size(); i++) {
1020 // id of temporary variable that we will use to hold this argument, or 0 if it is being
1021 // passed directly
1022 SpvId tmpVar;
1023 // if we need a temporary var to store this argument, this is the value to store in the var
1024 SpvId tmpValueId;
1025 if (is_out(*c.fFunction.fParameters[i])) {
1026 std::unique_ptr<LValue> lv = this->getLValue(*c.fArguments[i], out);
1027 SpvId ptr = lv->getPointer();
1028 if (ptr) {
1029 arguments.push_back(ptr);
1030 continue;
1031 } else {
1032 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1033 // copy it into a temp, call the function, read the value out of the temp, and then
1034 // update the lvalue.
1035 tmpValueId = lv->load(out);
1036 tmpVar = this->nextId();
1037 lvalues.push_back(std::make_tuple(tmpVar, &c.fArguments[i]->fType, std::move(lv)));
1038 }
1039 } else {
1040 // see getFunctionType for an explanation of why we're always using pointer parameters
1041 tmpValueId = this->writeExpression(*c.fArguments[i], out);
1042 tmpVar = this->nextId();
1043 }
1044 this->writeInstruction(SpvOpVariable,
1045 this->getPointerType(c.fArguments[i]->fType,
1046 SpvStorageClassFunction),
1047 tmpVar,
1048 SpvStorageClassFunction,
1049 fVariableBuffer);
1050 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
1051 arguments.push_back(tmpVar);
1052 }
1053 SpvId result = this->nextId();
1054 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) c.fArguments.size(), out);
1055 this->writeWord(this->getType(c.fType), out);
1056 this->writeWord(result, out);
1057 this->writeWord(entry->second, out);
1058 for (SpvId id : arguments) {
1059 this->writeWord(id, out);
1060 }
1061 // now that the call is complete, we may need to update some lvalues with the new values of out
1062 // arguments
1063 for (const auto& tuple : lvalues) {
1064 SpvId load = this->nextId();
1065 this->writeInstruction(SpvOpLoad, getType(*std::get<1>(tuple)), load, std::get<0>(tuple),
1066 out);
1067 this->writePrecisionModifier(*std::get<1>(tuple), load);
1068 std::get<2>(tuple)->store(load, out);
1069 }
1070 return result;
1071}
1072
1073SpvId SPIRVCodeGenerator::writeConstantVector(const Constructor& c) {
1074 SkASSERT(c.fType.kind() == Type::kVector_Kind && c.isCompileTimeConstant());
1075 SpvId result = this->nextId();
1076 std::vector<SpvId> arguments;
1077 for (size_t i = 0; i < c.fArguments.size(); i++) {
1078 arguments.push_back(this->writeExpression(*c.fArguments[i], fConstantBuffer));
1079 }
1080 SpvId type = this->getType(c.fType);
1081 if (c.fArguments.size() == 1) {
1082 // with a single argument, a vector will have all of its entries equal to the argument
1083 this->writeOpCode(SpvOpConstantComposite, 3 + c.fType.columns(), fConstantBuffer);
1084 this->writeWord(type, fConstantBuffer);
1085 this->writeWord(result, fConstantBuffer);
1086 for (int i = 0; i < c.fType.columns(); i++) {
1087 this->writeWord(arguments[0], fConstantBuffer);
1088 }
1089 } else {
1090 this->writeOpCode(SpvOpConstantComposite, 3 + (int32_t) c.fArguments.size(),
1091 fConstantBuffer);
1092 this->writeWord(type, fConstantBuffer);
1093 this->writeWord(result, fConstantBuffer);
1094 for (SpvId id : arguments) {
1095 this->writeWord(id, fConstantBuffer);
1096 }
1097 }
1098 return result;
1099}
1100
1101SpvId SPIRVCodeGenerator::writeFloatConstructor(const Constructor& c, OutputStream& out) {
1102 SkASSERT(c.fType.isFloat());
1103 SkASSERT(c.fArguments.size() == 1);
1104 SkASSERT(c.fArguments[0]->fType.isNumber());
1105 SpvId result = this->nextId();
1106 SpvId parameter = this->writeExpression(*c.fArguments[0], out);
1107 if (c.fArguments[0]->fType.isSigned()) {
1108 this->writeInstruction(SpvOpConvertSToF, this->getType(c.fType), result, parameter,
1109 out);
1110 } else {
1111 SkASSERT(c.fArguments[0]->fType.isUnsigned());
1112 this->writeInstruction(SpvOpConvertUToF, this->getType(c.fType), result, parameter,
1113 out);
1114 }
1115 return result;
1116}
1117
1118SpvId SPIRVCodeGenerator::writeIntConstructor(const Constructor& c, OutputStream& out) {
1119 SkASSERT(c.fType.isSigned());
1120 SkASSERT(c.fArguments.size() == 1);
1121 SkASSERT(c.fArguments[0]->fType.isNumber());
1122 SpvId result = this->nextId();
1123 SpvId parameter = this->writeExpression(*c.fArguments[0], out);
1124 if (c.fArguments[0]->fType.isFloat()) {
1125 this->writeInstruction(SpvOpConvertFToS, this->getType(c.fType), result, parameter,
1126 out);
1127 }
1128 else {
1129 SkASSERT(c.fArguments[0]->fType.isUnsigned());
1130 this->writeInstruction(SpvOpBitcast, this->getType(c.fType), result, parameter,
1131 out);
1132 }
1133 return result;
1134}
1135
1136SpvId SPIRVCodeGenerator::writeUIntConstructor(const Constructor& c, OutputStream& out) {
1137 SkASSERT(c.fType.isUnsigned());
1138 SkASSERT(c.fArguments.size() == 1);
1139 SkASSERT(c.fArguments[0]->fType.isNumber());
1140 SpvId result = this->nextId();
1141 SpvId parameter = this->writeExpression(*c.fArguments[0], out);
1142 if (c.fArguments[0]->fType.isFloat()) {
1143 this->writeInstruction(SpvOpConvertFToU, this->getType(c.fType), result, parameter,
1144 out);
1145 } else {
1146 SkASSERT(c.fArguments[0]->fType.isSigned());
1147 this->writeInstruction(SpvOpBitcast, this->getType(c.fType), result, parameter,
1148 out);
1149 }
1150 return result;
1151}
1152
1153void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
1154 OutputStream& out) {
1155 FloatLiteral zero(fContext, -1, 0);
1156 SpvId zeroId = this->writeFloatLiteral(zero);
1157 std::vector<SpvId> columnIds;
1158 for (int column = 0; column < type.columns(); column++) {
1159 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1160 out);
1161 this->writeWord(this->getType(type.componentType().toCompound(fContext, type.rows(), 1)),
1162 out);
1163 SpvId columnId = this->nextId();
1164 this->writeWord(columnId, out);
1165 columnIds.push_back(columnId);
1166 for (int row = 0; row < type.columns(); row++) {
1167 this->writeWord(row == column ? diagonal : zeroId, out);
1168 }
1169 this->writePrecisionModifier(type, columnId);
1170 }
1171 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1172 out);
1173 this->writeWord(this->getType(type), out);
1174 this->writeWord(id, out);
1175 for (SpvId id : columnIds) {
1176 this->writeWord(id, out);
1177 }
1178 this->writePrecisionModifier(type, id);
1179}
1180
1181void SPIRVCodeGenerator::writeMatrixCopy(SpvId id, SpvId src, const Type& srcType,
1182 const Type& dstType, OutputStream& out) {
1183 SkASSERT(srcType.kind() == Type::kMatrix_Kind);
1184 SkASSERT(dstType.kind() == Type::kMatrix_Kind);
1185 SkASSERT(srcType.componentType() == dstType.componentType());
1186 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1187 srcType.rows(),
1188 1));
1189 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1190 dstType.rows(),
1191 1));
1192 SpvId zeroId;
1193 if (dstType.componentType() == *fContext.fFloat_Type) {
1194 FloatLiteral zero(fContext, -1, 0.0);
1195 zeroId = this->writeFloatLiteral(zero);
1196 } else if (dstType.componentType() == *fContext.fInt_Type) {
1197 IntLiteral zero(fContext, -1, 0);
1198 zeroId = this->writeIntLiteral(zero);
1199 } else {
1200 ABORT("unsupported matrix component type");
1201 }
1202 SpvId zeroColumn = 0;
1203 SpvId columns[4];
1204 for (int i = 0; i < dstType.columns(); i++) {
1205 if (i < srcType.columns()) {
1206 // we're still inside the src matrix, copy the column
1207 SpvId srcColumn = this->nextId();
1208 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1209 this->writePrecisionModifier(dstType, srcColumn);
1210 SpvId dstColumn;
1211 if (srcType.rows() == dstType.rows()) {
1212 // columns are equal size, don't need to do anything
1213 dstColumn = srcColumn;
1214 }
1215 else if (dstType.rows() > srcType.rows()) {
1216 // dst column is bigger, need to zero-pad it
1217 dstColumn = this->nextId();
1218 int delta = dstType.rows() - srcType.rows();
1219 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1220 this->writeWord(dstColumnType, out);
1221 this->writeWord(dstColumn, out);
1222 this->writeWord(srcColumn, out);
1223 for (int i = 0; i < delta; ++i) {
1224 this->writeWord(zeroId, out);
1225 }
1226 this->writePrecisionModifier(dstType, dstColumn);
1227 }
1228 else {
1229 // dst column is smaller, need to swizzle the src column
1230 dstColumn = this->nextId();
1231 int count = dstType.rows();
1232 this->writeOpCode(SpvOpVectorShuffle, 5 + count, out);
1233 this->writeWord(dstColumnType, out);
1234 this->writeWord(dstColumn, out);
1235 this->writeWord(srcColumn, out);
1236 this->writeWord(srcColumn, out);
1237 for (int i = 0; i < count; i++) {
1238 this->writeWord(i, out);
1239 }
1240 this->writePrecisionModifier(dstType, dstColumn);
1241 }
1242 columns[i] = dstColumn;
1243 } else {
1244 // we're past the end of the src matrix, need a vector of zeroes
1245 if (!zeroColumn) {
1246 zeroColumn = this->nextId();
1247 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1248 this->writeWord(dstColumnType, out);
1249 this->writeWord(zeroColumn, out);
1250 for (int i = 0; i < dstType.rows(); ++i) {
1251 this->writeWord(zeroId, out);
1252 }
1253 this->writePrecisionModifier(dstType, zeroColumn);
1254 }
1255 columns[i] = zeroColumn;
1256 }
1257 }
1258 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1259 this->writeWord(this->getType(dstType), out);
1260 this->writeWord(id, out);
1261 for (int i = 0; i < dstType.columns(); i++) {
1262 this->writeWord(columns[i], out);
1263 }
1264 this->writePrecisionModifier(dstType, id);
1265}
1266
1267void SPIRVCodeGenerator::addColumnEntry(SpvId columnType, Precision precision,
1268 std::vector<SpvId>* currentColumn,
1269 std::vector<SpvId>* columnIds,
1270 int* currentCount, int rows, SpvId entry,
1271 OutputStream& out) {
1272 SkASSERT(*currentCount < rows);
1273 ++(*currentCount);
1274 currentColumn->push_back(entry);
1275 if (*currentCount == rows) {
1276 *currentCount = 0;
1277 this->writeOpCode(SpvOpCompositeConstruct, 3 + currentColumn->size(), out);
1278 this->writeWord(columnType, out);
1279 SpvId columnId = this->nextId();
1280 this->writeWord(columnId, out);
1281 columnIds->push_back(columnId);
1282 for (SpvId id : *currentColumn) {
1283 this->writeWord(id, out);
1284 }
1285 currentColumn->clear();
1286 this->writePrecisionModifier(precision, columnId);
1287 }
1288}
1289
1290SpvId SPIRVCodeGenerator::writeMatrixConstructor(const Constructor& c, OutputStream& out) {
1291 SkASSERT(c.fType.kind() == Type::kMatrix_Kind);
1292 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1293 // an instruction
1294 std::vector<SpvId> arguments;
1295 for (size_t i = 0; i < c.fArguments.size(); i++) {
1296 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
1297 }
1298 SpvId result = this->nextId();
1299 int rows = c.fType.rows();
1300 int columns = c.fType.columns();
1301 if (arguments.size() == 1 && c.fArguments[0]->fType.kind() == Type::kScalar_Kind) {
1302 this->writeUniformScaleMatrix(result, arguments[0], c.fType, out);
1303 } else if (arguments.size() == 1 && c.fArguments[0]->fType.kind() == Type::kMatrix_Kind) {
1304 this->writeMatrixCopy(result, arguments[0], c.fArguments[0]->fType, c.fType, out);
1305 } else if (arguments.size() == 1 && c.fArguments[0]->fType.kind() == Type::kVector_Kind) {
1306 SkASSERT(c.fType.rows() == 2 && c.fType.columns() == 2);
1307 SkASSERT(c.fArguments[0]->fType.columns() == 4);
1308 SpvId componentType = this->getType(c.fType.componentType());
1309 SpvId v[4];
1310 for (int i = 0; i < 4; ++i) {
1311 v[i] = this->nextId();
1312 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i, out);
1313 }
1314 SpvId columnType = this->getType(c.fType.componentType().toCompound(fContext, 2, 1));
1315 SpvId column1 = this->nextId();
1316 this->writeInstruction(SpvOpCompositeConstruct, columnType, column1, v[0], v[1], out);
1317 SpvId column2 = this->nextId();
1318 this->writeInstruction(SpvOpCompositeConstruct, columnType, column2, v[2], v[3], out);
1319 this->writeInstruction(SpvOpCompositeConstruct, this->getType(c.fType), result, column1,
1320 column2, out);
1321 } else {
1322 SpvId columnType = this->getType(c.fType.componentType().toCompound(fContext, rows, 1));
1323 std::vector<SpvId> columnIds;
1324 // ids of vectors and scalars we have written to the current column so far
1325 std::vector<SpvId> currentColumn;
1326 // the total number of scalars represented by currentColumn's entries
1327 int currentCount = 0;
1328 Precision precision = c.fType.highPrecision() ? Precision::kHigh : Precision::kLow;
1329 for (size_t i = 0; i < arguments.size(); i++) {
1330 if (currentCount == 0 && c.fArguments[i]->fType.kind() == Type::kVector_Kind &&
1331 c.fArguments[i]->fType.columns() == c.fType.rows()) {
1332 // this is a complete column by itself
1333 columnIds.push_back(arguments[i]);
1334 } else {
1335 if (c.fArguments[i]->fType.columns() == 1) {
1336 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1337 &currentCount, rows, arguments[i], out);
1338 } else {
1339 SpvId componentType = this->getType(c.fArguments[i]->fType.componentType());
1340 for (int j = 0; j < c.fArguments[i]->fType.columns(); ++j) {
1341 SpvId swizzle = this->nextId();
1342 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1343 arguments[i], j, out);
1344 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1345 &currentCount, rows, swizzle, out);
1346 }
1347 }
1348 }
1349 }
1350 SkASSERT(columnIds.size() == (size_t) columns);
1351 this->writeOpCode(SpvOpCompositeConstruct, 3 + columns, out);
1352 this->writeWord(this->getType(c.fType), out);
1353 this->writeWord(result, out);
1354 for (SpvId id : columnIds) {
1355 this->writeWord(id, out);
1356 }
1357 }
1358 this->writePrecisionModifier(c.fType, result);
1359 return result;
1360}
1361
1362SpvId SPIRVCodeGenerator::writeVectorConstructor(const Constructor& c, OutputStream& out) {
1363 SkASSERT(c.fType.kind() == Type::kVector_Kind);
1364 if (c.isCompileTimeConstant()) {
1365 return this->writeConstantVector(c);
1366 }
1367 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1368 // an instruction
1369 std::vector<SpvId> arguments;
1370 for (size_t i = 0; i < c.fArguments.size(); i++) {
1371 if (c.fArguments[i]->fType.kind() == Type::kVector_Kind) {
1372 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to
1373 // extract the components and convert them in that case manually. On top of that,
1374 // as of this writing there's a bug in the Intel Vulkan driver where OpCreateComposite
1375 // doesn't handle vector arguments at all, so we always extract vector components and
1376 // pass them into OpCreateComposite individually.
1377 SpvId vec = this->writeExpression(*c.fArguments[i], out);
1378 SpvOp_ op = SpvOpUndef;
1379 const Type& src = c.fArguments[i]->fType.componentType();
1380 const Type& dst = c.fType.componentType();
1381 if (dst == *fContext.fFloat_Type || dst == *fContext.fHalf_Type) {
1382 if (src == *fContext.fFloat_Type || src == *fContext.fHalf_Type) {
1383 if (c.fArguments.size() == 1) {
1384 return vec;
1385 }
1386 } else if (src == *fContext.fInt_Type ||
1387 src == *fContext.fShort_Type ||
1388 src == *fContext.fByte_Type) {
1389 op = SpvOpConvertSToF;
1390 } else if (src == *fContext.fUInt_Type ||
1391 src == *fContext.fUShort_Type ||
1392 src == *fContext.fUByte_Type) {
1393 op = SpvOpConvertUToF;
1394 } else {
1395 SkASSERT(false);
1396 }
1397 } else if (dst == *fContext.fInt_Type ||
1398 dst == *fContext.fShort_Type ||
1399 dst == *fContext.fByte_Type) {
1400 if (src == *fContext.fFloat_Type || src == *fContext.fHalf_Type) {
1401 op = SpvOpConvertFToS;
1402 } else if (src == *fContext.fInt_Type ||
1403 src == *fContext.fShort_Type ||
1404 src == *fContext.fByte_Type) {
1405 if (c.fArguments.size() == 1) {
1406 return vec;
1407 }
1408 } else if (src == *fContext.fUInt_Type ||
1409 src == *fContext.fUShort_Type ||
1410 src == *fContext.fUByte_Type) {
1411 op = SpvOpBitcast;
1412 } else {
1413 SkASSERT(false);
1414 }
1415 } else if (dst == *fContext.fUInt_Type ||
1416 dst == *fContext.fUShort_Type ||
1417 dst == *fContext.fUByte_Type) {
1418 if (src == *fContext.fFloat_Type || src == *fContext.fHalf_Type) {
1419 op = SpvOpConvertFToS;
1420 } else if (src == *fContext.fInt_Type ||
1421 src == *fContext.fShort_Type ||
1422 src == *fContext.fByte_Type) {
1423 op = SpvOpBitcast;
1424 } else if (src == *fContext.fUInt_Type ||
1425 src == *fContext.fUShort_Type ||
1426 src == *fContext.fUByte_Type) {
1427 if (c.fArguments.size() == 1) {
1428 return vec;
1429 }
1430 } else {
1431 SkASSERT(false);
1432 }
1433 }
1434 for (int j = 0; j < c.fArguments[i]->fType.columns(); j++) {
1435 SpvId swizzle = this->nextId();
1436 this->writeInstruction(SpvOpCompositeExtract, this->getType(src), swizzle, vec, j,
1437 out);
1438 if (op != SpvOpUndef) {
1439 SpvId cast = this->nextId();
1440 this->writeInstruction(op, this->getType(dst), cast, swizzle, out);
1441 arguments.push_back(cast);
1442 } else {
1443 arguments.push_back(swizzle);
1444 }
1445 }
1446 } else {
1447 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
1448 }
1449 }
1450 SpvId result = this->nextId();
1451 if (arguments.size() == 1 && c.fArguments[0]->fType.kind() == Type::kScalar_Kind) {
1452 this->writeOpCode(SpvOpCompositeConstruct, 3 + c.fType.columns(), out);
1453 this->writeWord(this->getType(c.fType), out);
1454 this->writeWord(result, out);
1455 for (int i = 0; i < c.fType.columns(); i++) {
1456 this->writeWord(arguments[0], out);
1457 }
1458 } else {
1459 SkASSERT(arguments.size() > 1);
1460 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1461 this->writeWord(this->getType(c.fType), out);
1462 this->writeWord(result, out);
1463 for (SpvId id : arguments) {
1464 this->writeWord(id, out);
1465 }
1466 }
1467 return result;
1468}
1469
1470SpvId SPIRVCodeGenerator::writeArrayConstructor(const Constructor& c, OutputStream& out) {
1471 SkASSERT(c.fType.kind() == Type::kArray_Kind);
1472 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1473 // an instruction
1474 std::vector<SpvId> arguments;
1475 for (size_t i = 0; i < c.fArguments.size(); i++) {
1476 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
1477 }
1478 SpvId result = this->nextId();
1479 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) c.fArguments.size(), out);
1480 this->writeWord(this->getType(c.fType), out);
1481 this->writeWord(result, out);
1482 for (SpvId id : arguments) {
1483 this->writeWord(id, out);
1484 }
1485 return result;
1486}
1487
1488SpvId SPIRVCodeGenerator::writeConstructor(const Constructor& c, OutputStream& out) {
1489 if (c.fArguments.size() == 1 &&
1490 this->getActualType(c.fType) == this->getActualType(c.fArguments[0]->fType)) {
1491 return this->writeExpression(*c.fArguments[0], out);
1492 }
1493 if (c.fType == *fContext.fFloat_Type || c.fType == *fContext.fHalf_Type) {
1494 return this->writeFloatConstructor(c, out);
1495 } else if (c.fType == *fContext.fInt_Type ||
1496 c.fType == *fContext.fShort_Type ||
1497 c.fType == *fContext.fByte_Type) {
1498 return this->writeIntConstructor(c, out);
1499 } else if (c.fType == *fContext.fUInt_Type ||
1500 c.fType == *fContext.fUShort_Type ||
1501 c.fType == *fContext.fUByte_Type) {
1502 return this->writeUIntConstructor(c, out);
1503 }
1504 switch (c.fType.kind()) {
1505 case Type::kVector_Kind:
1506 return this->writeVectorConstructor(c, out);
1507 case Type::kMatrix_Kind:
1508 return this->writeMatrixConstructor(c, out);
1509 case Type::kArray_Kind:
1510 return this->writeArrayConstructor(c, out);
1511 default:
1512#ifdef SK_DEBUG
1513 ABORT("unsupported constructor: %s", c.description().c_str());
1514#endif
1515 return -1;
1516 }
1517}
1518
1519SpvStorageClass_ get_storage_class(const Modifiers& modifiers) {
1520 if (modifiers.fFlags & Modifiers::kIn_Flag) {
1521 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
1522 return SpvStorageClassInput;
1523 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
1524 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
1525 return SpvStorageClassOutput;
1526 } else if (modifiers.fFlags & Modifiers::kUniform_Flag) {
1527 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
1528 return SpvStorageClassPushConstant;
1529 }
1530 return SpvStorageClassUniform;
1531 } else {
1532 return SpvStorageClassFunction;
1533 }
1534}
1535
1536SpvStorageClass_ get_storage_class(const Expression& expr) {
1537 switch (expr.fKind) {
1538 case Expression::kVariableReference_Kind: {
1539 const Variable& var = ((VariableReference&) expr).fVariable;
1540 if (var.fStorage != Variable::kGlobal_Storage) {
1541 return SpvStorageClassFunction;
1542 }
1543 SpvStorageClass_ result = get_storage_class(var.fModifiers);
1544 if (result == SpvStorageClassFunction) {
1545 result = SpvStorageClassPrivate;
1546 }
1547 return result;
1548 }
1549 case Expression::kFieldAccess_Kind:
1550 return get_storage_class(*((FieldAccess&) expr).fBase);
1551 case Expression::kIndex_Kind:
1552 return get_storage_class(*((IndexExpression&) expr).fBase);
1553 default:
1554 return SpvStorageClassFunction;
1555 }
1556}
1557
1558std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
1559 std::vector<SpvId> chain;
1560 switch (expr.fKind) {
1561 case Expression::kIndex_Kind: {
1562 IndexExpression& indexExpr = (IndexExpression&) expr;
1563 chain = this->getAccessChain(*indexExpr.fBase, out);
1564 chain.push_back(this->writeExpression(*indexExpr.fIndex, out));
1565 break;
1566 }
1567 case Expression::kFieldAccess_Kind: {
1568 FieldAccess& fieldExpr = (FieldAccess&) expr;
1569 chain = this->getAccessChain(*fieldExpr.fBase, out);
1570 IntLiteral index(fContext, -1, fieldExpr.fFieldIndex);
1571 chain.push_back(this->writeIntLiteral(index));
1572 break;
1573 }
1574 default: {
1575 SpvId id = this->getLValue(expr, out)->getPointer();
1576 SkASSERT(id != 0);
1577 chain.push_back(id);
1578 }
1579 }
1580 return chain;
1581}
1582
1583class PointerLValue : public SPIRVCodeGenerator::LValue {
1584public:
1585 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, SpvId type,
1586 SPIRVCodeGenerator::Precision precision)
1587 : fGen(gen)
1588 , fPointer(pointer)
1589 , fType(type)
1590 , fPrecision(precision) {}
1591
1592 SpvId getPointer() override {
1593 return fPointer;
1594 }
1595
1596 SpvId load(OutputStream& out) override {
1597 SpvId result = fGen.nextId();
1598 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1599 fGen.writePrecisionModifier(fPrecision, result);
1600 return result;
1601 }
1602
1603 void store(SpvId value, OutputStream& out) override {
1604 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1605 }
1606
1607private:
1608 SPIRVCodeGenerator& fGen;
1609 const SpvId fPointer;
1610 const SpvId fType;
1611 const SPIRVCodeGenerator::Precision fPrecision;
1612};
1613
1614class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1615public:
1616 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const std::vector<int>& components,
1617 const Type& baseType, const Type& swizzleType,
1618 SPIRVCodeGenerator::Precision precision)
1619 : fGen(gen)
1620 , fVecPointer(vecPointer)
1621 , fComponents(components)
1622 , fBaseType(baseType)
1623 , fSwizzleType(swizzleType)
1624 , fPrecision(precision) {}
1625
1626 SpvId getPointer() override {
1627 return 0;
1628 }
1629
1630 SpvId load(OutputStream& out) override {
1631 SpvId base = fGen.nextId();
1632 fGen.writeInstruction(SpvOpLoad, fGen.getType(fBaseType), base, fVecPointer, out);
1633 fGen.writePrecisionModifier(fPrecision, base);
1634 SpvId result = fGen.nextId();
1635 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
1636 fGen.writeWord(fGen.getType(fSwizzleType), out);
1637 fGen.writeWord(result, out);
1638 fGen.writeWord(base, out);
1639 fGen.writeWord(base, out);
1640 for (int component : fComponents) {
1641 fGen.writeWord(component, out);
1642 }
1643 fGen.writePrecisionModifier(fPrecision, result);
1644 return result;
1645 }
1646
1647 void store(SpvId value, OutputStream& out) override {
1648 // use OpVectorShuffle to mix and match the vector components. We effectively create
1649 // a virtual vector out of the concatenation of the left and right vectors, and then
1650 // select components from this virtual vector to make the result vector. For
1651 // instance, given:
1652 // float3L = ...;
1653 // float3R = ...;
1654 // L.xz = R.xy;
1655 // we end up with the virtual vector (L.x, L.y, L.z, R.x, R.y, R.z). Then we want
1656 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1657 // (3, 1, 4).
1658 SpvId base = fGen.nextId();
1659 fGen.writeInstruction(SpvOpLoad, fGen.getType(fBaseType), base, fVecPointer, out);
1660 SpvId shuffle = fGen.nextId();
1661 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType.columns(), out);
1662 fGen.writeWord(fGen.getType(fBaseType), out);
1663 fGen.writeWord(shuffle, out);
1664 fGen.writeWord(base, out);
1665 fGen.writeWord(value, out);
1666 for (int i = 0; i < fBaseType.columns(); i++) {
1667 // current offset into the virtual vector, defaults to pulling the unmodified
1668 // value from the left side
1669 int offset = i;
1670 // check to see if we are writing this component
1671 for (size_t j = 0; j < fComponents.size(); j++) {
1672 if (fComponents[j] == i) {
1673 // we're writing to this component, so adjust the offset to pull from
1674 // the correct component of the right side instead of preserving the
1675 // value from the left
1676 offset = (int) (j + fBaseType.columns());
1677 break;
1678 }
1679 }
1680 fGen.writeWord(offset, out);
1681 }
1682 fGen.writePrecisionModifier(fPrecision, shuffle);
1683 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1684 }
1685
1686private:
1687 SPIRVCodeGenerator& fGen;
1688 const SpvId fVecPointer;
1689 const std::vector<int>& fComponents;
1690 const Type& fBaseType;
1691 const Type& fSwizzleType;
1692 const SPIRVCodeGenerator::Precision fPrecision;
1693};
1694
1695std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
1696 OutputStream& out) {
1697 Precision precision = expr.fType.highPrecision() ? Precision::kHigh : Precision::kLow;
1698 switch (expr.fKind) {
1699 case Expression::kVariableReference_Kind: {
1700 SpvId type;
1701 const Variable& var = ((VariableReference&) expr).fVariable;
1702 if (var.fModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
1703 type = this->getType(Type("sk_in", Type::kArray_Kind, var.fType.componentType(),
1704 fSkInCount));
1705 } else {
1706 type = this->getType(expr.fType);
1707 }
1708 auto entry = fVariableMap.find(&var);
1709 SkASSERT(entry != fVariableMap.end());
1710 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue(*this,
1711 entry->second,
1712 type,
1713 precision));
1714 }
1715 case Expression::kIndex_Kind: // fall through
1716 case Expression::kFieldAccess_Kind: {
1717 std::vector<SpvId> chain = this->getAccessChain(expr, out);
1718 SpvId member = this->nextId();
1719 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
1720 this->writeWord(this->getPointerType(expr.fType, get_storage_class(expr)), out);
1721 this->writeWord(member, out);
1722 for (SpvId idx : chain) {
1723 this->writeWord(idx, out);
1724 }
1725 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue(
1726 *this,
1727 member,
1728 this->getType(expr.fType),
1729 precision));
1730 }
1731 case Expression::kSwizzle_Kind: {
1732 Swizzle& swizzle = (Swizzle&) expr;
1733 size_t count = swizzle.fComponents.size();
1734 SpvId base = this->getLValue(*swizzle.fBase, out)->getPointer();
1735 SkASSERT(base);
1736 if (count == 1) {
1737 IntLiteral index(fContext, -1, swizzle.fComponents[0]);
1738 SpvId member = this->nextId();
1739 this->writeInstruction(SpvOpAccessChain,
1740 this->getPointerType(swizzle.fType,
1741 get_storage_class(*swizzle.fBase)),
1742 member,
1743 base,
1744 this->writeIntLiteral(index),
1745 out);
1746 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue(
1747 *this,
1748 member,
1749 this->getType(expr.fType),
1750 precision));
1751 } else {
1752 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new SwizzleLValue(
1753 *this,
1754 base,
1755 swizzle.fComponents,
1756 swizzle.fBase->fType,
1757 expr.fType,
1758 precision));
1759 }
1760 }
1761 case Expression::kTernary_Kind: {
1762 TernaryExpression& t = (TernaryExpression&) expr;
1763 SpvId test = this->writeExpression(*t.fTest, out);
1764 SpvId end = this->nextId();
1765 SpvId ifTrueLabel = this->nextId();
1766 SpvId ifFalseLabel = this->nextId();
1767 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
1768 this->writeInstruction(SpvOpBranchConditional, test, ifTrueLabel, ifFalseLabel, out);
1769 this->writeLabel(ifTrueLabel, out);
1770 SpvId ifTrue = this->getLValue(*t.fIfTrue, out)->getPointer();
1771 SkASSERT(ifTrue);
1772 this->writeInstruction(SpvOpBranch, end, out);
1773 ifTrueLabel = fCurrentBlock;
1774 SpvId ifFalse = this->getLValue(*t.fIfFalse, out)->getPointer();
1775 SkASSERT(ifFalse);
1776 ifFalseLabel = fCurrentBlock;
1777 this->writeInstruction(SpvOpBranch, end, out);
1778 SpvId result = this->nextId();
1779 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fBool_Type), result, ifTrue,
1780 ifTrueLabel, ifFalse, ifFalseLabel, out);
1781 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue(
1782 *this,
1783 result,
1784 this->getType(expr.fType),
1785 precision));
1786 }
1787 default:
1788 // expr isn't actually an lvalue, create a dummy variable for it. This case happens due
1789 // to the need to store values in temporary variables during function calls (see
1790 // comments in getFunctionType); erroneous uses of rvalues as lvalues should have been
1791 // caught by IRGenerator
1792 SpvId result = this->nextId();
1793 SpvId type = this->getPointerType(expr.fType, SpvStorageClassFunction);
1794 this->writeInstruction(SpvOpVariable, type, result, SpvStorageClassFunction,
1795 fVariableBuffer);
1796 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
1797 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue(
1798 *this,
1799 result,
1800 this->getType(expr.fType),
1801 precision));
1802 }
1803}
1804
1805SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
1806 SpvId result = this->nextId();
1807 auto entry = fVariableMap.find(&ref.fVariable);
1808 SkASSERT(entry != fVariableMap.end());
1809 SpvId var = entry->second;
1810 this->writeInstruction(SpvOpLoad, this->getType(ref.fVariable.fType), result, var, out);
1811 this->writePrecisionModifier(ref.fVariable.fType, result);
1812 if (ref.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN &&
1813 (fProgram.fSettings.fFlipY || fProgram.fSettings.fInverseW)) {
1814 // The x component never changes, so just grab it
1815 SpvId xId = this->nextId();
1816 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fFloat_Type), xId,
1817 result, 0, out);
1818
1819 // Calculate the y component which may need to be flipped
1820 SpvId rawYId = this->nextId();
1821 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fFloat_Type), rawYId,
1822 result, 1, out);
1823 SpvId flippedYId = 0;
1824 if (fProgram.fSettings.fFlipY) {
1825 // need to remap to a top-left coordinate system
1826 if (fRTHeightStructId == (SpvId)-1) {
1827 // height variable hasn't been written yet
1828 std::shared_ptr<SymbolTable> st(new SymbolTable(&fErrors));
1829 SkASSERT(fRTHeightFieldIndex == (SpvId)-1);
1830 std::vector<Type::Field> fields;
1831 SkASSERT(fProgram.fSettings.fRTHeightOffset >= 0);
1832 fields.emplace_back(
1833 Modifiers(Layout(0, -1, fProgram.fSettings.fRTHeightOffset, -1, -1, -1, -1,
1834 -1, Layout::Format::kUnspecified,
1835 Layout::kUnspecified_Primitive, 1, -1, "", "",
1836 Layout::kNo_Key, Layout::CType::kDefault),
1837 0),
1838 SKSL_RTHEIGHT_NAME, fContext.fFloat_Type.get());
1839 StringFragment name("sksl_synthetic_uniforms");
1840 Type intfStruct(-1, name, fields);
1841
1842 int binding = fProgram.fSettings.fRTHeightBinding;
1843 int set = fProgram.fSettings.fRTHeightSet;
1844 SkASSERT(binding != -1 && set != -1);
1845
1846 Layout layout(0, -1, -1, binding, -1, set, -1, -1, Layout::Format::kUnspecified,
1847 Layout::kUnspecified_Primitive, -1, -1, "", "", Layout::kNo_Key,
1848 Layout::CType::kDefault);
1849 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
1850 std::make_unique<Variable>(/*offset=*/-1,
1851 Modifiers(layout, Modifiers::kUniform_Flag),
1852 name,
1853 intfStruct,
1854 Variable::kGlobal_Storage));
1855 InterfaceBlock intf(-1, intfVar, name, String(""),
1856 std::vector<std::unique_ptr<Expression>>(), st);
1857
1858 fRTHeightStructId = this->writeInterfaceBlock(intf, false);
1859 fRTHeightFieldIndex = 0;
1860 }
1861 SkASSERT(fRTHeightFieldIndex != (SpvId)-1);
1862
1863 IntLiteral fieldIndex(fContext, -1, fRTHeightFieldIndex);
1864 SpvId fieldIndexId = this->writeIntLiteral(fieldIndex);
1865 SpvId heightPtr = this->nextId();
1866 this->writeOpCode(SpvOpAccessChain, 5, out);
1867 this->writeWord(this->getPointerType(*fContext.fFloat_Type, SpvStorageClassUniform),
1868 out);
1869 this->writeWord(heightPtr, out);
1870 this->writeWord(fRTHeightStructId, out);
1871 this->writeWord(fieldIndexId, out);
1872 SpvId heightRead = this->nextId();
1873 this->writeInstruction(SpvOpLoad, this->getType(*fContext.fFloat_Type), heightRead,
1874 heightPtr, out);
1875
1876 flippedYId = this->nextId();
1877 this->writeInstruction(SpvOpFSub, this->getType(*fContext.fFloat_Type), flippedYId,
1878 heightRead, rawYId, out);
1879 }
1880
1881 // The z component will always be zero so we just get an id to the 0 literal
1882 FloatLiteral zero(fContext, -1, 0.0);
1883 SpvId zeroId = writeFloatLiteral(zero);
1884
1885 // Calculate the w component which may need to be inverted
1886 SpvId rawWId = this->nextId();
1887 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fFloat_Type), rawWId,
1888 result, 3, out);
1889 SpvId invWId = 0;
1890 if (fProgram.fSettings.fInverseW) {
1891 // We need to invert w
1892 FloatLiteral one(fContext, -1, 1.0);
1893 SpvId oneId = writeFloatLiteral(one);
1894 invWId = this->nextId();
1895 this->writeInstruction(SpvOpFDiv, this->getType(*fContext.fFloat_Type), invWId, oneId,
1896 rawWId, out);
1897 }
1898
1899 // Fill in the new fragcoord with the components from above
1900 SpvId adjusted = this->nextId();
1901 this->writeOpCode(SpvOpCompositeConstruct, 7, out);
1902 this->writeWord(this->getType(*fContext.fFloat4_Type), out);
1903 this->writeWord(adjusted, out);
1904 this->writeWord(xId, out);
1905 if (fProgram.fSettings.fFlipY) {
1906 this->writeWord(flippedYId, out);
1907 } else {
1908 this->writeWord(rawYId, out);
1909 }
1910 this->writeWord(zeroId, out);
1911 if (fProgram.fSettings.fInverseW) {
1912 this->writeWord(invWId, out);
1913 } else {
1914 this->writeWord(rawWId, out);
1915 }
1916
1917 return adjusted;
1918 }
1919 if (ref.fVariable.fModifiers.fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN &&
1920 !fProgram.fSettings.fFlipY) {
1921 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia, we use
1922 // the default convention of "counter-clockwise face is front".
1923 SpvId inverse = this->nextId();
1924 this->writeInstruction(SpvOpLogicalNot, this->getType(*fContext.fBool_Type), inverse,
1925 result, out);
1926 return inverse;
1927 }
1928 return result;
1929}
1930
1931SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
1932 if (expr.fBase->fType.kind() == Type::Kind::kVector_Kind) {
1933 SpvId base = this->writeExpression(*expr.fBase, out);
1934 SpvId index = this->writeExpression(*expr.fIndex, out);
1935 SpvId result = this->nextId();
1936 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.fType), result, base,
1937 index, out);
1938 return result;
1939 }
1940 return getLValue(expr, out)->load(out);
1941}
1942
1943SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
1944 return getLValue(f, out)->load(out);
1945}
1946
1947SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
1948 SpvId base = this->writeExpression(*swizzle.fBase, out);
1949 SpvId result = this->nextId();
1950 size_t count = swizzle.fComponents.size();
1951 if (count == 1) {
1952 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.fType), result, base,
1953 swizzle.fComponents[0], out);
1954 } else {
1955 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
1956 this->writeWord(this->getType(swizzle.fType), out);
1957 this->writeWord(result, out);
1958 this->writeWord(base, out);
1959 SpvId other = base;
1960 for (int c : swizzle.fComponents) {
1961 if (c < 0) {
1962 if (!fConstantZeroOneVector) {
1963 FloatLiteral zero(fContext, -1, 0);
1964 SpvId zeroId = this->writeFloatLiteral(zero);
1965 FloatLiteral one(fContext, -1, 1);
1966 SpvId oneId = this->writeFloatLiteral(one);
1967 SpvId type = this->getType(*fContext.fFloat2_Type);
1968 fConstantZeroOneVector = this->nextId();
1969 this->writeOpCode(SpvOpConstantComposite, 5, fConstantBuffer);
1970 this->writeWord(type, fConstantBuffer);
1971 this->writeWord(fConstantZeroOneVector, fConstantBuffer);
1972 this->writeWord(zeroId, fConstantBuffer);
1973 this->writeWord(oneId, fConstantBuffer);
1974 }
1975 other = fConstantZeroOneVector;
1976 break;
1977 }
1978 }
1979 this->writeWord(other, out);
1980 for (int component : swizzle.fComponents) {
1981 if (component == SKSL_SWIZZLE_0) {
1982 this->writeWord(swizzle.fBase->fType.columns(), out);
1983 } else if (component == SKSL_SWIZZLE_1) {
1984 this->writeWord(swizzle.fBase->fType.columns() + 1, out);
1985 } else {
1986 this->writeWord(component, out);
1987 }
1988 }
1989 }
1990 return result;
1991}
1992
1993SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
1994 const Type& operandType, SpvId lhs,
1995 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
1996 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
1997 SpvId result = this->nextId();
1998 if (is_float(fContext, operandType)) {
1999 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
2000 } else if (is_signed(fContext, operandType)) {
2001 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
2002 } else if (is_unsigned(fContext, operandType)) {
2003 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
2004 } else if (operandType == *fContext.fBool_Type) {
2005 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2006 return result; // skip RelaxedPrecision check
2007 } else {
2008#ifdef SK_DEBUG
2009 ABORT("invalid operandType: %s", operandType.description().c_str());
2010#endif
2011 }
2012 if (getActualType(resultType) == operandType && !resultType.highPrecision()) {
2013 this->writeInstruction(SpvOpDecorate, result, SpvDecorationRelaxedPrecision,
2014 fDecorationBuffer);
2015 }
2016 return result;
2017}
2018
2019SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2020 OutputStream& out) {
2021 if (operandType.kind() == Type::kVector_Kind) {
2022 SpvId result = this->nextId();
2023 this->writeInstruction(op, this->getType(*fContext.fBool_Type), result, id, out);
2024 return result;
2025 }
2026 return id;
2027}
2028
2029SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2030 SpvOp_ floatOperator, SpvOp_ intOperator,
2031 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
2032 OutputStream& out) {
2033 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
2034 SkASSERT(operandType.kind() == Type::kMatrix_Kind);
2035 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2036 operandType.rows(),
2037 1));
2038 SpvId bvecType = this->getType(fContext.fBool_Type->toCompound(fContext,
2039 operandType.rows(),
2040 1));
2041 SpvId boolType = this->getType(*fContext.fBool_Type);
2042 SpvId result = 0;
2043 for (int i = 0; i < operandType.columns(); i++) {
2044 SpvId columnL = this->nextId();
2045 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
2046 SpvId columnR = this->nextId();
2047 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
2048 SpvId compare = this->nextId();
2049 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
2050 SpvId merge = this->nextId();
2051 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
2052 if (result != 0) {
2053 SpvId next = this->nextId();
2054 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
2055 result = next;
2056 }
2057 else {
2058 result = merge;
2059 }
2060 }
2061 return result;
2062}
2063
2064SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
2065 SpvId rhs, SpvOp_ floatOperator,
2066 SpvOp_ intOperator,
2067 OutputStream& out) {
2068 SpvOp_ op = is_float(fContext, operandType) ? floatOperator : intOperator;
2069 SkASSERT(operandType.kind() == Type::kMatrix_Kind);
2070 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2071 operandType.rows(),
2072 1));
2073 SpvId columns[4];
2074 for (int i = 0; i < operandType.columns(); i++) {
2075 SpvId columnL = this->nextId();
2076 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
2077 SpvId columnR = this->nextId();
2078 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
2079 columns[i] = this->nextId();
2080 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
2081 }
2082 SpvId result = this->nextId();
2083 this->writeOpCode(SpvOpCompositeConstruct, 3 + operandType.columns(), out);
2084 this->writeWord(this->getType(operandType), out);
2085 this->writeWord(result, out);
2086 for (int i = 0; i < operandType.columns(); i++) {
2087 this->writeWord(columns[i], out);
2088 }
2089 return result;
2090}
2091
2092std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
2093 if (type.isInteger()) {
2094 return std::unique_ptr<Expression>(new IntLiteral(-1, 1, &type));
2095 }
2096 else if (type.isFloat()) {
2097 return std::unique_ptr<Expression>(new FloatLiteral(-1, 1.0, &type));
2098 } else {
2099 ABORT("math is unsupported on type '%s'", type.name().c_str());
2100 }
2101}
2102
2103SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Token::Kind op,
2104 const Type& rightType, SpvId rhs,
2105 const Type& resultType, OutputStream& out) {
2106 Type tmp("<invalid>");
2107 // overall type we are operating on: float2, int, uint4...
2108 const Type* operandType;
2109 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2110 // handling in SPIR-V
2111 if (this->getActualType(leftType) != this->getActualType(rightType)) {
2112 if (leftType.kind() == Type::kVector_Kind && rightType.isNumber()) {
2113 if (op == Token::Kind::TK_SLASH) {
2114 SpvId one = this->writeExpression(*create_literal_1(fContext, rightType), out);
2115 SpvId inverse = this->nextId();
2116 this->writeInstruction(SpvOpFDiv, this->getType(rightType), inverse, one, rhs, out);
2117 rhs = inverse;
2118 op = Token::Kind::TK_STAR;
2119 }
2120 if (op == Token::Kind::TK_STAR) {
2121 SpvId result = this->nextId();
2122 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2123 result, lhs, rhs, out);
2124 return result;
2125 }
2126 // promote number to vector
2127 SpvId vec = this->nextId();
2128 const Type& vecType = leftType;
2129 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2130 this->writeWord(this->getType(vecType), out);
2131 this->writeWord(vec, out);
2132 for (int i = 0; i < vecType.columns(); i++) {
2133 this->writeWord(rhs, out);
2134 }
2135 rhs = vec;
2136 operandType = &leftType;
2137 } else if (rightType.kind() == Type::kVector_Kind && leftType.isNumber()) {
2138 if (op == Token::Kind::TK_STAR) {
2139 SpvId result = this->nextId();
2140 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2141 result, rhs, lhs, out);
2142 return result;
2143 }
2144 // promote number to vector
2145 SpvId vec = this->nextId();
2146 const Type& vecType = rightType;
2147 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2148 this->writeWord(this->getType(vecType), out);
2149 this->writeWord(vec, out);
2150 for (int i = 0; i < vecType.columns(); i++) {
2151 this->writeWord(lhs, out);
2152 }
2153 lhs = vec;
2154 operandType = &rightType;
2155 } else if (leftType.kind() == Type::kMatrix_Kind) {
2156 SpvOp_ spvop;
2157 if (rightType.kind() == Type::kMatrix_Kind) {
2158 spvop = SpvOpMatrixTimesMatrix;
2159 } else if (rightType.kind() == Type::kVector_Kind) {
2160 spvop = SpvOpMatrixTimesVector;
2161 } else {
2162 SkASSERT(rightType.kind() == Type::kScalar_Kind);
2163 spvop = SpvOpMatrixTimesScalar;
2164 }
2165 SpvId result = this->nextId();
2166 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
2167 return result;
2168 } else if (rightType.kind() == Type::kMatrix_Kind) {
2169 SpvId result = this->nextId();
2170 if (leftType.kind() == Type::kVector_Kind) {
2171 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType), result,
2172 lhs, rhs, out);
2173 } else {
2174 SkASSERT(leftType.kind() == Type::kScalar_Kind);
2175 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType), result,
2176 rhs, lhs, out);
2177 }
2178 return result;
2179 } else {
2180 SkASSERT(false);
2181 return -1;
2182 }
2183 } else {
2184 tmp = this->getActualType(leftType);
2185 operandType = &tmp;
2186 SkASSERT(*operandType == this->getActualType(rightType));
2187 }
2188 switch (op) {
2189 case Token::Kind::TK_EQEQ: {
2190 if (operandType->kind() == Type::kMatrix_Kind) {
2191 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
2192 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
2193 }
2194 SkASSERT(resultType == *fContext.fBool_Type);
2195 const Type* tmpType;
2196 if (operandType->kind() == Type::kVector_Kind) {
2197 tmpType = &fContext.fBool_Type->toCompound(fContext,
2198 operandType->columns(),
2199 operandType->rows());
2200 } else {
2201 tmpType = &resultType;
2202 }
2203 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
2204 SpvOpFOrdEqual, SpvOpIEqual,
2205 SpvOpIEqual, SpvOpLogicalEqual, out),
2206 *operandType, SpvOpAll, out);
2207 }
2208 case Token::Kind::TK_NEQ:
2209 if (operandType->kind() == Type::kMatrix_Kind) {
2210 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
2211 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
2212 }
2213 SkASSERT(resultType == *fContext.fBool_Type);
2214 const Type* tmpType;
2215 if (operandType->kind() == Type::kVector_Kind) {
2216 tmpType = &fContext.fBool_Type->toCompound(fContext,
2217 operandType->columns(),
2218 operandType->rows());
2219 } else {
2220 tmpType = &resultType;
2221 }
2222 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
2223 SpvOpFOrdNotEqual, SpvOpINotEqual,
2224 SpvOpINotEqual, SpvOpLogicalNotEqual,
2225 out),
2226 *operandType, SpvOpAny, out);
2227 case Token::Kind::TK_GT:
2228 SkASSERT(resultType == *fContext.fBool_Type);
2229 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2230 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
2231 SpvOpUGreaterThan, SpvOpUndef, out);
2232 case Token::Kind::TK_LT:
2233 SkASSERT(resultType == *fContext.fBool_Type);
2234 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
2235 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
2236 case Token::Kind::TK_GTEQ:
2237 SkASSERT(resultType == *fContext.fBool_Type);
2238 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2239 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
2240 SpvOpUGreaterThanEqual, SpvOpUndef, out);
2241 case Token::Kind::TK_LTEQ:
2242 SkASSERT(resultType == *fContext.fBool_Type);
2243 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2244 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
2245 SpvOpULessThanEqual, SpvOpUndef, out);
2246 case Token::Kind::TK_PLUS:
2247 if (leftType.kind() == Type::kMatrix_Kind &&
2248 rightType.kind() == Type::kMatrix_Kind) {
2249 SkASSERT(leftType == rightType);
2250 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs,
2251 SpvOpFAdd, SpvOpIAdd, out);
2252 }
2253 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
2254 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2255 case Token::Kind::TK_MINUS:
2256 if (leftType.kind() == Type::kMatrix_Kind &&
2257 rightType.kind() == Type::kMatrix_Kind) {
2258 SkASSERT(leftType == rightType);
2259 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs,
2260 SpvOpFSub, SpvOpISub, out);
2261 }
2262 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
2263 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2264 case Token::Kind::TK_STAR:
2265 if (leftType.kind() == Type::kMatrix_Kind &&
2266 rightType.kind() == Type::kMatrix_Kind) {
2267 // matrix multiply
2268 SpvId result = this->nextId();
2269 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2270 lhs, rhs, out);
2271 return result;
2272 }
2273 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
2274 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
2275 case Token::Kind::TK_SLASH:
2276 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
2277 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
2278 case Token::Kind::TK_PERCENT:
2279 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2280 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
2281 case Token::Kind::TK_SHL:
2282 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2283 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2284 SpvOpUndef, out);
2285 case Token::Kind::TK_SHR:
2286 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2287 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2288 SpvOpUndef, out);
2289 case Token::Kind::TK_BITWISEAND:
2290 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2291 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
2292 case Token::Kind::TK_BITWISEOR:
2293 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2294 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
2295 case Token::Kind::TK_BITWISEXOR:
2296 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2297 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
2298 case Token::Kind::TK_COMMA:
2299 return rhs;
2300 default:
2301 SkASSERT(false);
2302 return -1;
2303 }
2304}
2305
2306SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
2307 // handle cases where we don't necessarily evaluate both LHS and RHS
2308 switch (b.fOperator) {
2309 case Token::Kind::TK_EQ: {
2310 SpvId rhs = this->writeExpression(*b.fRight, out);
2311 this->getLValue(*b.fLeft, out)->store(rhs, out);
2312 return rhs;
2313 }
2314 case Token::Kind::TK_LOGICALAND:
2315 return this->writeLogicalAnd(b, out);
2316 case Token::Kind::TK_LOGICALOR:
2317 return this->writeLogicalOr(b, out);
2318 default:
2319 break;
2320 }
2321
2322 std::unique_ptr<LValue> lvalue;
2323 SpvId lhs;
2324 if (is_assignment(b.fOperator)) {
2325 lvalue = this->getLValue(*b.fLeft, out);
2326 lhs = lvalue->load(out);
2327 } else {
2328 lvalue = nullptr;
2329 lhs = this->writeExpression(*b.fLeft, out);
2330 }
2331 SpvId rhs = this->writeExpression(*b.fRight, out);
2332 SpvId result = this->writeBinaryExpression(b.fLeft->fType, lhs, remove_assignment(b.fOperator),
2333 b.fRight->fType, rhs, b.fType, out);
2334 if (lvalue) {
2335 lvalue->store(result, out);
2336 }
2337 return result;
2338}
2339
2340SpvId SPIRVCodeGenerator::writeLogicalAnd(const BinaryExpression& a, OutputStream& out) {
2341 SkASSERT(a.fOperator == Token::Kind::TK_LOGICALAND);
2342 BoolLiteral falseLiteral(fContext, -1, false);
2343 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
2344 SpvId lhs = this->writeExpression(*a.fLeft, out);
2345 SpvId rhsLabel = this->nextId();
2346 SpvId end = this->nextId();
2347 SpvId lhsBlock = fCurrentBlock;
2348 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2349 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2350 this->writeLabel(rhsLabel, out);
2351 SpvId rhs = this->writeExpression(*a.fRight, out);
2352 SpvId rhsBlock = fCurrentBlock;
2353 this->writeInstruction(SpvOpBranch, end, out);
2354 this->writeLabel(end, out);
2355 SpvId result = this->nextId();
2356 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fBool_Type), result, falseConstant,
2357 lhsBlock, rhs, rhsBlock, out);
2358 return result;
2359}
2360
2361SpvId SPIRVCodeGenerator::writeLogicalOr(const BinaryExpression& o, OutputStream& out) {
2362 SkASSERT(o.fOperator == Token::Kind::TK_LOGICALOR);
2363 BoolLiteral trueLiteral(fContext, -1, true);
2364 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
2365 SpvId lhs = this->writeExpression(*o.fLeft, out);
2366 SpvId rhsLabel = this->nextId();
2367 SpvId end = this->nextId();
2368 SpvId lhsBlock = fCurrentBlock;
2369 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2370 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2371 this->writeLabel(rhsLabel, out);
2372 SpvId rhs = this->writeExpression(*o.fRight, out);
2373 SpvId rhsBlock = fCurrentBlock;
2374 this->writeInstruction(SpvOpBranch, end, out);
2375 this->writeLabel(end, out);
2376 SpvId result = this->nextId();
2377 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fBool_Type), result, trueConstant,
2378 lhsBlock, rhs, rhsBlock, out);
2379 return result;
2380}
2381
2382SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
2383 SpvId test = this->writeExpression(*t.fTest, out);
2384 if (t.fIfTrue->fType.columns() == 1 &&
2385 t.fIfTrue->isCompileTimeConstant() &&
2386 t.fIfFalse->isCompileTimeConstant()) {
2387 // both true and false are constants, can just use OpSelect
2388 SpvId result = this->nextId();
2389 SpvId trueId = this->writeExpression(*t.fIfTrue, out);
2390 SpvId falseId = this->writeExpression(*t.fIfFalse, out);
2391 this->writeInstruction(SpvOpSelect, this->getType(t.fType), result, test, trueId, falseId,
2392 out);
2393 return result;
2394 }
2395 // was originally using OpPhi to choose the result, but for some reason that is crashing on
2396 // Adreno. Switched to storing the result in a temp variable as glslang does.
2397 SpvId var = this->nextId();
2398 this->writeInstruction(SpvOpVariable, this->getPointerType(t.fType, SpvStorageClassFunction),
2399 var, SpvStorageClassFunction, fVariableBuffer);
2400 SpvId trueLabel = this->nextId();
2401 SpvId falseLabel = this->nextId();
2402 SpvId end = this->nextId();
2403 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2404 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2405 this->writeLabel(trueLabel, out);
2406 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.fIfTrue, out), out);
2407 this->writeInstruction(SpvOpBranch, end, out);
2408 this->writeLabel(falseLabel, out);
2409 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.fIfFalse, out), out);
2410 this->writeInstruction(SpvOpBranch, end, out);
2411 this->writeLabel(end, out);
2412 SpvId result = this->nextId();
2413 this->writeInstruction(SpvOpLoad, this->getType(t.fType), result, var, out);
2414 this->writePrecisionModifier(t.fType, result);
2415 return result;
2416}
2417
2418SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
2419 if (p.fOperator == Token::Kind::TK_MINUS) {
2420 SpvId result = this->nextId();
2421 SpvId typeId = this->getType(p.fType);
2422 SpvId expr = this->writeExpression(*p.fOperand, out);
2423 if (is_float(fContext, p.fType)) {
2424 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
2425 } else if (is_signed(fContext, p.fType)) {
2426 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2427 } else {
2428#ifdef SK_DEBUG
2429 ABORT("unsupported prefix expression %s", p.description().c_str());
2430#endif
2431 }
2432 this->writePrecisionModifier(p.fType, result);
2433 return result;
2434 }
2435 switch (p.fOperator) {
2436 case Token::Kind::TK_PLUS:
2437 return this->writeExpression(*p.fOperand, out);
2438 case Token::Kind::TK_PLUSPLUS: {
2439 std::unique_ptr<LValue> lv = this->getLValue(*p.fOperand, out);
2440 SpvId one = this->writeExpression(*create_literal_1(fContext, p.fType), out);
2441 SpvId result = this->writeBinaryOperation(p.fType, p.fType, lv->load(out), one,
2442 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
2443 out);
2444 lv->store(result, out);
2445 return result;
2446 }
2447 case Token::Kind::TK_MINUSMINUS: {
2448 std::unique_ptr<LValue> lv = this->getLValue(*p.fOperand, out);
2449 SpvId one = this->writeExpression(*create_literal_1(fContext, p.fType), out);
2450 SpvId result = this->writeBinaryOperation(p.fType, p.fType, lv->load(out), one,
2451 SpvOpFSub, SpvOpISub, SpvOpISub, SpvOpUndef,
2452 out);
2453 lv->store(result, out);
2454 return result;
2455 }
2456 case Token::Kind::TK_LOGICALNOT: {
2457 SkASSERT(p.fOperand->fType == *fContext.fBool_Type);
2458 SpvId result = this->nextId();
2459 this->writeInstruction(SpvOpLogicalNot, this->getType(p.fOperand->fType), result,
2460 this->writeExpression(*p.fOperand, out), out);
2461 return result;
2462 }
2463 case Token::Kind::TK_BITWISENOT: {
2464 SpvId result = this->nextId();
2465 this->writeInstruction(SpvOpNot, this->getType(p.fOperand->fType), result,
2466 this->writeExpression(*p.fOperand, out), out);
2467 return result;
2468 }
2469 default:
2470#ifdef SK_DEBUG
2471 ABORT("unsupported prefix expression: %s", p.description().c_str());
2472#endif
2473 return -1;
2474 }
2475}
2476
2477SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
2478 std::unique_ptr<LValue> lv = this->getLValue(*p.fOperand, out);
2479 SpvId result = lv->load(out);
2480 SpvId one = this->writeExpression(*create_literal_1(fContext, p.fType), out);
2481 switch (p.fOperator) {
2482 case Token::Kind::TK_PLUSPLUS: {
2483 SpvId temp = this->writeBinaryOperation(p.fType, p.fType, result, one, SpvOpFAdd,
2484 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2485 lv->store(temp, out);
2486 return result;
2487 }
2488 case Token::Kind::TK_MINUSMINUS: {
2489 SpvId temp = this->writeBinaryOperation(p.fType, p.fType, result, one, SpvOpFSub,
2490 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2491 lv->store(temp, out);
2492 return result;
2493 }
2494 default:
2495#ifdef SK_DEBUG
2496 ABORT("unsupported postfix expression %s", p.description().c_str());
2497#endif
2498 return -1;
2499 }
2500}
2501
2502SpvId SPIRVCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
2503 if (b.fValue) {
2504 if (fBoolTrue == 0) {
2505 fBoolTrue = this->nextId();
2506 this->writeInstruction(SpvOpConstantTrue, this->getType(b.fType), fBoolTrue,
2507 fConstantBuffer);
2508 }
2509 return fBoolTrue;
2510 } else {
2511 if (fBoolFalse == 0) {
2512 fBoolFalse = this->nextId();
2513 this->writeInstruction(SpvOpConstantFalse, this->getType(b.fType), fBoolFalse,
2514 fConstantBuffer);
2515 }
2516 return fBoolFalse;
2517 }
2518}
2519
2520SpvId SPIRVCodeGenerator::writeIntLiteral(const IntLiteral& i) {
2521 ConstantType type;
2522 if (i.fType == *fContext.fInt_Type) {
2523 type = ConstantType::kInt;
2524 } else if (i.fType == *fContext.fUInt_Type) {
2525 type = ConstantType::kUInt;
2526 } else if (i.fType == *fContext.fShort_Type || i.fType == *fContext.fByte_Type) {
2527 type = ConstantType::kShort;
2528 } else if (i.fType == *fContext.fUShort_Type || i.fType == *fContext.fUByte_Type) {
2529 type = ConstantType::kUShort;
2530 } else {
2531 SkASSERT(false);
2532 }
2533 std::pair<ConstantValue, ConstantType> key(i.fValue, type);
2534 auto entry = fNumberConstants.find(key);
2535 if (entry == fNumberConstants.end()) {
2536 SpvId result = this->nextId();
2537 this->writeInstruction(SpvOpConstant, this->getType(i.fType), result, (SpvId) i.fValue,
2538 fConstantBuffer);
2539 fNumberConstants[key] = result;
2540 return result;
2541 }
2542 return entry->second;
2543}
2544
2545SpvId SPIRVCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
2546 ConstantType type;
2547 if (f.fType == *fContext.fHalf_Type) {
2548 type = ConstantType::kHalf;
2549 } else {
2550 type = ConstantType::kFloat;
2551 }
2552 float value = (float) f.fValue;
2553 std::pair<ConstantValue, ConstantType> key(f.fValue, type);
2554 auto entry = fNumberConstants.find(key);
2555 if (entry == fNumberConstants.end()) {
2556 SpvId result = this->nextId();
2557 uint32_t bits;
2558 SkASSERT(sizeof(bits) == sizeof(value));
2559 memcpy(&bits, &value, sizeof(bits));
2560 this->writeInstruction(SpvOpConstant, this->getType(f.fType), result, bits,
2561 fConstantBuffer);
2562 fNumberConstants[key] = result;
2563 return result;
2564 }
2565 return entry->second;
2566}
2567
2568SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
2569 SpvId result = fFunctionMap[&f];
2570 this->writeInstruction(SpvOpFunction, this->getType(f.fReturnType), result,
2571 SpvFunctionControlMaskNone, this->getFunctionType(f), out);
2572 this->writeInstruction(SpvOpName, result, f.fName, fNameBuffer);
2573 for (size_t i = 0; i < f.fParameters.size(); i++) {
2574 SpvId id = this->nextId();
2575 fVariableMap[f.fParameters[i]] = id;
2576 SpvId type;
2577 type = this->getPointerType(f.fParameters[i]->fType, SpvStorageClassFunction);
2578 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2579 }
2580 return result;
2581}
2582
2583SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2584 fVariableBuffer.reset();
2585 SpvId result = this->writeFunctionStart(f.fDeclaration, out);
2586 this->writeLabel(this->nextId(), out);
2587 StringStream bodyBuffer;
2588 this->writeBlock((Block&) *f.fBody, bodyBuffer);
2589 write_stringstream(fVariableBuffer, out);
2590 if (f.fDeclaration.fName == "main") {
2591 write_stringstream(fGlobalInitializersBuffer, out);
2592 }
2593 write_stringstream(bodyBuffer, out);
2594 if (fCurrentBlock) {
2595 if (f.fDeclaration.fReturnType == *fContext.fVoid_Type) {
2596 this->writeInstruction(SpvOpReturn, out);
2597 } else {
2598 this->writeInstruction(SpvOpUnreachable, out);
2599 }
2600 }
2601 this->writeInstruction(SpvOpFunctionEnd, out);
2602 return result;
2603}
2604
2605void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2606 if (layout.fLocation >= 0) {
2607 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
2608 fDecorationBuffer);
2609 }
2610 if (layout.fBinding >= 0) {
2611 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
2612 fDecorationBuffer);
2613 }
2614 if (layout.fIndex >= 0) {
2615 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
2616 fDecorationBuffer);
2617 }
2618 if (layout.fSet >= 0) {
2619 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
2620 fDecorationBuffer);
2621 }
2622 if (layout.fInputAttachmentIndex >= 0) {
2623 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2624 layout.fInputAttachmentIndex, fDecorationBuffer);
2625 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
2626 }
2627 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN &&
2628 layout.fBuiltin != SK_IN_BUILTIN && layout.fBuiltin != SK_OUT_BUILTIN) {
2629 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
2630 fDecorationBuffer);
2631 }
2632}
2633
2634void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2635 if (layout.fLocation >= 0) {
2636 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
2637 layout.fLocation, fDecorationBuffer);
2638 }
2639 if (layout.fBinding >= 0) {
2640 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
2641 layout.fBinding, fDecorationBuffer);
2642 }
2643 if (layout.fIndex >= 0) {
2644 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
2645 layout.fIndex, fDecorationBuffer);
2646 }
2647 if (layout.fSet >= 0) {
2648 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
2649 layout.fSet, fDecorationBuffer);
2650 }
2651 if (layout.fInputAttachmentIndex >= 0) {
2652 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
2653 layout.fInputAttachmentIndex, fDecorationBuffer);
2654 }
2655 if (layout.fBuiltin >= 0) {
2656 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
2657 layout.fBuiltin, fDecorationBuffer);
2658 }
2659}
2660
2661static void update_sk_in_count(const Modifiers& m, int* outSkInCount) {
2662 switch (m.fLayout.fPrimitive) {
2663 case Layout::kPoints_Primitive:
2664 *outSkInCount = 1;
2665 break;
2666 case Layout::kLines_Primitive:
2667 *outSkInCount = 2;
2668 break;
2669 case Layout::kLinesAdjacency_Primitive:
2670 *outSkInCount = 4;
2671 break;
2672 case Layout::kTriangles_Primitive:
2673 *outSkInCount = 3;
2674 break;
2675 case Layout::kTrianglesAdjacency_Primitive:
2676 *outSkInCount = 6;
2677 break;
2678 default:
2679 return;
2680 }
2681}
2682
2683SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTHeight) {
2684 bool isBuffer = (0 != (intf.fVariable.fModifiers.fFlags & Modifiers::kBuffer_Flag));
2685 bool pushConstant = (0 != (intf.fVariable.fModifiers.fLayout.fFlags &
2686 Layout::kPushConstant_Flag));
2687 MemoryLayout memoryLayout = (pushConstant || isBuffer) ?
2688 MemoryLayout(MemoryLayout::k430_Standard) :
2689 fDefaultLayout;
2690 SpvId result = this->nextId();
2691 const Type* type = &intf.fVariable.fType;
2692 if (fProgram.fInputs.fRTHeight && appendRTHeight) {
2693 SkASSERT(fRTHeightStructId == (SpvId) -1);
2694 SkASSERT(fRTHeightFieldIndex == (SpvId) -1);
2695 std::vector<Type::Field> fields = type->fields();
2696 fRTHeightStructId = result;
2697 fRTHeightFieldIndex = fields.size();
2698 fields.emplace_back(Modifiers(), StringFragment(SKSL_RTHEIGHT_NAME), fContext.fFloat_Type.get());
2699 type = new Type(type->fOffset, type->name(), fields);
2700 }
2701 SpvId typeId;
2702 if (intf.fVariable.fModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
2703 for (const auto& e : fProgram) {
2704 if (e.fKind == ProgramElement::kModifiers_Kind) {
2705 const Modifiers& m = ((ModifiersDeclaration&) e).fModifiers;
2706 update_sk_in_count(m, &fSkInCount);
2707 }
2708 }
2709 typeId = this->getType(Type("sk_in", Type::kArray_Kind, intf.fVariable.fType.componentType(),
2710 fSkInCount), memoryLayout);
2711 } else {
2712 typeId = this->getType(*type, memoryLayout);
2713 }
2714 if (intf.fVariable.fModifiers.fFlags & Modifiers::kBuffer_Flag) {
2715 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBufferBlock, fDecorationBuffer);
2716 } else if (intf.fVariable.fModifiers.fLayout.fBuiltin == -1) {
2717 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
2718 }
2719 SpvStorageClass_ storageClass = get_storage_class(intf.fVariable.fModifiers);
2720 SpvId ptrType = this->nextId();
2721 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
2722 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
2723 Layout layout = intf.fVariable.fModifiers.fLayout;
2724 if (intf.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
2725 layout.fSet = 0;
2726 }
2727 this->writeLayout(layout, result);
2728 fVariableMap[&intf.fVariable] = result;
2729 if (fProgram.fInputs.fRTHeight && appendRTHeight) {
2730 delete type;
2731 }
2732 return result;
2733}
2734
2735void SPIRVCodeGenerator::writePrecisionModifier(const Type& type, SpvId id) {
2736 this->writePrecisionModifier(type.highPrecision() ? Precision::kHigh : Precision::kLow, id);
2737}
2738
2739void SPIRVCodeGenerator::writePrecisionModifier(Precision precision, SpvId id) {
2740 if (precision == Precision::kLow) {
2741 this->writeInstruction(SpvOpDecorate, id, SpvDecorationRelaxedPrecision, fDecorationBuffer);
2742 }
2743}
2744
2745bool is_dead(const Variable& var) {
2746 if (var.fReadCount || var.fWriteCount) {
2747 return false;
2748 }
2749 // not entirely sure what the rules are for when it's safe to elide interface variables, but it
2750 // causes various problems to elide some of them even when dead. But it also causes problems
2751 // *not* to elide sk_SampleMask when it's not being used.
2752 if (!(var.fModifiers.fFlags & (Modifiers::kIn_Flag |
2753 Modifiers::kOut_Flag |
2754 Modifiers::kUniform_Flag |
2755 Modifiers::kBuffer_Flag))) {
2756 return true;
2757 }
2758 return var.fModifiers.fLayout.fBuiltin == SK_SAMPLEMASK_BUILTIN;
2759}
2760
2761#define BUILTIN_IGNORE 9999
2762void SPIRVCodeGenerator::writeGlobalVars(Program::Kind kind, const VarDeclarations& decl,
2763 OutputStream& out) {
2764 for (size_t i = 0; i < decl.fVars.size(); i++) {
2765 if (decl.fVars[i]->fKind == Statement::kNop_Kind) {
2766 continue;
2767 }
2768 const VarDeclaration& varDecl = (VarDeclaration&) *decl.fVars[i];
2769 const Variable* var = varDecl.fVar;
2770 // These haven't been implemented in our SPIR-V generator yet and we only currently use them
2771 // in the OpenGL backend.
2772 SkASSERT(!(var->fModifiers.fFlags & (Modifiers::kReadOnly_Flag |
2773 Modifiers::kWriteOnly_Flag |
2774 Modifiers::kCoherent_Flag |
2775 Modifiers::kVolatile_Flag |
2776 Modifiers::kRestrict_Flag)));
2777 if (var->fModifiers.fLayout.fBuiltin == BUILTIN_IGNORE) {
2778 continue;
2779 }
2780 if (var->fModifiers.fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
2781 kind != Program::kFragment_Kind) {
2782 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
2783 continue;
2784 }
2785 if (is_dead(*var)) {
2786 continue;
2787 }
2788 SpvStorageClass_ storageClass;
2789 if (var->fModifiers.fFlags & Modifiers::kIn_Flag) {
2790 storageClass = SpvStorageClassInput;
2791 } else if (var->fModifiers.fFlags & Modifiers::kOut_Flag) {
2792 storageClass = SpvStorageClassOutput;
2793 } else if (var->fModifiers.fFlags & Modifiers::kUniform_Flag) {
2794 if (var->fType.kind() == Type::kSampler_Kind ||
2795 var->fType.kind() == Type::kSeparateSampler_Kind ||
2796 var->fType.kind() == Type::kTexture_Kind) {
2797 storageClass = SpvStorageClassUniformConstant;
2798 } else {
2799 storageClass = SpvStorageClassUniform;
2800 }
2801 } else {
2802 storageClass = SpvStorageClassPrivate;
2803 }
2804 SpvId id = this->nextId();
2805 fVariableMap[var] = id;
2806 SpvId type;
2807 if (var->fModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
2808 type = this->getPointerType(Type("sk_in", Type::kArray_Kind,
2809 var->fType.componentType(), fSkInCount),
2810 storageClass);
2811 } else {
2812 type = this->getPointerType(var->fType, storageClass);
2813 }
2814 this->writeInstruction(SpvOpVariable, type, id, storageClass, fConstantBuffer);
2815 this->writeInstruction(SpvOpName, id, var->fName, fNameBuffer);
2816 this->writePrecisionModifier(var->fType, id);
2817 if (varDecl.fValue) {
2818 SkASSERT(!fCurrentBlock);
2819 fCurrentBlock = -1;
2820 SpvId value = this->writeExpression(*varDecl.fValue, fGlobalInitializersBuffer);
2821 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
2822 fCurrentBlock = 0;
2823 }
2824 this->writeLayout(var->fModifiers.fLayout, id);
2825 if (var->fModifiers.fFlags & Modifiers::kFlat_Flag) {
2826 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
2827 }
2828 if (var->fModifiers.fFlags & Modifiers::kNoPerspective_Flag) {
2829 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
2830 fDecorationBuffer);
2831 }
2832 }
2833}
2834
2835void SPIRVCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, OutputStream& out) {
2836 for (const auto& stmt : decl.fVars) {
2837 SkASSERT(stmt->fKind == Statement::kVarDeclaration_Kind);
2838 VarDeclaration& varDecl = (VarDeclaration&) *stmt;
2839 const Variable* var = varDecl.fVar;
2840 // These haven't been implemented in our SPIR-V generator yet and we only currently use them
2841 // in the OpenGL backend.
2842 SkASSERT(!(var->fModifiers.fFlags & (Modifiers::kReadOnly_Flag |
2843 Modifiers::kWriteOnly_Flag |
2844 Modifiers::kCoherent_Flag |
2845 Modifiers::kVolatile_Flag |
2846 Modifiers::kRestrict_Flag)));
2847 SpvId id = this->nextId();
2848 fVariableMap[var] = id;
2849 SpvId type = this->getPointerType(var->fType, SpvStorageClassFunction);
2850 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
2851 this->writeInstruction(SpvOpName, id, var->fName, fNameBuffer);
2852 if (varDecl.fValue) {
2853 SpvId value = this->writeExpression(*varDecl.fValue, out);
2854 this->writeInstruction(SpvOpStore, id, value, out);
2855 }
2856 }
2857}
2858
2859void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
2860 switch (s.fKind) {
2861 case Statement::kNop_Kind:
2862 break;
2863 case Statement::kBlock_Kind:
2864 this->writeBlock((Block&) s, out);
2865 break;
2866 case Statement::kExpression_Kind:
2867 this->writeExpression(*((ExpressionStatement&) s).fExpression, out);
2868 break;
2869 case Statement::kReturn_Kind:
2870 this->writeReturnStatement((ReturnStatement&) s, out);
2871 break;
2872 case Statement::kVarDeclarations_Kind:
2873 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, out);
2874 break;
2875 case Statement::kIf_Kind:
2876 this->writeIfStatement((IfStatement&) s, out);
2877 break;
2878 case Statement::kFor_Kind:
2879 this->writeForStatement((ForStatement&) s, out);
2880 break;
2881 case Statement::kWhile_Kind:
2882 this->writeWhileStatement((WhileStatement&) s, out);
2883 break;
2884 case Statement::kDo_Kind:
2885 this->writeDoStatement((DoStatement&) s, out);
2886 break;
2887 case Statement::kSwitch_Kind:
2888 this->writeSwitchStatement((SwitchStatement&) s, out);
2889 break;
2890 case Statement::kBreak_Kind:
2891 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
2892 break;
2893 case Statement::kContinue_Kind:
2894 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
2895 break;
2896 case Statement::kDiscard_Kind:
2897 this->writeInstruction(SpvOpKill, out);
2898 break;
2899 default:
2900#ifdef SK_DEBUG
2901 ABORT("unsupported statement: %s", s.description().c_str());
2902#endif
2903 break;
2904 }
2905}
2906
2907void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
2908 for (size_t i = 0; i < b.fStatements.size(); i++) {
2909 this->writeStatement(*b.fStatements[i], out);
2910 }
2911}
2912
2913void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
2914 SpvId test = this->writeExpression(*stmt.fTest, out);
2915 SpvId ifTrue = this->nextId();
2916 SpvId ifFalse = this->nextId();
2917 if (stmt.fIfFalse) {
2918 SpvId end = this->nextId();
2919 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2920 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
2921 this->writeLabel(ifTrue, out);
2922 this->writeStatement(*stmt.fIfTrue, out);
2923 if (fCurrentBlock) {
2924 this->writeInstruction(SpvOpBranch, end, out);
2925 }
2926 this->writeLabel(ifFalse, out);
2927 this->writeStatement(*stmt.fIfFalse, out);
2928 if (fCurrentBlock) {
2929 this->writeInstruction(SpvOpBranch, end, out);
2930 }
2931 this->writeLabel(end, out);
2932 } else {
2933 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
2934 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
2935 this->writeLabel(ifTrue, out);
2936 this->writeStatement(*stmt.fIfTrue, out);
2937 if (fCurrentBlock) {
2938 this->writeInstruction(SpvOpBranch, ifFalse, out);
2939 }
2940 this->writeLabel(ifFalse, out);
2941 }
2942}
2943
2944void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
2945 if (f.fInitializer) {
2946 this->writeStatement(*f.fInitializer, out);
2947 }
2948 SpvId header = this->nextId();
2949 SpvId start = this->nextId();
2950 SpvId body = this->nextId();
2951 SpvId next = this->nextId();
2952 fContinueTarget.push(next);
2953 SpvId end = this->nextId();
2954 fBreakTarget.push(end);
2955 this->writeInstruction(SpvOpBranch, header, out);
2956 this->writeLabel(header, out);
2957 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
2958 this->writeInstruction(SpvOpBranch, start, out);
2959 this->writeLabel(start, out);
2960 if (f.fTest) {
2961 SpvId test = this->writeExpression(*f.fTest, out);
2962 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
2963 }
2964 this->writeLabel(body, out);
2965 this->writeStatement(*f.fStatement, out);
2966 if (fCurrentBlock) {
2967 this->writeInstruction(SpvOpBranch, next, out);
2968 }
2969 this->writeLabel(next, out);
2970 if (f.fNext) {
2971 this->writeExpression(*f.fNext, out);
2972 }
2973 this->writeInstruction(SpvOpBranch, header, out);
2974 this->writeLabel(end, out);
2975 fBreakTarget.pop();
2976 fContinueTarget.pop();
2977}
2978
2979void SPIRVCodeGenerator::writeWhileStatement(const WhileStatement& w, OutputStream& out) {
2980 SpvId header = this->nextId();
2981 SpvId start = this->nextId();
2982 SpvId body = this->nextId();
2983 SpvId continueTarget = this->nextId();
2984 fContinueTarget.push(continueTarget);
2985 SpvId end = this->nextId();
2986 fBreakTarget.push(end);
2987 this->writeInstruction(SpvOpBranch, header, out);
2988 this->writeLabel(header, out);
2989 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
2990 this->writeInstruction(SpvOpBranch, start, out);
2991 this->writeLabel(start, out);
2992 SpvId test = this->writeExpression(*w.fTest, out);
2993 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
2994 this->writeLabel(body, out);
2995 this->writeStatement(*w.fStatement, out);
2996 if (fCurrentBlock) {
2997 this->writeInstruction(SpvOpBranch, continueTarget, out);
2998 }
2999 this->writeLabel(continueTarget, out);
3000 this->writeInstruction(SpvOpBranch, header, out);
3001 this->writeLabel(end, out);
3002 fBreakTarget.pop();
3003 fContinueTarget.pop();
3004}
3005
3006void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
3007 SpvId header = this->nextId();
3008 SpvId start = this->nextId();
3009 SpvId next = this->nextId();
3010 SpvId continueTarget = this->nextId();
3011 fContinueTarget.push(continueTarget);
3012 SpvId end = this->nextId();
3013 fBreakTarget.push(end);
3014 this->writeInstruction(SpvOpBranch, header, out);
3015 this->writeLabel(header, out);
3016 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
3017 this->writeInstruction(SpvOpBranch, start, out);
3018 this->writeLabel(start, out);
3019 this->writeStatement(*d.fStatement, out);
3020 if (fCurrentBlock) {
3021 this->writeInstruction(SpvOpBranch, next, out);
3022 }
3023 this->writeLabel(next, out);
3024 SpvId test = this->writeExpression(*d.fTest, out);
3025 this->writeInstruction(SpvOpBranchConditional, test, continueTarget, end, out);
3026 this->writeLabel(continueTarget, out);
3027 this->writeInstruction(SpvOpBranch, header, out);
3028 this->writeLabel(end, out);
3029 fBreakTarget.pop();
3030 fContinueTarget.pop();
3031}
3032
3033void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
3034 SpvId value = this->writeExpression(*s.fValue, out);
3035 std::vector<SpvId> labels;
3036 SpvId end = this->nextId();
3037 SpvId defaultLabel = end;
3038 fBreakTarget.push(end);
3039 int size = 3;
3040 for (const auto& c : s.fCases) {
3041 SpvId label = this->nextId();
3042 labels.push_back(label);
3043 if (c->fValue) {
3044 size += 2;
3045 } else {
3046 defaultLabel = label;
3047 }
3048 }
3049 labels.push_back(end);
3050 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3051 this->writeOpCode(SpvOpSwitch, size, out);
3052 this->writeWord(value, out);
3053 this->writeWord(defaultLabel, out);
3054 for (size_t i = 0; i < s.fCases.size(); ++i) {
3055 if (!s.fCases[i]->fValue) {
3056 continue;
3057 }
3058 SkASSERT(s.fCases[i]->fValue->fKind == Expression::kIntLiteral_Kind);
3059 this->writeWord(((IntLiteral&) *s.fCases[i]->fValue).fValue, out);
3060 this->writeWord(labels[i], out);
3061 }
3062 for (size_t i = 0; i < s.fCases.size(); ++i) {
3063 this->writeLabel(labels[i], out);
3064 for (const auto& stmt : s.fCases[i]->fStatements) {
3065 this->writeStatement(*stmt, out);
3066 }
3067 if (fCurrentBlock) {
3068 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3069 }
3070 }
3071 this->writeLabel(end, out);
3072 fBreakTarget.pop();
3073}
3074
3075void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
3076 if (r.fExpression) {
3077 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.fExpression, out),
3078 out);
3079 } else {
3080 this->writeInstruction(SpvOpReturn, out);
3081 }
3082}
3083
3084void SPIRVCodeGenerator::writeGeometryShaderExecutionMode(SpvId entryPoint, OutputStream& out) {
3085 SkASSERT(fProgram.fKind == Program::kGeometry_Kind);
3086 int invocations = 1;
3087 for (const auto& e : fProgram) {
3088 if (e.fKind == ProgramElement::kModifiers_Kind) {
3089 const Modifiers& m = ((ModifiersDeclaration&) e).fModifiers;
3090 if (m.fFlags & Modifiers::kIn_Flag) {
3091 if (m.fLayout.fInvocations != -1) {
3092 invocations = m.fLayout.fInvocations;
3093 }
3094 SpvId input;
3095 switch (m.fLayout.fPrimitive) {
3096 case Layout::kPoints_Primitive:
3097 input = SpvExecutionModeInputPoints;
3098 break;
3099 case Layout::kLines_Primitive:
3100 input = SpvExecutionModeInputLines;
3101 break;
3102 case Layout::kLinesAdjacency_Primitive:
3103 input = SpvExecutionModeInputLinesAdjacency;
3104 break;
3105 case Layout::kTriangles_Primitive:
3106 input = SpvExecutionModeTriangles;
3107 break;
3108 case Layout::kTrianglesAdjacency_Primitive:
3109 input = SpvExecutionModeInputTrianglesAdjacency;
3110 break;
3111 default:
3112 input = 0;
3113 break;
3114 }
3115 update_sk_in_count(m, &fSkInCount);
3116 if (input) {
3117 this->writeInstruction(SpvOpExecutionMode, entryPoint, input, out);
3118 }
3119 } else if (m.fFlags & Modifiers::kOut_Flag) {
3120 SpvId output;
3121 switch (m.fLayout.fPrimitive) {
3122 case Layout::kPoints_Primitive:
3123 output = SpvExecutionModeOutputPoints;
3124 break;
3125 case Layout::kLineStrip_Primitive:
3126 output = SpvExecutionModeOutputLineStrip;
3127 break;
3128 case Layout::kTriangleStrip_Primitive:
3129 output = SpvExecutionModeOutputTriangleStrip;
3130 break;
3131 default:
3132 output = 0;
3133 break;
3134 }
3135 if (output) {
3136 this->writeInstruction(SpvOpExecutionMode, entryPoint, output, out);
3137 }
3138 if (m.fLayout.fMaxVertices != -1) {
3139 this->writeInstruction(SpvOpExecutionMode, entryPoint,
3140 SpvExecutionModeOutputVertices, m.fLayout.fMaxVertices,
3141 out);
3142 }
3143 }
3144 }
3145 }
3146 this->writeInstruction(SpvOpExecutionMode, entryPoint, SpvExecutionModeInvocations,
3147 invocations, out);
3148}
3149
3150void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
3151 fGLSLExtendedInstructions = this->nextId();
3152 StringStream body;
3153 std::set<SpvId> interfaceVars;
3154 // assign IDs to functions, determine sk_in size
3155 int skInSize = -1;
3156 for (const auto& e : program) {
3157 switch (e.fKind) {
3158 case ProgramElement::kFunction_Kind: {
3159 FunctionDefinition& f = (FunctionDefinition&) e;
3160 fFunctionMap[&f.fDeclaration] = this->nextId();
3161 break;
3162 }
3163 case ProgramElement::kModifiers_Kind: {
3164 Modifiers& m = ((ModifiersDeclaration&) e).fModifiers;
3165 if (m.fFlags & Modifiers::kIn_Flag) {
3166 switch (m.fLayout.fPrimitive) {
3167 case Layout::kPoints_Primitive: // break
3168 case Layout::kLines_Primitive:
3169 skInSize = 1;
3170 break;
3171 case Layout::kLinesAdjacency_Primitive: // break
3172 skInSize = 2;
3173 break;
3174 case Layout::kTriangles_Primitive: // break
3175 case Layout::kTrianglesAdjacency_Primitive:
3176 skInSize = 3;
3177 break;
3178 default:
3179 break;
3180 }
3181 }
3182 break;
3183 }
3184 default:
3185 break;
3186 }
3187 }
3188 for (const auto& e : program) {
3189 if (e.fKind == ProgramElement::kInterfaceBlock_Kind) {
3190 InterfaceBlock& intf = (InterfaceBlock&) e;
3191 if (SK_IN_BUILTIN == intf.fVariable.fModifiers.fLayout.fBuiltin) {
3192 SkASSERT(skInSize != -1);
3193 intf.fSizes.emplace_back(new IntLiteral(fContext, -1, skInSize));
3194 }
3195 SpvId id = this->writeInterfaceBlock(intf);
3196 if (((intf.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) ||
3197 (intf.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) &&
3198 intf.fVariable.fModifiers.fLayout.fBuiltin == -1 &&
3199 !is_dead(intf.fVariable)) {
3200 interfaceVars.insert(id);
3201 }
3202 }
3203 }
3204 for (const auto& e : program) {
3205 if (e.fKind == ProgramElement::kVar_Kind) {
3206 this->writeGlobalVars(program.fKind, ((VarDeclarations&) e), body);
3207 }
3208 }
3209 for (const auto& e : program) {
3210 if (e.fKind == ProgramElement::kFunction_Kind) {
3211 this->writeFunction(((FunctionDefinition&) e), body);
3212 }
3213 }
3214 const FunctionDeclaration* main = nullptr;
3215 for (auto entry : fFunctionMap) {
3216 if (entry.first->fName == "main") {
3217 main = entry.first;
3218 }
3219 }
3220 if (!main) {
3221 fErrors.error(0, "program does not contain a main() function");
3222 return;
3223 }
3224 for (auto entry : fVariableMap) {
3225 const Variable* var = entry.first;
3226 if (var->fStorage == Variable::kGlobal_Storage &&
3227 ((var->fModifiers.fFlags & Modifiers::kIn_Flag) ||
3228 (var->fModifiers.fFlags & Modifiers::kOut_Flag)) && !is_dead(*var)) {
3229 interfaceVars.insert(entry.second);
3230 }
3231 }
3232 this->writeCapabilities(out);
3233 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3234 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
3235 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->fName.fLength + 4) / 4) +
3236 (int32_t) interfaceVars.size(), out);
3237 switch (program.fKind) {
3238 case Program::kVertex_Kind:
3239 this->writeWord(SpvExecutionModelVertex, out);
3240 break;
3241 case Program::kFragment_Kind:
3242 this->writeWord(SpvExecutionModelFragment, out);
3243 break;
3244 case Program::kGeometry_Kind:
3245 this->writeWord(SpvExecutionModelGeometry, out);
3246 break;
3247 default:
3248 ABORT("cannot write this kind of program to SPIR-V\n");
3249 }
3250 SpvId entryPoint = fFunctionMap[main];
3251 this->writeWord(entryPoint, out);
3252 this->writeString(main->fName.fChars, main->fName.fLength, out);
3253 for (int var : interfaceVars) {
3254 this->writeWord(var, out);
3255 }
3256 if (program.fKind == Program::kGeometry_Kind) {
3257 this->writeGeometryShaderExecutionMode(entryPoint, out);
3258 }
3259 if (program.fKind == Program::kFragment_Kind) {
3260 this->writeInstruction(SpvOpExecutionMode,
3261 fFunctionMap[main],
3262 SpvExecutionModeOriginUpperLeft,
3263 out);
3264 }
3265 for (const auto& e : program) {
3266 if (e.fKind == ProgramElement::kExtension_Kind) {
3267 this->writeInstruction(SpvOpSourceExtension, ((Extension&) e).fName.c_str(), out);
3268 }
3269 }
3270
3271 write_stringstream(fExtraGlobalsBuffer, out);
3272 write_stringstream(fNameBuffer, out);
3273 write_stringstream(fDecorationBuffer, out);
3274 write_stringstream(fConstantBuffer, out);
3275 write_stringstream(fExternalFunctionsBuffer, out);
3276 write_stringstream(body, out);
3277}
3278
3279bool SPIRVCodeGenerator::generateCode() {
3280 SkASSERT(!fErrors.errorCount());
3281 this->writeWord(SpvMagicNumber, *fOut);
3282 this->writeWord(SpvVersion, *fOut);
3283 this->writeWord(SKSL_MAGIC, *fOut);
3284 StringStream buffer;
3285 this->writeInstructions(fProgram, buffer);
3286 this->writeWord(fIdCount, *fOut);
3287 this->writeWord(0, *fOut); // reserved, always zero
3288 write_stringstream(buffer, *fOut);
3289 return 0 == fErrors.errorCount();
3290}
3291
3292} // namespace SkSL
3293